Example usage for java.util.jar JarFile JarFile

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

Introduction

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

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:JarUtil.java

/**
 * Adds the given file to the specified JAR file.
 * /*ww w .j  a  v a  2s . c  o 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:net.technicpack.launchercore.util.ZipUtils.java

public static void copyMinecraftJar(File minecraft, File output) throws IOException {
    String[] security = { "MOJANG_C.DSA", "MOJANG_C.SF", "CODESIGN.RSA", "CODESIGN.SF" };
    JarFile jarFile = new JarFile(minecraft);
    try {//  w  w w  .j a  v  a2s .  c  o  m
        String fileName = jarFile.getName();
        String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));

        JarOutputStream jos = new JarOutputStream(new FileOutputStream(output));
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (containsAny(entry.getName(), security)) {
                continue;
            }
            InputStream is = jarFile.getInputStream(entry);

            //jos.putNextEntry(entry);
            //create a new entry to avoid ZipException: invalid entry compressed size
            jos.putNextEntry(new JarEntry(entry.getName()));
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = is.read(buffer)) != -1) {
                jos.write(buffer, 0, bytesRead);
            }
            is.close();
            jos.flush();
            jos.closeEntry();
        }
        jos.close();
    } finally {
        jarFile.close();
    }

}

From source file:org.eclipse.virgo.kernel.artifact.bundle.BundleBridgeTests.java

@Test
public void testBuildDictionary() throws ArtifactGenerationException, IOException {
    File testFile = new File(System.getProperty("user.home")
            + "/virgo-build-cache/ivy-cache/repository/org.eclipse.virgo.mirrored/javax.servlet/3.0.0.v201112011016/javax.servlet-3.0.0.v201112011016.jar");

    ArtifactDescriptor inputArtefact = BUNDLE_BRIDGE.generateArtifactDescriptor(testFile);

    Dictionary<String, String> dictionary = BundleBridge.convertToDictionary(inputArtefact);

    JarFile testJar = new JarFile(testFile);
    Attributes attributes = testJar.getManifest().getMainAttributes();

    testJar.close();//w w  w. java 2 s.  c  om

    assertEquals("Failed to match regenerated " + Constants.BUNDLE_SYMBOLICNAME,
            dictionary.get(Constants.BUNDLE_SYMBOLICNAME), attributes.getValue(Constants.BUNDLE_SYMBOLICNAME));
    assertEquals("Failed to match regenerated " + Constants.BUNDLE_VERSION,
            dictionary.get(Constants.BUNDLE_VERSION), attributes.getValue(Constants.BUNDLE_VERSION));
    assertEquals("Failed to match regenerated " + BUNDLE_MANIFEST_VERSION_HEADER_NAME,
            dictionary.get(BUNDLE_MANIFEST_VERSION_HEADER_NAME),
            attributes.getValue(BUNDLE_MANIFEST_VERSION_HEADER_NAME));
    assertEquals("Failed to match regenerated " + BUNDLE_NAME_HEADER_NAME,
            dictionary.get(BUNDLE_NAME_HEADER_NAME), attributes.getValue(BUNDLE_NAME_HEADER_NAME));

}

From source file:org.batfish.common.plugin.PluginConsumer.java

private void loadPluginJar(Path path) {
    /*/*from  www .j a v  a2 s.  co  m*/
     * Adapted from
     * http://stackoverflow.com/questions/11016092/how-to-load-classes-at-
     * runtime-from-a-folder-or-jar Retrieved: 2016-08-31 Original Authors:
     * Kevin Crain http://stackoverflow.com/users/2688755/kevin-crain
     * Apfelsaft http://stackoverflow.com/users/1447641/apfelsaft License:
     * https://creativecommons.org/licenses/by-sa/3.0/
     */
    String pathString = path.toString();
    if (pathString.endsWith(".jar")) {
        try {
            URL[] urls = { new URL("jar:file:" + pathString + "!/") };
            URLClassLoader cl = URLClassLoader.newInstance(urls, _currentClassLoader);
            _currentClassLoader = cl;
            Thread.currentThread().setContextClassLoader(cl);
            JarFile jar = new JarFile(path.toFile());
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry element = entries.nextElement();
                String name = element.getName();
                if (element.isDirectory() || !name.endsWith(CLASS_EXTENSION)) {
                    continue;
                }
                String className = name.substring(0, name.length() - CLASS_EXTENSION.length()).replace("/",
                        ".");
                try {
                    cl.loadClass(className);
                    Class<?> pluginClass = Class.forName(className, true, cl);
                    if (!Plugin.class.isAssignableFrom(pluginClass)
                            || Modifier.isAbstract(pluginClass.getModifiers())) {
                        continue;
                    }
                    Constructor<?> pluginConstructor;
                    try {
                        pluginConstructor = pluginClass.getConstructor();
                    } catch (NoSuchMethodException | SecurityException e) {
                        throw new BatfishException(
                                "Could not find default constructor in plugin: '" + className + "'", e);
                    }
                    Object pluginObj;
                    try {
                        pluginObj = pluginConstructor.newInstance();
                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                            | InvocationTargetException e) {
                        throw new BatfishException(
                                "Could not instantiate plugin '" + className + "' from constructor", e);
                    }
                    Plugin plugin = (Plugin) pluginObj;
                    plugin.initialize(this);

                } catch (ClassNotFoundException e) {
                    jar.close();
                    throw new BatfishException("Unexpected error loading classes from jar", e);
                }
            }
            jar.close();
        } catch (IOException e) {
            throw new BatfishException("Error loading plugin jar: '" + path.toString() + "'", e);
        }
    }
}

From source file:com.qcadoo.plugin.internal.descriptorparser.DefaultPluginDescriptorParser.java

@Override
public InternalPlugin parse(final File file) {
    JarFile jarFile = null;/*from ww  w. j av  a 2 s . c  o m*/
    try {
        LOG.info("Parsing descriptor for:" + file.getAbsolutePath());

        boolean ignoreModules = true;

        jarFile = new JarFile(file);

        JarEntry descriptorEntry = findDescriptorEntry(jarFile.entries(), file.getAbsolutePath());

        return parse(jarFile.getInputStream(descriptorEntry), ignoreModules, file.getName());
    } catch (IOException e) {
        throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(),
                e);
    } catch (Exception e) {
        throw new PluginException(e.getMessage(), e);
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
                throw new PluginException(
                        "Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(), e);
            }
        }
    }
}

From source file:org.dspace.installer_edm.InstallerEDMConfEDMExport.java

/**
 * Abre el archivo EDMExport.war y se recorre la lista de archivos que lo componen.
 * En web.xml lo abre con jdom y pide la ruta de dspace.cfg para modificarlo
 * Para los jar con la api de dspace y de lucene muestra cul hay en el war y cul en dspace y pregunta si se cambia
 *//* www.  j a  v a 2  s. c  o m*/
public void configure() {
    try {
        // comprobar validez del war
        if (checkEDMExporWar()) {
            // copiar al directorio de trabajo
            eDMExportWarWorkFile = new File(
                    myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
            copyDspaceFile2Work(eDMExportWarFile, eDMExportWarWorkFile, "configure.edmexport");

            // abrir el war
            eDMExportWarJarFile = new JarFile(eDMExportWarWorkFile);
            // buscar web.xml
            ZipEntry edmExportWebZipentry = eDMExportWarJarFile.getEntry("WEB-INF/web.xml");
            if (edmExportWebZipentry == null)
                installerEDMDisplay.showQuestion(currentStepGlobal, "configure.notwebxml");
            else {
                // crear dom de web.xml
                InputStream is = eDMExportWarJarFile.getInputStream(edmExportWebZipentry);
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                eDMExportDocument = builder.parse(is);
                // buscar dspace-config
                XPath xpathInputForms = XPathFactory.newInstance().newXPath();
                NodeList resultsDspaceConfig = (NodeList) xpathInputForms.evaluate(xpathDspaceConfigTemplate,
                        eDMExportDocument, XPathConstants.NODESET);
                if (resultsDspaceConfig.getLength() == 0) {
                    installerEDMDisplay.showQuestion(currentStepGlobal, "configure.nopath");
                } else {
                    // preguntar ruta de dspace.cfg y configurar los jar
                    Element contextParam = (Element) resultsDspaceConfig.item(0);
                    if (contextParam.getTagName().equals("context-param")) {
                        NodeList resultsParamValue = contextParam.getElementsByTagName("param-value");
                        if (resultsParamValue.getLength() > 0) {
                            Element valueParam = (Element) resultsParamValue.item(0);
                            String dspaceCfg = DspaceDir + "config" + fileSeparator + "dspace.cfg";
                            installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg",
                                    new String[] { dspaceCfg });
                            File dspaceCfgFile = new File(dspaceCfg);
                            String response = null;
                            do {
                                response = br.readLine();
                                if (response == null)
                                    continue;
                                response = response.trim();
                                if (response.isEmpty()) {
                                    break;
                                } else {
                                    dspaceCfgFile = new File(response);
                                    if (dspaceCfgFile.exists())
                                        break;
                                }
                            } while (true);
                            Text text = eDMExportDocument.createTextNode(dspaceCfgFile.getAbsolutePath());
                            valueParam.replaceChild(text, valueParam.getFirstChild());
                            // jar con la api de dspace
                            findDspaceApi();
                            // jars con lucene
                            findLuceneLib();
                            // escribir el nuevo war con las modificaciones
                            writeNewJar();
                            eDMExportWarJarFile = new JarFile(eDMExportWarWorkFile);
                            installerEDMDisplay.showLn();
                            installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg.ok",
                                    new String[] { eDMExportWarWorkFile.getAbsolutePath() });
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        showException(e);
        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg.nok");
    } catch (ParserConfigurationException e) {
        showException(e);
        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg.nok");
    } catch (SAXException e) {
        showException(e);
        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg.nok");
    } catch (XPathExpressionException e) {
        showException(e);
        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg.nok");
    } catch (TransformerException e) {
        showException(e);
        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg.nok");
    }
}

From source file:com.orange.mmp.module.osgi.MMPOSGiContainer.java

/**
 * Deploy a module bundle on MMP server/*from   ww  w  . j a v a2 s  .  co  m*/
 * @param moduleFile The module file (JAR file)
 */
@SuppressWarnings("unchecked")
public Module deployModule(File moduleFile) throws MMPException {
    try {
        JarFile jarFile = new JarFile(new File(moduleFile.toURI()));
        Manifest manifest = jarFile.getManifest();
        if (manifest == null) {
            throw new MMPException("invalid module archive, MANIFEST file not found");
        }
        // Get Bundle category
        Attributes attributes = manifest.getMainAttributes();
        String category = attributes.getValue(BUNDLE_CATEGORY_HEADER);
        // Test if the module is a widget
        if (category != null && category.equals(com.orange.mmp.core.Constants.MODULE_CATEGORY_WIDGET)) {
            Widget widget = new Widget();
            String symbName = attributes.getValue(BUNDLE_SYMBOLICNAME_HEADER);
            String branch = symbName.split(com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN)[1];
            widget.setLocation(moduleFile.toURI());
            widget.setBranchId(branch);
            DaoManagerFactory.getInstance().getDaoManager().getDao("module").createOrUdpdate(widget);
            this.lastUpdate = 0;
            this.refresh();
            return widget;
        } else {
            Module module = new Module();
            module.setLocation(moduleFile.toURI());
            DaoManagerFactory.getInstance().getDaoManager().getDao("module").createOrUdpdate(module);
            this.lastUpdate = 0;
            this.refresh();
            return module;
        }

    } catch (IOException ioe) {
        throw new MMPException("Failed to deploy module", ioe);
    }
}

From source file:com.netflix.nicobar.core.persistence.JarArchiveRepository.java

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleJarPath = getModuleJarPath(moduleId);
    Files.deleteIfExists(moduleJarPath);
    JarFile sourceJarFile;/*from   ww  w  .  j av  a 2 s .c o m*/
    try {
        sourceJarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    JarOutputStream destJarFile = new JarOutputStream(new FileOutputStream(moduleJarPath.toFile()));
    try {
        String moduleSpecFileName = moduleSpecSerializer.getModuleSpecFileName();
        Enumeration<JarEntry> sourceEntries = sourceJarFile.entries();
        while (sourceEntries.hasMoreElements()) {
            JarEntry sourceEntry = sourceEntries.nextElement();
            if (sourceEntry.getName().equals(moduleSpecFileName)) {
                // avoid double entry for module spec
                continue;
            }
            destJarFile.putNextEntry(sourceEntry);
            if (!sourceEntry.isDirectory()) {
                InputStream inputStream = sourceJarFile.getInputStream(sourceEntry);
                IOUtils.copy(inputStream, destJarFile);
                IOUtils.closeQuietly(inputStream);
            }
            destJarFile.closeEntry();
        }
        // write the module spec
        String serialized = moduleSpecSerializer.serialize(moduleSpec);
        JarEntry moduleSpecEntry = new JarEntry(moduleSpecSerializer.getModuleSpecFileName());
        destJarFile.putNextEntry(moduleSpecEntry);
        IOUtils.write(serialized, destJarFile);
        destJarFile.closeEntry();
    } finally {
        IOUtils.closeQuietly(sourceJarFile);
        IOUtils.closeQuietly(destJarFile);
    }
    // update the timestamp on the jar file to indicate that the module has been updated
    Files.setLastModifiedTime(moduleJarPath, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}

From source file:org.apache.apex.common.util.JarHelper.java

/**
 * Returns a full path to the jar-file that contains the given class and all full paths to dependent jar-files
 * that are defined in the property "apex-dependencies" of the manifest of the root jar-file.
 * If the class is an independent file the method makes jar file from the folder that contains the class
 * @param jarClass Class//from w w  w .j av  a2 s.  com
 * @param makeJarFromFolder True if the method should make jar from folder that contains the independent class
 * @param addJarDependencies True if the method should include dependent jar files
 * @return Set of names of the jar-files
 */
public Set<String> getJars(Class<?> jarClass, boolean makeJarFromFolder, boolean addJarDependencies) {
    String jar = getJar(jarClass, makeJarFromFolder);
    Set<String> set = new HashSet<>();
    if (jar != null) {
        set.add(jar);
        if (addJarDependencies) {
            try {
                getDependentJarsFromManifest(new JarFile(jar), set);
            } catch (IOException ex) {
                logger.warn("Cannot open Jar-file {}", jar);
            }
        }
    }
    return set;
}

From source file:com.netflix.nicobar.core.persistence.PathArchiveRepository.java

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleDir = rootDir.resolve(moduleId.toString());
    if (Files.exists(moduleDir)) {
        FileUtils.deleteDirectory(moduleDir.toFile());
    }//w w  w.j  av a  2s .  co  m
    JarFile jarFile;
    try {
        jarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    try {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            Path entryName = moduleDir.resolve(jarEntry.getName());
            if (jarEntry.isDirectory()) {
                Files.createDirectories(entryName);
            } else {
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                try {
                    Files.copy(inputStream, entryName);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(jarFile);
    }
    // write the module spec
    String serialized = moduleSpecSerializer.serialize(moduleSpec);
    Files.write(moduleDir.resolve(moduleSpecSerializer.getModuleSpecFileName()),
            serialized.getBytes(Charsets.UTF_8));

    // update the timestamp on the module directory to indicate that the module has been updated
    Files.setLastModifiedTime(moduleDir, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}