Example usage for java.lang ClassLoader getSystemClassLoader

List of usage examples for java.lang ClassLoader getSystemClassLoader

Introduction

In this page you can find the example usage for java.lang ClassLoader getSystemClassLoader.

Prototype

@CallerSensitive
public static ClassLoader getSystemClassLoader() 

Source Link

Document

Returns the system class loader.

Usage

From source file:edu.brown.utils.ArgumentsParser.java

/**
 * @param args//  w w w  .j a  v a  2 s . co m
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public void process(String[] args, String... required) throws Exception {
    final boolean debug = LOG.isDebugEnabled();

    if (debug)
        LOG.debug("Processing " + args.length + " parameters...");
    final Pattern p = Pattern.compile("=");
    for (int i = 0, cnt = args.length; i < cnt; i++) {
        final String arg = args[i];
        final String[] parts = p.split(arg, 2);
        if (parts[0].startsWith("-"))
            parts[0] = parts[0].substring(1);

        if (parts.length == 1) {
            if (parts[0].startsWith("${") == false)
                this.opt_params.add(parts[0]);
            continue;
        } else if (parts[0].equalsIgnoreCase("tag")) {
            continue;
        } else if (parts[1].startsWith("${") || parts[0].startsWith("#")) {
            continue;
        }
        if (debug)
            LOG.debug(String.format("%-35s = %s", parts[0], parts[1]));

        // DesignerHints Override
        if (parts[0].startsWith(PARAM_DESIGNER_HINTS_PREFIX)) {
            String param = parts[0].replace(PARAM_DESIGNER_HINTS_PREFIX, "").toLowerCase();
            try {
                Field f = DesignerHints.class.getField(param);
                this.hints_params.put(f.getName(), parts[1]);
                if (debug)
                    LOG.debug(String.format("DesignerHints.%s = %s", param, parts[1]));
            } catch (NoSuchFieldException ex) {
                throw new Exception("Unknown DesignerHints parameter: " + param, ex);
            }

        }
        // HStoreConf Parameter
        else if (HStoreConf.isConfParameter(parts[0])) {
            this.conf_params.put(parts[0].toLowerCase(), parts[1]);
        }
        // ArgumentsParser Parameter
        else if (PARAMS.contains(parts[0].toLowerCase())) {
            this.params.put(parts[0].toLowerCase(), parts[1]);
        }
        // Invalid!
        else {
            String suggestions = "";
            i = 0;
            String end = CollectionUtil.last(parts[0].split("\\."));
            for (String param : PARAMS) {
                String param_end = CollectionUtil.last(param.split("\\."));
                if (param.startsWith(parts[0]) || (end != null && param.endsWith(end))
                        || (end != null && param_end != null && param_end.startsWith(end))) {
                    if (suggestions.isEmpty())
                        suggestions = ". Possible Matches:";
                    suggestions += String.format("\n [%02d] %s", ++i, param);
                }
            } // FOR
            throw new Exception("Unknown parameter '" + parts[0] + "'" + suggestions);
        }
    } // FOR

    // -------------------------------------------------------
    // CATALOGS
    // -------------------------------------------------------

    // Text File
    if (this.params.containsKey(PARAM_CATALOG)) {
        String path = this.params.get(PARAM_CATALOG);
        if (debug)
            LOG.debug("Loading catalog from file '" + path + "'");
        Catalog catalog = CatalogUtil.loadCatalog(path);
        if (catalog == null)
            throw new Exception("Failed to load catalog object from file '" + path + "'");
        this.updateCatalog(catalog, new File(path));
    }
    // Jar File
    else if (this.params.containsKey(PARAM_CATALOG_JAR)) {
        String path = this.params.get(PARAM_CATALOG_JAR);
        this.params.put(PARAM_CATALOG, path);
        File jar_file = new File(path);
        Catalog catalog = CatalogUtil.loadCatalogFromJar(path);
        if (catalog == null)
            throw new Exception("Failed to load catalog object from jar file '" + path + "'");
        if (debug)
            LOG.debug("Loaded catalog from jar file '" + path + "'");
        this.updateCatalog(catalog, jar_file);

        if (!this.params.containsKey(PARAM_CATALOG_TYPE)) {
            String jar_name = jar_file.getName();
            int jar_idx = jar_name.lastIndexOf(".jar");
            if (jar_idx != -1) {
                ProjectType type = ProjectType.get(jar_name.substring(0, jar_idx));
                if (type != null) {
                    if (debug)
                        LOG.debug("Set catalog type '" + type + "' from catalog jar file name");
                    this.catalog_type = type;
                    this.params.put(PARAM_CATALOG_TYPE, this.catalog_type.toString());
                }
            }
        }

        // HACK: Extract the ParameterMappings embedded in jar and write them to a temp file
        // This is terrible, confusing, and a total mess...
        // I have no one to blame but myself...
        JarReader reader = new JarReader(jar_file.getAbsolutePath());
        for (String file : reader.getContentsFromJarfile()) {
            if (file.endsWith(".mappings")) {
                String contents = new String(JarReader.readFileFromJarAtURL(jar_file.getAbsolutePath(), file));
                File copy = FileUtil.writeStringToTempFile(contents, "mappings", true);
                this.params.put(PARAM_MAPPINGS, copy.toString());
                break;
            }
        } // FOR
    }
    // Schema File
    else if (this.params.containsKey(PARAM_CATALOG_SCHEMA)) {
        String path = this.params.get(PARAM_CATALOG_SCHEMA);
        Catalog catalog = CompilerUtil.compileCatalog(path);
        if (catalog == null)
            throw new Exception("Failed to load schema from '" + path + "'");
        if (debug)
            LOG.debug("Loaded catalog from schema file '" + path + "'");
        this.updateCatalog(catalog, new File(path));
    }

    // Catalog Type
    if (this.params.containsKey(PARAM_CATALOG_TYPE)) {
        String catalog_type = this.params.get(PARAM_CATALOG_TYPE);
        ProjectType type = ProjectType.get(catalog_type);
        if (type == null) {
            throw new Exception("Unknown catalog type '" + catalog_type + "'");
        }
        this.catalog_type = type;
    }

    // Update Cluster Configuration
    if (this.params.containsKey(ArgumentsParser.PARAM_CATALOG_HOSTS) && DISABLE_UPDATE_CATALOG == false) {
        ClusterConfiguration cc = new ClusterConfiguration(this.getParam(ArgumentsParser.PARAM_CATALOG_HOSTS));
        this.updateCatalog(FixCatalog.cloneCatalog(this.catalog, cc), null);
    }

    // Check the requirements after loading the catalog, because some of the
    // above parameters will set the catalog one
    if (required != null && required.length > 0)
        this.require(required);

    // -------------------------------------------------------
    // PHYSICAL DESIGN COMPONENTS
    // -------------------------------------------------------
    if (this.params.containsKey(PARAM_PARTITION_PLAN)) {
        assert (this.catalog_db != null);
        File path = new File(this.params.get(PARAM_PARTITION_PLAN));
        boolean ignoreMissing = this.getBooleanParam(ArgumentsParser.PARAM_PARTITION_PLAN_IGNORE_MISSING,
                false);
        if (path.exists() || (path.exists() == false && ignoreMissing == false)) {
            if (debug)
                LOG.debug("Loading in partition plan from '" + path + "'");
            this.pplan = new PartitionPlan();
            this.pplan.load(path, this.catalog_db);

            // Apply!
            if (this.params.containsKey(PARAM_PARTITION_PLAN_APPLY)
                    && this.getBooleanParam(PARAM_PARTITION_PLAN_APPLY)) {
                boolean secondaryIndexes = this.getBooleanParam(PARAM_PARTITION_PLAN_NO_SECONDARY,
                        false) == false;
                LOG.info(String.format("Applying PartitionPlan '%s' to catalog [enableSecondaryIndexes=%s]",
                        path.getName(), secondaryIndexes));
                this.pplan.apply(this.catalog_db, secondaryIndexes);
            }
        }
    }

    // -------------------------------------------------------
    // DESIGNER COMPONENTS
    // -------------------------------------------------------

    if (this.params.containsKey(PARAM_DESIGNER_THREADS)) {
        this.max_concurrent = Integer.valueOf(this.params.get(PARAM_DESIGNER_THREADS));
    }
    if (this.params.containsKey(PARAM_DESIGNER_INTERVALS)) {
        this.num_intervals = Integer.valueOf(this.params.get(PARAM_DESIGNER_INTERVALS));
    }
    if (this.params.containsKey(PARAM_DESIGNER_HINTS)) {
        File path = this.getFileParam(PARAM_DESIGNER_HINTS);
        if (debug)
            LOG.debug("Loading in designer hints from '" + path + "'.\nForced Values:\n"
                    + StringUtil.formatMaps(this.hints_params));
        this.designer_hints.load(path, catalog_db, this.hints_params);
    }
    if (this.params.containsKey(PARAM_DESIGNER_CHECKPOINT)) {
        this.designer_checkpoint = new File(this.params.get(PARAM_DESIGNER_CHECKPOINT));
    }

    String designer_attributes[] = { PARAM_DESIGNER_PARTITIONER, PARAM_DESIGNER_MAPPER, PARAM_DESIGNER_INDEXER,
            PARAM_DESIGNER_COSTMODEL };
    ClassLoader loader = ClassLoader.getSystemClassLoader();
    for (String key : designer_attributes) {
        if (this.params.containsKey(key)) {
            String target_name = this.params.get(key);
            Class<?> target_class = loader.loadClass(target_name);
            assert (target_class != null);
            if (debug)
                LOG.debug("Set " + key + " class to " + target_class.getName());

            if (key.equals(PARAM_DESIGNER_PARTITIONER)) {
                this.partitioner_class = (Class<? extends AbstractPartitioner>) target_class;
            } else if (key.equals(PARAM_DESIGNER_MAPPER)) {
                this.mapper_class = (Class<? extends AbstractMapper>) target_class;
            } else if (key.equals(PARAM_DESIGNER_INDEXER)) {
                this.indexer_class = (Class<? extends AbstractIndexSelector>) target_class;
            } else if (key.equals(PARAM_DESIGNER_COSTMODEL)) {
                this.costmodel_class = (Class<? extends AbstractCostModel>) target_class;

                // Special Case: TimeIntervalCostModel
                if (target_name.endsWith(TimeIntervalCostModel.class.getSimpleName())) {
                    this.costmodel = new TimeIntervalCostModel<SingleSitedCostModel>(this.catalogContext,
                            SingleSitedCostModel.class, this.num_intervals);
                } else {
                    this.costmodel = ClassUtil.newInstance(this.costmodel_class,
                            new Object[] { this.catalogContext }, new Class[] { Database.class });
                }
            } else {
                assert (false) : "Invalid key '" + key + "'";
            }
        }
    } // FOR

    // -------------------------------------------------------
    // TRANSACTION ESTIMATION COMPONENTS
    // -------------------------------------------------------
    if (this.params.containsKey(PARAM_MAPPINGS) && DISABLE_UPDATE_CATALOG == false) {
        assert (this.catalog_db != null);
        File path = new File(this.params.get(PARAM_MAPPINGS));
        if (path.exists()) {
            this.param_mappings.load(path, this.catalog_db);
        } else {
            LOG.warn("The ParameterMappings file '" + path + "' does not exist");
        }
    }
    if (this.params.containsKey(PARAM_MARKOV_THRESHOLDS_VALUE)) {
        assert (this.catalog_db != null);
        float defaultValue = this.getDoubleParam(PARAM_MARKOV_THRESHOLDS_VALUE).floatValue();
        this.thresholds = new EstimationThresholds(defaultValue);
        this.params.put(PARAM_MARKOV_THRESHOLDS, this.thresholds.toString());
        LOG.debug("CREATED THRESHOLDS: " + this.thresholds);

    } else if (this.params.containsKey(PARAM_MARKOV_THRESHOLDS)) {
        assert (this.catalog_db != null);
        this.thresholds = new EstimationThresholds();
        File path = new File(this.params.get(PARAM_MARKOV_THRESHOLDS));
        if (path.exists()) {
            this.thresholds.load(path, this.catalog_db);
        } else {
            LOG.warn("The estimation thresholds file '" + path + "' does not exist");
        }
        LOG.debug("LOADED THRESHOLDS: " + this.thresholds);
    }

    // -------------------------------------------------------
    // HASHER
    // -------------------------------------------------------
    if (this.catalog != null) {
        if (this.params.containsKey(PARAM_HASHER_CLASS)) {
            String hasherClassName = this.params.get(PARAM_HASHER_CLASS);
            this.hasher_class = (Class<? extends AbstractHasher>) loader.loadClass(hasherClassName);
        }
        Class<?> paramClasses[] = new Class[] { CatalogContext.class, int.class };
        Object paramValues[] = new Object[] { this.catalogContext, this.catalogContext.numberOfPartitions };

        Constructor<? extends AbstractHasher> constructor = this.hasher_class.getConstructor(paramClasses);
        this.hasher = constructor.newInstance(paramValues);

        if (!(this.hasher instanceof DefaultHasher))
            LOG.debug("Loaded hasher " + this.hasher.getClass());

        if (this.params.containsKey(PARAM_HASHER_PROFILE)) {
            this.hasher.load(this.getFileParam(PARAM_HASHER_PROFILE), null);
        }
    }

    // -------------------------------------------------------
    // SAMPLE WORKLOAD TRACE
    // -------------------------------------------------------
    this.loadWorkload();
}

From source file:com.link_intersystems.lang.reflect.Class2.java

/**
 * Nullsafe {@link ClassLoader} resolution. If this {@link Class2}
 * represents a system class the {@link ClassLoader#getSystemClassLoader()}
 * will be returned.//from   w w  w  . j  a  va  2  s .c  o  m
 *
 * @return the class loader of this {@link Class2}.
 * @since 1.2.0.0
 */
public ClassLoader getClassLoader() {
    ClassLoader classLoader = getType().getClassLoader();
    if (classLoader == null) {
        classLoader = ClassLoader.getSystemClassLoader();
    }
    return classLoader;
}

From source file:com.google.gwt.dev.shell.CompilingClassLoader.java

@Override
protected Class<?> findClass(String className) throws ClassNotFoundException {
    if (className == null) {
        throw new ClassNotFoundException("null class name", new NullPointerException());
    }/* ww  w .  jav  a  2 s.c o  m*/

    if (className.equals("com.google.gwt.core.ext.debug.JsoEval")) {
        // In addition to the system ClassLoader, we let JsoEval be available
        // from this CompilingClassLoader in case that's where the debugger
        // happens to look.
        return ClassLoader.getSystemClassLoader().loadClass(className);
    }

    loadLock.lock();
    try {

        if (scriptOnlyClasses.contains(className)) {
            // Allow the child ClassLoader to handle this
            throw new ClassNotFoundException();
        }

        // Check for a bridge class that spans hosted and user space.
        if (BRIDGE_CLASS_NAMES.containsKey(className)) {
            return BRIDGE_CLASS_NAMES.get(className);
        }

        // Get the bytes, compiling if necessary.
        byte[] classBytes = findClassBytes(className);
        if (classBytes == null) {
            throw new ClassNotFoundException(className);
        }

        if (HasAnnotation.hasAnnotation(classBytes, GwtScriptOnly.class)) {
            scriptOnlyClasses.add(className);
            maybeInitializeScriptOnlyClassLoader();

            /*
             * Release the lock before side-loading from scriptOnlyClassLoader. This prevents deadlock
             * conditions when a class from scriptOnlyClassLoader ends up trying to call back into this
             * classloader from another thread. 
             */
            loadLock.unlock();

            // Also don't run the static initializer to lower the risk of deadlock. 
            return Class.forName(className, false, scriptOnlyClassLoader);
        }

        /*
         * Prevent reentrant problems where classes that need to be injected have
         * circular dependencies on one another via JSNI and inheritance. This check
         * ensures that a class's supertype can refer to the subtype (static
         * members, etc) via JSNI references by ensuring that the Class for the
         * subtype will have been defined before injecting the JSNI for the
         * supertype.
         */
        boolean localInjection;
        if (!isInjectingClass) {
            localInjection = isInjectingClass = true;
        } else {
            localInjection = false;
        }

        Class<?> newClass = defineClass(className, classBytes, 0, classBytes.length);
        if (className.equals(JavaScriptHost.class.getName())) {
            javaScriptHostClass = newClass;
            updateJavaScriptHost();
        }

        /*
        * We have to inject the JSNI code after defining the class, since dispId
        * assignment is based around reflection on Class objects. Don't inject JSNI
        * when loading a JSO interface class; just wait until the implementation
        * class is loaded.
        */
        if (!classRewriter.isJsoIntf(className)) {
            CompilationUnit unit = getUnitForClassName(canonicalizeClassName(className));
            if (unit != null) {
                toInject.push(unit);
            }
        }

        if (localInjection) {
            try {
                /*
                * Can't use an iterator here because calling injectJsniFor may cause
                * additional entries to be added.
                */
                while (toInject.size() > 0) {
                    CompilationUnit unit = toInject.remove(0);
                    if (!alreadyInjected.contains(unit)) {
                        injectJsniMethods(unit);
                        alreadyInjected.add(unit);
                    }
                }
            } finally {
                isInjectingClass = false;
            }
        }

        if (className.equals("com.google.gwt.core.client.GWT")) {
            gwtClass = newClass;
            updateGwtClass();
        }

        return newClass;
    } finally {
        if (loadLock.isLocked()) {
            loadLock.unlock();
        }
    }
}

From source file:org.wso2.carbon.analytics.spark.core.internal.AnalyticsSparkExecutorTest.java

private List<Record> generateRecordsForCompressedEventAnalytics(int tenantId, String tableName,
        boolean generateRecordIds) throws Exception {
    List<Record> result = new ArrayList<>();
    Map<String, Object> values;
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    String[] sampleData;/*from www  . j a  v  a2s .  co m*/
    try {
        sampleData = IOUtils.toString(classLoader.getResourceAsStream("sample-data/CompressedEventData"))
                .split("\n");
    } catch (IOException e) {
        throw new AnalyticsException(e.getMessage());
    }
    long timeTmp = System.currentTimeMillis();
    for (String aSampleData : sampleData) {
        values = new HashMap<>();
        String[] fields = aSampleData.split(",", 2);
        values.put("meta_compressed", Boolean.parseBoolean(fields[0]));
        values.put("flowData", fields[1]);
        timeTmp = timeTmp + 5000;
        result.add(new Record(generateRecordIds ? GenericUtils.generateRecordID() : null, tenantId, tableName,
                values, timeTmp));
    }
    return result;
}

From source file:org.allcolor.yahp.converter.CClassLoader.java

/**
 * Destroy instance variables./* w  w w .  j  a  v  a  2s.  co m*/
 * 
 * @param logFactoryRelease
 *            method to release commons logging
 */
private final void _destroy(final Method logFactoryRelease) {
    for (final Iterator it = this.childrenMap.entrySet().iterator(); it.hasNext();) {
        final Map.Entry entry = (Map.Entry) it.next();
        final CClassLoader loader = (CClassLoader) entry.getValue();
        loader._destroy(logFactoryRelease);
        it.remove();
    }

    try {
        // remove ref from commons logging
        logFactoryRelease.invoke(null, new Object[] { this });
    } catch (final Exception e) {
    }

    try {
        // reset parent to system class loader
        final Field parent = ClassLoader.class.getDeclaredField("parent");
        parent.setAccessible(true);
        parent.set(this, ClassLoader.getSystemClassLoader());
        parent.setAccessible(false);
    } catch (final Throwable ignore) {
    }

    this.classesMap.clear();
    for (final Iterator it = this.dllMap.entrySet().iterator(); it.hasNext();) {
        final Object element = it.next();
        final Map.Entry entry = (Map.Entry) element;
        if (entry.getValue() instanceof File) {
            ((File) entry.getValue()).delete();
        }
    }
    this.cacheMap.clear();
    this.dllMap.clear();
    this.resourcesMap.clear();
    this.config = null;
    this.name = null;
    this.finalizepath = this.path;
    this.path = null;
    //classes
    System.runFinalization();
    System.gc();
}

From source file:org.allcolor.yahp.converter.CClassLoader.java

protected final Class findClass(final String name) throws ClassNotFoundException {
    try {//from  ww  w .j  a v a  2s  .  c  o m
        if (name == null) {
            return null;
        }

        if (name.startsWith("java.") || name.startsWith("sun.reflect")) {
            return ClassLoader.getSystemClassLoader().loadClass(name);
        }

        final String searchClass = name.replace('.', '/') + ".class";
        final CThreadContext context = CThreadContext.getInstance();
        final String cpName = CClassLoader.CCLASSLOADER_NAMESPACE + name;

        List lPriorLoader = (List) context.get(cpName);

        if (lPriorLoader == null) {
            lPriorLoader = new Vector();
            context.set(cpName, lPriorLoader);
        }

        if (lPriorLoader.contains(this.toString())) {
            return null;
        }

        lPriorLoader.add(this.toString());

        if (CClassLoader.sl(CClassLoader.DEBUG)) {
            CClassLoader.log("Searching " + name + " in " + this.getPath(), CClassLoader.DEBUG);
        }

        final WeakReference cache = (WeakReference) this.cacheMap.get(name);
        if (cache != null) {
            final Class c = (Class) cache.get();
            if (c != null) {
                return c;
            }
        }

        // first check if this class as a mandatory loader
        if (!this.booAlone) {
            CClassLoader loader = null;

            for (final Iterator it = CClassLoader.mandatoryLoadersMap.entrySet().iterator(); it.hasNext();) {
                final Entry entry = (Entry) it.next();
                loader = (CClassLoader) entry.getValue();

                if (loader.classesMap.containsKey(searchClass)) {
                    if (loader != this) {
                        break;
                    }
                    loader = null;
                    break;
                }
                loader = null;
            }

            if (loader != null) {
                final Class c = loader.findClass(name);
                if (c != null) {
                    return c;
                }
            }
        }

        // second search in this repository
        byte buffer[] = null;

        final URL urlToResource = (URL) this.classesMap.get(searchClass);

        if (urlToResource != null) {
            buffer = CClassLoader.loadByteArray(urlToResource);
        }

        if (buffer != null) {
            if (CClassLoader.sl(CClassLoader.DEBUG)) {
                CClassLoader.log("Loaded " + name + " in " + this.getPath(), CClassLoader.DEBUG);
            }

            Class c = null;
            c = this.findLoadedClass(name);

            if (c == null) {
                try {
                    c = this.defineClass(name, buffer, 0, buffer.length);
                } catch (final LinkageError e) {
                    c = this.findLoadedClass(name);

                    if (c == null) {
                        throw new ClassNotFoundException(name + " was not found !");
                    }
                }
            }

            if (c != null) {
                return c;
            }
        }

        // then search in each children
        final List tmpLoader = new ArrayList();

        for (final Iterator it = this.childrenMap.entrySet().iterator(); it.hasNext();) {
            final Entry entry = (Entry) it.next();
            final CClassLoader child = (CClassLoader) entry.getValue();

            if (lPriorLoader.contains(child.toString())) {
                continue;
            }

            tmpLoader.add(child);
        }

        for (final Iterator it = tmpLoader.iterator(); it.hasNext();) {
            final Object element = it.next();
            final CClassLoader child = (CClassLoader) element;
            final Class c = child.findClass(name);

            if (c != null) {
                return c;
            }
        }

        // then follow to parents
        if ((this != CClassLoader.getRootLoader()) && !this.booDoNotForwardToParent) {
            if (lPriorLoader.contains(this.getParent().toString())) {
                return null;
            } else {
                if (this.getParent() instanceof CClassLoader) {
                    return ((CClassLoader) this.getParent()).findClass(name);
                } else {
                    return this.getParent().loadClass(name);
                }
            }
        } else {
            try {
                ClassLoader contextLoader = CClassLoader.getContextLoader();
                if (contextLoader == null) {
                    contextLoader = CClassLoader.getRootLoader().getParent();
                }
                final Class c = contextLoader.loadClass(name);
                if (c != null) {
                    return c;
                }
            } catch (Throwable e) {
                final Class c = CClassLoader.getRootLoader().getParent().loadClass(name);
                if (c != null) {
                    return c;
                }
            }
            throw new ClassNotFoundException(name);
        }
    } catch (ClassNotFoundException e) {
        throw e;
    } catch (NoClassDefFoundError e) {
        throw e;
    } catch (Throwable e) {
        throw new ClassNotFoundException(name, e);
    }
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

protected Class findClass(String className, boolean trySystemCL) {
    try {//from   w  w  w.  j av  a2 s  .c  o  m
        return Class.forName(className);
    }
    //    catch (NoClassDefFoundError e) {
    //      // Silently ignore
    //      return null;
    //    }
    catch (ClassNotFoundException e) {
        if (trySystemCL) {
            try {
                return Class.forName(className, true, ClassLoader.getSystemClassLoader());
            } catch (ClassNotFoundException e1) {
                // Silently ignore
                return null;
            }
        }
        // Silently ignore
        return null;
    } catch (Exception ex) { // Example SecurityException
        warn(ex);
        return null;
    }
}

From source file:au.org.ala.delta.util.Utils.java

private static void launchIntkeyViaClassLoader(String inputFile) throws Exception {
    // Gah.... this is a horrible work around for the fact that
    // the swing application framework relies on a static
    // Application instance so we can't have the Editor and
    // Intkey playing together nicely in the same JVM.
    // It doesn't really work properly anyway, the swing application
    // framework generates exceptions during loading and saving
    // state due to failing instanceof checks.
    String classPath = System.getProperty("java.class.path");
    String[] path = classPath.split(File.pathSeparator);
    List<URL> urls = new ArrayList<URL>();
    for (String pathEntry : path) {
        urls.add(new File(pathEntry).toURI().toURL());
    }//from   ww w.  ja v  a  2s  .co m
    ClassLoader intkeyLoader = new URLClassLoader(urls.toArray(new URL[0]),
            ClassLoader.getSystemClassLoader().getParent());
    Class<?> intkey = intkeyLoader.loadClass("au.org.ala.delta.intkey.Intkey");
    Method main = intkey.getMethod("main", String[].class);
    main.invoke(null, (Object) new String[] { inputFile });
}

From source file:org.wso2.carbon.context.internal.CarbonContextDataHolder.java

private static Class<?> classForName(final String className) throws ClassNotFoundException {

    Class<?> cls = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
        public Class<?> run() {
            // try thread context class loader first
            try {
                return Class.forName(className, true, Thread.currentThread().getContextClassLoader());
            } catch (ClassNotFoundException ignored) {
                if (log.isDebugEnabled()) {
                    log.debug(ignored);//from   w w  w. j  a v  a 2s  .c o m
                }

            }
            // try system class loader second
            try {
                return Class.forName(className, true, ClassLoader.getSystemClassLoader());
            } catch (ClassNotFoundException ignored) {
                if (log.isDebugEnabled()) {
                    log.debug(ignored);
                }
            }
            // return null, if fail to load class
            return null;
        }
    });

    if (cls == null) {
        throw new ClassNotFoundException("class " + className + " not found");
    }

    return cls;
}

From source file:com.rapidminer.tools.Tools.java

/** TODO: Looks like this can be replaced by {@link Plugin#getMajorClassLoader()} */
public static Class<?> classForName(String className) throws ClassNotFoundException {
    try {//w w  w .  j a  v a2s. co  m
        return Class.forName(className);
    } catch (ClassNotFoundException e) {
    }
    try {
        return ClassLoader.getSystemClassLoader().loadClass(className);
    } catch (ClassNotFoundException e) {
    }
    Iterator<Plugin> i = Plugin.getAllPlugins().iterator();
    while (i.hasNext()) {
        Plugin p = i.next();
        try {
            return p.getClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) {
            // this wasn't it, so continue
        }
    }
    throw new ClassNotFoundException(className);
}