Source for org.jfree.util.ObjectUtilities

   1: /* ========================================================================
   2:  * JCommon : a free general purpose class library for the Java(tm) platform
   3:  * ========================================================================
   4:  *
   5:  * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
   6:  * 
   7:  * Project Info:  http://www.jfree.org/jcommon/index.html
   8:  *
   9:  * This library is free software; you can redistribute it and/or modify it 
  10:  * under the terms of the GNU Lesser General Public License as published by 
  11:  * the Free Software Foundation; either version 2.1 of the License, or 
  12:  * (at your option) any later version.
  13:  *
  14:  * This library is distributed in the hope that it will be useful, but 
  15:  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
  16:  * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
  17:  * License for more details.
  18:  *
  19:  * You should have received a copy of the GNU Lesser General Public
  20:  * License along with this library; if not, write to the Free Software
  21:  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
  22:  * USA.  
  23:  *
  24:  * [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
  25:  * in the United States and other countries.]
  26:  * 
  27:  * ---------------------
  28:  * ObjectUtilitiess.java
  29:  * ---------------------
  30:  * (C) Copyright 2003-2005, by Object Refinery Limited.
  31:  *
  32:  * Original Author:  David Gilbert (for Object Refinery Limited);
  33:  * Contributor(s):   -;
  34:  *
  35:  * $Id: ObjectUtilities.java,v 1.16 2006/07/04 10:20:40 taqua Exp $
  36:  *
  37:  * Changes
  38:  * -------
  39:  * 25-Mar-2003 : Version 1 (DG);
  40:  * 15-Sep-2003 : Fixed bug in clone(List) method (DG);
  41:  * 25-Nov-2004 : Modified clone(Object) method to fail with objects that
  42:  *               cannot be cloned, added new deepClone(Collection) method.
  43:  *               Renamed ObjectUtils --> ObjectUtilities (DG);
  44:  * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG);
  45:  * 18-Aug-2005 : Added casts to suppress compiler warnings, as suggested in 
  46:  *               patch 1260622 (DG);
  47:  * 
  48:  */
  49: 
  50: package org.jfree.util;
  51: 
  52: import java.io.IOException;
  53: import java.io.InputStream;
  54: import java.lang.reflect.InvocationTargetException;
  55: import java.lang.reflect.Method;
  56: import java.lang.reflect.Modifier;
  57: import java.net.URL;
  58: import java.util.Collection;
  59: import java.util.Iterator;
  60: import java.util.ArrayList;
  61: import java.util.StringTokenizer;
  62: 
  63: /**
  64:  * A collection of useful static utility methods for handling classes and object
  65:  * instantiation.
  66:  *
  67:  * @author Thomas Morgner
  68:  */
  69: public final class ObjectUtilities {
  70: 
  71:     /**
  72:      * A constant for using the TheadContext as source for the classloader.
  73:      */
  74:     public static final String THREAD_CONTEXT = "ThreadContext";
  75:     /**
  76:      * A constant for using the ClassContext as source for the classloader.
  77:      */
  78:     public static final String CLASS_CONTEXT = "ClassContext";
  79: 
  80:     /**
  81:      * By default use the thread context.
  82:      */
  83:     private static String classLoaderSource = THREAD_CONTEXT;
  84:     /**
  85:      * The custom classloader to be used (if not null).
  86:      */
  87:     private static ClassLoader classLoader;
  88: 
  89:     /**
  90:      * Default constructor - private.
  91:      */
  92:     private ObjectUtilities() {
  93:     }
  94: 
  95:     /**
  96:      * Returns the internal configuration entry, whether the classloader of
  97:      * the thread context or the context classloader should be used.
  98:      *
  99:      * @return the classloader source, either THREAD_CONTEXT or CLASS_CONTEXT.
 100:      */
 101:     public static String getClassLoaderSource() {
 102:         return classLoaderSource;
 103:     }
 104: 
 105:     /**
 106:      * Defines the internal configuration entry, whether the classloader of
 107:      * the thread context or the context classloader should be used.
 108:      * <p/>
 109:      * This setting can only be defined using the API, there is no safe way
 110:      * to put this into an external configuration file.
 111:      *
 112:      * @param classLoaderSource the classloader source,
 113:      *                          either THREAD_CONTEXT or CLASS_CONTEXT.
 114:      */
 115:     public static void setClassLoaderSource(final String classLoaderSource) {
 116:         ObjectUtilities.classLoaderSource = classLoaderSource;
 117:     }
 118: 
 119:     /**
 120:      * Returns <code>true</code> if the two objects are equal OR both 
 121:      * <code>null</code>.
 122:      *
 123:      * @param o1 object 1 (<code>null</code> permitted).
 124:      * @param o2 object 2 (<code>null</code> permitted).
 125:      * @return <code>true</code> or <code>false</code>.
 126:      */
 127:     public static boolean equal(final Object o1, final Object o2) {
 128:         if (o1 == o2) {
 129:             return true;
 130:         }
 131:         if (o1 != null) {
 132:             return o1.equals(o2);
 133:         }
 134:         else {
 135:             return false;
 136:         }
 137:     }
 138: 
 139:     /**
 140:      * Returns a hash code for an object, or zero if the object is 
 141:      * <code>null</code>.
 142:      *
 143:      * @param object the object (<code>null</code> permitted).
 144:      * @return The object's hash code (or zero if the object is
 145:      *         <code>null</code>).
 146:      */
 147:     public static int hashCode(final Object object) {
 148:         int result = 0;
 149:         if (object != null) {
 150:             result = object.hashCode();
 151:         }
 152:         return result;
 153:     }
 154: 
 155:     /**
 156:      * Returns a clone of the specified object, if it can be cloned, otherwise
 157:      * throws a CloneNotSupportedException.
 158:      *
 159:      * @param object the object to clone (<code>null</code> not permitted).
 160:      * @return A clone of the specified object.
 161:      * @throws CloneNotSupportedException if the object cannot be cloned.
 162:      */
 163:     public static Object clone(final Object object)
 164:         throws CloneNotSupportedException {
 165:         if (object == null) {
 166:             throw new IllegalArgumentException("Null 'object' argument.");
 167:         }
 168:         if (object instanceof PublicCloneable) {
 169:             final PublicCloneable pc = (PublicCloneable) object;
 170:             return pc.clone();
 171:         }
 172:         else {
 173:             try {
 174:                 final Method method = object.getClass().getMethod("clone",
 175:                         (Class[]) null);
 176:                 if (Modifier.isPublic(method.getModifiers())) {
 177:                     return method.invoke(object, (Object[]) null);
 178:                 }
 179:             }
 180:             catch (NoSuchMethodException e) {
 181:                 Log.warn("Object without clone() method is impossible.");
 182:             }
 183:             catch (IllegalAccessException e) {
 184:                 Log.warn("Object.clone(): unable to call method.");
 185:             }
 186:             catch (InvocationTargetException e) {
 187:                 Log.warn("Object without clone() method is impossible.");
 188:             }
 189:         }
 190:         throw new CloneNotSupportedException("Failed to clone.");
 191:     }
 192: 
 193:     /**
 194:      * Returns a new collection containing clones of all the items in the
 195:      * specified collection.
 196:      *
 197:      * @param collection the collection (<code>null</code> not permitted).
 198:      * @return A new collection containing clones of all the items in the 
 199:      *         specified collection.
 200:      * @throws CloneNotSupportedException if any of the items in the collection
 201:      *                                    cannot be cloned.
 202:      */
 203:     public static Collection deepClone(final Collection collection)
 204:         throws CloneNotSupportedException {
 205: 
 206:         if (collection == null) {
 207:             throw new IllegalArgumentException("Null 'collection' argument.");
 208:         }
 209:         // all JDK-Collections are cloneable ...
 210:         // and if the collection is not clonable, then we should throw
 211:         // a CloneNotSupportedException anyway ...
 212:         final Collection result
 213:             = (Collection) ObjectUtilities.clone(collection);
 214:         result.clear();
 215:         final Iterator iterator = collection.iterator();
 216:         while (iterator.hasNext()) {
 217:             final Object item = iterator.next();
 218:             if (item != null) {
 219:                 result.add(clone(item));
 220:             }
 221:             else {
 222:                 result.add(null);
 223:             }
 224:         }
 225:         return result;
 226:     }
 227: 
 228:     /**
 229:      * Redefines the custom classloader.
 230:      *
 231:      * @param classLoader the new classloader or null to use the default.
 232:      */
 233:     public synchronized static void setClassLoader(
 234:             final ClassLoader classLoader) {
 235:         ObjectUtilities.classLoader = classLoader;
 236:     }
 237: 
 238:     /**
 239:      * Returns the custom classloader or null, if no custom classloader is defined.
 240:      *
 241:      * @return the custom classloader or null to use the default.
 242:      */
 243:     public static ClassLoader getClassLoader() {
 244:       return classLoader;
 245:     }
 246: 
 247:     /**
 248:      * Returns the classloader, which was responsible for loading the given
 249:      * class.
 250:      *
 251:      * @param c the classloader, either an application class loader or the
 252:      *          boot loader.
 253:      * @return the classloader, never null.
 254:      * @throws SecurityException if the SecurityManager does not allow to grab
 255:      *                           the context classloader.
 256:      */
 257:     public synchronized static ClassLoader getClassLoader(final Class c) {
 258:         if (classLoader != null) {
 259:             return classLoader;
 260:         }
 261:         if ("ThreadContext".equals(classLoaderSource)) {
 262:             final ClassLoader threadLoader
 263:                 = Thread.currentThread().getContextClassLoader();
 264:             if (threadLoader != null) {
 265:                 return threadLoader;
 266:             }
 267:         }
 268: 
 269:         // Context classloader - do not cache ..
 270:         final ClassLoader applicationCL = c.getClassLoader();
 271:         if (applicationCL == null) {
 272:             return ClassLoader.getSystemClassLoader();
 273:         }
 274:         else {
 275:             return applicationCL;
 276:         }
 277:     }
 278: 
 279: 
 280:     /**
 281:      * Returns the resource specified by the <strong>absolute</strong> name.
 282:      *
 283:      * @param name the name of the resource
 284:      * @param c    the source class
 285:      * @return the url of the resource or null, if not found.
 286:      */
 287:     public static URL getResource(final String name, final Class c) {
 288:         final ClassLoader cl = getClassLoader(c);
 289:         if (cl == null) {
 290:             return null;
 291:         }
 292:         return cl.getResource(name);
 293:     }
 294: 
 295:     /**
 296:      * Returns the resource specified by the <strong>relative</strong> name.
 297:      *
 298:      * @param name the name of the resource relative to the given class
 299:      * @param c    the source class
 300:      * @return the url of the resource or null, if not found.
 301:      */
 302:     public static URL getResourceRelative(final String name, final Class c) {
 303:         final ClassLoader cl = getClassLoader(c);
 304:         final String cname = convertName(name, c);
 305:         if (cl == null) {
 306:             return null;
 307:         }
 308:         return cl.getResource(cname);
 309:     }
 310: 
 311:     /**
 312:      * Transform the class-relative resource name into a global name by 
 313:      * appending it to the classes package name. If the name is already a 
 314:      * global name (the name starts with a "/"), then the name is returned 
 315:      * unchanged.
 316:      *
 317:      * @param name the resource name
 318:      * @param c    the class which the resource is relative to
 319:      * @return the tranformed name.
 320:      */
 321:     private static String convertName(final String name, Class c) {
 322:         if (name.startsWith("/")) {
 323:             // strip leading slash..
 324:             return name.substring(1);
 325:         }
 326: 
 327:         // we cant work on arrays, so remove them ...
 328:         while (c.isArray()) {
 329:             c = c.getComponentType();
 330:         }
 331:         // extract the package ...
 332:         final String baseName = c.getName();
 333:         final int index = baseName.lastIndexOf('.');
 334:         if (index == -1) {
 335:             return name;
 336:         }
 337: 
 338:         final String pkgName = baseName.substring(0, index);
 339:         return pkgName.replace('.', '/') + "/" + name;
 340:     }
 341: 
 342:     /**
 343:      * Returns the inputstream for the resource specified by the
 344:      * <strong>absolute</strong> name.
 345:      *
 346:      * @param name the name of the resource
 347:      * @param context the source class
 348:      * @return the url of the resource or null, if not found.
 349:      */
 350:     public static InputStream getResourceAsStream(final String name,
 351:                                                   final Class context) {
 352:         final URL url = getResource(name, context);
 353:         if (url == null) {
 354:             return null;
 355:         }
 356: 
 357:         try {
 358:             return url.openStream();
 359:         }
 360:         catch (IOException e) {
 361:             return null;
 362:         }
 363:     }
 364: 
 365:     /**
 366:      * Returns the inputstream for the resource specified by the
 367:      * <strong>relative</strong> name.
 368:      *
 369:      * @param name the name of the resource relative to the given class
 370:      * @param context the source class
 371:      * @return the url of the resource or null, if not found.
 372:      */
 373:     public static InputStream getResourceRelativeAsStream
 374:         (final String name, final Class context) {
 375:         final URL url = getResourceRelative(name, context);
 376:         if (url == null) {
 377:             return null;
 378:         }
 379: 
 380:         try {
 381:             return url.openStream();
 382:         }
 383:         catch (IOException e) {
 384:             return null;
 385:         }
 386:     }
 387: 
 388:     /**
 389:      * Tries to create a new instance of the given class. This is a short cut
 390:      * for the common bean instantiation code.
 391:      *
 392:      * @param className the class name as String, never null.
 393:      * @param source    the source class, from where to get the classloader.
 394:      * @return the instantiated object or null, if an error occured.
 395:      */
 396:     public static Object loadAndInstantiate(final String className,
 397:                                             final Class source) {
 398:         try {
 399:             final ClassLoader loader = getClassLoader(source);
 400:             final Class c = loader.loadClass(className);
 401:             return c.newInstance();
 402:         }
 403:         catch (Exception e) {
 404:             return null;
 405:         }
 406:     }
 407: 
 408: 
 409:     public static boolean isJDK14() {
 410:         final ClassLoader loader = getClassLoader(ObjectUtilities.class);
 411:         if (loader != null) {
 412:             try {
 413:               loader.loadClass("java.util.RandomAccess");
 414:               return true;
 415:             }
 416:             catch (ClassNotFoundException e) {
 417:               return false;
 418:             }
 419:             catch(Exception e) {
 420:               // do nothing, but do not crash ...
 421:             }
 422:         }
 423:         // OK, the quick and dirty, but secure way failed. Lets try it
 424:         // using the standard way.
 425:         try {
 426:             final String version = System.getProperty
 427:                     ("java.vm.specification.version");
 428:             // parse the beast...
 429:             if (version == null) {
 430:                 return false;
 431:             }
 432: 
 433:             String[] versions = parseVersions(version);
 434:             String[] target = new String[]{ "1", "4" };
 435:             return (ArrayUtilities.compareVersionArrays(versions, target) >= 0);
 436:         }
 437:         catch(Exception e) {
 438:             return false;
 439:         }
 440:     }
 441: 
 442:     private static String[] parseVersions (String version)
 443:     {
 444:       if (version == null)
 445:       {
 446:         return new String[0];
 447:       }
 448: 
 449:       final ArrayList versions = new ArrayList();
 450:       StringTokenizer strtok = new StringTokenizer(version, ".");
 451:       while (strtok.hasMoreTokens())
 452:       {
 453:         versions.add (strtok.nextToken());
 454:       }
 455:       return (String[]) versions.toArray(new String[versions.size()]);
 456:     }
 457: }