Example usage for java.lang ClassLoader getResource

List of usage examples for java.lang ClassLoader getResource

Introduction

In this page you can find the example usage for java.lang ClassLoader getResource.

Prototype

public URL getResource(String name) 

Source Link

Document

Finds the resource with the given name.

Usage

From source file:com.joyent.manta.client.crypto.EncryptingEntityTest.java

private void canCountBytesFromStreamWithUnknownLength(SupportedCipherDetails cipherDetails) throws Exception {
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    URL resource = classLoader.getResource("com/joyent/manta/client/crypto/EncryptingEntityTest.class");
    Path path = Paths.get(resource.toURI());
    long size = path.toFile().length();

    MantaInputStreamEntity entity = new MantaInputStreamEntity(resource.openStream());

    Assert.assertEquals(entity.getContentLength(), -1L, "Content length should be set to unknown value");

    byte[] keyBytes = SecretKeyUtils.generate(cipherDetails).getEncoded();

    verifyEncryptionWorksRoundTrip(keyBytes, cipherDetails, entity, (actualBytes) -> {
        Assert.assertEquals(actualBytes.length, size, "Incorrect number of bytes counted");
        return true;
    });/*w w w .ja  v a2s  .  c  o  m*/
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.HttpClientIntegrationTest.java

@Test
public void doGetTest() throws URISyntaxException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL fileUrl = loader.getResource(INPUT_FILENAME);
    File inputFile = new File(fileUrl.toURI());
    assertNotNull(inputFile);//ww w.  j av a  2s  . c  o  m
    assertTrue(inputFile.exists());
    assertTrue(inputFile.isFile());
    assertTrue(inputFile.canRead());

    CloseableHttpClient httpclient = HttpClients.createDefault();
    String fileLocation = fileUrl.getPath();
    String url = LOCAL_TOMCAT_SERVICE_URL + "?file=" + fileLocation;
    HttpGet httpGet = new HttpGet(url);

    CloseableHttpResponse response = null;
    try {
        logger.debug("executing request " + httpGet.getRequestLine());
        response = httpclient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        logger.debug("Response status line : " + statusLine);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            long len = entity.getContentLength();
            if (len != -1 && len < 2048) {
                logger.debug("len: " + len);
                logger.debug(EntityUtils.toString(entity));
            } else {
                logger.debug("len: " + len);
                Header[] allHeaders = response.getAllHeaders();
                for (Header h : allHeaders) {
                    logger.debug("Header: name:" + h.getName() + " -- value: " + h.getValue()
                            + " -- toString(): " + h);
                }
                Header header = entity.getContentEncoding();
                header = entity.getContentType();
                logger.debug("header content type: " + header.toString());
                header = response.getFirstHeader("filename");
                String filename = header.getValue();
                String savedFilename = filename == null ? "file.pdf" : filename;
                InputStream is = entity.getContent();
                OutputStream out = new FileOutputStream("target/" + savedFilename);
                int bytesCnt;
                while ((bytesCnt = is.read()) != -1) {
                    out.write(bytesCnt);
                }
                out.close();
            }
        }
    } catch (IOException e) {
        logger.error("Something went wrong...", e);
        fail(e.getMessage());
    } finally {
        if (response != null) {
            try {
                response.close();
                httpclient.close();
            } catch (IOException e) {
                // nothing to do
                ;
            }
        }
    }
    logger.debug("DONE");
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.HttpClientIntegrationTest.java

@Test
public void doPostTest() throws URISyntaxException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL fileUrl = loader.getResource(INPUT_FILENAME);
    File inputFile = new File(fileUrl.toURI());
    assertNotNull(inputFile);// w ww . j  a va2s .com
    assertTrue(inputFile.exists());
    assertTrue(inputFile.isFile());
    assertTrue(inputFile.canRead());

    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(LOCAL_TOMCAT_SERVICE_URL);
    FileBody fileContent = new FileBody(inputFile);
    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, fileContent).build();
    httpPost.setEntity(reqEntity);

    CloseableHttpResponse response = null;
    try {
        logger.debug("executing request " + httpPost.getRequestLine());
        response = httpclient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        logger.debug("Response status line : " + statusLine);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            long len = entity.getContentLength();
            if (len != -1 && len < 2048) {
                logger.debug("len: " + len);
                logger.debug(EntityUtils.toString(entity));
            } else {
                logger.debug("len: " + len);
                Header[] allHeaders = response.getAllHeaders();
                for (Header h : allHeaders) {
                    logger.debug("Header: name:" + h.getName() + " -- value: " + h.getValue()
                            + " -- toString(): " + h);
                }
                Header header = entity.getContentEncoding();
                // logger.debug("header encoding: " + header.toString());
                header = entity.getContentType();
                logger.debug("header content type: " + header.toString());
                header = response.getFirstHeader("filename");
                String filename = header.getValue();
                String savedFilename = filename == null ? "file.pdf" : filename;
                InputStream is = entity.getContent();
                OutputStream out = new FileOutputStream("target/" + savedFilename);
                int bytesCnt;
                while ((bytesCnt = is.read()) != -1) {
                    out.write(bytesCnt);
                }
                out.close();
            }
        }
    } catch (IOException e) {
        logger.error("Something went wrong...", e);
        fail(e.getMessage());
    } finally {
        if (response != null) {
            try {
                response.close();
                httpclient.close();
            } catch (IOException e) {
                // nothing to do
                ;
            }
        }
    }
    logger.debug("DONE");

}

From source file:com.aurel.track.dbase.HandleHome.java

/**
 * Copies images, templates, etc. from the WAR to TRACKPLUS_HOME. Original files are
 * overwritten unless they have been modified. Modification is checked via an MD5 digest.
 * @throws ServletException//from   ww  w .j  ava  2s.c o m
 */
public static void copyObject(ServletContext servletContext, String sourcePath, String file, String targetDir)
        throws ServletException {
    File targetFile = null;
    File targetDirAbsolutePath = null;
    try {
        // First check if we already have a file there
        if (HandleHome.getTrackplus_Home() != null && !"".equals(HandleHome.getTrackplus_Home())) {
            targetFile = new File(
                    HandleHome.getTrackplus_Home() + File.separator + targetDir + File.separator + file);
            targetDirAbsolutePath = new File(HandleHome.getTrackplus_Home() + File.separator + targetDir);
        }

        if (targetDirAbsolutePath != null && !targetDirAbsolutePath.exists()) {
            targetDirAbsolutePath.mkdirs();
        }

        if (targetDirAbsolutePath != null && !targetDirAbsolutePath.canWrite()) {
            LOGGER.error(file + " not writable to " + targetDirAbsolutePath.getAbsolutePath() + " by user "
                    + System.getProperty("user.name"));
            return;
        }

        URL sourceURL = null;
        try {
            sourceURL = servletContext.getResource(sourcePath + "/" + file);
        } catch (Exception e) {
            LOGGER.debug(
                    "Could not get file " + sourcePath + "/" + file + " from context. Now trying classpath.");
        }

        if (sourceURL == null) {
            ClassLoader cl = HandleHome.class.getClassLoader();
            sourceURL = cl.getResource(sourcePath + "/" + file);
        }

        String hashTarget = "";
        String hashSource = computeHash(sourceURL);
        boolean copy = true;

        if (targetFile.exists() && targetFile.canRead()) {
            hashTarget = computeHash(targetFile);
            if (!fileIsTheOriginal(targetFile, hashTarget) || hashSource.equals(hashTarget)) {
                copy = false;
            }
        }

        writeHash(targetFile, hashSource);

        if (copy) {
            LOGGER.info("Copying file " + sourcePath + "/" + file + " to " + targetFile.getAbsolutePath());
            InputStream from = null;
            FileOutputStream to = null; // Stream to write to destination

            try {
                from = sourceURL.openStream(); // Create input stream
                to = new FileOutputStream(targetFile); // Create temporary output stream
                byte[] buffer = new byte[4096]; // To hold file contents
                int bytes_read; // How many bytes in buffer
                while ((bytes_read = from.read(buffer)) != -1)
                    // Read until EOF
                    to.write(buffer, 0, bytes_read); // write
            }
            // Always close the streams, even if exceptions were thrown
            finally {
                if (from != null)
                    try {
                        from.close();
                    } catch (IOException e) {
                    }
                if (to != null)
                    try {
                        to.close();
                    } catch (IOException e) {
                    }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Could not read " + file + ". Exiting: " + e.getMessage());
        LOGGER.error(ExceptionUtils.getStackTrace(e));
        throw new ServletException(e);
    }
}

From source file:de.ipk_gatersleben.ag_nw.graffiti.plugins.gui.webstart.KgmlEdMain.java

/**
 * Constructs a new instance of the editor.
 *///w  ww.  j  a  v a2  s.  c o  m
public KgmlEdMain(final boolean showMainFrame, String applicationName, String[] args) {
    // URL config,
    final ThreadSafeOptions tso = new ThreadSafeOptions();
    SplashScreenInterface splashScreen = new DBEsplashScreen(applicationName, "", new Runnable() {
        public void run() {
            if (showMainFrame) {
                ClassLoader cl = this.getClass().getClassLoader();
                String path = this.getClass().getPackage().getName().replace('.', '/');
                ImageIcon icon = new ImageIcon(cl.getResource(path + "/ipklogo16x16_5.png"));
                final MainFrame mainFrame = MainFrame.getInstance();
                mainFrame.setIconImage(icon.getImage());

                Thread t = new Thread(new Runnable() {
                    public void run() {
                        long waitTime = 0;
                        long start = System.currentTimeMillis();
                        do {
                            if (ErrorMsg.getAppLoadingStatus() == ApplicationStatus.ADDONS_LOADED)
                                break;
                            try {
                                Thread.sleep(50);
                            } catch (InterruptedException e) {
                            }
                            waitTime = System.currentTimeMillis() - start;
                        } while (waitTime < 2000);
                        SplashScreenInterface ss = (SplashScreenInterface) tso.getParam(0, null);
                        ss.setVisible(false);
                        mainFrame.setVisible(true);
                    }
                }, "wait for add-on initialization");
                t.start();
            }

        }
    });
    tso.setParam(0, splashScreen);

    ClassLoader cl = this.getClass().getClassLoader();
    String path = this.getClass().getPackage().getName().replace('.', '/');
    ImageIcon icon = new ImageIcon(cl.getResource(path + "/ipklogo16x16_5.png"));
    ((DBEsplashScreen) splashScreen).setIconImage(icon.getImage());

    splashScreen.setVisible(true);
    GravistoMainHelper.createApplicationSettingsFolder(splashScreen);
    if (!(new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_accepted")).exists()
            && !(new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_rejected")).exists()) {

        ReleaseInfo.setIsFirstRun(true);

        splashScreen.setVisible(false);
        splashScreen.setText("Request KEGG License Status");
        JOptionPane.showMessageDialog(null, "<html><h3>KEGG License Status Evaluation</h3>" + "While "
                + DBEgravistoHelper.DBE_GRAVISTO_VERSION
                + " is available as a academic research tool at no cost to commercial and non-commercial users, for using<br>"
                + "KEGG related functions, it is necessary for all users to adhere to the KEGG license.<br>"
                + "For using " + DBEgravistoHelper.DBE_GRAVISTO_VERSION
                + " you need also be aware of information about licenses and conditions for<br>"
                + "usage, listed at the program info dialog and the " + DBEgravistoHelper.DBE_GRAVISTO_VERSION
                + " website (" + ReleaseInfo.getAppWebURL() + ").<br><br>"
                + DBEgravistoHelper.DBE_GRAVISTO_VERSION
                + " does not distribute information from KEGG but contains functionality for the online-access to  information from KEGG wesite.<br><br>"
                + "<b>Before these functions are available to you, you should  carefully read the following license information<br>"
                + "and decide if it is legit for you to use the KEGG related program functions. If you choose not to use the KEGG functions<br>"
                + "all other features of this application are still available and fully working.",
                DBEgravistoHelper.DBE_GRAVISTO_VERSION + " Program Features Initialization",
                JOptionPane.INFORMATION_MESSAGE);

        JOptionPane.showMessageDialog(null,
                "<html><h3>KEGG License Status Evaluation</h3>" + MenuItemInfoDialog.getKEGGlibText(),
                DBEgravistoHelper.DBE_GRAVISTO_VERSION + " Program Features Initialization",
                JOptionPane.INFORMATION_MESSAGE);

        int result = JOptionPane.showConfirmDialog(null, "<html><h3>Enable KEGG functions?",
                DBEgravistoHelper.DBE_GRAVISTO_VERSION + " Program Features Initialization",
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (result == JOptionPane.YES_OPTION) {
            try {
                new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_accepted").createNewFile();
            } catch (IOException e) {
                ErrorMsg.addErrorMessage(e);
            }
        }
        if (result == JOptionPane.NO_OPTION) {
            try {
                new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_rejected").createNewFile();
            } catch (IOException e) {
                ErrorMsg.addErrorMessage(e);
            }
        }
        if (result == JOptionPane.CANCEL_OPTION) {
            JOptionPane.showMessageDialog(null, "Startup aborted.",
                    DBEgravistoHelper.DBE_GRAVISTO_VERSION + " Program Features Initialization",
                    JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
        }
        splashScreen.setVisible(true);
    }

    GravistoMainHelper.initApplicationExt(args, splashScreen, cl, null, null);

}

From source file:org.apache.commons.vfs2.util.NHttpServer.java

public void runBlock(final int port, final File docRoot) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
    if (docRoot == null) {
        throw new IllegalArgumentException("No doc root specified.");
    }/*from www .j a  va 2s.  c  o m*/
    // HTTP parameters for the server
    final HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpTest/1.1");
    // Create HTTP protocol processing chain
    final HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
            // Use standard server-side protocol interceptors
            new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() });
    // Create request handler registry
    final HttpAsyncRequestHandlerRegistry reqistry = new HttpAsyncRequestHandlerRegistry();
    // Register the default handler for all URIs
    reqistry.register("*", new HttpFileHandler(docRoot));
    // Create server-side HTTP protocol handler
    final HttpAsyncService protocolHandler = new HttpAsyncService(httpproc,
            new DefaultConnectionReuseStrategy(), reqistry, params) {

        @Override
        public void closed(final NHttpServerConnection conn) {
            NHttpServer.debug(conn + ": connection closed");
            super.closed(conn);
        }

        @Override
        public void connected(final NHttpServerConnection conn) {
            NHttpServer.debug(conn + ": connection open");
            super.connected(conn);
        }

    };
    // Create HTTP connection factory
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (port == 8443) {
        // Initialize SSL context
        final ClassLoader cl = NHttpServer.class.getClassLoader();
        final URL url = cl.getResource("my.keystore");
        if (url == null) {
            NHttpServer.debug("Keystore not found");
            System.exit(1);
        }
        final KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        final KeyManagerFactory kmfactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        final KeyManager[] keymanagers = kmfactory.getKeyManagers();
        final SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, params);
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(params);
    }
    // Create server-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    // Create server-side I/O reactor
    this.ioReactor = new DefaultListeningIOReactor();
    try {
        // Listen of the given port
        this.ioReactor.listen(new InetSocketAddress(port));
        // Ready to go!
        this.ioReactor.execute(ioEventDispatch);
    } catch (final InterruptedIOException ex) {
        System.err.println("Interrupted");
    } catch (final IOException e) {
        System.err.println("I/O error: " + e.getMessage());
    }
    NHttpServer.debug("Shutdown");
}

From source file:com.blackducksoftware.tools.vuln_collector.VCProcessor.java

/**
 * Creates a directory using the project name Parses the name to escape
 * offensive characters.//from   w  ww  .j a va 2s  .c  o  m
 * 
 * @param reportLocation
 * @param project
 * @return
 * @throws Exception
 */
private File prepareSubDirectory(File reportLocation, String project) throws Exception {
    project = formatProjectPath(project);
    File reportLocationSubDir = new File(reportLocation.toString() + File.separator + project);
    if (!reportLocationSubDir.exists()) {
        boolean dirsMade = reportLocationSubDir.mkdirs();
        if (!dirsMade) {
            throw new Exception("Unable to create report sub-directory for project: " + project);
        }
    }

    // Copy the web resources into this new location
    ClassLoader classLoader = getClass().getClassLoader();
    File webresources = new File(classLoader.getResource(WEB_RESOURCE).getFile());

    if (!webresources.exists()) {
        throw new Exception("Fatal exception, internal web resources are missing!");
    }

    File[] webSubDirs = webresources.listFiles();
    if (webSubDirs.length == 0) {
        throw new Exception(
                "Fatal exception, internal web resources sub directories are missing!  Corrupt archive.");
    }

    boolean readable = webresources.setReadable(true);
    if (!readable) {
        throw new Exception("Fatal. Cannot read internal web resource directory!");
    }

    try {
        for (File webSubDir : webSubDirs) {
            if (webSubDir.isDirectory()) {
                FileUtils.copyDirectoryToDirectory(webSubDir, reportLocationSubDir);
            } else {
                FileUtils.copyFileToDirectory(webSubDir, reportLocationSubDir);
            }
        }
    } catch (IOException ioe) {
        throw new Exception("Error during creation of report directory", ioe);
    }

    return reportLocationSubDir;
}

From source file:com.datatorrent.stram.StramMiniClusterTest.java

private static String getTestRuntimeClasspath() {

    InputStream classpathFileStream = null;
    BufferedReader reader = null;
    String envClassPath = "";

    LOG.info("Trying to generate classpath for app master from current thread's classpath");
    try {//from   w ww.  ja v  a2s.c o m

        // Create classpath from generated classpath
        // Check maven pom.xml for generated classpath info
        // Works in tests where compile time env is same as runtime.
        ClassLoader thisClassLoader = Thread.currentThread().getContextClassLoader();
        String generatedClasspathFile = "mvn-generated-classpath";
        classpathFileStream = thisClassLoader.getResourceAsStream(generatedClasspathFile);
        if (classpathFileStream == null) {
            LOG.info("Could not load classpath resource " + generatedClasspathFile);
            return envClassPath;
        }
        LOG.info("Readable bytes from stream=" + classpathFileStream.available());
        reader = new BufferedReader(new InputStreamReader(classpathFileStream));
        String cp = reader.readLine();
        if (cp != null) {
            envClassPath += cp.trim() + ":";
        }
        // Put the file itself on classpath for tasks.
        envClassPath += thisClassLoader.getResource(generatedClasspathFile).getFile();
    } catch (IOException e) {
        LOG.info("Could not find the necessary resource to generate class path for tests. Error="
                + e.getMessage());
    }

    try {
        if (classpathFileStream != null) {
            classpathFileStream.close();
        }
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
        LOG.info("Failed to close class path file stream or reader. Error=" + e.getMessage());
    }
    return envClassPath;
}

From source file:io.apiman.test.common.echo.EchoServerVertx.java

private Buffer getResource(String fPath) {
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource(fPath).getFile());
    Buffer buff;//from  w ww .j  a  v a 2 s.  c om
    try {
        buff = Buffer.buffer(Files.readAllBytes(file.toPath()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return buff;
}

From source file:net.sf.jasperreports.jsf.resource.DefaultResourceResolver.java

public Resource resolveResource(FacesContext context, UIComponent component, String name) {
    if (name == null || name.length() == 0) {
        throw new IllegalArgumentException("Resource name must be provided.");
    }/*from   w w  w  . ja v  a2  s .  co m*/

    Resource resource = null;
    try {
        final URL url = new URL(name);
        resource = new URLResource(url);
    } catch (MalformedURLException e) {
        final ClassLoader loader = Util.getClassLoader(this);
        if (name.startsWith(ClasspathResource.PREFIX)) {
            resource = new ClasspathResource(name, loader);
        } else if (name.startsWith("/")) {
            resource = new ContextResource(name);
        } else if (loader.getResource(name) != null) {
            resource = new ClasspathResource(name, loader);
        } else {
            resource = resolveRelative(context, component, name);
        }
    }

    // If at this point 'resource' is null then the resource couldn't
    // be resolved by this ResourceResolver implementation
    return resource;
}