View Javadoc

1   /*
2    * org.riverock.dbrevision - Database revision engine
3    * For more information about DbRevision, please visit project site
4    * http://www.riverock.org
5    *
6    * Copyright (C) 2006-2006, Riverock Software, All Rights Reserved.
7    *
8    * Riverock - The Open-source Java Development Community
9    * http://www.riverock.org
10   *
11   *
12   * This library is free software; you can redistribute it and/or
13   * modify it under the terms of the GNU Lesser General Public
14   * License as published by the Free Software Foundation; either
15   * version 2.1 of the License, or (at your option) any later version.
16   *
17   * This library is distributed in the hope that it will be useful,
18   * but WITHOUT ANY WARRANTY; without even the implied warranty of
19   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20   * Lesser General Public License for more details.
21   *
22   * You should have received a copy of the GNU Lesser General Public
23   * License along with this library; if not, write to the Free Software
24   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25   */
26  package org.riverock.dbrevision.utils;
27  
28  import java.io.*;
29  import java.sql.Timestamp;
30  import java.text.SimpleDateFormat;
31  import java.util.*;
32  
33  import javax.xml.bind.*;
34  import javax.xml.namespace.QName;
35  import javax.xml.transform.Source;
36  import javax.xml.transform.stream.StreamSource;
37  
38  import org.apache.commons.lang.StringUtils;
39  import org.apache.commons.lang.time.DateFormatUtils;
40  import org.apache.log4j.Logger;
41  
42  import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
43  
44  /**
45   * Common utils
46   *
47   * @author Sergei Maslyukov
48   *         Date: 14.12.2006
49   *         Time: 16:37:21
50   *         <p/>
51   *         $Id$
52   */
53  public class Utils {
54      /**
55       * Logger for this class
56       */
57      private final static Logger log = Logger.getLogger(Utils.class);
58  
59      /**
60       * Put value in map. If map already contained value for specified key, this value and previous value
61       * inserted in list and this list associated with given key
62       *
63       * @param map map
64       * @param key key
65       * @param value value
66       */
67      public static void putKey(final Map<String, Object> map, final String key, final Object value) {
68          Object obj = map.get(key);
69          if (obj == null) {
70              map.put(key, value);
71              return;
72          }
73  
74          if (obj instanceof List) {
75              if (value instanceof List) {
76                  ((List) obj).addAll((List) value);
77              }
78              else {
79                  ((List) obj).add(value);
80              }
81          }
82          else {
83              List<Object> v = new ArrayList<Object>();
84              v.add(obj);
85  
86              if (value instanceof List) {
87                  v.addAll((List) value);
88              }
89              else {
90                  v.add(value);
91              }
92  
93              map.remove(key);
94              map.put(key, v);
95          }
96      }
97  
98      /**
99       * Get current time as java.sql.Timestamp
100      *
101      * @return current time
102      */
103     public static java.sql.Timestamp getCurrentTime() {
104         return new Timestamp(System.currentTimeMillis());
105     }
106 
107     /**
108      * convert given Calendar with mask and locale to String
109      *
110      * @param c calendar
111      * @param mask format mask
112      * @param loc locale
113      * @return date as String
114      */
115     public static String getStringDate( final Calendar c, final String mask, final Locale loc ) {
116         if (c == null) return null;
117         return DateFormatUtils.format(c.getTimeInMillis(), mask, c.getTimeZone(), loc);
118     }
119 
120     /**
121      * convert given Calendar with mask to String. 
122      *
123      * @param c calendar
124      * @param mask format mask
125      * @return date as String
126      */
127     public static String getStringDate( final Calendar c, final String mask ) {
128         return DateFormatUtils.format(c.getTimeInMillis(), mask, c.getTimeZone(), Locale.ENGLISH);
129     }
130 
131     /**
132      *
133      * @param date
134      * @param mask
135      * @return
136      * @throws java.text.ParseException
137      */
138     public static java.util.Date getDateWithMask( final String date, final String mask )
139         throws java.text.ParseException {
140         if (date == null || mask == null)
141             return null;
142 
143         SimpleDateFormat dFormat = new SimpleDateFormat(mask);
144 
145         return dFormat.parse(date);
146     }
147 
148     /**
149      *
150      * @param date
151      * @param mask
152      * @param loc
153      * @param tz
154      * @return
155      */
156     public static String getStringDate( final java.util.Date date, final String mask, final Locale loc, final TimeZone tz) {
157         if (date == null) return null;
158 
159         SimpleDateFormat df = new SimpleDateFormat(mask, loc);
160         df.setTimeZone( tz );
161 
162         return df.format( date );
163     }
164 
165     /**
166      *
167      * @param obj
168      * @param rootElement
169      * @return
170      * @throws Exception
171      */
172     public static byte[] getXml(final Object obj, final String rootElement) throws Exception {
173         return getXml(obj, rootElement, "utf-8");
174     }
175 
176     /**
177      *
178      * @param obj
179      * @param rootElement
180      * @param encoding
181      * @return
182      * @throws JAXBException
183      */
184     public static byte[] getXml(final Object obj, final String rootElement, final String encoding) throws JAXBException {
185         return getXml(obj, rootElement, encoding, false, null);
186     }
187 
188 
189     /**
190      *
191      * @param obj
192      * @param rootElement
193      * @param encoding
194      * @param isIndent
195      * @param namespacePrefixMappers
196      * @return
197      * @throws JAXBException
198      */
199     public static byte[] getXml(final Object obj, final String rootElement, final String encoding, boolean isIndent, NamespacePrefixMapper[] namespacePrefixMappers) throws JAXBException {
200 /*
201         if (log.isDebugEnabled()) {
202             log.debug("getXml(). Object to marshaling " + obj);
203             log.debug("getXml(). rootElement " + rootElement);
204             log.debug("getXml(). encoding " + encoding);
205         }
206 */
207         ByteArrayOutputStream fos = new ByteArrayOutputStream(1000);
208 
209 /*
210         if (log.isDebugEnabled()) {
211             log.debug("ByteArrayOutputStream object - " + fos);
212         }
213 */
214 
215         writeMarshalToOutputStream(obj, encoding, rootElement, fos, isIndent, namespacePrefixMappers);
216         return fos.toByteArray();
217     }
218 
219 
220     /**
221      * 
222      * @param obj
223      * @param encoding
224      * @param rootElement
225      * @param fos
226      * @throws JAXBException
227      */
228     public static void writeMarshalToOutputStream(
229         Object obj, String encoding, String rootElement, OutputStream fos,
230         boolean isIndent, NamespacePrefixMapper[] namespacePrefixMappers) throws JAXBException {
231 
232         JAXBContext jaxbContext = JAXBContext.newInstance ( obj.getClass().getPackage().getName() );
233         Marshaller marshaller = jaxbContext.createMarshaller();
234         marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
235         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, isIndent);
236 
237         if (namespacePrefixMappers!=null) {
238             for (NamespacePrefixMapper namespacePrefixMapper : namespacePrefixMappers) {
239                 marshaller.setProperty( "com.sun.xml.bind.namespacePrefixMapper", namespacePrefixMapper );
240             }
241         }
242 
243         if (rootElement != null && rootElement.trim().length() > 0) {
244             // http://weblogs.java.net/blog/kohsuke/archive/2005/10/101_ways_to_mar.html
245             marshaller.marshal( new JAXBElement(new QName("",rootElement), obj.getClass(), obj ), fos);
246         }
247         else {
248             marshaller.marshal(obj, fos);
249         }
250     }
251 
252     /**
253      *
254      * @param obj
255      * @param fileName
256      * @throws JAXBException
257      * @throws FileNotFoundException
258      */
259     public static void writeToFile(final Object obj, final String fileName) throws JAXBException, FileNotFoundException {
260         writeToFile(obj, fileName, "utf-8");
261     }
262 
263     /**
264      *
265      * @param obj
266      * @param fileName
267      * @param encoding
268      * @throws FileNotFoundException
269      * @throws JAXBException
270      */
271     public static void writeToFile(final Object obj, final String fileName, final String encoding) throws FileNotFoundException, JAXBException {
272         writeMarshalToOutputStream(obj, encoding, null, new FileOutputStream(fileName), false, null );
273     }
274 
275     /**
276      *
277      * @param obj
278      * @param outputStream
279      * @param encoding
280      * @throws JAXBException
281      */
282     public static void writeObjectAsXml(final Object obj, OutputStream outputStream, final String encoding) throws JAXBException {
283         writeMarshalToOutputStream(obj, encoding, null, outputStream, false, null );
284     }
285 
286     /**
287      *
288      * @param obj
289      * @param outputStream
290      * @param rootElement
291      * @param encoding
292      * @throws JAXBException
293      */
294     public static void writeObjectAsXml(final Object obj, OutputStream outputStream, String rootElement, final String encoding) throws JAXBException {
295         writeMarshalToOutputStream(obj, encoding, rootElement, outputStream, false, null );
296     }
297 
298     public static <T> T getObjectFromXml(final Class<T> classType, final String str) throws JAXBException {
299         return getObjectFromXml(classType, new StreamSource(new StringReader(str)), null);
300     }
301 
302     /**
303      *
304      * @param classType
305      * @param is
306      * @return
307      * @throws javax.xml.bind.JAXBException on error
308      */
309     public static <T> T getObjectFromXml(final Class<T> classType, InputStream is) throws JAXBException {
310         return getObjectFromXml(classType, new StreamSource(is), null);
311     }
312 
313     public static <T> T getObjectFromXml(final Class<T> classType, InputStream is, ValidationEventHandler handler) throws JAXBException {
314         return getObjectFromXml(classType, new StreamSource(is), handler);
315     }
316 
317     public static <T> T getObjectFromXml(final Class<T> classType, Source inSrc, ValidationEventHandler handler) throws JAXBException {
318         JAXBContext jaxbContext = JAXBContext.newInstance ( classType.getPackage().getName() );
319         Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
320 
321         if (handler!=null) {
322             unmarshaller.setEventHandler(handler);
323         }
324 
325         return unmarshaller.unmarshal(inSrc, classType).getValue();
326     }
327 
328     /**
329      *
330      * @param s
331      * @return
332      * @throws ClassNotFoundException
333      * @throws InstantiationException
334      * @throws IllegalAccessException
335      */
336     public static Object createCustomObject(final String s)
337         throws ClassNotFoundException, InstantiationException, IllegalAccessException {
338         Object obj;
339         try {
340             ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
341             if (log.isDebugEnabled()) {
342                 log.debug("Starting create class object for name '" + s + "'");
343                 log.debug("    class loader:\n" + classLoader +"\nhash: "+ classLoader.hashCode() );
344             }
345 
346             if (s == null)
347                 return null;
348 
349             Class className;
350 
351             if (log.isDebugEnabled())
352                 log.debug("Create class for name '" + s + "'");
353 
354             className = Class.forName(s, true, classLoader);
355 
356             if (log.isDebugEnabled())
357                 log.debug("Class for name '" + s + "' is " + className);
358 
359             if (className == null)
360                 throw new ClassNotFoundException("Error create class for name " + s);
361 
362             if (log.isDebugEnabled())
363                 log.debug("Create object for name '" + s + "'");
364 
365             obj = className.newInstance();
366 
367             if (log.isDebugEnabled())
368                 log.debug("Object for name '" + s + "' is " + obj);
369         }
370         catch (ClassNotFoundException e) {
371             log.error("Error create reflection object for class name '" + s + "'", e);
372             throw e;
373         }
374         catch (InstantiationException e) {
375             log.error("Error create reflection object for class name '" + s + "'", e);
376             throw e;
377         }
378         catch (IllegalAccessException e) {
379             log.error("Error create reflection object for class name '" + s + "'", e);
380             throw e;
381         }
382         return obj;
383     }
384 
385     /**
386      * @param str_ source string
387      * @param repl array of values for search and replace
388      * @return resulting string
389      */
390     public static String replaceStringArray( final String str_, final String repl[][]) {
391         String qqq = str_;
392         for (final String[] newVar : repl) {
393             qqq = StringUtils.replace(qqq, newVar[0], newVar[1]);
394         }
395         return qqq;
396 
397     }
398 
399     /**
400      *
401      * @param s
402      * @return
403      */
404     public static byte[] getBytesUTF( final String s) {
405         if (s==null)
406             return new byte[0];
407 
408         try {
409             return s.getBytes("utf-8");
410         }
411         catch (java.io.UnsupportedEncodingException e) {
412             log.warn("String.getBytes(\"utf-8\") not supported");
413             return new byte[0];
414         }
415     }
416 
417     /**
418      *
419      * @param s
420      * @param maxByte
421      * @return
422      */
423     public static int getStartUTF( final String s, final int maxByte) {
424         return getStartUTF(getBytesUTF(s), maxByte);
425     }
426 
427     /**
428      *
429      * @param b
430      * @param maxByte
431      * @return
432      */
433     public static int getStartUTF( final byte[] b, final int maxByte) {
434         return getStartUTF(b, maxByte, 0);
435     }
436 
437     /**
438      *
439      * @param b
440      * @param maxByte
441      * @param offset
442      * @return
443      */
444     public static int getStartUTF( final byte[] b, final int maxByte, final int offset) {
445         if (b.length <= offset)
446             return -1;
447 
448         if (b.length < maxByte)
449             return b.length;
450 
451         int idx = Math.min(b.length, maxByte + offset);
452 
453         for (int i = idx - 1; i > offset; i--)
454         {
455             int j = (b[i] < 0?0x100 + b[i]:b[i]);
456             if (j < 0x80)
457             {
458                 return i + 1;
459             }
460         }
461         return -1;
462     }
463 
464     /**
465      * 
466      * @return
467      */
468     public static String getTempDir() {
469         return System.getProperty("java.io.tmpdir");
470     }
471 }