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:consumer.kafka.client.Consumer.java

private void init(String[] args) throws Exception {

    Options options = new Options();
    this._props = new Properties();

    options.addOption("p", true, "properties filename from the classpath");
    options.addOption("P", true, "external properties filename");

    OptionBuilder.withArgName("property=value");
    OptionBuilder.hasArgs(2);/*from   ww w  .ja  v a  2 s .  c o  m*/
    OptionBuilder.withValueSeparator();
    OptionBuilder.withDescription("use value for given property");
    options.addOption(OptionBuilder.create("D"));

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption('p')) {
        this._props.load(ClassLoader.getSystemClassLoader().getResourceAsStream(cmd.getOptionValue('p')));
    }
    if (cmd.hasOption('P')) {
        File file = new File(cmd.getOptionValue('P'));
        FileInputStream fStream = new FileInputStream(file);
        this._props.load(fStream);
    }
    this._props.putAll(cmd.getOptionProperties("D"));

}

From source file:org.wso2.extension.siddhi.io.jms.source.client.JMSClient.java

public void sendJMSEvents(String filePath, String topicName, String queueName, String format, String broker,
        String providerURL) {/*from   w w  w .j  a  v  a2 s. co m*/
    if (format == null || "map".equals(format)) {
        format = "csv";
    }
    if ("".equalsIgnoreCase(broker)) {
        broker = "activemq";
    }
    Session session = null;
    Properties properties = new Properties();
    if (!"activemq".equalsIgnoreCase(broker) && !"mb".equalsIgnoreCase(broker)
            && !"qpid".equalsIgnoreCase(broker)) {
        log.error("Please enter a valid JMS message broker. (ex: activemq, mb, qpid");
        return;
    }
    try {
        if (topicName != null && !"".equalsIgnoreCase(topicName)) {
            TopicConnection topicConnection;
            TopicConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                // to provide custom provider urls
                if (providerURL != null) {
                    properties.put(Context.PROVIDER_URL, providerURL);
                }
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                topicConnection = connFactory.createTopicConnection();
                topicConnection.start();
                session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Topic topic = session.createTopic(topicName);
                    MessageProducer producer = session.createProducer(topic);
                    List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + topicName + "' topic");
                            JMSClientUtil.publishMapMessage(producer, session, messagesList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + topicName + "' topic");
                            JMSClientUtil.publishTextMessage(producer, session, messagesList);
                        }
                        log.info("All Order Messages sent");
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        topicConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else if (queueName != null && !queueName.equalsIgnoreCase("")) {
            QueueConnection queueConnection;
            QueueConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                queueConnection = connFactory.createQueueConnection();
                queueConnection.start();
                session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Queue queue = session.createQueue(queueName);
                    MessageProducer producer = session.createProducer(queue);
                    List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + queueName + "' queue");
                            JMSClientUtil.publishMapMessage(producer, session, messagesList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + queueName + "' queue");
                            JMSClientUtil.publishTextMessage(producer, session, messagesList);
                        }
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        queueConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else {
            log.error("Enter queue name or topic name to be published!");
        }
    } catch (Exception e) {
        log.error("Error when publishing" + e.getMessage(), e);
    }
}

From source file:org.apache.axiom.util.stax.dialect.StAXDialectDetector.java

/**
 * Get the URL corresponding to the root folder of the classpath entry from which a given
 * resource is loaded. This URL can be used to load other resources from the same classpath
 * entry (JAR file or directory).// w ww. j av a  2  s  .c  o  m
 * 
 * @return the root URL or <code>null</code> if the resource can't be found or if it is not
 *         possible to determine the root URL
 */
private static URL getRootUrlForResource(ClassLoader classLoader, String resource) {
    if (classLoader == null) {
        // A null class loader means the bootstrap class loader. In this case we use the
        // system class loader. This is safe since we can assume that the system class
        // loader uses parent first as delegation policy.
        classLoader = ClassLoader.getSystemClassLoader();
    }
    URL url = classLoader.getResource(resource);
    if (url == null) {
        return null;
    }
    String file = url.getFile();
    if (file.endsWith(resource)) {
        try {
            return new URL(url.getProtocol(), url.getHost(), url.getPort(),
                    file.substring(0, file.length() - resource.length()));
        } catch (MalformedURLException ex) {
            return null;
        }
    } else {
        return null;
    }
}

From source file:de.tudarmstadt.lt.ltbot.postprocessor.DecesiveValuePerplexityTest.java

@Test
public void test_local() throws Exception {
    File f = new File(ClassLoader.getSystemClassLoader().getResource("untokenizable.txt").getPath());
    String text = FileUtils.readFileToString(f, "UTF-8");
    _prio.computePerplexity(text);//, "http://localtest/test");
}

From source file:org.tamilunicodeconverter.converter.BaminiConverter.java

protected URL getScriptUrl() {
    return ClassLoader.getSystemClassLoader().getResource(SCRIPT_FILE);
}

From source file:org.talend.metadata.managment.hive.HiveClassLoaderFactory.java

/**
 * Gets an instance of <code>ClassLoader</code> by the given argument, it invokes {
 * {@link #getHive1ClassLoader(IMetadataConnection)} and {@link #getHive2ClassLoader(IMetadataConnection)}. Added by
 * Marvin Wang on Mar 13, 2013.//  w  w w  .  j  a  v  a2 s.  c  o m
 * 
 * @param metadataConn
 * @return
 */
public ClassLoader getClassLoader(IMetadataConnection metadataConn) {
    if (!Platform.isRunning()) {
        return ClassLoader.getSystemClassLoader();
    }
    ClassLoader classloader = null;
    String url = metadataConn.getUrl();

    // url = "jdbc:hive2://";
    if (url != null) {
        if (url.startsWith(DatabaseConnConstants.HIVE_2_URL_FORMAT)) {
            classloader = getHive2ClassLoader(metadataConn);
        } else if (url.startsWith(DatabaseConnConstants.HIVE_1_URL_FORMAT)) {
            classloader = getHive1ClassLoader(metadataConn);
        } else {
            // do nothing
        }
    }

    appendExtraJars(metadataConn, classloader);

    return classloader;
}

From source file:org.epri.pt2.DNP3PacketReassemblyTest.java

protected void setUp() throws Exception {
    dnp3File = new File(ClassLoader.getSystemClassLoader().getResource("packets/81_byte_packet.bin").getPath());

    appData = FileUtils.readFileToByteArray(dnp3File);

    dnp3AppPacket = new DNP3ApplicationPacketDO();
    dnp3AppPacket.setData(appData);// w  ww.j av a2 s.  c  o  m

    packetData = dnp3AppPacket.updatePacket();

    dnp3AppPacket.initialize();

    dnp3AppPacket.addData(packetData);
}

From source file:com.glaf.core.util.ClassUtils.java

public static Class<?> loadClass(String className, ClassLoader classLoader) {
    Class<?> cls = ClassUtils.cache.get(className);
    if (cls == null) {
        try {//from w w w.jav  a  2s  .c o m
            cls = Class.forName(className);
        } catch (Exception e) {
        }

        if (cls == null && classLoader != null) {
            try {
                cls = classLoader.loadClass(className);
            } catch (Exception e) {
            }
        }

        if (cls == null) {
            try {
                cls = ClassUtils.class.getClassLoader().loadClass(className);
            } catch (Exception e) {
            }
        }

        if (cls == null) {
            try {
                cls = Thread.currentThread().getContextClassLoader().loadClass(className);
            } catch (Exception e) {
            }
        }

        if (cls == null) {
            try {
                cls = ClassLoader.getSystemClassLoader().loadClass(className);
            } catch (Exception e) {
            }
        }

        if (cls == null) {

        }

        if (cls != null) {
            ClassUtils.cache.put(className, cls);
        } else {
            throw new RuntimeException("Unable to load class '" + className + "'");
        }
    }

    return cls;
}

From source file:org.apache.drill.jdbc.ITTestShadedJar.java

@Test
public void testDatabaseVersion() throws Exception {

    // print class path for debugging
    System.out.println("java.class.path:");
    System.out.println(System.getProperty("java.class.path"));

    final URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);/*from   w w w. j  ava 2 s.c  om*/
    method.invoke(loader, getJdbcUrl());

    Class<?> clazz = loader.loadClass("org.apache.drill.jdbc.Driver");
    try {
        Driver driver = (Driver) clazz.newInstance();
        try (Connection c = driver.connect("jdbc:drill:drillbit=localhost:31010", null)) {
            DatabaseMetaData metadata = c.getMetaData();
            assertEquals("Apache Drill JDBC Driver", metadata.getDriverName());
            assertEquals("Apache Drill Server", metadata.getDatabaseProductName());
            //assertEquals()
        }
    } catch (Exception ex) {
        throw ex;
    }

}

From source file:org.apache.jena.atlas.logging.java.ConsoleHandlerStream.java

public ConsoleHandlerStream(OutputStream outputStream) {
    super(protectStdOutput(outputStream), new TextFormatter());

    LogManager manager = LogManager.getLogManager();
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    String cname = getClass().getName();

    // -- Level/*from   www  . jav  a 2  s.  c om*/
    Level level = Level.INFO;
    String pLevel = getProperty(manager, cname, "level");
    if (pLevel != null)
        level = Level.parse(pLevel);
    setLevel(level);

    // -- Formatter
    // The default is TextFormatter above
    // (we had to pass a Formatter of some kind to super(,)).
    String pFormatter = getProperty(manager, cname, "formatter");
    if (pFormatter != null) {
        try {
            Class<?> cls = classLoader.loadClass(pFormatter);
            setFormatter((Formatter) cls.newInstance());
        } catch (Exception ex) {
            System.err.println("Problems setting the logging formatter");
            ex.printStackTrace(System.err);
        }
    }

    // -- Filter
    String pFilter = getProperty(manager, cname, "filter");
    if (pFilter != null) {
        try {
            Class<?> cls = classLoader.loadClass(pFilter);
            setFilter((Filter) cls.newInstance());
        } catch (Exception ex) {
            System.err.println("Problems setting the logging filter");
            ex.printStackTrace(System.err);
        }
    }

    // -- Encoding : Default UTF-8
    String pEncoding = getProperty(manager, cname, "encoding");
    if (pEncoding == null)
        pEncoding = StandardCharsets.UTF_8.name();
    try {
        setEncoding(pEncoding);
    } catch (Exception e) {
        // That should work for UTF-8 as it is a required charset. 
        System.err.print("Failed to set encoding: " + e.getMessage());
    }
}