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.jeeframework.util.resource.ResolverUtil.java

/**
 * Finds matching classes within a jar files that contains a folder structure
 * matching the package structure.  If the File is not a JarFile or does not exist a warning
 * will be logged, but no error will be raised.
 *
 * @param test a Test used to filter the classes that are discovered
 * @param parent the parent package under which classes must be in order to be considered
 * @param jarfile the jar file to be examined for classes
 *///from   w  w  w .  ja v a2 s  .c om
private void loadImplementationsInJar(Test test, String parent, File jarfile) {

    try {
        JarEntry entry;
        JarInputStream jarStream = new JarInputStream(new FileInputStream(jarfile));

        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) {
                addIfMatching(test, name);
            }
        }
    } catch (IOException ioe) {
        log.error("Could not search jar file '" + jarfile + "' for classes matching criteria: " + test
                + " due to an IOException", ioe);
    }
}

From source file:de.tobiasroeser.maven.featurebuilder.FeatureBuilder.java

public List<Bundle> scanBundlesAtDir(final String scanJarsAtDir) {
    final File file = new File(scanJarsAtDir);

    final LinkedList<Bundle> bundles = new LinkedList<Bundle>();

    if (!file.exists() || !file.isDirectory()) {
        log.error("Directory '" + file.getAbsolutePath() + "' does not exists.");
        return bundles;
    }//w ww  . ja  v a 2 s.com

    for (final File jar : file.listFiles()) {
        if (jar.isFile() && jar.getName().toLowerCase().endsWith(".jar")) {
            try {
                final JarInputStream jarStream = new JarInputStream(
                        new BufferedInputStream(new FileInputStream(jar)));
                final Manifest manifest = jarStream.getManifest();
                String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
                final String version = manifest.getMainAttributes().getValue("Bundle-Version");
                if (symbolicName != null && version != null) {
                    symbolicName = symbolicName.split(";")[0].trim();
                    final Bundle bundle = new Bundle(symbolicName, version, jar.length(), jar);
                    bundles.add(bundle);
                } else {
                    log.warn("jar '" + jar.getAbsolutePath() + "' is not an OSGi bundle.");
                }

            } catch (final FileNotFoundException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            } catch (final IOException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            }

        }
    }
    log.info("Found " + bundles.size() + " bundles in scanned directory: " + file.getAbsolutePath());

    Collections.sort(bundles);
    return bundles;
}

From source file:org.getobjects.foundation.NSJavaRuntime.java

private static void getClassNamesFromJarFile(String _jarPath, String _pkg, Set<String> classes_) {
    FileInputStream fos;/*from w  w  w.  j  a va 2  s .com*/
    try {
        fos = new FileInputStream(_jarPath);
    } catch (FileNotFoundException e1) {
        return; // TBD: log
    }

    JarInputStream jarFile;
    try {
        jarFile = new JarInputStream(fos);
    } catch (IOException e) {
        return; // TBD: log
    }

    do {
        JarEntry jarEntry;
        try {
            jarEntry = jarFile.getNextJarEntry();
        } catch (IOException e) {
            jarEntry = null;
        }

        if (jarEntry == null)
            break;

        String className = jarEntry.getName();
        if (!className.endsWith(".class"))
            continue;

        className = stripFilenameExtension(className);
        if (className.startsWith(_pkg))
            classes_.add(className.replace('/', '.'));
    } while (true);

    if (jarFile != null) {
        try {
            jarFile.close();
        } catch (IOException e) {
            // TBD: log?
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.maltparser.MaltParser.java

private String getRealName(URL aUrl) throws IOException {
    JarEntry je = null;//from  www . j  a v a 2 s .  co m
    JarInputStream jis = null;

    try {
        jis = new JarInputStream(aUrl.openConnection().getInputStream());
        while ((je = jis.getNextJarEntry()) != null) {
            String entryName = je.getName();
            if (entryName.endsWith(".info")) {
                int indexUnderScore = entryName.lastIndexOf('_');
                int indexSeparator = entryName.lastIndexOf(File.separator);
                if (indexSeparator == -1) {
                    indexSeparator = entryName.lastIndexOf('/');
                }
                if (indexSeparator == -1) {
                    indexSeparator = entryName.lastIndexOf('\\');
                }
                int indexDot = entryName.lastIndexOf('.');
                if (indexUnderScore == -1 || indexDot == -1) {
                    throw new IllegalStateException(
                            "Could not find the configuration name and type from the URL '" + aUrl.toString()
                                    + "'. ");
                }

                return entryName.substring(indexSeparator + 1, indexUnderScore) + ".mco";
            }
        }

        throw new IllegalStateException(
                "Could not find the configuration name and type from the URL '" + aUrl.toString() + "'. ");
    } finally {
        IOUtils.closeQuietly(jis);
    }
}

From source file:org.artifactory.maven.MavenModelUtils.java

/**
 * @param file The file from which to try to extract the POM entry from.
 * @return The POM from the JAR in its String representation.
 *//* www.j a  v a  2  s  .  c o m*/
public static String getPomFileAsStringFromJar(File file) {
    JarEntry pomEntry;
    JarInputStream inputStream = null;
    try {
        inputStream = new JarInputStream(new FileInputStream(file));
        pomEntry = getPomFile(inputStream);
        if (pomEntry != null) {
            return IOUtils.toString(inputStream);
        }
    } catch (IOException e) {
        log.warn("Unable to read JAR to extract the POM from it.");
        // If the file has a corrupt file, the following error will be thrown.
        // See java.util.zip.ZipInputStream.getUTF8String()
    } catch (IllegalArgumentException iae) {
        log.warn("Unable to read JAR to extract the POM from it.");
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return null;
}

From source file:org.phenotips.tool.packager.PackageMojo.java

private void generateConfigurationFiles(File configurationFileTargetDirectory) throws MojoExecutionException {
    String parsedExtension = ".vm";
    getLog().info("Copying Configuration files ...");
    VelocityContext context = createVelocityContext();
    Artifact configurationResourcesArtifact = this.repositorySystem.createArtifact(XWIKI_PLATFORM_GROUPID,
            "xwiki-platform-tool-configuration-resources", this.xwikiVersion, "", TYPE_JAR);
    resolveArtifact(configurationResourcesArtifact);

    configurationFileTargetDirectory.mkdirs();

    try (JarInputStream jarInputStream = new JarInputStream(
            new FileInputStream(configurationResourcesArtifact.getFile()))) {
        JarEntry entry;/*from   w  w  w.  j a  va2  s  . c  om*/
        while ((entry = jarInputStream.getNextJarEntry()) != null) {
            if (entry.getName().endsWith(parsedExtension)) {
                String fileName = entry.getName().replace(parsedExtension, "");
                File outputFile = new File(configurationFileTargetDirectory, fileName);
                OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outputFile));
                getLog().debug("Writing config file: " + outputFile);
                // Note: Init is done once even if this method is called several times...
                Velocity.init();
                Velocity.evaluate(context, writer, "", IOUtils.toString(jarInputStream));
                writer.close();
                jarInputStream.closeEntry();
            }
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to extract configuration files", e);
    }
}

From source file:org.talend.updates.runtime.nexus.component.ComponentIndexManager.java

/**
 * //www  .  ja  v  a2  s.c om
 * create one default index bean which based one the component zip file directly.
 * 
 * bundleId, version, mvn_uri are required
 */
public ComponentIndexBean create(File componentZipFile) {
    if (componentZipFile == null || !componentZipFile.exists() || componentZipFile.isDirectory()
            || !componentZipFile.getName().endsWith(FileExtensions.ZIP_FILE_SUFFIX)) {
        return null;
    }

    String name = null;
    String bundleId = null;
    String bundleVersion = null;
    String mvnUri = null;

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(componentZipFile);

        Enumeration<ZipEntry> enumeration = (Enumeration<ZipEntry>) zipFile.entries();
        while (enumeration.hasMoreElements()) {
            final ZipEntry zipEntry = enumeration.nextElement();
            String path = zipEntry.getName();
            if (path.endsWith(FileExtensions.JAR_FILE_SUFFIX)) { // is jar
                // if it's bundle, not from other folder, like lib, m2 repository.
                IPath p = new Path(path);
                // must be in plugins
                if (p.segmentCount() > 1
                        && p.removeLastSegments(1).lastSegment().equals(UpdatesHelper.FOLDER_PLUGINS)) {
                    if (UpdatesHelper.isComponentJar(zipFile.getInputStream(zipEntry))) {
                        JarInputStream jarEntryStream = null;
                        try {
                            // must use another stream
                            jarEntryStream = new JarInputStream(zipFile.getInputStream(zipEntry));
                            // find the bundleId and version
                            Manifest manifest = jarEntryStream.getManifest();
                            if (manifest != null) {
                                bundleId = JarMenifestUtil.getBundleSymbolicName(manifest);
                                bundleVersion = JarMenifestUtil.getBundleVersion(manifest);
                            }
                            boolean checkManifest = StringUtils.isBlank(bundleId)
                                    || StringUtils.isBlank(bundleVersion);

                            // find the pom.properties
                            JarEntry jarEntry = null;
                            while ((jarEntry = jarEntryStream.getNextJarEntry()) != null) {
                                final String entryPath = jarEntry.getName();
                                if (checkManifest && JarFile.MANIFEST_NAME.equalsIgnoreCase(entryPath)) {
                                    manifest = new Manifest();
                                    manifest.read(jarEntryStream);
                                    bundleId = JarMenifestUtil.getBundleSymbolicName(manifest);
                                    bundleVersion = JarMenifestUtil.getBundleVersion(manifest);
                                    checkManifest = false;
                                }
                                final Path fullPath = new Path(entryPath);
                                final String fileName = fullPath.lastSegment();

                                /*
                                 * for example,
                                 * META-INF/maven/org.talend.components/components-splunk/pom.properties
                                 */
                                if (fileName.equals("pom.properties") //$NON-NLS-1$
                                        && entryPath.contains("META-INF/maven/")) { //$NON-NLS-1$

                                    // FIXME, didn't find one way to read the inner jar
                                    // final InputStream propStream = jarFile.getInputStream(jarEntry);
                                    // if (propStream != null) {
                                    // Properties pomProp = new Properties();
                                    // pomProp.load(propStream);
                                    //
                                    // String version = pomProp.getProperty("version"); //$NON-NLS-1$
                                    // String groupId = pomProp.getProperty("groupId"); //$NON-NLS-1$
                                    // String artifactId = pomProp.getProperty("artifactId"); //$NON-NLS-1$
                                    // mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, version,
                                    // FileExtensions.ZIP_FILE_SUFFIX, null);
                                    //
                                    // propStream.close();
                                    // }

                                    // FIXME, try the path way
                                    // META-INF/maven/org.talend.components/components-splunk
                                    IPath tmpMavenPath = fullPath.removeLastSegments(1);
                                    String artifactId = tmpMavenPath.lastSegment(); // components-splunk
                                    // META-INF/maven/org.talend.components
                                    tmpMavenPath = tmpMavenPath.removeLastSegments(1);
                                    String groupId = tmpMavenPath.lastSegment(); // org.talend.components

                                    mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, bundleVersion,
                                            FileExtensions.ZIP_EXTENSION, null);

                                } else
                                /*
                                 * /OSGI-INF/installer$$splunk.xml
                                 */
                                if (fileName.endsWith(FileExtensions.XML_FILE_SUFFIX)
                                        && fileName.startsWith(UpdatesHelper.NEW_COMPONENT_PREFIX)
                                        && entryPath.contains(UpdatesHelper.FOLDER_OSGI_INF + '/')) {
                                    name = fullPath.removeFileExtension().lastSegment();
                                    name = name.substring(name.indexOf(UpdatesHelper.NEW_COMPONENT_PREFIX)
                                            + UpdatesHelper.NEW_COMPONENT_PREFIX.length());
                                }
                            }
                        } catch (IOException e) {
                            //
                        } finally {
                            try {
                                if (jarEntryStream != null) {
                                    jarEntryStream.close();
                                }
                            } catch (IOException e) {
                                //
                            }
                        }

                    }
                }
            }
        }

    } catch (ZipException e) {
        if (CommonsPlugin.isDebugMode()) {
            ExceptionHandler.process(e);
        }
    } catch (IOException e) {
        if (CommonsPlugin.isDebugMode()) {
            ExceptionHandler.process(e);
        }
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                //
            }
        }
    }
    // set the required
    if (name != null && bundleId != null && bundleVersion != null && mvnUri != null) {
        final ComponentIndexBean indexBean = new ComponentIndexBean();
        final boolean set = indexBean.setRequiredFieldsValue(name, bundleId, bundleVersion, mvnUri);
        indexBean.setValue(ComponentIndexNames.types,
                PathUtils.convert2StringTypes(Arrays.asList(Type.TCOMP_V0)));
        if (set) {
            return indexBean;
        }
    }
    return null;
}

From source file:org.ngrinder.common.util.CompressionUtil.java

/**
 * Unpack the given jar file.//from w ww .  j  a v  a  2 s  .  c o  m
 * 
 * @param jarFile
 *            file to be uncompressed
 * @param destDir
 *            destination directory
 * @throws IOException
 *             occurs when IO has a problem.
 */
public static void unjar(File jarFile, String destDir) throws IOException {
    File dest = new File(destDir);
    if (!dest.exists()) {
        dest.mkdirs();
    }
    if (!dest.isDirectory()) {
        LOGGER.error("Destination must be a directory.");
        throw new IOException("Destination must be a directory.");
    }
    JarInputStream jin = new JarInputStream(new FileInputStream(jarFile));
    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();
            IOUtils.closeQuietly(out);
            jin.closeEntry();
            file.setLastModified(entry.getTime());
        }
        entry = jin.getNextEntry();
    }
    Manifest mf = jin.getManifest();
    if (mf != null) {
        File file = new File(dest, "META-INF/MANIFEST.MF");
        File parent = file.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        OutputStream out = new FileOutputStream(file);
        mf.write(out);
        out.flush();
        IOUtils.closeQuietly(out);
    }
    IOUtils.closeQuietly(jin);
}

From source file:com.opensymphony.xwork2.util.finder.DefaultClassFinder.java

private List<String> jar(URL location) throws IOException {
    URL url = fileManager.normalizeToFileProtocol(location);
    if (url != null) {
        InputStream in = url.openStream();
        try {//w w  w. j  av  a2s  .  co  m
            JarInputStream jarStream = new JarInputStream(in);
            return jar(jarStream);
        } finally {
            in.close();
        }
    } else {
        LOG.debug("Unable to read [{}]", location.toExternalForm());
    }
    return Collections.emptyList();
}

From source file:com.hortonworks.streamline.streams.runtime.splitjoin.SplitJoinTest.java

private JarInputStream createJarInputStream(String... classNames) throws Exception {

    final File tempFile = Files.createTempFile(UUID.randomUUID().toString(), ".jar").toFile();
    tempFile.deleteOnExit();/*from w ww  .  j a v a 2  s.  c  om*/

    try (JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(tempFile))) {
        for (String className : classNames) {
            final String classFileName = className.replace(".", "/") + ".class";
            try (InputStream classInputStream = this.getClass().getResourceAsStream("/" + classFileName)) {
                jarOutputStream.putNextEntry(new JarEntry(classFileName));
                IOUtils.copy(classInputStream, jarOutputStream);
            }
        }
    }

    return new JarInputStream(new FileInputStream(tempFile));
}