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:dyco4j.instrumentation.internals.CLI.java

private static void extendClassPath(final CommandLine cmdLine) throws IOException {
    try {//from   w w  w .j a  v  a 2s .com
        final URLClassLoader _urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        final Class<URLClassLoader> _urlClass = URLClassLoader.class;
        final Method _method = _urlClass.getDeclaredMethod("addURL", URL.class);
        _method.setAccessible(true);
        addEntryToClassPath(_urlClassLoader, _method, cmdLine.getOptionValue(IN_FOLDER_OPTION));
        final String _classpathConfig = cmdLine.getOptionValue(CLASSPATH_CONFIG_OPTION);
        if (_classpathConfig != null) {
            for (final String _s : Files.readAllLines(Paths.get(_classpathConfig))) {
                addEntryToClassPath(_urlClassLoader, _method, _s);
            }
        }
    } catch (final NoSuchMethodException _e) {
        throw new RuntimeException(_e);
    }
}

From source file:org.commoncrawl.server.ServletRegistry.java

HttpServlet loadServlet(String servletName) {

    String classesRoot = System.getProperty("commoncrawl.classes.root");

    // LOG.info("Classes Root is:" + classesRoot);

    if (classesRoot == null) {
        classesRoot = new File("/Users/rana/commoncrawl/commoncrawl_trunk/trunk/deploy/bin").getAbsolutePath();
    }/*from  w  ww.  ja  va2s.  com*/
    // LOG.info("Classes Root is:" + classesRoot);
    try {
        ArrayList<URL> urls = new ArrayList<URL>();
        urls.add(new File(classesRoot).toURI().toURL());
        LOG.info("URL is:" + urls.get(0).toString());

        addClassPathEntries(new File(classesRoot, "lib"), urls);

        DynamicClassLoader loader = new DynamicClassLoader(urls.toArray(new URL[0]),
                ClassLoader.getSystemClassLoader(), servletName);

        // LOG.info("Loader Init Successfull");
        try {
            LOG.info("Construct class type:" + servletName);
            Class theClass = loader.loadClass(servletName, true);
            LOG.info("Loaded Class Type:" + theClass);
            return (HttpServlet) theClass.newInstance();
        } catch (ClassNotFoundException e) {
            LOG.error(StringUtils.stringifyException(e));
            throw new RuntimeException(e);
        }
    } catch (MalformedURLException e1) {
        LOG.error(StringUtils.stringifyException(e1));
    } catch (Throwable e) {
        LOG.error(StringUtils.stringifyException(e));
        throw new RuntimeException(e);
    }
    return null;
}

From source file:geva.Mapper.ContextFreeGrammar.java

/**Read a BNF file to a string and call readBNFString to parse the grammar
 * string. Find file from the class loader
 * @param file_name name of file//from  www .  ja va2  s  . c om
 * @return parse success
 */
@SuppressWarnings({ "UnusedReturnValue", "IOResourceOpenedButNotSafelyClosed" })
public boolean readBNFFile(String file_name) throws MalformedGrammarException {
    StringBuffer contents = new StringBuffer();
    try {
        int bufferSize = 1024;
        String line;
        ClassLoader loader = ClassLoader.getSystemClassLoader();
        InputStream is = loader.getResourceAsStream(file_name);
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr, bufferSize);
        assert (br != null) : "Cannot load resource from classloader: " + file_name;
        while ((line = br.readLine()) != null) {
            contents.append(line);
            //readLine removes the lineseparator from http://www.javapractices.com/Topic42.cjp
            contents.append(System.getProperty("line.separator"));
        }
        br.close();
    } catch (FileNotFoundException e) {
        System.err.println("Grammar File not found: " + file_name);
        return false;
    } catch (NullPointerException e) {
        System.err.println("Grammar File not found in classloader: " + file_name);
        return false;
    } catch (IOException e) {
        System.err.println("IOException when looking for grammar file: " + file_name);
        return false;
    }
    contents.append("\n");
    return readBNFString(contents.toString());
}

From source file:org.tolven.plugin.repository.RepositoryMetadata.java

private static JAXBContext getJaxbContext() {
    if (jaxbContext == null) {
        try {//  w w w  .j  av  a 2 s  .  co m
            jaxbContext = JAXBContext.newInstance(PLUGINS_PACKAGE, ClassLoader.getSystemClassLoader());
        } catch (Exception ex) {
            throw new RuntimeException("Could not create JAXBContext", ex);
        }
    }
    return jaxbContext;
}

From source file:Main.java

/**
 * <P>Attempts to find the most suitable {@link ClassLoader} as follows:</P>
 * <UL>/*from  w w  w .  j a v a2  s. c  om*/
 * <LI><P>
 * Check the {@link Thread#getContextClassLoader()} value
 * </P></LI>
 *
 * <LI><P>
 * If no thread context class loader then check the anchor
 * class (if given) for its class loader
 * </P></LI>
 *
 * <LI><P>
 * If still no loader available, then use {@link ClassLoader#getSystemClassLoader()}
 * </P></LI>
 * </UL>
 *
 * @param anchor The anchor {@link Class} to use if no current thread
 *               - ignored if {@code null}
 *               context class loader
 * @return The resolver {@link ClassLoader}
 */
public static ClassLoader resolveDefaultClassLoader(Class<?> anchor) {
    Thread thread = Thread.currentThread();
    ClassLoader cl = thread.getContextClassLoader();
    if (cl != null) {
        return cl;
    }

    if (anchor != null) {
        cl = anchor.getClassLoader();
    }

    if (cl == null) { // can happen for core Java classes
        cl = ClassLoader.getSystemClassLoader();
    }

    return cl;
}

From source file:org.apache.james.http.jetty.JettyHttpServerFactory.java

@SuppressWarnings("unchecked")
private Class<? extends Filter> findFilter(String classname) {
    try {/*from   w  w  w  . ja  va 2s. c o m*/
        return (Class<? extends Filter>) ClassLoader.getSystemClassLoader().loadClass(classname);
    } catch (ClassNotFoundException e) {
        throw new ConfigurationException(String.format("'%s' filter cannot be found", classname), e);
    }
}

From source file:org.obm.sync.calendar.ImportICalendarIntegrationTest.java

@Test
@RunAsClient//from   w  w  w  .j  a v a 2  s .co m
public void testImportICS(@ArquillianResource @OperateOnDeployment(ARCHIVE) URL baseUrl) throws Exception {
    locatorService.configure(baseUrl);
    InputStream icsData = ClassLoader.getSystemClassLoader().getResourceAsStream("importICalendar.sample.ics");
    String calendar = "user1@domain.org";

    AccessToken accessToken = loginClient.login(calendar, "user1");
    int importCount = calendarClient.importICalendar(accessToken, calendar, IOUtils.toString(icsData),
            UUID.randomUUID().toString());
    EventChanges eventsInDB = calendarClient.getSync(accessToken, calendar,
            DateUtils.getEpochPlusOneSecondCalendar().getTime());

    UnidentifiedAttendee organizer = UnidentifiedAttendee.builder().asOrganizer().email("user1@domain.org")
            .displayName("Firstname Lastname").participation(Participation.accepted())
            .participationRole(ParticipationRole.REQ).build();

    Event event1 = new Event();
    event1.setTitle("event default");
    event1.setPrivacy(EventPrivacy.PUBLIC);
    event1.setDuration(3600);
    event1.setInternalEvent(true);
    event1.setOwner("user1");
    event1.setOwnerDisplayName("user1");
    event1.setOwnerEmail("user1@domain.org");
    event1.setDescription("");
    event1.setLocation("");
    event1.setCategory("");
    event1.setTimezoneName("Etc/GMT");
    event1.setPriority(0);
    event1.setExtId(new EventExtId(
            "2e8de6deb053002a23c664e11c94dc65032452a779399e26bce4f61598a28709c8a1cc84eb01e4a4d00ebaa2491186186cfa0bc97787ecec4dbc7522123b31b7d3726dcde275e362"));
    event1.setTimeCreate(dateUTC("2013-04-07T12:09:37"));
    event1.setTimeUpdate(dateUTC("2013-04-07T12:09:37"));
    event1.setStartDate(dateUTC("2013-04-01T10:00:00"));
    event1.addAttendee(organizer);
    Event event2 = new Event();
    event2.setTitle("event public");
    event2.setPrivacy(EventPrivacy.PUBLIC);
    event2.setDuration(3600);
    event2.setInternalEvent(true);
    event2.setOwner("user1");
    event2.setOwnerDisplayName("user1");
    event2.setOwnerEmail("user1@domain.org");
    event2.setDescription("description");
    event2.setLocation("location");
    event2.setCategory("existing_category");
    event2.setTimezoneName("Etc/GMT");
    event2.setPriority(0);
    event2.setExtId(new EventExtId(
            "3e8de6deb053002a23c664e11c94dc65032452a779399e26bce4f61598a28709c8a1cc84eb01e4a4d00ebaa2491186186cfa0bc97787ecec4dbc7522123b31b7d3726dcde275e362"));
    event2.setTimeCreate(dateUTC("2013-04-07T12:09:37"));
    event2.setTimeUpdate(dateUTC("2013-04-07T12:09:37"));
    event2.setStartDate(dateUTC("2013-04-02T08:00:00"));
    event2.addAttendee(organizer);
    Event event3 = new Event();
    event3.setTitle("event private");
    event3.setPrivacy(EventPrivacy.PRIVATE);
    event3.setDuration(3600);
    event3.setInternalEvent(true);
    event3.setOwner("user1");
    event3.setOwnerDisplayName("user1");
    event3.setOwnerEmail("user1@domain.org");
    event3.setDescription("");
    event3.setLocation("");
    event3.setCategory("");
    event3.setTimezoneName("Etc/GMT");
    event3.setPriority(0);
    event3.setExtId(new EventExtId(
            "4e8de6deb053002a23c664e11c94dc65032452a779399e26bce4f61598a28709c8a1cc84eb01e4a4d00ebaa2491186186cfa0bc97787ecec4dbc7522123b31b7d3726dcde275e362"));
    event3.setTimeCreate(dateUTC("2013-04-07T12:09:37"));
    event3.setTimeUpdate(dateUTC("2013-04-07T12:09:37"));
    event3.setStartDate(dateUTC("2013-04-03T14:00:00"));
    event3.addAttendee(organizer);
    Event event4 = new Event();
    event4.setTitle("event confidential");
    event4.setPrivacy(EventPrivacy.CONFIDENTIAL);
    event4.setDuration(3600);
    event4.setInternalEvent(true);
    event4.setOwner("user1");
    event4.setOwnerDisplayName("user1");
    event4.setOwnerEmail("user1@domain.org");
    event4.setDescription("");
    event4.setLocation("");
    event4.setCategory("");
    event4.setPriority(0);
    event4.setTimezoneName("Etc/GMT");
    event4.setExtId(new EventExtId(
            "5e8de6deb053002a23c664e11c94dc65032452a779399e26bce4f61598a28709c8a1cc84eb01e4a4d00ebaa2491186186cfa0bc97787ecec4dbc7522123b31b7d3726dcde275e362"));
    event4.setTimeCreate(dateUTC("2013-04-07T12:09:37"));
    event4.setTimeUpdate(dateUTC("2013-04-07T12:09:37"));
    event4.setStartDate(dateUTC("2013-04-04T08:00:00"));
    event4.addAttendee(organizer);

    assertThat(importCount).isEqualTo(4);
    assertThat(eventsInDB.getDeletedEvents()).isEmpty();
    assertThat(eventsInDB.getUpdated())
            .usingElementComparator(IntegrationTestUtils.ignoreDatabaseElementsComparator())
            .containsOnly(event1, event2, event3, event4);
}

From source file:org.apache.ranger.plugin.contextenricher.RangerFileBasedTagRetriever.java

@Override
public void init(Map<String, String> options) {

    if (LOG.isDebugEnabled()) {
        LOG.debug("==> init()");
    }//from  w w  w.  j  a  v  a2 s  . c  om

    gsonBuilder = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z").setPrettyPrinting().create();

    String serviceTagsFileNameProperty = "serviceTagsFileName";
    String serviceTagsDefaultFileName = "/testdata/test_servicetags_hive.json";

    if (StringUtils.isNotBlank(serviceName) && serviceDef != null && StringUtils.isNotBlank(appId)) {
        InputStream serviceTagsFileStream = null;

        // Open specified file from options- it should contain service-tags

        serviceTagsFileName = options != null ? options.get(serviceTagsFileNameProperty) : null;

        serviceTagsFileName = serviceTagsFileName == null ? serviceTagsDefaultFileName : serviceTagsFileName;

        File f = new File(serviceTagsFileName);

        if (f.exists() && f.isFile() && f.canRead()) {
            try {
                serviceTagsFileStream = new FileInputStream(f);
                serviceTagsFileURL = f.toURI().toURL();
            } catch (FileNotFoundException exception) {
                LOG.error("Error processing input file:" + serviceTagsFileName
                        + " or no privilege for reading file " + serviceTagsFileName, exception);
            } catch (MalformedURLException malformedException) {
                LOG.error("Error processing input file:" + serviceTagsFileName + " cannot be converted to URL "
                        + serviceTagsFileName, malformedException);
            }
        } else {

            URL fileURL = getClass().getResource(serviceTagsFileName);
            if (fileURL == null) {
                if (!serviceTagsFileName.startsWith("/")) {
                    fileURL = getClass().getResource("/" + serviceTagsFileName);
                }
            }

            if (fileURL == null) {
                fileURL = ClassLoader.getSystemClassLoader().getResource(serviceTagsFileName);
                if (fileURL == null) {
                    if (!serviceTagsFileName.startsWith("/")) {
                        fileURL = ClassLoader.getSystemClassLoader().getResource("/" + serviceTagsFileName);
                    }
                }
            }

            if (fileURL != null) {

                try {
                    serviceTagsFileStream = fileURL.openStream();
                    serviceTagsFileURL = fileURL;
                } catch (Exception exception) {
                    LOG.error(serviceTagsFileName + " is not a file", exception);
                }
            } else {
                LOG.warn("Error processing input file: URL not found for " + serviceTagsFileName
                        + " or no privilege for reading file " + serviceTagsFileName);
            }
        }

        if (serviceTagsFileStream != null) {
            try {
                serviceTagsFileStream.close();
            } catch (Exception e) {
                // Ignore
            }
        }

    } else {
        LOG.error(
                "FATAL: Cannot find service/serviceDef/serviceTagsFile to use for retrieving tags. Will NOT be able to retrieve tags.");
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== init() : serviceTagsFileName=" + serviceTagsFileName);
    }
}

From source file:org.kepler.gui.AboutAction.java

/**
 * Invoked when an action occurs.//w w  w .  j  a  v a 2 s.  c o  m
 * 
 * @param e
 *            ActionEvent
 */
public void actionPerformed(ActionEvent e) {

    // must call this first...
    super.actionPerformed(e);
    ConfigurationProperty commonProperty = ConfigurationManager.getInstance()
            .getProperty(ConfigurationManager.getModule("common"));
    String splashname = commonProperty.getProperty("splash.image").getValue();
    final URL splashURL = ClassLoader.getSystemClassLoader().getResource(splashname);
    SplashWindow.splash(splashURL, true);
}

From source file:org.hobbit.core.run.ComponentStarter.java

/**
 * This method simply creates an instance of the given class by calling a
 * constructor that needs no arguments and cats the newly created instance into
 * a {@link Component} instance. Note that this method assumes that a) there is
 * a constructor that needs no arguments to be executed and b) the class with
 * the given name is implementing the {@link Constructor} interface.
 *
 * @param className/*from   w  w  w . j  a va  2  s . c  o  m*/
 *            the name of the class implementing the {@link Component}
 *            interface.
 * @return an instance of that class.
 * @throws ClassNotFoundException
 *             - If the class with the given name can not be found.
 * @throws NoSuchMethodException
 *             - If there is no constructor that needs no parameters.
 * @throws SecurityException
 *             - If the constructor can not be accessed because of security
 *             policies.
 * @throws InstantiationException
 *             - If the class with the given class name represents an abstract
 *             class.
 * @throws IllegalAccessException
 *             - If the Constructor object is enforcing Java language access
 *             control and the underlying constructor is inaccessible.
 * @throws IllegalArgumentException
 *             - If the number of actual and formal parameters differ; if an
 *             unwrapping conversion for primitive arguments fails; or if, after
 *             possible unwrapping, a parameter value cannot be converted to the
 *             corresponding formal parameter type by a method invocation
 *             conversion; if this constructor pertains to an enum type. (Should
 *             not occur)
 * @throws InvocationTargetException
 *             - If the constructor throws an exception.
 */
private static Component createComponentInstance(String className)
        throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    Class<?> componentClass = ClassLoader.getSystemClassLoader().loadClass(className);
    Constructor<?> constructor = componentClass.getConstructor();
    return Component.class.cast(constructor.newInstance());
}