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:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java

/**
 * Reads the specified {@link JarEntry} from the {@link JarFile} assuming that the
 * entry represents another a JAR file. The files in the {@link JarEntry} will be
 * extracted using the contextDir as the base directory. 
 * //from w w  w .  j  av  a 2 s.co  m
 * @param earFile The JarEntry for the JAR to read from the archive.
 * @param earEntry The JarFile to get the {@link InputStream} for the file from.
 * @param contextDir The directory to extract the JAR to.
 * @throws IOException If the extracting of data from the JarEntry fails.
 */
protected void extractWar(JarFile earFile, final JarEntry earEntry, final File contextDir)
        throws MojoFailureException {
    if (this.getLogger().isInfoEnabled()) {
        this.getLogger().info("Extracting EAR entry '" + earFile.getName() + "!" + earEntry.getName() + "' to '"
                + contextDir + "'");
    }

    if (!contextDir.exists()) {
        if (this.getLogger().isDebugEnabled()) {
            this.getLogger().debug("Creating context directory entry '" + contextDir + "'");
        }

        try {
            FileUtils.forceMkdir(contextDir);
        } catch (IOException e) {
            throw new MojoFailureException("Failed to create '" + contextDir + "' to extract '"
                    + earEntry.getName() + "' out of '" + earFile.getName() + "' into", e);
        }
    }

    JarInputStream warInputStream = null;
    try {
        warInputStream = new JarInputStream(earFile.getInputStream(earEntry));

        // Write out the MANIFEST.MF file to the target directory
        Manifest manifest = warInputStream.getManifest();
        if (manifest != null) {
            FileOutputStream manifestFileOutputStream = null;
            try {
                final File manifestFile = new File(contextDir, MANIFEST_PATH);
                manifestFile.getParentFile().mkdirs();
                manifestFileOutputStream = new FileOutputStream(manifestFile);
                manifest.write(manifestFileOutputStream);
            } catch (Exception e) {
                this.getLogger().error("Failed to copy the MANIFEST.MF file for ear entry '"
                        + earEntry.getName() + "' out of '" + earFile.getName() + "'", e);
                throw new MojoFailureException("Failed to copy the MANIFEST.MF file for ear entry '"
                        + earEntry.getName() + "' out of '" + earFile.getName() + "'", e);
            } finally {
                try {
                    if (manifestFileOutputStream != null) {
                        manifestFileOutputStream.close();
                    }
                } catch (Exception e) {
                    this.getLogger().warn("Error closing the OutputStream for MANIFEST.MF in warEntry:  "
                            + earEntry.getName());
                }
            }
        }

        JarEntry warEntry;
        while ((warEntry = warInputStream.getNextJarEntry()) != null) {
            final File warEntryFile = new File(contextDir, warEntry.getName());

            if (warEntry.isDirectory()) {
                if (this.getLogger().isDebugEnabled()) {
                    this.getLogger().debug("Creating WAR directory entry '" + earEntry.getName() + "!"
                            + warEntry.getName() + "' as '" + warEntryFile + "'");
                }

                FileUtils.forceMkdir(warEntryFile);
            } else {
                if (this.getLogger().isDebugEnabled()) {
                    this.getLogger().debug("Extracting WAR entry '" + earEntry.getName() + "!"
                            + warEntry.getName() + "' to '" + warEntryFile + "'");
                }

                FileUtils.forceMkdir(warEntryFile.getParentFile());

                final FileOutputStream jarEntryFileOutputStream = new FileOutputStream(warEntryFile);
                try {
                    IOUtils.copy(warInputStream, jarEntryFileOutputStream);
                } finally {
                    IOUtils.closeQuietly(jarEntryFileOutputStream);
                }
            }
        }
    } catch (IOException e) {
        throw new MojoFailureException("Failed to extract EAR entry '" + earEntry.getName() + "' out of '"
                + earFile.getName() + "' to '" + contextDir + "'", e);
    } finally {
        IOUtils.closeQuietly(warInputStream);
    }
}

From source file:org.apache.catalina.util.ExtensionValidator.java

/**
 * Return the Manifest from a jar file or war file
 *
 * @param inStream Input stream to a WAR or JAR file
 * @return The WAR's or JAR's manifest/*from   w ww  . j a  va  2 s.c om*/
 */
private static Manifest getManifest(InputStream inStream) throws IOException {

    Manifest manifest = null;
    JarInputStream jin = null;

    try {
        jin = new JarInputStream(inStream);
        manifest = jin.getManifest();
        jin.close();
        jin = null;
    } finally {
        if (jin != null) {
            try {
                jin.close();
            } catch (Throwable t) {
                // Ignore
            }
        }
    }

    return manifest;
}

From source file:org.drools.guvnor.server.RepositoryPackageService.java

private JarInputStream typesForModel(List<String> res, AssetItem asset) throws IOException {
    JarInputStream jis;/*from   w  w  w .ja va  2 s.co m*/
    jis = new JarInputStream(asset.getBinaryContentAttachment());
    JarEntry entry = null;
    while ((entry = jis.getNextJarEntry()) != null) {
        if (!entry.isDirectory()) {
            if (entry.getName().endsWith(".class")) {
                res.add(ModelContentHandler.convertPathToName(entry.getName()));
            }
        }
    }
    return jis;
}

From source file:org.apache.camel.impl.DefaultPackageScanClassResolver.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//from  w  w w  . ja v  a2s . c  o  m
 * @param stream  the inputstream of the jar file to be examined for classes
 * @param urlPath the url of the jar file to be examined for classes
 */
private void loadImplementationsInJar(PackageScanFilter test, String parent, InputStream stream, String urlPath,
        Set<Class<?>> classes) {
    JarInputStream jarStream = null;
    try {
        jarStream = new JarInputStream(stream);

        JarEntry entry;
        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (name != null) {
                name = name.trim();
                if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) {
                    addIfMatching(test, name, classes);
                }
            }
        }
    } catch (IOException ioe) {
        log.warn("Cannot search jar file '" + urlPath + "' for classes matching criteria: " + test
                + " due to an IOException: " + ioe.getMessage(), ioe);
    } finally {
        IOHelper.close(jarStream, urlPath, log);
    }
}

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

private List<String> jar(URL location) throws IOException {
    URL url = fileManager.normalizeToFileProtocol(location);
    if (url != null) {
        InputStream in = url.openStream();
        try {//from   w  ww. j a  va 2 s . c o  m
            JarInputStream jarStream = new JarInputStream(in);
            return jar(jarStream);
        } finally {
            in.close();
        }
    } else if (LOG.isDebugEnabled())
        LOG.debug("Unable to read [#0]", location.toExternalForm());

    return Collections.emptyList();
}

From source file:co.cask.cdap.internal.app.runtime.spark.SparkRuntimeService.java

/**
 * Updates the dependency jar packaged by the {@link ApplicationBundler#createBundle(Location, Iterable,
 * Iterable)} by moving the things inside classes, lib, resources a level up as expected by spark.
 *
 * @param dependencyJar {@link Location} of the job jar to be updated
 * @param context       {@link BasicSparkContext} of this job
 *///  w w  w . ja v a  2  s .c  o  m
private Location updateDependencyJar(Location dependencyJar, BasicSparkContext context) throws IOException {

    final String[] prefixToStrip = { ApplicationBundler.SUBDIR_CLASSES, ApplicationBundler.SUBDIR_LIB,
            ApplicationBundler.SUBDIR_RESOURCES };

    Id.Program programId = context.getProgram().getId();

    Location updatedJar = locationFactory.create(String.format("%s.%s.%s.%s.%s.jar",
            ProgramType.SPARK.name().toLowerCase(), programId.getAccountId(), programId.getApplicationId(),
            programId.getId(), context.getRunId().getId()));

    // Creates Manifest
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0");
    JarOutputStream jarOutput = new JarOutputStream(updatedJar.getOutputStream(), manifest);

    try {
        JarInputStream jarInput = new JarInputStream(dependencyJar.getInputStream());

        try {
            JarEntry jarEntry = jarInput.getNextJarEntry();

            while (jarEntry != null) {
                boolean isDir = jarEntry.isDirectory();
                String entryName = jarEntry.getName();
                String newEntryName = entryName;

                for (String prefix : prefixToStrip) {
                    if (entryName.startsWith(prefix) && !entryName.equals(prefix)) {
                        newEntryName = entryName.substring(prefix.length());
                    }
                }

                jarEntry = new JarEntry(newEntryName);
                jarOutput.putNextEntry(jarEntry);
                if (!isDir) {
                    ByteStreams.copy(jarInput, jarOutput);
                }
                jarEntry = jarInput.getNextJarEntry();
            }
        } finally {
            jarInput.close();
            Locations.deleteQuietly(dependencyJar);
        }
    } finally {
        jarOutput.close();
    }
    return updatedJar;
}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

/**
 * From the constructor of {@link JarInputStream}:
 * <p>//w  w w  .j ava 2s .  c o m
 * This implementation assumes the META-INF/MANIFEST.MF entry
 * should be either the first or the second entry (when preceded
 * by the dir META-INF/). It skips the META-INF/ and then
 * "consumes" the MANIFEST.MF to initialize the Manifest object.
 * <p>
 * A simple implementation of {@link JarDirectoryStep} would iterate over all entries to be
 * included, adding them to the output jar, while merging manifest files, writing the merged
 * manifest as the last item in the jar. That will generate jars the {@code JarInputStream} won't
 * be able to find the manifest for.
 */
@Test
public void manifestShouldBeSecondEntryInJar() throws IOException {
    Path manifestPath = Paths.get(JarFile.MANIFEST_NAME);

    // Create a directory with a manifest in it and more than two files.
    Path dir = folder.newFolder();
    Manifest dirManifest = new Manifest();
    Attributes attrs = new Attributes();
    attrs.putValue("From-Dir", "cheese");
    dirManifest.getEntries().put("Section", attrs);

    Files.createDirectories(dir.resolve(manifestPath).getParent());
    try (OutputStream out = Files.newOutputStream(dir.resolve(manifestPath))) {
        dirManifest.write(out);
    }
    Files.write(dir.resolve("A.txt"), "hello world".getBytes(UTF_8));
    Files.write(dir.resolve("B.txt"), "hello world".getBytes(UTF_8));
    Files.write(dir.resolve("aa.txt"), "hello world".getBytes(UTF_8));
    Files.write(dir.resolve("bb.txt"), "hello world".getBytes(UTF_8));

    // Create a jar with a manifest and more than two other files.
    Path inputJar = folder.newFile("example.jar");
    try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(inputJar))) {
        byte[] data = "hello world".getBytes(UTF_8);
        ZipEntry entry = new ZipEntry("C.txt");
        zos.putNextEntry(entry);
        zos.write(data, 0, data.length);
        zos.closeEntry();

        entry = new ZipEntry("cc.txt");
        zos.putNextEntry(entry);
        zos.write(data, 0, data.length);
        zos.closeEntry();

        entry = new ZipEntry("META-INF/");
        zos.putNextEntry(entry);
        zos.closeEntry();

        // Note: at end of the stream. Technically invalid.
        entry = new ZipEntry(JarFile.MANIFEST_NAME);
        zos.putNextEntry(entry);
        Manifest zipManifest = new Manifest();
        attrs = new Attributes();
        attrs.putValue("From-Zip", "peas");
        zipManifest.getEntries().put("Section", attrs);
        zipManifest.write(zos);
        zos.closeEntry();
    }

    // Merge and check that the manifest includes everything
    Path output = folder.newFile("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new FakeProjectFilesystem(folder.getRoot()), output,
            ImmutableSortedSet.of(dir, inputJar), null, null);
    int exitCode = step.execute(TestExecutionContext.newInstance()).getExitCode();

    assertEquals(0, exitCode);

    Manifest manifest;
    try (InputStream is = Files.newInputStream(output); JarInputStream jis = new JarInputStream(is)) {
        manifest = jis.getManifest();
    }

    assertNotNull(manifest);
    Attributes readAttributes = manifest.getAttributes("Section");
    assertEquals(2, readAttributes.size());
    assertEquals("cheese", readAttributes.getValue("From-Dir"));
    assertEquals("peas", readAttributes.getValue("From-Zip"));
}

From source file:org.apache.axis2.jaxws.description.builder.JAXWSRIWSDLGenerator.java

/**
 * Check if this inputstream is a jar/zip
 *
 * @param is/*ww w .  ja va 2s .  c om*/
 * @return true if inputstream is a jar
 */
public static boolean isJar(InputStream is) {
    try {
        JarInputStream jis = new JarInputStream(is);
        if (jis.getNextEntry() != null) {
            return true;
        }
    } catch (IOException ioe) {
    }
    return false;
}

From source file:org.omegat.util.StaticUtils.java

public static void extractFileFromJar(InputStream in, String destination, String... filenames)
        throws IOException {
    if (filenames == null || filenames.length == 0) {
        throw new IllegalArgumentException("Caller must provide non-empty list of files to extract.");
    }/*w  ww. j  av a2 s .  co m*/
    List<String> toExtract = new ArrayList<>(Arrays.asList(filenames));
    try (JarInputStream jis = new JarInputStream(in)) {
        // parse the entries
        JarEntry entry;
        while ((entry = jis.getNextJarEntry()) != null) {
            if (!toExtract.contains(entry.getName())) {
                continue;
            }
            // match found
            File f = new File(destination, entry.getName());
            f.getParentFile().mkdirs();

            try (FileOutputStream fos = new FileOutputStream(f);
                    BufferedOutputStream out = new BufferedOutputStream(fos)) {
                byte[] byteBuffer = new byte[1024];
                int numRead;
                while ((numRead = jis.read(byteBuffer)) != -1) {
                    out.write(byteBuffer, 0, numRead);
                }
            }
            toExtract.remove(entry.getName());
        }
    }
    if (!toExtract.isEmpty()) {
        throw new FileNotFoundException("Failed to extract all of the specified files.");
    }
}

From source file:org.syncany.operations.plugin.PluginOperation.java

private PluginInfo readPluginInfoFromJar(File pluginJarFile) throws Exception {
    try (JarInputStream jarStream = new JarInputStream(new FileInputStream(pluginJarFile))) {
        Manifest jarManifest = jarStream.getManifest();

        if (jarManifest == null) {
            throw new Exception(
                    "Given file is not a valid Syncany plugin file (not a JAR file, or no manifest).");
        }//  w  w  w.  j  a  v a2 s  . com

        String pluginId = jarManifest.getMainAttributes().getValue("Plugin-Id");

        if (pluginId == null) {
            throw new Exception("Given file is not a valid Syncany plugin file (no plugin ID in manifest).");
        }

        PluginInfo pluginInfo = new PluginInfo();

        pluginInfo.setPluginId(pluginId);
        pluginInfo.setPluginName(jarManifest.getMainAttributes().getValue("Plugin-Name"));
        pluginInfo.setPluginVersion(jarManifest.getMainAttributes().getValue("Plugin-Version"));
        pluginInfo.setPluginDate(jarManifest.getMainAttributes().getValue("Plugin-Date"));
        pluginInfo.setPluginAppMinVersion(jarManifest.getMainAttributes().getValue("Plugin-App-Min-Version"));
        pluginInfo.setPluginRelease(
                Boolean.parseBoolean(jarManifest.getMainAttributes().getValue("Plugin-Release")));

        if (jarManifest.getMainAttributes().getValue("Plugin-Conflicts-With") != null) {
            pluginInfo.setConflictingPluginIds(
                    Arrays.asList(jarManifest.getMainAttributes().getValue("Plugin-Conflicts-With")));
        }

        return pluginInfo;
    }
}