View Javadoc

1   /*
2    * Created on 08.03.2005
3    *
4    */
5   package net.sf.crispy.util;
6   
7   import java.io.FileInputStream;
8   import java.io.FileNotFoundException;
9   import java.io.IOException;
10  import java.io.InputStream;
11  import java.net.InetAddress;
12  import java.net.Socket;
13  import java.util.Collection;
14  import java.util.Date;
15  import java.util.Enumeration;
16  import java.util.Iterator;
17  import java.util.Map;
18  import java.util.Properties;
19  import java.util.TreeMap;
20  import java.util.Map.Entry;
21  import java.util.logging.LogManager;
22  import java.util.logging.Logger;
23  
24  import javax.swing.JFrame;
25  import javax.swing.JScrollPane;
26  import javax.swing.JTree;
27  import javax.swing.tree.DefaultMutableTreeNode;
28  import javax.xml.namespace.QName;
29  
30  import net.sf.crispy.InvocationException;
31  
32  /**
33   * Utility (helper) class.
34   * 
35   * @author Linke
36   *
37   */
38  public class Util {
39  	
40  	/**
41  	 * Find the deepest Exception by nested Exception.
42  	 * Example:
43  	 * 
44  	 * <pre>
45  	 * Exception e0 = new Exception ();
46  	 * Exception e1 = new Exception (e0);
47  	 * 
48  	 * Exception eFind = findDeepestThrowable(e1);
49  	 * The result: eFind == e0
50  	 * </pre>
51  	 * 
52  	 * @param pvThrowable Root-Exception.
53  	 * @return The deepest Exception.
54  	 */
55  	public static Throwable findDeepestThrowable(Throwable pvThrowable) {
56  	 	if (pvThrowable.getCause() != null) {
57  	 		Throwable lvThrowable = pvThrowable.getCause();
58   			return findDeepestThrowable(lvThrowable);
59  	 	} else {
60  	 		return pvThrowable;
61  	 	}
62  	}
63  
64  	/**
65  	 * Test to free port.
66  	 * 
67  	 * @param pvPort tested port
68  	 * @return <code>true</code>, if the port is free, else <code>false</code>.
69  	 */
70  	public static boolean isPortFree (int pvPort) {
71  		try {
72  			InetAddress lvAddress = InetAddress.getLocalHost();
73  			Socket lvSocket = new Socket(lvAddress, pvPort);
74  			lvSocket.isBound(); 
75  			return false;
76  		} catch (Exception e) {
77  			return true;
78  		} 
79  	}
80  	
81  	/**
82  	 * Separate from url the url and the port: <code>localhost:8080 --> http://localhost and 8080</code>
83  	 * @param pvUrlAndPort
84  	 * @return String-Array with pos 0 = URL and pos 1 = the Port
85  	 */
86  	public static String[] separateHostAndPort (String pvUrlAndPort) {
87  		if (pvUrlAndPort == null) {
88  			return null;
89  		} else {
90  			String s[] = pvUrlAndPort.split(":");
91  			if (s.length != 2) {
92  				throw new IllegalArgumentException(pvUrlAndPort + " is a not separatable URL. Expected a String with two ':', how by http://localhost:8080.");
93  			}
94  			String lvUrl = s[0];
95  			String lvPort = s[1];
96  			// test whether port is a integer
97  			Integer.parseInt(lvPort);
98  			s = new String[] {lvUrl, lvPort};
99  			return s;
100 		}
101 	}
102 	
103 	/**
104 	 * Cut a String on the end of a input-String.
105 	 * Example: Input-String <code>rmi://localhost:1099/</code>, Cutting-String <code>/</code>, New-String <code>rmi://localhost:1099</code>.
106 	 * 
107 	 * @param pvString Input-String
108 	 * @param pvCuttingString Cutting-String
109 	 * @return New String, without Cutting-String.
110 	 */
111 	public static String cutString(final String pvString, final String pvCuttingString) {
112     	if ((pvString != null) && (pvCuttingString != null) && (pvString.endsWith(pvCuttingString))) {
113     		return pvString.substring(0, (pvString.length() - pvCuttingString.length()));
114     	} else {
115     		return pvString;
116     	}
117 		
118 	}
119 	
120 	/**
121 	 * Create a object with the reflection API.
122 	 * 
123 	 * @param pvObjectString String from the object.
124 	 * @return Created object.
125 	 * @throws Exception
126 	 */
127 	public static Object createObject (String pvObjectString) throws Exception {
128 		if (pvObjectString == null) {
129 			return null;
130 		} else {
131 			Class clazz = Class.forName(pvObjectString);
132 			return clazz.newInstance();
133 		}
134 	}
135 	
136 	/**
137 	 * Test as search class is exist in the class array.
138 	 * 
139 	 * @param pvClassArray class array
140 	 * @param pvSearchClass search class 
141 	 * @return if the class is finding than <code>true</code>, else <code>false</code>
142 	 */
143 	public static boolean isClassInArray (Class[] pvClassArray, Class pvSearchClass) {
144 		if ((pvClassArray == null) || (pvSearchClass == null)) { return false; }
145 		for (int i = 0; i < pvClassArray.length; i++) {
146 			boolean equals = pvClassArray[i].equals(pvSearchClass);
147 			if (equals == true) { return true; }
148 		}
149 		return false;
150 	}
151 	
152 	public static String printArray(Object[] pvArray) {
153 		StringBuffer sb = new StringBuffer();
154 		if (pvArray == null) {
155 			return "Array is NULL";
156 		} else {
157 			for (int i = 0; i < pvArray.length; i++) {
158 				sb.append(pvArray[i]).append(" -> ").append(pvArray[i].getClass().getName()).append("\n");
159 			}
160 			return sb.toString();
161 		}
162 	}
163 	
164 	public static String array2String (Object pvStrArray[]) {
165 		if (pvStrArray == null) { return null; }
166 		StringBuffer ret = new StringBuffer();
167 		for (int i = 0; i < pvStrArray.length; i++) {
168 			ret.append(pvStrArray[i]).append(" ; ");
169 		}
170 		return ret.toString();
171 	}
172 	
173 	
174 	public static void printMapInfo(Map pvMap) {
175 		if (pvMap == null) {
176 			System.out.println("Util.printMapInfo: Map ist null");
177 		} else {
178 			Iterator it = pvMap.entrySet().iterator();
179 			while (it.hasNext()) {
180 				Map.Entry lvMapEntry = (Entry) it.next();
181 				System.out.println(lvMapEntry.getKey() + " = " + lvMapEntry.getValue() + " (" + lvMapEntry.getValue().getClass().getName() + ")");
182 			}
183 		}
184 	}
185 
186 	public static String getClassNameWithOutPackage(final Class pvClass) {
187 		if (pvClass == null) {
188 			return null;
189 		} else {
190 			return getClassNameWithOutPackage(pvClass.getName());
191 		}
192 	}
193 	
194 	public static String getClassNameWithOutPackage(final String pvClassName) {
195 		if (pvClassName == null) {
196 			return null;
197 		} else {
198 			String lvNames[] = pvClassName.split("\\.");
199 			return lvNames[(lvNames.length - 1)];
200 		}
201 	}
202 	
203 	/**
204 	 * Reverse the package fro class. For example:
205 	 * <code>test.crispy.example.model.Kunde</code> -> <code>model.example.crispy.test</code>.
206 	 * By a class without a package, is the return value a empty String.
207 	 *   
208 	 * @param pvClass
209 	 * @return reverse string.
210 	 */
211 	public static String reverse(Class pvClass) {
212 		if (pvClass == null) { return null; }
213 		String lvClassName = pvClass.getName();
214 		String lvParts[] = lvClassName.split("\\.");
215 		String lvRet = "";
216 		int l = lvParts.length -1;
217 		for (int i = l; i > 0; i--) {
218 			lvRet = lvRet + lvParts[i-1] + ".";
219 		}
220 		lvRet = lvRet.substring(0, (lvRet.length() - 1)); 
221 		return lvRet;
222 	}
223 	
224 	/**
225 	 * Create a <code>javax.xml.namespace.QName</code> by the class. For example
226 	 * class: <code>test.crispy.example.model.Kunde</code> ->
227 	 * LocalPart: <code>test.crispy.example.model.Kunde</code> and 
228 	 * NamespaceURI: <code>model.example.crispy.test</code>.
229 	 * 
230 	 * @param pvClass The class for create a QName.
231 	 * @return The created QName object.
232 	 */
233 	public static QName createQNameByClass(Class pvClass) {
234 		if (pvClass == null) { return null; }
235 		return new QName(Util.reverse(pvClass), pvClass.getName());
236 	}
237     
238 	/**
239 	 * Get from the properites all properties, that begins with the prefix and sorted this
240 	 * properties to the property keys.
241 	 * 
242 	 * @param pvProperties all properties
243 	 * @param pvPrefix filter = prefix from property key
244 	 * @return sorted Map from all properties with correct prefix.
245 	 */
246 	public static Map getAllPropertiesByPrefixAndSort(Properties pvProperties, String pvPrefix) {
247         Enumeration enumeration = pvProperties.keys();
248         Map lvSorterMap = new TreeMap();
249         while (enumeration.hasMoreElements()) {
250         	Object lvPropertyObject = enumeration.nextElement();
251         	if ( ! (lvPropertyObject.getClass().getName().equals(String.class.getName()))) {
252         		throw new InvocationException("The property must be a String, but is: " 
253         						+ lvPropertyObject.getClass().getName() 
254         						+ " --> with value (key): " + lvPropertyObject);
255         	}
256         	String lvKey = (String) lvPropertyObject;
257         	
258         	if (lvKey.startsWith(pvPrefix)) {
259         		String lvProxyInterceptorStr = pvProperties.getProperty(lvKey);
260         		lvSorterMap.put(lvKey, lvProxyInterceptorStr);
261         	}
262         }
263         return lvSorterMap;
264 	}
265 	
266 	
267     public static byte[] inputStream2ByteArray(InputStream is) throws IOException {
268     	int BUFFER_SIZE = 8192;
269         byte[] buffer = new byte[BUFFER_SIZE];
270         byte[] content = new byte[0];
271         int length;
272         while ((length = is.read(buffer)) > 0) {
273           byte[] tmp = content;
274           content = new byte[tmp.length + length];
275           System.arraycopy(tmp, 0, content, 0, tmp.length);
276           System.arraycopy(buffer, 0, content, tmp.length, length);
277         }
278         return content;
279       }
280 
281 
282     public static void visualisationTree(Object pvObject) {
283     	DefaultMutableTreeNode lvRoot = new DefaultMutableTreeNode("ROOT");
284     	createTree(pvObject, lvRoot);
285     	JFrame lvFrame = new JFrame("Crispy tree visualisation ...");
286     	JTree lvTree = new JTree(lvRoot);
287     	lvFrame.getContentPane().add(new JScrollPane(lvTree));
288     	lvFrame.setVisible(true);
289     	lvFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
290     	lvFrame.show();
291     	lvFrame.pack();
292     	
293     }
294 
295 
296     public static void createTree (Object pvObject, DefaultMutableTreeNode pvRoot) {
297         if (pvObject != null) {
298             Class clazz = pvObject.getClass();
299             if (pvObject instanceof Collection) {
300                 createTreeByCollection((Collection) pvObject, pvRoot, null);
301             }
302             else if (pvObject instanceof Map) {
303                 createTreeByMap((Map) pvObject, pvRoot, null);
304             }
305             else if ((clazz.equals(Integer.class))
306                     || (clazz.equals(Double.class)) 
307                     || (clazz.equals(Boolean.class)) 
308                     || (clazz.equals(String.class)) 
309                     || (clazz.equals(Date.class))) {  
310                         pvRoot.add(new DefaultMutableTreeNode (pvObject));
311                     }
312             else {
313                 pvRoot.add(new DefaultMutableTreeNode ("-- Ungueltiger Typ: " + clazz + ": " + pvObject));
314             }
315         }
316     }
317 
318     public static String map2String (Map pvMap, String pvPropertyName) {
319         if (pvMap == null) { return null; }
320         StringBuffer sb = null;
321         if (pvPropertyName != null) {
322         	sb = new StringBuffer(pvPropertyName + ": ");
323         } else {
324         	sb = new StringBuffer();
325         }
326         StringBuffer sbClazz = new StringBuffer();
327         
328         Iterator it = pvMap.entrySet().iterator();
329         while (it.hasNext()) {
330         	Map.Entry lvMapEntry = (Entry) it.next();
331             Object key = lvMapEntry.getKey();
332             Object value = lvMapEntry.getValue();
333 //            if ((value instanceof Collection) || (value instanceof Map)) {
334             	
335                 // mache nichts
336 //            } else {
337             // ???????????
338             if (!(value instanceof Collection) && !(value instanceof Map)) {            	
339                 if (key.toString().compareTo("class") == 0) {
340                     sbClazz.append(" -> (").append(key).append(" = ").append(value).append(")");
341                 } else {
342                     sb.append("[").append(key).append(" = ").append(value).append("] ");
343                 }
344             }
345         }
346         return sb.append(sbClazz).toString();
347     }
348 
349     public static void createTreeByMap (Map pvMap, DefaultMutableTreeNode pvRoot, String pvPropertyName) {
350         if (pvMap != null) {
351             DefaultMutableTreeNode child = new DefaultMutableTreeNode (map2String(pvMap, pvPropertyName));
352             pvRoot.add(child);
353             
354             Iterator it = pvMap.entrySet().iterator();
355             while (it.hasNext()) {
356             	Map.Entry lvMapEntry = (Entry) it.next();
357                 if (lvMapEntry.getValue() instanceof Collection) {
358                     createTreeByCollection((Collection) lvMapEntry.getValue(), child, lvMapEntry.getKey().toString());
359                 }
360                 else if (lvMapEntry.getValue() instanceof Map) {
361                     createTreeByMap((Map) lvMapEntry.getValue(), child, lvMapEntry.getKey().toString());
362                 }
363             }
364         }        
365     }
366 
367     public static void createTreeByCollection (Collection pvCollection, DefaultMutableTreeNode pvRoot, String pvPropertyName) {
368         if ((pvCollection != null) && (pvCollection.size() > 0)) {
369             Iterator it = pvCollection.iterator();
370             while (it.hasNext()) {
371                 Object value = it.next();
372                 if (value instanceof Collection) {
373                     createTreeByCollection((Collection) value, pvRoot, pvPropertyName);
374                 }
375                 else if (value instanceof Map) {
376                     createTreeByMap((Map) value, pvRoot, pvPropertyName);
377                 }
378             }
379         }
380     }
381 
382         
383 	public static boolean initJdkLogger () {
384     	return initJdkLogger2 (Util.class.getResourceAsStream("jdk14-logging.properties"));
385 	}
386 
387 	public static boolean initJdkLogger (String pvFileName) {
388 		try {
389 			return initJdkLogger2 (new FileInputStream(pvFileName));
390 		} catch (FileNotFoundException e) {
391 			e.printStackTrace();
392 		}
393     	return false;
394 	}
395 
396 	public static boolean initJdkLogger2 (InputStream pvInputStream) {
397 		try {
398 			LogManager.getLogManager().readConfiguration(pvInputStream);
399 			Logger logger = Logger.global;
400 			LogManager.getLogManager().addLogger(logger);
401 			logger.finest("Jdk14Logger initialisiert ...");
402 			return true;
403 		} catch (Exception e) {
404 			e.printStackTrace();
405 		}		
406 		return false;
407 	}
408 }