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.jboss.rusheye.parser.Parser.java

public void parseResource(String resourceName) {
    InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceName);
    parseStream(inputStream);
}

From source file:at.ac.tuwien.infosys.jcloudscale.classLoader.simple.RemoteClassProvider.java

@Override
public void onMessage(Message message) {
    String className = null;// w w w  .  j av a2 s . c om

    try {
        className = ((ClassRequest) ((ObjectMessage) message).getObject()).className;

        log.fine("Message received:" + className);

        // we expect sender to specify the query he's waiting response into the JMSReplyTo
        Destination destination = message.getJMSReplyTo();
        UUID correlationId = UUID.fromString(message.getJMSCorrelationID());

        // preparing class bytecode.
        byte[] bytecode = null;

        try {
            String classPath = className.replace('.', '/') + ".class";//TODO: use utils.
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(classPath);

            // If the class cannot be found, attempt to find a resource with the requested name
            if (is == null) {
                try {
                    ClassPathResource resource = new ClassPathResource(className);
                    if (resource.exists()) {
                        is = resource.getInputStream();
                    }
                } catch (IOException e) {
                    // Ignore
                }
            }

            if (is == null)
                log.severe(String.format("Requested class %s was not found.", className));
            else
                bytecode = RemoteClassLoaderUtils.getByteArray(is);

        } catch (Exception ex) {
            log.severe("Failed to provide required class " + className + ": " + ex.toString());
            ex.printStackTrace();
        } finally {
            mq.respond(new ClassResponse(bytecode), destination, correlationId);
        }

    } catch (JMSException e) {
        log.severe("Failed to process message (" + className + "): " + e.toString());
        e.printStackTrace();
    }
}

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

/**
 * Constructor./*from  w  w  w  . java  2 s  .c  om*/
 *
 * @param textOutput
 */
public LogoPanel(TorgoTextConsole textOutput) {
    console = textOutput;
    turtleState = new TurtleState();
    turtleState.penup = false;
    turtleState.showTurtle = true;
    URL resource = ClassLoader.getSystemClassLoader().getResource("turtle.png");
    try {
        if (resource != null) {
            turtle = ImageIO.read(resource);
        }
    } catch (IOException ex) {
        org.tros.utils.logging.Logging.getLogFactory().getLogger(LogoPanel.class).fatal(null, ex);
    }
}

From source file:de.fuberlin.wiwiss.r2r.FunctionFactoryLoader.java

/**
 * tries to instantiate an FunctionFactory object.
 * It tries to load the class referenced by the TransformationFunction URI from the class path first.
 * The it tries to load it from the code location.
 * @param URI The URI of the TransformationFunction
 * @return the FunctionFactory object described by the information found at the given URI or null.
 * @throws MalformedURLException//ww  w . java  2 s.c  o m
 */
public FunctionFactory getFunctionFactory(String URI) throws MalformedURLException {
    boolean loadFromURLs = Config.getProperty("r2r.FunctionManager.loadFromURLs", "false")
            .equalsIgnoreCase("true");
    FunctionFactory functionFactory = null;
    String codeLocation = null;
    String qualifiedClassName = null;
    String error = null;
    String query = "DESCRIBE <" + URI + ">";
    Model model = repository.executeDescribeQuery(query);
    if (model.isEmpty()) {
        if (log.isDebugEnabled())
            log.debug("External Function <" + URI + "> not found in repository.");
        return null;
    }
    Resource funcRes = model.getResource(URI);
    StmtIterator it = funcRes.listProperties(model.getProperty(R2R.qualifiedClassName));
    if (it.hasNext())
        qualifiedClassName = it.next().getString();
    else {
        if (log.isDebugEnabled())
            log.debug("External Function <" + URI + "> did not specify a qualified class name for loading!");
        return null;
    }
    try {
        // First try to load from class path
        functionFactory = loadFunctionFactory(qualifiedClassName, ClassLoader.getSystemClassLoader());
        // If FunctionFactory has been loaded, return it
        if (functionFactory != null)
            return functionFactory;

        if (!loadFromURLs) {
            if (log.isDebugEnabled())
                log.debug("External Function <" + URI
                        + "> could not be loaded from class path and loading by URL is disabled!");
            return null;
        }

        // Now try the original code location
        it = funcRes.listProperties(model.getProperty(R2R.codeLocation));
        if (it.hasNext())
            codeLocation = it.next().getString();
        else {
            if (log.isDebugEnabled())
                log.debug("External Function <" + URI
                        + "> could not be loaded from class path and did not specify any further code location!");
            return null;
        }

        final String cl = codeLocation;
        URLClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
            public URLClassLoader run() {
                try {
                    return new URLClassLoader(new URL[] { new URL(cl) });
                } catch (MalformedURLException e) {
                    if (log.isDebugEnabled())
                        log.debug("Malformed URL for code location: " + cl);
                    return null;
                }
            }
        });
        functionFactory = loadFunctionFactory(qualifiedClassName, loader);
        if (functionFactory != null)
            return functionFactory;
        else {
            if (log.isDebugEnabled())
                log.debug("External Function <" + URI + "> could not be loaded: class " + qualifiedClassName
                        + " could not be loaded from " + codeLocation + ".");
            return null;
        }
    } catch (InstantiationException e) {
        error = e.toString();
    } catch (IllegalAccessException e) {
        error = e.toString();
    } catch (ClassCastException e) {
        error = e.toString();
    }
    if (error != null && log.isDebugEnabled())
        log.debug("External Function <" + URI + "> could not be loaded: " + error);
    return functionFactory;
}

From source file:org.apache.xmlgraphics.util.Service.java

/**
 * Returns an iterator where each element should implement the
 * interface (or subclass the baseclass) described by cls.  The
 * Classes are found by searching the classpath for service files
 * named: 'META-INF/services/&lt;fully qualified classname&gt; that list
 * fully qualifted classnames of classes that implement the
 * service files classes interface.  These classes must have
 * default constructors if returnInstances is true.
 *
 * @param cls The class/interface to search for providers of.
 * @param returnInstances true if the iterator should return instances rather than class names.
 *///from  w  w  w  .j a v  a2  s  .  co  m
public static synchronized Iterator providers(Class cls, boolean returnInstances) {
    String serviceFile = "META-INF/services/" + cls.getName();
    Map cacheMap = (returnInstances ? instanceMap : classMap);

    List l = (List) cacheMap.get(serviceFile);
    if (l != null) {
        return l.iterator();
    }

    l = new java.util.ArrayList();
    cacheMap.put(serviceFile, l);

    ClassLoader cl = null;
    try {
        cl = cls.getClassLoader();
    } catch (SecurityException se) {
        // Ooops! can't get his class loader.
    }
    // Can always request your own class loader. But it might be 'null'.
    if (cl == null) {
        cl = Service.class.getClassLoader();
    }
    if (cl == null) {
        cl = ClassLoader.getSystemClassLoader();
    }

    // No class loader so we can't find 'serviceFile'.
    if (cl == null) {
        return l.iterator();
    }

    Enumeration e;
    try {
        e = cl.getResources(serviceFile);
    } catch (IOException ioe) {
        return l.iterator();
    }

    while (e.hasMoreElements()) {
        try {
            URL u = (URL) e.nextElement();

            InputStream is = u.openStream();
            Reader r = new InputStreamReader(is, "UTF-8");
            BufferedReader br = new BufferedReader(r);
            try {
                String line = br.readLine();
                while (line != null) {
                    try {
                        // First strip any comment...
                        int idx = line.indexOf('#');
                        if (idx != -1) {
                            line = line.substring(0, idx);
                        }

                        // Trim whitespace.
                        line = line.trim();

                        // If nothing left then loop around...
                        if (line.length() == 0) {
                            line = br.readLine();
                            continue;
                        }

                        if (returnInstances) {
                            // Try and load the class
                            Object obj = cl.loadClass(line).newInstance();
                            // stick it into our vector...
                            l.add(obj);
                        } else {
                            l.add(line);
                        }
                    } catch (Exception ex) {
                        // Just try the next line
                    }
                    line = br.readLine();
                }
            } finally {
                IOUtils.closeQuietly(br);
                IOUtils.closeQuietly(is);
            }
        } catch (Exception ex) {
            // Just try the next file...
        } catch (LinkageError le) {
            // Just try the next file...
        }
    }
    return l.iterator();
}

From source file:ren.hankai.cordwood.core.ApplicationInitializer.java

/**
 * ??//from ww  w  . j a v a 2s.co  m
 *
 * @author hankai
 * @since Oct 13, 2016 9:52:48 AM
 */
private static void printClassPaths() {
    logger.info("Class paths:");
    final URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
    final URL[] urls = cl.getURLs();
    for (final URL url : urls) {
        logger.info(url.getPath());
    }
}

From source file:wasr.UserSettings.java

public static void copyResource(String fromResource, File toFile) {
    LOG.info("Loading from resource: " + fromResource);
    InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(fromResource);
    if (in == null) {
        in = ClassLoader.getSystemClassLoader().getResourceAsStream(RESOURCE_FOLDER + fromResource);
    }//from w ww  . ja  va  2  s .c  om

    if (in == null) {
        LOG.error("Default resource could not be located: " + fromResource);
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        LOG.debug("Reading from resource...");
        try {
            int b = in.read();

            while (b > -1) {
                baos.write(b);
                b = in.read();
            }

            LOG.debug("Writing to file...");

            baos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();

        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        try {
            if (!toFile.exists()) {
                toFile.createNewFile(); // not sure if this is needed
            }
            FileUtils.copyInputStreamToFile(bais, toFile);
            bais.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

@SuppressWarnings("unchecked")
private Class<? extends Servlet> findServlet(String classname) {
    try {/*from  w w w . j  a v a  2s .co  m*/
        return (Class<? extends Servlet>) ClassLoader.getSystemClassLoader().loadClass(classname);
    } catch (ClassNotFoundException e) {
        throw new ConfigurationException(String.format("'%s' servlet cannot be found", classname), e);
    }
}

From source file:org.castor.jaxb.CastorJAXBContextFactoryTest.java

/**
 * Tests the {@link CastorJAXBContextFactory#createContext(String, ClassLoader, java.util.Map)}
 * method when properties is null.//from   ww  w .ja va  2  s. c  om
 * <p/>
 * {@link IllegalArgumentException} is expected.
 *
 * @throws Exception
 *             if any error occurs during test
 */
@Test(expected = IllegalArgumentException.class)
public void testCreateContextContextPathNull3() throws Exception {

    CastorJAXBContextFactory.createContext("org.castor.jaxb.entities", ClassLoader.getSystemClassLoader(),
            null);
}

From source file:com.soteradefense.dga.DGARunner.java

public void run(String[] args) throws Exception {
    System.out.println("command line args: ");
    for (String arg : args)
        System.out.print(arg + " ");

    System.out.println();/*from  www.jav a2s . com*/

    Options options = DGACommandLineUtil.generateOptions();
    if (args.length < 4)
        DGACommandLineUtil.printUsageAndExit(options);

    String libDir = args[0];
    String analytic = args[1].toLowerCase();
    String inputPath = args[2];
    String outputPath = args[3];

    if (!supportedAnalytics.contains(analytic)) {
        DGACommandLineUtil.printUsageAndExit(options);
    }

    String[] subsetArguments = new String[args.length - 4];
    for (int i = 0; i < subsetArguments.length; i++) {
        subsetArguments[i] = args[i + 4];
    }
    DGAConfiguration commandLineConf = DGACommandLineUtil.parseCommandLine(subsetArguments, options);
    String logLevel = commandLineConf.getCustomArgumentProperties().get(DGALoggingUtil.DGA_LOG_LEVEL);
    DGALoggingUtil.setDGALogLevel(logLevel);

    try {
        InputStream configurationIS = ClassLoader.getSystemClassLoader().getResourceAsStream("dga-config.xml");

        DGAConfiguration fileConf = DGAXMLConfigurationParser.parse(configurationIS);

        if (analytic.equals("wcc")) {
            logger.info("Analytic: Weakly Connected Components");
            DGAConfiguration requiredConf = new DGAConfiguration();
            requiredConf.setDGAGiraphProperty("-eif", DGATextEdgeValueInputFormat.class.getCanonicalName());
            requiredConf.setDGAGiraphProperty("-eof", DGAEdgeTTTOutputFormat.class.getCanonicalName());
            requiredConf.setDGAGiraphProperty("-eip", inputPath);
            requiredConf.setDGAGiraphProperty("-op", outputPath);
            requiredConf.setDGAGiraphProperty("-esd", outputPath);
            DGAConfiguration minimalDefaults = new DGAConfiguration();
            minimalDefaults.setCustomProperty(DGAEdgeTTTOutputFormat.WRITE_VERTEX_VALUE, "true");
            DGAConfiguration finalConf = DGAConfiguration.coalesce(minimalDefaults, fileConf, commandLineConf,
                    requiredConf);

            finalConf.setLibDir(libDir);

            String[] giraphArgs = finalConf.convertToCommandLineArguments(
                    WeaklyConnectedComponentComputation.class.getCanonicalName());
            System.exit(ToolRunner.run(new GiraphRunner(), giraphArgs));

        } else if (analytic.equals("hbse")) {
            logger.info("Analytic: High Betweenness Set Extraction");
            DGAConfiguration requiredConf = new DGAConfiguration();
            requiredConf.setDGAGiraphProperty("-eif", DGATextEdgeValueInputFormat.class.getCanonicalName());
            requiredConf.setDGAGiraphProperty("-vof", HBSEOutputFormat.class.getCanonicalName());
            requiredConf.setDGAGiraphProperty("-eip", inputPath);
            requiredConf.setDGAGiraphProperty("-mc", HBSEMasterCompute.class.getCanonicalName());
            requiredConf.setDGAGiraphProperty("-op", outputPath);
            requiredConf.setDGAGiraphProperty("-vsd", outputPath);
            DGAConfiguration minimalDefaults = new DGAConfiguration();
            minimalDefaults.setCustomProperty(HBSEConfigurationConstants.BETWEENNESS_SET_MAX_SIZE, "10");
            minimalDefaults.setCustomProperty(HBSEConfigurationConstants.BETWEENNESS_OUTPUT_DIR, outputPath);
            minimalDefaults.setCustomProperty(HBSEConfigurationConstants.PIVOT_BATCH_SIZE, "10");
            minimalDefaults.setCustomProperty(HBSEConfigurationConstants.PIVOT_BATCH_SIZE_INITIAL, "10");
            minimalDefaults.setCustomProperty(HBSEConfigurationConstants.TOTAL_PIVOT_COUNT, "5");
            DGAConfiguration finalConf = DGAConfiguration.coalesce(minimalDefaults, fileConf, commandLineConf,
                    requiredConf);

            finalConf.setLibDir(libDir);

            String[] giraphArgs = finalConf
                    .convertToCommandLineArguments(HBSEComputation.class.getCanonicalName());
            System.exit(ToolRunner.run(new GiraphRunner(), giraphArgs));
        } else if (analytic.equals("louvain")) {
            logger.info("Analytic: Louvain Modularity");
            DGAConfiguration partialConfiguration = DGAConfiguration.coalesce(fileConf, commandLineConf);
            partialConfiguration.setDGAGiraphProperty("-eip", inputPath);
            partialConfiguration.setDGAGiraphProperty("-op", outputPath);

            partialConfiguration.setLibDir(libDir);

            LouvainRunner louvainRunner = new LouvainRunner();
            System.exit(louvainRunner.runUntilComplete(inputPath, outputPath, partialConfiguration));
        } else if (analytic.equals("lc")) {
            logger.info("Analytic: Leaf Compression");
            DGAConfiguration requiredConf = new DGAConfiguration();
            requiredConf.setDGAGiraphProperty("-eif", DGATextEdgeValueInputFormat.class.getCanonicalName());
            requiredConf.setDGAGiraphProperty("-eof", DGAEdgeTTTOutputFormat.class.getCanonicalName());
            requiredConf.setDGAGiraphProperty("-eip", inputPath);
            requiredConf.setDGAGiraphProperty("-op", outputPath);
            requiredConf.setDGAGiraphProperty("-esd", outputPath);
            DGAConfiguration finalConf = DGAConfiguration.coalesce(fileConf, commandLineConf, requiredConf);

            finalConf.setLibDir(libDir);

            String[] giraphArgs = finalConf
                    .convertToCommandLineArguments(LeafCompressionComputation.class.getCanonicalName());
            System.exit(ToolRunner.run(new GiraphRunner(), giraphArgs));
        } else if (analytic.equals("pr")) {
            logger.info("Analytic: PageRank");
            DGAConfiguration requiredConf = new DGAConfiguration();
            requiredConf.setDGAGiraphProperty("-eif", DGATextEdgeValueInputFormat.class.getCanonicalName());
            requiredConf.setDGAGiraphProperty("-vof", DGAVertexOutputFormat.class.getCanonicalName());
            requiredConf.setDGAGiraphProperty("-eip", inputPath);
            requiredConf.setDGAGiraphProperty("-mc", PageRankMasterCompute.class.getCanonicalName());
            requiredConf.setDGAGiraphProperty("-op", outputPath);
            requiredConf.setDGAGiraphProperty("-vsd", outputPath);
            requiredConf.setCustomProperty(DGAEdgeTDTOutputFormat.WRITE_VERTEX_VALUE, "true");
            DGAConfiguration finalConf = DGAConfiguration.coalesce(fileConf, commandLineConf, requiredConf);

            finalConf.setLibDir(libDir);

            String[] giraphArgs = finalConf
                    .convertToCommandLineArguments(PageRankComputation.class.getCanonicalName());
            System.exit(ToolRunner.run(new GiraphRunner(), giraphArgs));
        }

    } catch (Exception e) {
        logger.error("Unable to run analytic; ", e);
    }
}