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:JarUtil.java

/**
 * Adds the given file to the specified JAR file.
 * // www  .j a  va  2 s . co  m
 * @param file
 *            the file that should be added
 * @param jarFile
 *            The JAR to which the file should be added
 * @param parentDir
 *            the parent directory of the file, this is used to calculate
 *            the path witin the JAR file. When null is given, the file will
 *            be added into the root of the JAR.
 * @param compress
 *            True when the jar file should be compressed
 * @throws FileNotFoundException
 *             when the jarFile does not exist
 * @throws IOException
 *             when a file could not be written or the jar-file could not
 *             read.
 */
public static void addToJar(File file, File jarFile, File parentDir, boolean compress)
        throws FileNotFoundException, IOException {
    File tmpJarFile = File.createTempFile("tmp", ".jar", jarFile.getParentFile());
    JarOutputStream out = new JarOutputStream(new FileOutputStream(tmpJarFile));
    if (compress) {
        out.setLevel(ZipOutputStream.DEFLATED);
    } else {
        out.setLevel(ZipOutputStream.STORED);
    }
    // copy contents of old jar to new jar:
    JarFile inputFile = new JarFile(jarFile);
    JarInputStream in = new JarInputStream(new FileInputStream(jarFile));
    CRC32 crc = new CRC32();
    byte[] buffer = new byte[512 * 1024];
    JarEntry entry = (JarEntry) in.getNextEntry();
    while (entry != null) {
        InputStream entryIn = inputFile.getInputStream(entry);
        add(entry, entryIn, out, crc, buffer);
        entryIn.close();
        entry = (JarEntry) in.getNextEntry();
    }
    in.close();
    inputFile.close();

    int sourceDirLength;
    if (parentDir == null) {
        sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1;
    } else {
        sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1
                - parentDir.getAbsolutePath().length();
    }
    addFile(file, out, crc, sourceDirLength, buffer);
    out.close();

    // remove old jar file and rename temp file to old one:
    if (jarFile.delete()) {
        if (!tmpJarFile.renameTo(jarFile)) {
            throw new IOException(
                    "Unable to rename temporary JAR file to [" + jarFile.getAbsolutePath() + "].");
        }
    } else {
        throw new IOException("Unable to delete old JAR file [" + jarFile.getAbsolutePath() + "].");
    }

}

From source file:com.jkoolcloud.tnt4j.streams.inputs.ZipLineStream.java

@Override
protected void initialize() throws Exception {
    super.initialize();

    if (StringUtils.isEmpty(zipFileName)) {
        throw new IllegalStateException(
                StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                        "TNTInputStream.property.undefined", StreamProperties.PROP_FILENAME));
    }/*from   www .ja  v  a  2s.  c o  m*/
    logger().log(OpLevel.DEBUG, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
            "ZipLineStream.initializing.stream"), zipFileName);

    InputStream fis = loadFile(zipPath);

    try {
        if (ArchiveTypes.JAR.name().equalsIgnoreCase(archType)) {
            zipStream = new JarInputStream(fis);
        } else if (ArchiveTypes.GZIP.name().equalsIgnoreCase(archType)) {
            zipStream = new GZIPInputStream(fis);
        } else {
            zipStream = new ZipInputStream(fis);
        }
    } catch (IOException exc) {
        Utils.close(fis);

        throw exc;
    }

    if (zipStream instanceof GZIPInputStream) {
        lineReader = new LineNumberReader(new BufferedReader(new InputStreamReader(zipStream)));
    } else {
        hasNextEntry();
    }
}

From source file:org.sherlok.utils.BundleCreatorUtil.java

private static void createBundle(Set<BundleDef> bundleDefs) throws Exception {

    // create fake POM from bundles and copy it
    String fakePom = MavenPom.writePom(bundleDefs, "BundleCreator", System.currentTimeMillis() + "");// must be unique
    Artifact rootArtifact = new DefaultArtifact(fakePom);
    LOG.trace("* rootArtifact: '{}'", rootArtifact);

    // add remote repository urls
    RepositorySystem system = AetherResolver.newRepositorySystem();
    RepositorySystemSession session = AetherResolver.newRepositorySystemSession(system,
            AetherResolver.LOCAL_REPO_PATH);
    Map<String, String> repositoriesDefs = map();
    for (BundleDef b : bundleDefs) {
        b.validate(b.getId());//from   ww  w. j  a va 2s .  c om
        for (Entry<String, String> id_url : b.getRepositories().entrySet()) {
            repositoriesDefs.put(id_url.getKey(), id_url.getValue());
        }
    }
    List<RemoteRepository> repos = AetherResolver.newRepositories(system, session, repositoriesDefs);

    // solve dependencies
    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(new Dependency(rootArtifact, ""));
    collectRequest
            .setRepositories(AetherResolver.newRepositories(system, session, new HashMap<String, String>()));
    CollectResult collectResult = system.collectDependencies(session, collectRequest);
    collectResult.getRoot().accept(new AetherResolver.ConsoleDependencyGraphDumper());
    PreorderNodeListGenerator p = new PreorderNodeListGenerator();
    collectResult.getRoot().accept(p);

    // now do the real fetching, and add jars to classpath
    List<Artifact> resolvedArtifacts = list();
    for (Dependency dependency : p.getDependencies(true)) {
        Artifact resolvedArtifact = system
                .resolveArtifact(session, new ArtifactRequest(dependency.getArtifact(), repos, ""))
                .getArtifact();
        resolvedArtifacts.add(resolvedArtifact);
        File jar = resolvedArtifact.getFile();

        // add this jar to the classpath
        ClassPathHack.addFile(jar);
        LOG.trace("* resolved artifact '{}', added to classpath: '{}'", resolvedArtifact,
                jar.getAbsolutePath());
    }

    BundleDef createdBundle = new BundleDef();
    createdBundle.setVersion("TODO!");
    createdBundle.setName("TODO!");
    for (BundleDef bundleDef : bundleDefs) {
        for (BundleDependency dep : bundleDef.getDependencies()) {
            createdBundle.addDependency(dep);
        }
    }

    for (Artifact a : resolvedArtifacts) {

        // only consider artifacts that were included in the initial bundle
        boolean found = false;
        for (BundleDef bundleDef : bundleDefs) {
            for (BundleDependency dep : bundleDef.getDependencies()) {
                if (a.getArtifactId().equals(dep.getArtifactId())) {
                    found = true;
                    break;
                }
            }
        }

        if (found) {

            JarInputStream is = new JarInputStream(new FileInputStream(a.getFile()));
            JarEntry entry;
            while ((entry = is.getNextJarEntry()) != null) {
                if (entry.getName().endsWith(".class")) {

                    try {
                        Class<?> clazz = Class.forName(entry.getName().replace('/', '.').replace(".class", ""));

                        // scan for all uimafit AnnotationEngines
                        if (JCasAnnotator_ImplBase.class.isAssignableFrom(clazz)) {
                            LOG.debug("AnnotationEngine: {}", clazz.getSimpleName());

                            final EngineDef engine = new EngineDef().setClassz(clazz.getName())
                                    .setName(clazz.getSimpleName()).setBundle(createdBundle);
                            createdBundle.addEngine(engine);
                            LOG.debug("{}", engine);

                            ReflectionUtils.doWithFields(clazz, new FieldCallback() {
                                public void doWith(final Field f)
                                        throws IllegalArgumentException, IllegalAccessException {

                                    ConfigurationParameter c = f.getAnnotation(ConfigurationParameter.class);
                                    if (c != null) {
                                        LOG.debug("* param: {} {} {} {}", new Object[] { c.name(),
                                                c.defaultValue(), c.mandatory(), f.getType() });

                                        String deflt = c.mandatory() ? "TODO" : "IS OPTIONAL";

                                        String value = c.defaultValue()[0]
                                                .equals(ConfigurationParameter.NO_DEFAULT_VALUE) ? deflt
                                                        : c.defaultValue()[0].toString();
                                        engine.addParameter(c.name(), list(value));
                                    }
                                }
                            });
                        }
                    } catch (Throwable e) {
                        System.err.println("something wrong with class " + entry.getName() + " " + e);
                    }
                }
            }
            is.close();
        }
    }

    // delete fake pom
    deleteDirectory(new File(LOCAL_REPO_PATH + "/org/sherlok/BundleCreator"));

    System.out.println(FileBased.writeAsString(createdBundle));
}

From source file:io.joynr.util.JoynrUtil.java

public static void copyDirectoryFromJar(String jarName, String srcDir, File tmpDir) throws IOException {

    JarFile jf = null;//w  ww .ja v  a 2 s.  c  o m
    JarInputStream jarInputStream = null;

    try {
        jf = new JarFile(jarName);
        JarEntry je = jf.getJarEntry(srcDir);
        if (je.isDirectory()) {
            FileInputStream fis = new FileInputStream(jarName);
            BufferedInputStream bis = new BufferedInputStream(fis);
            jarInputStream = new JarInputStream(bis);
            JarEntry ze = null;
            while ((ze = jarInputStream.getNextJarEntry()) != null) {
                if (ze.isDirectory()) {
                    continue;
                }
                if (ze.getName().contains(je.getName())) {
                    InputStream is = jf.getInputStream(ze);
                    String name = ze.getName().substring(ze.getName().lastIndexOf("/") + 1);
                    File tmpFile = new File(tmpDir + "/" + name); //File.createTempFile(file.getName(), "tmp");
                    tmpFile.deleteOnExit();
                    OutputStream outputStreamRuntime = new FileOutputStream(tmpFile);
                    copyStream(is, outputStreamRuntime);
                }
            }
        }
    } finally {
        if (jf != null) {
            jf.close();
        }
        if (jarInputStream != null) {
            jarInputStream.close();
        }
    }
}

From source file:org.jahia.modules.serversettings.portlets.BasePortletHelper.java

/**
 * Returns a file descriptor for the modified (prepared) portlet WAR file.
 * /*from  ww w  .j a v  a2 s .c  o m*/
 * @param sourcePortletWar
 *            the source portlet WAR file
 * @return a file descriptor for the modified (prepared) portlet WAR file
 * @throws IOException
 *             in case of processing error
 */
public File process(File sourcePortletWar) throws IOException {
    JarFile jar = new JarFile(sourcePortletWar);
    File dest = new File(FilenameUtils.getFullPathNoEndSeparator(sourcePortletWar.getPath()),
            FilenameUtils.getBaseName(sourcePortletWar.getName()) + ".war");
    try {
        boolean needsServerSpecificProcessing = needsProcessing(jar);
        if (portletTldsPresent(jar) && !needsServerSpecificProcessing) {
            return sourcePortletWar;
        }
        jar.close();
        final JarInputStream jarIn = new JarInputStream(new FileInputStream(sourcePortletWar));
        final Manifest manifest = jarIn.getManifest();
        final JarOutputStream jarOut;
        if (manifest != null) {
            jarOut = new JarOutputStream(new FileOutputStream(dest), manifest);
        } else {
            jarOut = new JarOutputStream(new FileOutputStream(dest));
        }

        try {
            copyEntries(jarIn, jarOut);

            process(jarIn, jarOut);

            if (!hasPortletTld) {
                addToJar("META-INF/portlet-resources/portlet.tld", "WEB-INF/portlet.tld", jarOut);
            }
            if (!hasPortlet2Tld) {
                addToJar("META-INF/portlet-resources/portlet_2_0.tld", "WEB-INF/portlet_2_0.tld", jarOut);
            }
        } finally {
            jarIn.close();
            jarOut.close();
            FileUtils.deleteQuietly(sourcePortletWar);
        }
        return dest;
    } finally {
        jar.close();
    }
}

From source file:org.romaframework.core.resource.ResourceResolver.java

/**
 * Examine a jar file searching for entities.
 * //from   ww  w  .  j  a va2 s  .c om
 * @param f
 * @throws IOException
 */
protected void examineJarFile(File f, String iStartingPackage) {
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(f);

        final JarInputStream jis = new JarInputStream(new BufferedInputStream(fis));
        JarEntry entry;
        String fullName, packagePrefix, name;
        String pathStartingPackage = Utility.getResourcePath(iStartingPackage);
        int i;

        while ((entry = jis.getNextJarEntry()) != null) {
            fullName = entry.getName();
            if (fullName.startsWith(pathStartingPackage) && acceptResorce(fullName)) {
                i = fullName.lastIndexOf(JAR_PATH_SEPARATOR) + 1;
                packagePrefix = fullName.substring(0, i).replace(JAR_PATH_SEPARATOR, PACKAGE_SEPARATOR);
                name = fullName.substring(i, fullName.length());
                addResource(f, name, packagePrefix, iStartingPackage);
            }
        }
    } catch (Exception e) {
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {
        }
    }
}

From source file:pl.otros.logview.api.BaseLoader.java

public List<String> getClassesFromJar(File jarFile) throws IOException {
    ArrayList<String> list = new ArrayList<>();
    try (JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile))) {
        JarEntry jarEntry;/*from w w w . ja  v  a  2 s.  c  o  m*/
        while (true) {
            jarEntry = jarInputStream.getNextJarEntry();
            if (null == jarEntry) {
                break;//
            }
            String s = jarEntry.getName();
            if (s.endsWith(".class")) {
                list.add(s.replace('/', '.').substring(0, s.length() - 6));
            }
        }
    } catch (IOException e) {
        throw e;
    }

    return list;
}

From source file:com.photon.phresco.service.util.ServerUtil.java

/**
 * Validate the given jar is valid maven plugin jar
 * /*from w  w  w .  j  av a2  s.  co  m*/
 * @return
 * @throws PhrescoException
 */
public static boolean validatePluginJar(InputStream inputJar) throws PhrescoException {
    try {
        jarInputStream = new JarInputStream(inputJar);
        JarEntry nextJarEntry = jarInputStream.getNextJarEntry();
        while ((nextJarEntry = jarInputStream.getNextJarEntry()) != null) {
            if (nextJarEntry.getName().equals(ServerConstants.PLUGIN_COMPONENTS_XML_FILE)
                    || nextJarEntry.getName().equals(ServerConstants.PLUGIN_XML_FILE)) {
                return true;
            }
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return false;
}

From source file:com.amalto.core.jobox.watch.JoboxListener.java

public void contextChanged(String jobFile, String context) {
    File entity = new File(jobFile);
    String sourcePath = jobFile;//from w w  w . j  av a  2s . c  o  m
    int dotMark = jobFile.lastIndexOf("."); //$NON-NLS-1$
    int separateMark = jobFile.lastIndexOf(File.separatorChar);
    if (dotMark != -1) {
        sourcePath = System.getProperty("java.io.tmpdir") + File.separatorChar //$NON-NLS-1$
                + jobFile.substring(separateMark, dotMark);
    }
    try {
        JoboxUtil.extract(jobFile, System.getProperty("java.io.tmpdir") + File.separatorChar); //$NON-NLS-1$
    } catch (Exception e1) {
        LOGGER.error("Extraction exception occurred.", e1);
        return;
    }
    List<File> resultList = new ArrayList<File>();
    JoboxUtil.findFirstFile(null, new File(sourcePath), "classpath.jar", resultList); //$NON-NLS-1$
    if (!resultList.isEmpty()) {
        JarInputStream jarIn = null;
        JarOutputStream jarOut = null;
        try {
            JarFile jarFile = new JarFile(resultList.get(0));
            Manifest mf = jarFile.getManifest();
            jarIn = new JarInputStream(new FileInputStream(resultList.get(0)));
            Manifest newManifest = jarIn.getManifest();
            if (newManifest == null) {
                newManifest = new Manifest();
            }
            newManifest.getMainAttributes().putAll(mf.getMainAttributes());
            newManifest.getMainAttributes().putValue("activeContext", context); //$NON-NLS-1$
            jarOut = new JarOutputStream(new FileOutputStream(resultList.get(0)), newManifest);
            byte[] buf = new byte[4096];
            JarEntry entry;
            while ((entry = jarIn.getNextJarEntry()) != null) {
                if ("META-INF/MANIFEST.MF".equals(entry.getName())) { //$NON-NLS-1$
                    continue;
                }
                jarOut.putNextEntry(entry);
                int read;
                while ((read = jarIn.read(buf)) != -1) {
                    jarOut.write(buf, 0, read);
                }
                jarOut.closeEntry();
            }
        } catch (Exception e) {
            LOGGER.error("Extraction exception occurred.", e);
        } finally {
            IOUtils.closeQuietly(jarIn);
            IOUtils.closeQuietly(jarOut);
        }
        // re-zip file
        if (entity.getName().endsWith(".zip")) { //$NON-NLS-1$
            File sourceFile = new File(sourcePath);
            try {
                JoboxUtil.zip(sourceFile, jobFile);
            } catch (Exception e) {
                LOGGER.error("Zip exception occurred.", e);
            }
        }
    }
}

From source file:org.apache.pluto.util.assemble.io.AssemblyStreamTest.java

protected void verifyAssembly(File warFile) throws Exception {
    PlutoWebXmlRewriter webXmlRewriter = null;
    PortletAppDescriptorService portletSvc = new PortletAppDescriptorServiceImpl();
    int entryCount = 0;
    ByteArrayOutputStream portletXmlBytes = new ByteArrayOutputStream();
    ByteArrayOutputStream webXmlBytes = new ByteArrayOutputStream();
    PortletApplicationDefinition portletApp = null;

    JarInputStream assembledWarIn = new JarInputStream(new FileInputStream(warFile));
    JarEntry tempEntry;//from  w  ww .  ja va 2  s  .c o m

    while ((tempEntry = assembledWarIn.getNextJarEntry()) != null) {
        entryCount++;

        if (Assembler.PORTLET_XML.equals(tempEntry.getName())) {
            IOUtils.copy(assembledWarIn, portletXmlBytes);
            portletApp = portletSvc.read("test", "/test",
                    new ByteArrayInputStream(portletXmlBytes.toByteArray()));
        }
        if (Assembler.SERVLET_XML.equals(tempEntry.getName())) {
            IOUtils.copy(assembledWarIn, webXmlBytes);
            webXmlRewriter = new PlutoWebXmlRewriter(new ByteArrayInputStream(webXmlBytes.toByteArray()));
        }
    }

    assertTrue("Assembled WAR file was empty.", entryCount > 0);
    assertNotNull("Web Application Descripter was null.", webXmlRewriter);
    assertNotNull("Portlet Application Descriptor was null.", portletApp);
    assertTrue("Portlet Application Descriptor doesn't define any portlets.",
            portletApp.getPortlets().size() > 0);
    assertTrue("Web Application Descriptor doesn't define any servlets.", webXmlRewriter.hasServlets());
    assertTrue("Web Application Descriptor doesn't define any servlet mappings.",
            webXmlRewriter.hasServletMappings());

    PortletDefinition portlet = (PortletDefinition) portletApp.getPortlets().iterator().next();
    assertTrue("Unable to retrieve test portlet named [" + testPortletName + "]",
            portlet.getPortletName().equals(testPortletName));

    String servletClassName = webXmlRewriter.getServletClass(testPortletName);
    assertNotNull("Unable to retrieve portlet dispatch for portlet named [" + testPortletName + "]",
            servletClassName);
    assertEquals("Dispatcher servlet incorrect for test portlet [" + testPortletName + "]",
            Assembler.DISPATCH_SERVLET_CLASS, servletClassName);
}