]>
git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.util/src/org/argeo/util/LangUtils.java
1 package org
.argeo
.util
;
3 import java
.io
.IOException
;
4 import java
.io
.InputStream
;
5 import java
.io
.OutputStream
;
6 import java
.nio
.file
.Files
;
7 import java
.nio
.file
.Path
;
8 import java
.util
.Dictionary
;
9 import java
.util
.Enumeration
;
10 import java
.util
.Hashtable
;
12 import java
.util
.Properties
;
14 public class LangUtils
{
19 * Returns an array with the names of the provided classes. Useful when
20 * registering services with multiple interfaces in OSGi.
22 public static String
[] names(Class
<?
>... clzz
) {
23 String
[] res
= new String
[clzz
.length
];
24 for (int i
= 0; i
< clzz
.length
; i
++)
25 res
[i
] = clzz
[i
].getName();
34 * Creates a new {@link Dictionary} with one key-value pair (neither key not
35 * value should be null)
37 public static Dictionary
<String
, Object
> init(String key
, Object value
) {
40 Hashtable
<String
, Object
> props
= new Hashtable
<>();
41 props
.put(key
, value
);
46 * Wraps the keys of the provided {@link Dictionary} as an {@link Iterable}.
48 public static Iterable
<String
> keys(Dictionary
<String
, ?
> props
) {
50 return new DictionaryKeys(props
);
53 public static String
toJson(Dictionary
<String
, ?
> props
) {
54 return toJson(props
, false);
57 public static String
toJson(Dictionary
<String
, ?
> props
, boolean pretty
) {
58 StringBuilder sb
= new StringBuilder();
62 Enumeration
<String
> keys
= props
.keys();
63 while (keys
.hasMoreElements()) {
64 String key
= keys
.nextElement();
67 sb
.append('\"').append(key
).append('\"');
72 sb
.append('\"').append(props
.get(key
)).append('\"');
73 if (keys
.hasMoreElements())
82 public static void storeAsProperties(Dictionary
<String
, Object
> props
, Path path
) throws IOException
{
84 throw new IllegalArgumentException("Props cannot be null");
85 Properties toStore
= new Properties();
86 for (Enumeration
<String
> keys
= props
.keys(); keys
.hasMoreElements();) {
87 String key
= keys
.nextElement();
88 toStore
.setProperty(key
, props
.get(key
).toString());
90 try (OutputStream out
= Files
.newOutputStream(path
)) {
91 toStore
.store(out
, null);
95 public static Dictionary
<String
, Object
> loadFromProperties(Path path
) throws IOException
{
96 Properties toLoad
= new Properties();
97 try (InputStream in
= Files
.newInputStream(path
)) {
100 Dictionary
<String
, Object
> res
= new Hashtable
<String
, Object
>();
101 for (Object key
: toLoad
.keySet())
102 res
.put(key
.toString(), toLoad
.get(key
));
106 /** Singleton constructor. */
107 private LangUtils() {