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:com.google.gdt.eclipse.designer.hosted.tdt.HostedModeSupport.java

/**
 * Creates the special {@link ClassLoader}'s to work with GWT "dev" classes and "user" classes.
 *///  w  ww  . j a  va 2s .  c om
private void createClassLoaders() throws Exception {
    if (javaProject == null) {
        projectClassLoader = ClassLoader.getSystemClassLoader();
    } else {
        ClassLoader devClassLoader = getDevClassLoader0();
        projectClassLoader = new LocalProjectClassLoader(moduleDescription.getURLs(), devClassLoader);
    }
}

From source file:org.apache.storm.utils.Utils.java

@VisibleForTesting
public static void resetClassLoaderForJavaDeSerialize() {
    Utils.cl = ClassLoader.getSystemClassLoader();
}

From source file:SecuritySupport.java

ClassLoader getSystemClassLoader() {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader cl = null;
            try {
                cl = ClassLoader.getSystemClassLoader();
            } catch (SecurityException ex) {
            }//from   ww w.  ja  v  a 2  s. com
            return cl;
        }
    });
}

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

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

    spoofData = FileUtils.readFileToByteArray(dnp3File);

    listen = new InetSocketAddress("localhost", 8080);
    StreamInterceptor<InetSocketAddress, InetSocketAddress> si = new StreamInterceptor<InetSocketAddress, InetSocketAddress>() {
        public void connected(StreamHandle cs, StreamHandle sc, InetSocketAddress cl, InetSocketAddress sl) {
            logger.info("Connected " + cl + " to " + sl);
            if (!handlers.contains(cs)) {
                handlers.add(cs);/*from w w w  .  j  ava2 s  .  co m*/
            } else {
                fail("Connect called twice for the same handler");
            }
            if (!handlers.contains(sc)) {
                handlers.add(sc);
            } else {
                fail("Connect called twice for the same handler");
            }
        }

        public void inputClosed(StreamHandle handle) {
            logger.info(handle + " : input closed, closing output");
            handle.close();
            if (handlers.contains(handle)) {
                handlers.remove(handle);
            } else {
                fail("Closed called twice for the same handler");
            }
        }

        public void readException(StreamHandle handle, IOException ioe) {
            logger.info(handle + ": error reading: " + ioe);
            if (!handlers.contains(handle))
                fail("readException called for nonexistent handler");
        }

        /**
         * StreamHandle handle - An instance of RelayInterceptor This can be
         * used to identify the direction of the connection
         */
        public void received(StreamHandle handle, byte[] b, int off, int len) {

            // logger.info(handle + ": received '"
            // + bytesToHex(Arrays.copyOfRange(b, off, len)));
            //
            // try {
            // handle.write(b, off, len);
            // } catch (IOException ioe) {
            // logger.info(handle + ": error writing to the output: "
            // + ioe);
            // }

            /**
             * Parse initial packet information to determine what to do with
             * it
             */
            DNP3LinkHeader linkHeader = new DNP3LinkHeader(Arrays.copyOfRange(b, off, len));

            /*
             * Have we seen this conversation stream before? If so, lets add
             * to it
             */
            DNP3Flow flow = new DNP3Flow(linkHeader.getSource(), linkHeader.getDestination());

            if (!flowMap.containsKey(flow)) {
                flowMap.put(flow, new DNP3ApplicationPacketDO());
            }

            DNP3ApplicationPacketDO appPacket = flowMap.get(flow);

            if (appPacket.addData(Arrays.copyOfRange(b, off, len))) {
                logger.info("We received a DNP3 transport packet or app packet");
                if (appPacket.isAppPacket()) {
                    logger.info("This is an app packet");

                    byte[] appPacketData;

                    /*
                     * Our criteria for replacing the packet is it is
                     * greater than or equal to 1077 bytes
                     */
                    if (appPacket.getData().length >= 1077) {
                        /*
                         * Perform a little packet reconstruction
                         */
                        logger.info("spoofing");
                        appPacket.setData(spoofData);

                        appPacketData = appPacket.updatePacket();

                    }
                    /* Otherwise this is the packet we want to spoof */
                    else {
                        appPacketData = appPacket.updatePacket();

                        logger.info("Spoofing response");
                    }

                    try {
                        handle.write(appPacketData, 0, appPacketData.length);
                    } catch (IOException ioe) {
                        logger.info(handle + ": error writing to the output: " + ioe);
                    }

                    appPacket.initialize();

                    /*
                     * Sometimes multiple DNP3 packets are packed into one,
                     * this makes sure that we process all of these as well.
                     */
                    while (appPacket.getRemainingData().length > 0) {
                        if (appPacket.addData(appPacket.getRemainingData())) {

                            /*
                             * add the completed packet to the list of
                             * packets
                             */
                            /*
                             * Our criteria for replacing the packet is it
                             * is greater than or equal to 1077 bytes
                             */
                            if (appPacket.getData().length >= 1077) {
                                /*
                                 * Perform a little packet reconstruction
                                 */
                                logger.info("spoofing");
                                appPacket.setData(spoofData);

                                appPacketData = appPacket.updatePacket();

                            }
                            /* Otherwise this is the packet we want to spoof */
                            else {
                                appPacketData = appPacket.updatePacket();

                                logger.info("Spoofing response");
                            }

                            try {
                                handle.write(appPacketData, 0, appPacketData.length);
                            } catch (IOException ioe) {
                                logger.info(handle + ": error writing to the output: " + ioe);
                            }

                            /* reset the application packet */
                            appPacket.initialize();
                        }
                    }
                } else {
                    logger.info("Plain message");
                    try {
                        handle.write(appPacket.getData(), 0, appPacket.getData().length);
                    } catch (IOException ioe) {
                        logger.info(handle + ": error writing to the output: " + ioe);
                    }

                    // Reset the packet
                    appPacket.initialize();
                }
            }

            if (!handlers.contains(handle))
                fail("receive called for nonexistent handler");

        }

    };
    ch = new InterceptingConnectionHandler(si);

    ConnectionHandler socks = new SocksConnectionHandler(ch, true); // true
    // ->
    // autodetect
    // SOCKS
    Server proxy = new Server(listen, socks);

    proxy.start();
}

From source file:org.apache.accumulo.start.classloader.vfs.AccumuloReloadingVFSClassLoaderTest.java

@Test
@Ignore/*from w w w .j  a v  a2s.  c o  m*/
public void testFastDeleteAndReAdd() throws Exception {
    FileObject testDir = vfs.resolveFile(folder1.getRoot().toURI().toString());
    FileObject[] dirContents = testDir.getChildren();

    AccumuloReloadingVFSClassLoader arvcl = new AccumuloReloadingVFSClassLoader(folderPath, vfs,
            new ReloadingClassLoader() {

                @Override
                public ClassLoader getClassLoader() {
                    return ClassLoader.getSystemClassLoader();
                }
            }, 1000, true);

    FileObject[] files = ((VFSClassLoader) arvcl.getClassLoader()).getFileObjects();
    Assert.assertArrayEquals(createFileSystems(dirContents), files);

    Class<?> clazz1 = arvcl.getClassLoader().loadClass("test.HelloWorld");
    Object o1 = clazz1.newInstance();
    Assert.assertEquals("Hello World!", o1.toString());

    // Check that the class is the same before the update
    Class<?> clazz1_5 = arvcl.getClassLoader().loadClass("test.HelloWorld");
    Assert.assertEquals(clazz1, clazz1_5);

    assertTrue(new File(folder1.getRoot(), "HelloWorld.jar").delete());

    // Update the class
    FileUtils.copyURLToFile(this.getClass().getResource("/HelloWorld.jar"), folder1.newFile("HelloWorld.jar"));

    // Wait for the monitor to notice
    // VFS-487 significantly wait to avoid failure
    Thread.sleep(7000);

    Class<?> clazz2 = arvcl.getClassLoader().loadClass("test.HelloWorld");
    Object o2 = clazz2.newInstance();
    Assert.assertEquals("Hello World!", o2.toString());

    // This is false because they are loaded by a different classloader
    Assert.assertFalse(clazz1.equals(clazz2));
    Assert.assertFalse(o1.equals(o2));

    arvcl.close();
}

From source file:org.apache.ranger.tagsync.source.file.FileTagSource.java

@Override
public boolean initialize(Properties props) {

    if (LOG.isDebugEnabled()) {
        LOG.debug("==> FileTagSource.initialize()");
    }/*from  w ww  . j av  a  2s  .c  om*/

    Properties properties;

    if (props == null || MapUtils.isEmpty(props)) {
        LOG.error("No properties specified for FileTagSource initialization");
        properties = new Properties();
    } else {
        properties = props;
    }

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

    boolean ret = true;

    serviceTagsFileName = TagSyncConfig.getTagSourceFileName(properties);

    if (StringUtils.isBlank(serviceTagsFileName)) {
        ret = false;
        LOG.error(
                "value of property 'ranger.tagsync.source.impl.class' is file and no value specified for property 'ranger.tagsync.filesource.filename'!");
    }

    if (ret) {

        fileModTimeCheckIntervalInMs = TagSyncConfig.getTagSourceFileModTimeCheckIntervalInMillis(properties);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Provided serviceTagsFileName=" + serviceTagsFileName);
            LOG.debug("'ranger.tagsync.filesource.modtime.check.interval':" + fileModTimeCheckIntervalInMs
                    + "ms");
        }

        InputStream serviceTagsFileStream = null;

        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
            }
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== FileTagSource.initialize(): sourceFileName=" + serviceTagsFileName + ", result=" + ret);
    }

    return ret;
}

From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java

@Parameterized.Parameters
public static Collection<Object[]> data() {
    final Configuration config = getBaseConfig();

    final ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    final String truststorePath = new File(classLoader.getResource("local127.truststore").getFile())
            .getAbsolutePath();//www. j  a v a2  s  .  c o m
    final String keystorePath = new File(classLoader.getResource("local127.keystore").getFile())
            .getAbsolutePath();

    final Configuration sslConfig = new Configuration(config);
    sslConfig.setBoolean(SecurityOptions.SSL_REST_ENABLED, true);
    sslConfig.setString(SecurityOptions.SSL_REST_TRUSTSTORE, truststorePath);
    sslConfig.setString(SecurityOptions.SSL_REST_TRUSTSTORE_PASSWORD, "password");
    sslConfig.setString(SecurityOptions.SSL_REST_KEYSTORE, keystorePath);
    sslConfig.setString(SecurityOptions.SSL_REST_KEYSTORE_PASSWORD, "password");
    sslConfig.setString(SecurityOptions.SSL_REST_KEY_PASSWORD, "password");

    final Configuration sslRestAuthConfig = new Configuration(sslConfig);
    sslRestAuthConfig.setBoolean(SecurityOptions.SSL_REST_AUTHENTICATION_ENABLED, true);

    return Arrays.asList(new Object[][] { { config }, { sslConfig }, { sslRestAuthConfig } });
}

From source file:eu.stork.peps.auth.engine.core.impl.SignP12.java

/**
 * Initialize the file configuration.//from w  ww.  j a  v a2s.c  om
 * 
 * @param fileConf name of the file configuration
 * 
 * @throws SAMLEngineException error at the load from  file configuration
 */
@Override
public void init(final String fileConf) throws SAMLEngineException {
    InputStream fileProperties = null;
    properties = new Properties();
    try {
        try {
            LOG.debug("Fichero a cargar " + fileConf);
            fileProperties = new FileInputStream(fileConf);
            properties.loadFromXML(fileProperties);
        } catch (Exception e) {
            LOG.error("Fallo al cargar el recurso externo. Se reintenta como fichero interno.");
            fileProperties = SignP12.class.getResourceAsStream("/" + fileConf);
            if (fileProperties == null) {
                fileProperties = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileConf);
                if (fileProperties == null) {
                    Enumeration<URL> files = ClassLoader.getSystemClassLoader().getResources(fileConf);
                    if (files != null && files.hasMoreElements()) {
                        LOG.info("Se han encontrado recurso/s. Se toma el primero.");
                        fileProperties = ClassLoader.getSystemClassLoader()
                                .getResourceAsStream(files.nextElement().getFile());
                    } else {
                        throw new IOException("No se pudo recuperar el fichero: " + fileConf, e);
                    }
                }
            }
            LOG.debug("Recuperados " + fileProperties.available() + " bytes");
            properties.loadFromXML(fileProperties);
        }
    } catch (InvalidPropertiesFormatException e) {
        LOG.info("Exception: invalid properties format.");
        throw new SAMLEngineException(e);
    } catch (IOException e) {
        LOG.info("Exception: invalid file: " + fileConf);
        throw new SAMLEngineException(e);
    } finally {
        IOUtils.closeQuietly(fileProperties);
    }
}

From source file:org.apache.airavata.datacat.parsers.gridchem.GridChemParser.java

private HashMap<String, String> loadAndParse(String classname, final FileReader reader) throws Exception {
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    Class parser = null;/* w ww . ja v  a  2s .c  o m*/
    try {
        //todo: handle unparsed documents and log and ignore
        parser = classLoader.loadClass(classname);
        Constructor parserConstructor = parser.getConstructor(FileReader.class);
        GridChemQueueParser queueParser = (GridChemQueueParser) parserConstructor.newInstance(reader);
        HashMap<String, String> parsedData = queueParser.getParsedData();
        return parsedData;
    } catch (ClassNotFoundException e) {
        logger.error("Could not load the class ..." + e.getMessage());
    } catch (NoSuchMethodException e) {
        logger.error("Could not load the constructor ... " + e.getMessage());
    } catch (InvocationTargetException e) {
        logger.error("Could not load the Class ... " + e.getMessage());
    } catch (InstantiationException e) {
        logger.error("Could not load the Class ... " + e.getMessage());
    } catch (IllegalAccessException e) {
        logger.error("Could not load the Class ... " + e.getMessage());
    }
    return null;
}

From source file:org.apache.hadoop.yarn.logaggregation.TestAggregatedLogsBlock.java

/**
 * Reading from logs should succeed (from a HAR archive) and they should be
 * shown in the AggregatedLogsBlock html.
 *
 * @throws Exception/*from ww  w .j  a  v  a 2  s . c  om*/
 */
@Test
public void testAggregatedLogsBlockHar() throws Exception {
    FileUtil.fullyDelete(new File("target/logs"));
    Configuration configuration = getConfiguration();

    URL harUrl = ClassLoader.getSystemClassLoader().getResource("application_1440536969523_0001.har");
    assertNotNull(harUrl);
    String path = "target/logs/admin/logs/application_1440536969523_0001"
            + "/application_1440536969523_0001.har";
    FileUtils.copyDirectory(new File(harUrl.getPath()), new File(path));

    AggregatedLogsBlockForTest aggregatedBlock = getAggregatedLogsBlockForTest(configuration, "admin",
            "container_1440536969523_0001_01_000001", "host1:1111");
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    PrintWriter printWriter = new PrintWriter(data);
    HtmlBlock html = new HtmlBlockForTest();
    HtmlBlock.Block block = new BlockForTest(html, printWriter, 10, false);
    aggregatedBlock.render(block);

    block.getWriter().flush();
    String out = data.toString();
    assertTrue(out.contains("Hello stderr"));
    assertTrue(out.contains("Hello stdout"));
    assertTrue(out.contains("Hello syslog"));

    aggregatedBlock = getAggregatedLogsBlockForTest(configuration, "admin",
            "container_1440536969523_0001_01_000002", "host2:2222");
    data = new ByteArrayOutputStream();
    printWriter = new PrintWriter(data);
    html = new HtmlBlockForTest();
    block = new BlockForTest(html, printWriter, 10, false);
    aggregatedBlock.render(block);
    block.getWriter().flush();
    out = data.toString();
    assertTrue(out.contains("Goodbye stderr"));
    assertTrue(out.contains("Goodbye stdout"));
    assertTrue(out.contains("Goodbye syslog"));
}