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:org.emoseman.aconf.AutoConfig.java

private static void readConfigFromFile(Class<? extends ConfigContainer> configContainer,
        String configFilename) {//from   w w  w  .  jav  a2  s  .c o m

    configLock.writeLock().lock();

    URL fileURL = null;
    if (configFilename.startsWith("file:///")) {
        try {
            fileURL = new URL(configFilename);
        } catch (MalformedURLException e) {
            throw new RuntimeException("Failed to create URL from " + configFilename, e);
        }
    } else {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        fileURL = cl.getResource(configFilename);
    }
    if (fileURL == null) {
        throw new RuntimeException("Failed to load config file " + configFilename);
    }

    Gson gson = new Gson();
    String val;
    Field field;
    Class type;
    try {
        // read json from config file
        // TODO enforce extension?
        HashMap<String, String> tmp = gson.fromJson(new InputStreamReader(fileURL.openStream()), HashMap.class);

        // search for required keys
        ArrayList<String> missingKeys = new ArrayList<>();
        for (String k : configContainerRequiredFields.get(configContainer)) {
            if (!tmp.containsKey(k)) {
                missingKeys.add(k);
            }
        }
        if (missingKeys.size() > 0) {
            throw new RuntimeException(
                    "Properties " + StringUtils.join(missingKeys, ", ") + " are required, and missing");
        }

        // assign defaults
        for (Field f : configContainerFields.get(configContainer)) {
            ConfigElement configElement = f.getAnnotation(ConfigElement.class);
            if (configElement == null) {
                continue;
            }
            if (StringUtils.isEmpty(configElement.defaultValue())) {
                continue;
            }
            if (!tmp.containsKey(configElement.propertyName())) {
                tmp.put(configElement.propertyName(), configElement.defaultValue());
            }
        }

        // populate fields
        for (String k : tmp.keySet()) {
            if (fieldMap.get(configContainer).containsKey(k)) {
                val = tmp.get(k);
                if (val.equalsIgnoreCase("${hostname}")) {
                    val = populateMacro(val);
                }
                field = fieldMap.get(configContainer).get(k);
                field.setAccessible(true);

                type = fieldTypeMap.get(configContainer).get(k);

                if (type == String.class) {
                    field.set(configContainer, String.valueOf(val));
                } else if (type == BigInteger.class) {
                    field.set(configContainer, new BigInteger(val));
                } else if (type == Float.class || type == float.class) {
                    field.set(configContainer, Float.valueOf(val));
                } else if (type == Long.class || type == long.class) {
                    field.set(configContainer, Long.valueOf(val));
                } else if (type == Double.class || type == double.class) {
                    field.set(configContainer, Double.valueOf(val));
                } else if (type == Integer.class || type == int.class) {
                    field.set(configContainer, Integer.valueOf(val));
                } else if (type == Boolean.class || type == boolean.class) {
                    field.set(configContainer, Boolean.valueOf(val));
                } else {
                    // try to execute the method reflectively
                    try {
                        Method m = type.getDeclaredMethod("valueOf", String.class);
                        Invokable invokable = new TypeToken() {
                        }.method(m);
                        if (invokable.isStatic() && !invokable.isPrivate()) {
                            field.set(configContainer, m.invoke(type, val));
                            continue;
                        }
                    } catch (Throwable ignored) {
                        // ignored
                    }
                    try {
                        Constructor typeConstructor = type.getConstructor(String.class);
                        Invokable invokable = new TypeToken() {
                        }.constructor(typeConstructor);
                        if (!invokable.isPrivate()) {
                            field.set(configContainer, typeConstructor.newInstance(val));
                            continue;
                        }
                    } catch (Throwable ignored) {
                        // ignored
                    }

                    throw new RuntimeException(
                            "Not coded for type " + type + " and could not find a method to execute!");
                }
            }
        }
        for (ConfigChangeListener listener : listeners) {
            listener.configReloaded();
        }
    } catch (Exception e) {
        log.error(e.getClass() + "-" + e.getMessage());
        if (log.isDebugEnabled()) {
            e.printStackTrace(System.err);
        }

        shutdown.set(true);
        timedPool.shutdownNow();
        throw new RuntimeException(e);
    }

    configLock.writeLock().unlock();
}

From source file:org.beangle.model.persist.hibernate.internal.ClassUtils.java

/**
 * Returns the classloader for the given class. This method deals with JDK
 * classes which return by default, a null classloader.
 * //  w w w.  j a v a2s . c o m
 * @param clazz
 * @return
 */
public static ClassLoader getClassLoader(Class<?> clazz) {
    Validate.notNull(clazz);
    ClassLoader loader = clazz.getClassLoader();
    return (loader == null ? ClassLoader.getSystemClassLoader() : loader);
}

From source file:org.apache.ranger.ldapconfigcheck.LdapConfig.java

private InputStream getFileInputStream(String path) throws FileNotFoundException {

    InputStream ret = null;/*from  w  w  w .  j  av  a 2 s. c o m*/

    File f = new File(path);

    if (f.exists()) {
        ret = new FileInputStream(f);
    } else {
        ret = getClass().getResourceAsStream(path);

        if (ret == null) {
            if (!path.startsWith("/")) {
                ret = getClass().getResourceAsStream("/" + path);
            }
        }

        if (ret == null) {
            ret = ClassLoader.getSystemClassLoader().getResourceAsStream(path);
            if (ret == null) {
                if (!path.startsWith("/")) {
                    ret = ClassLoader.getSystemResourceAsStream("/" + path);
                }
            }
        }
    }

    return ret;
}

From source file:com.silverpeas.bootstrap.SilverpeasContextBootStrapper.java

private static void addURLs(URL[] urls) throws NoSuchMethodException, IllegalArgumentException,
        IllegalAccessException, InvocationTargetException {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    if (cl instanceof URLClassLoader) {
        URLClassLoader urlClassloader = (URLClassLoader) cl;
        // addURL is a protected method, but we can use reflection to call it
        Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
        // change access to true, otherwise, it will throw exception
        method.setAccessible(true);//ww  w .  j av a 2s .  com
        for (URL url : urls) {
            method.invoke(urlClassloader, new Object[] { url });
        }
    } else {
        // SystemClassLoader is not URLClassLoader....
    }
}

From source file:org.obm.push.spushnik.resources.FolderSyncScenarioTest.java

private HttpResponse folderSyncScenarioWithRequest(String baseURL, String certificate) throws Exception {
    InputStream requestInputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(certificate);
    byte[] requestContent = ByteStreams.toByteArray(requestInputStream);

    HttpPost httpPost = new HttpPost(buildRequestUrl(baseURL));
    httpPost.setEntity(new ByteArrayEntity(requestContent, ContentType.APPLICATION_JSON));
    return httpClient.execute(httpPost);
}

From source file:org.tros.utils.PropertiesInitializer.java

/**
 * Initialize from JSON if possible./*from   w ww. j av  a2s.c o  m*/
 */
private void initializeFromJson() {
    try {
        java.util.Enumeration<URL> resources = ClassLoader.getSystemClassLoader()
                .getResources(this.getClass().getCanonicalName().replace('.', '/') + ".json");
        ArrayList<URL> urls = new ArrayList<>();

        //HACK: semi sort classpath to put "files" first and "jars" second.
        //this has an impact once we are workin in tomcat where
        //the classes in tomcat are not stored in a jar.
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            if (url.toString().startsWith("file:")) {
                urls.add(0, url);
            } else {
                boolean added = false;
                for (int ii = 0; !added && ii < urls.size(); ii++) {
                    if (!urls.get(ii).toString().startsWith("file:")) {
                        urls.add(ii, url);
                        added = true;
                    }
                }
                if (!added) {
                    urls.add(url);
                }
            }
        }

        //reverse the list, so that the item found first in the
        //classpath will be the last one run though and thus
        //be the one to set the final value
        Collections.reverse(urls);

        PropertyDescriptor[] props = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors();
        for (URL url : urls) {
            try {
                PropertiesInitializer obj = (PropertiesInitializer) readValue(url.openStream(),
                        this.getClass());

                for (PropertyDescriptor p : props) {
                    if (p.getWriteMethod() != null && p.getReadMethod() != null
                            && p.getReadMethod().getDeclaringClass() != Object.class) {
                        Object val = p.getReadMethod().invoke(obj);
                        if (val != null) {
                            p.getWriteMethod().invoke(this, val);
                        }
                    }
                }
            } catch (NullPointerException | IOException | IllegalArgumentException | InvocationTargetException
                    | IllegalAccessException ex) {
                LOGGER.debug(null, ex);
            }
        }
    } catch (IOException ex) {
    } catch (IntrospectionException ex) {
        LOGGER.warn(null, ex);
    }
}

From source file:com.mockey.plugin.PluginStore.java

/**
 * Looks to the default plug-in directory location to initialize this store
 *//*  w  ww  .  j  a  v  a  2s .co m*/
public void initializeOrUpdateStore() {

    try {
        List<PackageInfo> list = PackageInfoPeerClassFinder.findPackageInfo();
        for (PackageInfo pi : list) {
            for (String className : pi.getClassList()) {

                try {
                    // If we don't have the class
                    Class<?> o = Class.forName(className);
                    if (o == null) {
                        throw new Exception("Class not available");
                    }
                } catch (NoClassDefFoundError ncdfe) {
                    // By Design: gobbling up this error to reduce the
                    // non-needed noise upon startup. If there is a real
                    // issue, then it will bubble up somewhere else.
                } catch (Exception e) {
                    // Explicitly load classes from packages that have
                    // package-info
                    try {
                        ClassLoader.getSystemClassLoader().loadClass(className);
                    } catch (java.lang.NoClassDefFoundError ncdfe) {
                        // By Design: gobbling up this error to reduce the
                        // non-needed noise upon startup. If there is a real
                        // issue, then it will bubble up somewhere else.
                    }
                }

                Package packageItem = Package.getPackage(pi.getName());
                if (null != packageItem.getAnnotation(MockeyRequestInspector.class)) {
                    Class<?> x = doesThisImplementIRequestInspector(className);
                    if (x != null && !this.reqInspectorClassNameList.contains(x)) {
                        this.reqInspectorClassNameList.add(x);
                        logger.debug("Plugin added: " + className);
                    }
                }
            }
        }

    } catch (Exception e) {
        logger.error("Found a Mockey.jar, but unable read mockey jar", e);
    }
}

From source file:org.apache.kylin.monitor.ConfigUtils.java

public static void addClasspath(String path) throws Exception {
    File file = new File(path);

    if (file.exists()) {
        URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Class<URLClassLoader> urlClass = URLClassLoader.class;
        Method method = urlClass.getDeclaredMethod("addURL", new Class[] { URL.class });
        method.setAccessible(true);/*from w w  w  .j  a va  2  s  .c  o  m*/
        method.invoke(urlClassLoader, new Object[] { file.toURI().toURL() });
    }
}

From source file:org.tros.logo.swing.LogoMenuBar.java

/**
 * Set up the menus for examples./*from w  w w .  jav  a  2s .  c  o m*/
 *
 * @param name
 * @param base
 * @return
 */
private JMenu setupMenu(String name, String base) {
    JMenu samplesMenu = new JMenu(name);
    try {
        InputStream resourceAsStream = TorgoToolkit.getDefaultResourceAccessor()
                .open(base + "/resource.manifest");
        List<String> readLines = IOUtils.readLines(resourceAsStream, "utf-8");
        Collections.sort(readLines);
        for (String line : readLines) {
            JMenuItem jmi = new JMenuItem(base + "/" + line);
            if (!jmi.getText().endsWith("manifest")) {
                samplesMenu.add(jmi);
                jmi.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String val = e.getActionCommand();
                        URL resource = ClassLoader.getSystemClassLoader().getResource(val);
                        LogoMenuBar.this.controller.openFile(resource);
                    }
                });
            }
        }
    } catch (IOException ex) {
        org.tros.utils.logging.Logging.getLogFactory().getLogger(LogoMenuBar.class).fatal(null, ex);
    }
    return samplesMenu;
}

From source file:lu.lippmann.cdb.graph.GraphViewImpl.java

private String buildTooltipFromTags(final String name, final List<CTag> tags) {
    if (tags.isEmpty())
        return null;
    final StringBuilder sb = new StringBuilder("<html>" + name + "<br/><table>");
    final Calendar cal = Calendar.getInstance();
    for (final CTag t : tags) {
        cal.setTimeInMillis(t.getTimestamp());
        final URL u = ClassLoader.getSystemClassLoader().getResource(t.getValue().getNote().getIconPath());
        sb.append("<tr><td>").append("<img width=16 height=16 src=\"").append(u).append("\"/>")
                .append("</td><td>").append("<i>").append(t.getUser().getName()).append("</i></td><td>")
                .append(cal.getTime()).append("</td><td>").append("<b>'").append(t.getValue().getDesc())
                .append("'</b>").append("</td></tr>");
    }//  w  w  w  .ja  v  a  2s .c  o  m
    sb.append("</html>");
    return sb.toString();
}