]>
git.argeo.org Git - lgpl/argeo-commons.git/blob - argeo/util/LangUtils.java
1 package org
.argeo
.util
;
3 import java
.io
.IOException
;
4 import java
.io
.InputStream
;
5 import java
.io
.OutputStream
;
7 import java
.nio
.file
.Files
;
8 import java
.nio
.file
.Path
;
9 import java
.nio
.file
.StandardOpenOption
;
10 import java
.time
.ZonedDateTime
;
11 import java
.time
.temporal
.ChronoUnit
;
12 import java
.time
.temporal
.Temporal
;
13 import java
.util
.Dictionary
;
14 import java
.util
.Enumeration
;
15 import java
.util
.HashMap
;
16 import java
.util
.Hashtable
;
18 import java
.util
.Properties
;
20 import javax
.naming
.InvalidNameException
;
21 import javax
.naming
.ldap
.LdapName
;
23 /** Utilities around Java basic features. */
24 public class LangUtils
{
29 * Returns an array with the names of the provided classes. Useful when
30 * registering services with multiple interfaces in OSGi.
32 public static String
[] names(Class
<?
>... clzz
) {
33 String
[] res
= new String
[clzz
.length
];
34 for (int i
= 0; i
< clzz
.length
; i
++)
35 res
[i
] = clzz
[i
].getName();
43 * Creates a new {@link Dictionary} with one key-value pair. Key should not be
44 * null, but if the value is null, it returns an empty {@link Dictionary}.
46 public static Map
<String
, Object
> map(String key
, Object value
) {
48 HashMap
<String
, Object
> props
= new HashMap
<>();
50 props
.put(key
, value
);
59 * Creates a new {@link Dictionary} with one key-value pair. Key should not be
60 * null, but if the value is null, it returns an empty {@link Dictionary}.
62 public static Dictionary
<String
, Object
> dict(String key
, Object value
) {
64 Hashtable
<String
, Object
> props
= new Hashtable
<>();
66 props
.put(key
, value
);
70 /** @deprecated Use {@link #dict(String, Object)} instead. */
72 public static Dictionary
<String
, Object
> dico(String key
, Object value
) {
73 return dict(key
, value
);
76 /** Converts a {@link Dictionary} to a {@link Map} of strings. */
77 public static Map
<String
, String
> dictToStringMap(Dictionary
<String
, ?
> properties
) {
78 if (properties
== null) {
81 Map
<String
, String
> res
= new HashMap
<>(properties
.size());
82 Enumeration
<String
> keys
= properties
.keys();
83 while (keys
.hasMoreElements()) {
84 String key
= keys
.nextElement();
85 res
.put(key
, properties
.get(key
).toString());
91 * Get a string property from this map, expecting to find it, or
92 * <code>null</code> if not found.
94 public static String
get(Map
<String
, ?
> map
, String key
) {
95 Object res
= map
.get(key
);
98 return res
.toString();
102 * Get a string property from this map, expecting to find it.
104 * @throws IllegalArgumentException if the key was not found
106 public static String
getNotNull(Map
<String
, ?
> map
, String key
) {
107 Object res
= map
.get(key
);
109 throw new IllegalArgumentException("Map " + map
+ " should contain key " + key
);
110 return res
.toString();
114 * Wraps the keys of the provided {@link Dictionary} as an {@link Iterable}.
116 public static Iterable
<String
> keys(Dictionary
<String
, ?
> props
) {
117 assert props
!= null;
118 return new DictionaryKeys(props
);
121 static String
toJson(Dictionary
<String
, ?
> props
) {
122 return toJson(props
, false);
125 static String
toJson(Dictionary
<String
, ?
> props
, boolean pretty
) {
126 StringBuilder sb
= new StringBuilder();
130 Enumeration
<String
> keys
= props
.keys();
131 while (keys
.hasMoreElements()) {
132 String key
= keys
.nextElement();
135 sb
.append('\"').append(key
).append('\"');
140 sb
.append('\"').append(props
.get(key
)).append('\"');
141 if (keys
.hasMoreElements())
147 return sb
.toString();
150 static void storeAsProperties(Dictionary
<String
, Object
> props
, Path path
) throws IOException
{
152 throw new IllegalArgumentException("Props cannot be null");
153 Properties toStore
= new Properties();
154 for (Enumeration
<String
> keys
= props
.keys(); keys
.hasMoreElements();) {
155 String key
= keys
.nextElement();
156 toStore
.setProperty(key
, props
.get(key
).toString());
158 try (OutputStream out
= Files
.newOutputStream(path
)) {
159 toStore
.store(out
, null);
163 static void appendAsLdif(String dnBase
, String dnKey
, Dictionary
<String
, Object
> props
, Path path
)
166 throw new IllegalArgumentException("Props cannot be null");
167 Object dnValue
= props
.get(dnKey
);
168 String dnStr
= dnKey
+ '=' + dnValue
+ ',' + dnBase
;
171 dn
= new LdapName(dnStr
);
172 } catch (InvalidNameException e
) {
173 throw new IllegalArgumentException("Cannot interpret DN " + dnStr
, e
);
176 throw new IllegalArgumentException("DN key " + dnKey
+ " must have a value");
177 try (Writer writer
= Files
.newBufferedWriter(path
, StandardOpenOption
.APPEND
, StandardOpenOption
.CREATE
)) {
178 writer
.append("\ndn: ");
179 writer
.append(dn
.toString());
181 for (Enumeration
<String
> keys
= props
.keys(); keys
.hasMoreElements();) {
182 String key
= keys
.nextElement();
183 Object value
= props
.get(key
);
186 // FIXME deal with binary and multiple values
187 writer
.append(value
.toString());
193 static Dictionary
<String
, Object
> loadFromProperties(Path path
) throws IOException
{
194 Properties toLoad
= new Properties();
195 try (InputStream in
= Files
.newInputStream(path
)) {
198 Dictionary
<String
, Object
> res
= new Hashtable
<String
, Object
>();
199 for (Object key
: toLoad
.keySet())
200 res
.put(key
.toString(), toLoad
.get(key
));
208 * Chain the messages of all causes (one per line, <b>starts with a line
209 * return</b>) without all the stack
211 public static String
chainCausesMessages(Throwable t
) {
212 StringBuffer buf
= new StringBuffer();
213 chainCauseMessage(buf
, t
);
214 return buf
.toString();
217 /** Recursive chaining of messages */
218 private static void chainCauseMessage(StringBuffer buf
, Throwable t
) {
219 buf
.append('\n').append(' ').append(t
.getClass().getCanonicalName()).append(": ").append(t
.getMessage());
220 if (t
.getCause() != null)
221 chainCauseMessage(buf
, t
.getCause());
227 /** Formats time elapsed since start. */
228 public static String
since(ZonedDateTime start
) {
229 ZonedDateTime now
= ZonedDateTime
.now();
230 return duration(start
, now
);
233 /** Formats a duration. */
234 public static String
duration(Temporal start
, Temporal end
) {
235 long count
= ChronoUnit
.DAYS
.between(start
, end
);
237 return count
> 1 ? count
+ " days" : count
+ " day";
238 count
= ChronoUnit
.HOURS
.between(start
, end
);
240 return count
> 1 ? count
+ " hours" : count
+ " hours";
241 count
= ChronoUnit
.MINUTES
.between(start
, end
);
243 return count
> 1 ? count
+ " minutes" : count
+ " minute";
244 count
= ChronoUnit
.SECONDS
.between(start
, end
);
245 return count
> 1 ? count
+ " seconds" : count
+ " second";
248 /** Singleton constructor. */
249 private LangUtils() {