Example usage for java.util.jar JarInputStream JarInputStream

List of usage examples for java.util.jar JarInputStream JarInputStream

Introduction

In this page you can find the example usage for java.util.jar JarInputStream JarInputStream.

Prototype

public JarInputStream(InputStream in) throws IOException 

Source Link

Document

Creates a new JarInputStream and reads the optional manifest.

Usage

From source file:com.ottogroup.bi.asap.repository.CachedComponentClassLoader.java

/**
 * Initializes the class loader by pointing it to folder holding managed JAR files
 * @param componentFolder/*w ww  .j a v a 2s. c o m*/
 * @throws IOException
 * @throws RequiredInputMissingException
 */
public void initialize(final String componentFolder) throws IOException, RequiredInputMissingException {

    ///////////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(componentFolder))
        throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'");

    File folder = new File(componentFolder);
    if (!folder.isDirectory())
        throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder");

    File[] jarFiles = folder.listFiles();
    if (jarFiles == null || jarFiles.length < 1)
        throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'");
    //
    ///////////////////////////////////////////////////////////////////

    logger.info("Initializing component classloader [folder=" + componentFolder + "]");

    // step through jar files, ensure it is a file and iterate through its contents
    for (File jarFile : jarFiles) {
        if (jarFile.isFile()) {

            JarInputStream jarInputStream = null;
            try {

                jarInputStream = new JarInputStream(new FileInputStream(jarFile));
                JarEntry jarEntry = null;
                while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
                    String jarEntryName = jarEntry.getName();
                    // if the current file references a class implementation, replace slashes by dots, strip 
                    // away the class suffix and add a reference to the classes-2-jar mapping 
                    if (StringUtils.endsWith(jarEntryName, ".class")) {
                        jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.');
                        this.byteCode.put(jarEntryName, loadBytes(jarInputStream));
                    } else {
                        // ...and add a mapping for resource to jar file as well
                        this.resources.put(jarEntryName, loadBytes(jarInputStream));
                    }
                }
            } catch (Exception e) {
                logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                        + e.getMessage());
            } finally {
                try {
                    jarInputStream.close();
                } catch (Exception e) {
                    logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                            + e.getMessage());
                }
            }
        }
    }

    logger.info("Analyzing " + this.byteCode.size() + " classes for component annotation");

    // load classes from jars marked component files and extract the deployment descriptors
    for (String cjf : this.byteCode.keySet()) {

        try {
            Class<?> c = loadClass(cjf);
            AsapComponent pc = c.getAnnotation(AsapComponent.class);
            if (pc != null) {
                this.managedComponents.put(getManagedComponentKey(pc.name(), pc.version()),
                        new ComponentDescriptor(c.getName(), pc.type(), pc.name(), pc.version(),
                                pc.description()));
                logger.info("pipeline component found [type=" + pc.type() + ", name=" + pc.name() + ", version="
                        + pc.version() + "]");
                ;
            }
        } catch (Throwable e) {
            //logger.info("Failed to load class '"+cjf+"'. Error: " + e.getMessage());
        }
    }
}

From source file:org.simplericity.jettyconsole.creator.DefaultCreator.java

private void unpackMainClassAndFilter(URL coredep) {
    try (JarInputStream in = new JarInputStream(coredep.openStream())) {
        while (true) {
            JarEntry entry = in.getNextJarEntry();
            if (entry == null) {
                break;
            }/*from   ww  w.  j a  va  2s. c o  m*/
            if (entry.getName().startsWith(MAIN_CLASS) && entry.getName().endsWith(".class")) {
                File file = new File(workingDirectory, entry.getName());
                file.getParentFile().mkdirs();
                FileOutputStream out = new FileOutputStream(file);
                IOUtils.copy(in, out);
                out.close();
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.micromata.genome.jpa.impl.JpaWithExtLibrariesScanner.java

/**
 * A jar may have also declared more deps in manifest (like surefire).
 * /* w w w.  j a v a  2 s  . co m*/
 * @param url the url
 * @param collector the collector to use
 */
@SuppressWarnings("deprecation")
private void handleClassManifestClassPath(URL url, ScanResultCollector collector, Matcher<String> urlMatcher) {
    String urls = url.toString();
    URL urltoopen = fixUrlToOpen(url);
    urls = urltoopen.toString();
    if (urls.endsWith(".jar") == false) {
        return;
    }

    try (InputStream is = urltoopen.openStream()) {
        try (JarInputStream jarStream = new JarInputStream(is)) {
            Manifest manifest = jarStream.getManifest();
            if (manifest == null) {
                return;
            }
            Attributes attr = manifest.getMainAttributes();
            String val = attr.getValue("Class-Path");
            if (StringUtils.isBlank(val) == true) {
                return;
            }
            String[] entries = StringUtils.split(val, " \t\n");
            for (String entry : entries) {
                URL surl = new URL(entry);
                visitUrl(surl, collector, urlMatcher);
            }

        }

    } catch (IOException ex) {
        log.warn("JpaScan; Cannot open jar: " + url + ": " + ex.getMessage());
    }

}

From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java

static String mainClass(Resource jar) throws IOException {
    JarInputStream jis = new JarInputStream(jar.getInputStream());
    try {/* w ww.  j av a2 s. c o  m*/
        Manifest mf = jis.getManifest();
        if (mf != null) {
            String main = mf.getMainAttributes().getValue("Main-Class");
            if (StringUtils.hasText(main)) {
                return main.replace("/", ".");
            }
        }
        return null;
    } finally {
        IOUtils.closeStream(jis);
    }
}

From source file:org.pentaho.pac.server.util.ResolverUtil.java

public void loadImplementationsInJar(String parent, URL jarfile, Test... tests) {
    try {/* w ww .j a v  a2  s .c o m*/
        JarEntry entry;
        JarInputStream jarStream = new JarInputStream(jarfile.openStream());
        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) { //$NON-NLS-1$
                addIfMatching(name, tests);
            }
        }
    } catch (IOException ioe) {
        log.debug("Could not search jar file \\\'" + jarfile //$NON-NLS-1$
                + "\\\' for classes matching criteria: " + tests //$NON-NLS-1$
                + " due to an IOException", ioe); //$NON-NLS-1$
    }
}

From source file:com.sachviet.bookman.server.util.ResolverUtil.java

public void loadImplementationsInJar(String parent, URL jarfile, Test... tests) {
    JarInputStream jarStream = null;
    try {/*from   w w w.j  ava  2 s. c  o m*/
        JarEntry entry;
        jarStream = new JarInputStream(jarfile.openStream());
        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) { //$NON-NLS-1$
                addIfMatching(name, tests);
            }
        }
    } catch (IOException ioe) {
        LOG.trace("Could not search jar file \\\'" + jarfile //$NON-NLS-1$
                + "\\\' for classes matching criteria: " + tests //$NON-NLS-1$
                + " due to an IOException", ioe); //$NON-NLS-1$
    } finally {
        if (jarStream != null)
            try {
                jarStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

From source file:org.talend.components.marketo.MarketoRuntimeInfoTest.java

@Ignore
@Test//from  w w w.j  a va2s .  c  o  m
public void testExtracDependencyFromStream() throws IOException {
    MavenResolver mavenResolver = MavenResolvers.createMavenResolver(null, "foo");
    File jarWithDeps = mavenResolver.resolve(MAVEN_PATH + "/0.18.0-SNAPSHOT");
    try (JarInputStream jis = new JarInputStream(new FileInputStream(jarWithDeps))) {
        List<URL> dependencyFromStream = extractDependencyFromStream(new DependenciesReader(null),
                DependenciesReader.computeDependenciesFilePath(MAVEN_GROUP_ID, MAVEN_ARTIFACT_ID), jis);
        checkFullExampleDependencies(dependencyFromStream);
    }
}

From source file:JarUtils.java

public static void unjar(InputStream in, File dest) throws IOException {
    if (!dest.exists()) {
        dest.mkdirs();//w  w  w  .  j  a v a  2 s . c  o  m
    }
    if (!dest.isDirectory()) {
        throw new IOException("Destination must be a directory.");
    }
    JarInputStream jin = new JarInputStream(in);
    byte[] buffer = new byte[1024];

    ZipEntry entry = jin.getNextEntry();
    while (entry != null) {
        String fileName = entry.getName();
        if (fileName.charAt(fileName.length() - 1) == '/') {
            fileName = fileName.substring(0, fileName.length() - 1);
        }
        if (fileName.charAt(0) == '/') {
            fileName = fileName.substring(1);
        }
        if (File.separatorChar != '/') {
            fileName = fileName.replace('/', File.separatorChar);
        }
        File file = new File(dest, fileName);
        if (entry.isDirectory()) {
            // make sure the directory exists
            file.mkdirs();
            jin.closeEntry();
        } else {
            // make sure the directory exists
            File parent = file.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            // dump the file
            OutputStream out = new FileOutputStream(file);
            int len = 0;
            while ((len = jin.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            jin.closeEntry();
            file.setLastModified(entry.getTime());
        }
        entry = jin.getNextEntry();
    }
    /* Explicity write out the META-INF/MANIFEST.MF so that any headers such
    as the Class-Path are see for the unpackaged jar
    */
    Manifest mf = jin.getManifest();
    if (mf != null) {
        File file = new File(dest, "META-INF/MANIFEST.MF");
        File parent = file.getParentFile();
        if (parent.exists() == false) {
            parent.mkdirs();
        }
        OutputStream out = new FileOutputStream(file);
        mf.write(out);
        out.flush();
        out.close();
    }
    jin.close();
}

From source file:org.echocat.nodoodle.transport.HandlerUnpacker.java

protected SplitResult splitMultipleJarIntoJars(InputStream inputStream, File targetDirectory)
        throws IOException {
    if (inputStream == null) {
        throw new NullPointerException();
    }/*  ww w.ja v a 2 s  . com*/
    if (targetDirectory == null) {
        throw new NullPointerException();
    }
    final Collection<File> jarFiles = new ArrayList<File>();
    final File mainJarFile = getMainJarFile(targetDirectory);
    jarFiles.add(mainJarFile);
    final JarInputStream jarInput = new JarInputStream(inputStream);
    final Manifest manifest = jarInput.getManifest();
    final FileOutputStream mainJarFileStream = new FileOutputStream(mainJarFile);
    try {
        final JarOutputStream jarOutput = new JarOutputStream(mainJarFileStream, manifest);
        try {
            JarEntry entry = jarInput.getNextJarEntry();
            while (entry != null) {
                final String entryName = entry.getName();
                if (!entry.isDirectory() && entryName.startsWith("lib/")) {
                    final File targetFile = new File(targetDirectory, entryName);
                    if (!targetFile.getParentFile().mkdirs()) {
                        throw new IOException("Could not create parent directory of " + targetFile + ".");
                    }
                    final OutputStream outputStream = new FileOutputStream(targetFile);
                    try {
                        IOUtils.copy(jarInput, outputStream);
                    } finally {
                        IOUtils.closeQuietly(outputStream);
                    }
                    jarFiles.add(targetFile);
                } else {
                    if (entryName.startsWith(TransportConstants.CLASSES_PREFIX)
                            && entryName.length() > TransportConstants.CLASSES_PREFIX.length()) {
                        try {
                            ZIP_ENTRY_NAME_FIELD.set(entry, entryName.substring(CLASSES_PREFIX.length()));
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException("Could not set " + ZIP_ENTRY_NAME_FIELD + ".", e);
                        }
                    }
                    jarOutput.putNextEntry(entry);
                    IOUtils.copy(jarInput, jarOutput);
                    jarOutput.closeEntry();
                }
                entry = jarInput.getNextJarEntry();
            }
        } finally {
            IOUtils.closeQuietly(jarOutput);
        }
    } finally {
        IOUtils.closeQuietly(mainJarFileStream);
    }
    return new SplitResult(Collections.unmodifiableCollection(jarFiles), manifest);
}

From source file:fll.xml.XMLUtils.java

/**
 * Get all challenge descriptors build into the software.
 *///from w  w w .  j  av a2s. c  om
public static Collection<URL> getAllKnownChallengeDescriptorURLs() {
    final String baseDir = "fll/resources/challenge-descriptors/";

    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    final URL directory = classLoader.getResource(baseDir);
    if (null == directory) {
        LOGGER.warn("base dir for challenge descriptors not found");
        return Collections.emptyList();
    }

    final Collection<URL> urls = new LinkedList<URL>();
    if ("file".equals(directory.getProtocol())) {
        try {
            final URI uri = directory.toURI();
            final File fileDir = new File(uri);
            final File[] files = fileDir.listFiles();
            if (null != files) {
                for (final File file : files) {
                    if (file.getName().endsWith(".xml")) {
                        try {
                            final URL fileUrl = file.toURI().toURL();
                            urls.add(fileUrl);
                        } catch (final MalformedURLException e) {
                            LOGGER.error("Unable to convert file to URL: " + file.getAbsolutePath(), e);
                        }
                    }
                }
            }
        } catch (final URISyntaxException e) {
            LOGGER.error("Unable to convert URL to URI: " + e.getMessage(), e);
        }
    } else if (directory.getProtocol().equals("jar")) {
        final CodeSource src = XMLUtils.class.getProtectionDomain().getCodeSource();
        if (null != src) {
            final URL jar = src.getLocation();

            JarInputStream zip = null;
            try {
                zip = new JarInputStream(jar.openStream());

                JarEntry ze = null;
                while ((ze = zip.getNextJarEntry()) != null) {
                    final String entryName = ze.getName();
                    if (entryName.startsWith(baseDir) && entryName.endsWith(".xml")) {
                        // add 1 to baseDir to skip past the path separator
                        final String challengeName = entryName.substring(baseDir.length());

                        // check that the file really exists and turn it into a URL
                        final URL challengeUrl = classLoader.getResource(baseDir + challengeName);
                        if (null != challengeUrl) {
                            urls.add(challengeUrl);
                        } else {
                            // TODO could write the resource out to a temporary file if
                            // needed
                            // then mark the file as delete on exit
                            LOGGER.warn("URL doesn't exist for " + baseDir + challengeName + " entry: "
                                    + entryName);
                        }
                    }
                }

                zip.close();
            } catch (final IOException e) {
                LOGGER.error("Error reading jar file at: " + jar.toString(), e);
            } finally {
                IOUtils.closeQuietly(zip);
            }

        } else {
            LOGGER.warn("Null code source in protection domain, cannot get challenge descriptors");
        }
    } else {
        throw new UnsupportedOperationException("Cannot list files for URL " + directory);

    }

    return urls;

}