Example usage for java.util.jar JarFile close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

From source file:interactivespaces.resource.analysis.OsgiResourceAnalyzer.java

@Override
public NamedVersionedResourceCollection<NamedVersionedResourceWithData<String>> getResourceCollection(
        File baseDir) {//from w w  w  . j a  va2s .  c  o m
    NamedVersionedResourceCollection<NamedVersionedResourceWithData<String>> resources = NamedVersionedResourceCollection
            .newNamedVersionedResourceCollection();

    File[] files = baseDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.getName().endsWith(".jar");
        }
    });

    if (files != null) {
        for (File file : files) {
            JarFile jarFile = null;
            try {
                jarFile = new JarFile(file);
                Manifest manifest = jarFile.getManifest();
                Attributes attributes = manifest.getMainAttributes();
                String name = attributes.getValue(OSGI_HEADER_SYMBOLIC_NAME);
                String version = attributes.getValue(OSGI_HEADER_VERSION);
                if (name != null && version != null) {
                    NamedVersionedResourceWithData<String> resource = new NamedVersionedResourceWithData<String>(
                            name, Version.parseVersion(version), file.getAbsolutePath());

                    resources.addResource(resource.getName(), resource.getVersion(), resource);
                } else {
                    log.warn(String.format(
                            "Resource %s is not a proper OSGi bundle (missing symbolic name and/or version) and is being ignored.",
                            file.getAbsolutePath()));
                }
            } catch (IOException e) {
                log.error(String.format("Could not open resource file jar manifest for %s",
                        file.getAbsolutePath()), e);
            } finally {
                // For some reason Closeables does not work with JarFile despite it
                // claiming it is Closeable in the Javadoc.
                if (jarFile != null) {
                    try {
                        jarFile.close();
                    } catch (IOException e) {
                        // Don't care.
                    }
                }
            }
        }
    }

    return resources;
}

From source file:org.openecard.addon.PluginDirectoryAlterationListener.java

private AddonSpecification getAddonSpecificationFromFile(File file) {
    String name = file.getName();
    JarFile jarFile;
    AddonSpecification abd;/* w w w. j av  a2 s  .  c o  m*/
    try {
        jarFile = new JarFile(file);
    } catch (IOException e) {
        logger.error("File {} will not be registered as plugin because it's not a JarFile.", name);
        return null;
    }
    try {
        InputStream manifestStream = getPluginEntryClass(jarFile);

        if (manifestStream == null) {
            logger.error("File {} will not be registered as plugin because it doesn't contain a Manifest.xml.",
                    name);
            return null;
        } else {
            marshaller.addXmlTypeClass(AddonSpecification.class);
            Document manifestDoc = marshaller.str2doc(manifestStream);
            abd = (AddonSpecification) marshaller.unmarshal(manifestDoc);
        }
    } catch (IOException ex) {
        logger.error("Failed to process Manifest.xml entry for file " + name, ex);
        return null;
    } catch (MarshallingTypeException e) {
        logger.error("Failed to process Manifest.xml entry for file " + name, e);
        return null;
    } catch (SAXException e) {
        logger.error("Failed to process Manifest.xml entry for file " + name, e);
        return null;
    } catch (WSMarshallerException e) {
        logger.error("Failed to process Manifest.xml entry for file " + name, e);
        return null;
    } finally {
        try {
            jarFile.close();
        } catch (IOException ex) {
            logger.error("Failed to close jar file.", ex);
        }
    }
    return abd;
}

From source file:es.jamisoft.comun.utils.compression.Jar.java

public void descomprimir(String lsDirDestino) {
    try {/*from ww  w  . j  a  va 2 s  .c  o  m*/
        JarFile lzfFichero = new JarFile(isFicheroJar);
        Enumeration lenum = lzfFichero.entries();
        JarArchiveEntry entrada = null;
        InputStream linput;

        for (; lenum.hasMoreElements(); linput.close()) {
            entrada = (JarArchiveEntry) lenum.nextElement();
            linput = lzfFichero.getInputStream(entrada);

            byte labBytes[] = new byte[2048];
            int liLeido = -1;
            String lsRutaDestino = lsDirDestino + File.separator + entrada.getName();

            lsRutaDestino = lsRutaDestino.replace('\\', File.separatorChar);

            File lfRutaCompleta = new File(lsRutaDestino);
            String lsRuta = lfRutaCompleta.getAbsolutePath();
            int liPosSeparator = lsRuta.lastIndexOf(File.separatorChar);

            lsRuta = lsRuta.substring(0, liPosSeparator);

            File ldDir = new File(lsRuta);
            boolean lbCreado = ldDir.mkdirs();

            if (entrada.isDirectory()) {
                continue;
            }

            FileOutputStream loutput = new FileOutputStream(lfRutaCompleta);

            if (entrada.getSize() > 0L) {
                while ((liLeido = linput.read(labBytes, 0, 2048)) != -1) {
                    loutput.write(labBytes, 0, liLeido);
                }
            }

            loutput.flush();
            loutput.close();
        }

        lzfFichero.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.moe.cli.ParameterParserTest.java

@Test
public void linkLibrary() throws Exception {

    File project = tmpDir.newFolder();
    File outputJar = new File(project, "TestLib.jar");

    // prepare file with ldFlags
    String flags = "-lTestLibrary";
    File ldFlags = new File(project, "ldflags");
    ldFlags.createNewFile();/* w  w w  .j  av  a  2  s .  c o  m*/
    PrintWriter write = new PrintWriter(ldFlags);
    write.print(flags);
    write.close();

    ClassLoader cl = this.getClass().getClassLoader();
    URL library = cl.getResource("natives/simulator/libTestLibrary.a");
    URL deviceLibrary = cl.getResource("natives/device/libTestLibrary.a");
    URL headersURL = cl.getResource("natives/Headers/TestFramework.h");

    File headers = new File(headersURL.getPath());
    URL bundle = cl.getResource("moe_logo.png");
    CommandLine argc = parseArgs(new String[] { "--library",
            String.format("%s:%s", library.getPath(), deviceLibrary.getPath()), "--headers",
            headers.getParentFile().getPath(), "--package-name", "org", "--output-file-path",
            outputJar.getPath(), "--ld-flags", ldFlags.getPath(), "--bundle", bundle.getPath() });

    IExecutor executor = ExecutorManager.getExecutorByParams(argc);
    assertNotNull(executor);
    assertTrue(executor instanceof ThirdPartyLibraryLinkExecutor);

    // generate binding & prepare output jar
    executor.execute();

    // check output jar file existence
    assertTrue(outputJar.exists());

    JarFile jarFile = new JarFile(outputJar);
    Manifest manifest = jarFile.getManifest();

    Attributes attributes = manifest.getMainAttributes();
    String manifestLDFlags = attributes.getValue("MOE_CUSTOM_LINKER_FLAGS");
    Set<String> realLDFlags = new HashSet<String>(Arrays.asList(flags.split(";")));
    realLDFlags.add("-ObjC");
    assertEquals(realLDFlags, new HashSet<String>(Arrays.asList(manifestLDFlags.split(";"))));

    String manifestSimFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_simulator");
    assertEquals("./lib/iphonesimulator/libTestLibrary.a", manifestSimFramework);

    String manifestDevFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_device");
    assertEquals("./lib/iphoneos/libTestLibrary.a", manifestDevFramework);

    String manifestBundle = attributes.getValue("MOE_BUNDLE_FILE_RESOURCES");
    assertEquals("./bundle/moe_logo.png;", manifestBundle);

    assertNotNull(jarFile.getEntry("bundle/moe_logo.png"));
    assertNotNull(jarFile.getEntry("lib/iphonesimulator/libTestLibrary.a"));
    assertNotNull(jarFile.getEntry("lib/iphoneos/libTestLibrary.a"));

    jarFile.close();

}

From source file:eu.stratosphere.yarn.Client.java

private File generateDefaultConf(Path localJarPath) throws IOException, FileNotFoundException {
    JarFile jar = null;
    try {/*from   ww w  . j  a v  a2  s . c  o  m*/
        jar = new JarFile(localJarPath.toUri().getPath());
    } catch (FileNotFoundException fne) {
        LOG.fatal("Unable to access jar file. Specify jar file or configuration file.", fne);
        System.exit(1);
    }
    InputStream confStream = jar.getInputStream(jar.getEntry("stratosphere-conf.yaml"));

    if (confStream == null) {
        LOG.warn("Given jar file does not contain yaml conf.");
        confStream = this.getClass().getResourceAsStream("stratosphere-conf.yaml");
        if (confStream == null) {
            throw new RuntimeException("Unable to find stratosphere-conf in jar file");
        }
    }
    File outFile = new File("stratosphere-conf.yaml");
    if (outFile.exists()) {
        throw new RuntimeException("File unexpectedly exists");
    }
    FileOutputStream outputStream = new FileOutputStream(outFile);
    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = confStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
    confStream.close();
    outputStream.close();
    jar.close();
    return outFile;
}

From source file:org.pepstock.jem.util.ReverseURLClassLoader.java

/**
  * Returns an input stream to a given resource in the given file which may
  * either be a directory or a jar file.
  */*from ww  w . j a  v  a  2 s .c o m*/
  * @param url the file (directory or jar) in which to search for the
  *             resource. Must not be <code>null</code>.
  * @param resourceName The name of the resource for which a stream is
  *                     required. Must not be <code>null</code>.
  *
  * @return a stream to the required resource or <code>null</code> if
  *         the resource cannot be found in the given file.
  */
private InputStream getResourceStream(URL url, String resourceName) {
    JarFile jFile = null;
    try {
        // gets the file from URL
        File file = new File(url.toURI());
        // if is a directory, then checks on the file system
        // where URL id the parent file and resource name is the file
        if (file.isDirectory()) {
            File resource = new File(file, resourceName);
            // checks if exists
            if (resource.exists()) {
                // returns inpu stream
                return new FileInputStream(resource);
            }
        } else if (file.exists()) {
            // if here, the URL must be a link to a JAR file
            jFile = new JarFile(file);
            // searches in the JAR for the resource name
            JarEntry entry = jFile.getJarEntry(resourceName);
            // if found return the JAR InputStream
            if (entry != null) {
                // FINDBUGS: it's correct do not close the jar file
                // otherwise the stream will be closed
                InputStream resourceIS = jFile.getInputStream(entry);
                // reads input stream in byte array
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                return copy(jFile, resourceIS, baos);
            }
            // close always the jar file
            jFile.close();
        }
    } catch (Exception e) {
        LogAppl.getInstance().ignore(e.getMessage(), e);
    }
    return null;
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleDeployMojo.java

/**
 * Change the version in jar//  w w  w.  j a va 2s  . c om
 * 
 * @param newVersion
 * @param file
 * @return
 * @throws MojoExecutionException
 */
protected File changeVersion(File file, String oldVersion, String newVersion) throws MojoExecutionException {
    String fileName = file.getName();
    int pos = fileName.indexOf(oldVersion);
    fileName = fileName.substring(0, pos) + newVersion + fileName.substring(pos + oldVersion.length());

    JarInputStream jis = null;
    JarOutputStream jos;
    OutputStream out = null;
    JarFile sourceJar = null;
    try {
        // now create a temporary file and update the version
        sourceJar = new JarFile(file);
        final Manifest manifest = sourceJar.getManifest();
        manifest.getMainAttributes().putValue("Bundle-Version", newVersion);

        jis = new JarInputStream(new FileInputStream(file));
        final File destJar = new File(file.getParentFile(), fileName);
        out = new FileOutputStream(destJar);
        jos = new JarOutputStream(out, manifest);

        jos.setMethod(JarOutputStream.DEFLATED);
        jos.setLevel(Deflater.BEST_COMPRESSION);

        JarEntry entryIn = jis.getNextJarEntry();
        while (entryIn != null) {
            JarEntry entryOut = new JarEntry(entryIn.getName());
            entryOut.setTime(entryIn.getTime());
            entryOut.setComment(entryIn.getComment());
            jos.putNextEntry(entryOut);
            if (!entryIn.isDirectory()) {
                IOUtils.copy(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();
        return destJar;
    } catch (IOException ioe) {
        throw new MojoExecutionException("Unable to update version in jar file.", ioe);
    } finally {
        if (sourceJar != null) {
            try {
                sourceJar.close();
            } catch (IOException ex) {
                // close
            }
        }
        IOUtils.closeQuietly(jis);
        IOUtils.closeQuietly(out);
    }

}

From source file:org.jahia.data.templates.ModulesPackage.java

private ModulesPackage(JarFile jarFile) throws IOException {
    modules = new LinkedHashMap<String, PackagedModule>();
    Attributes manifestAttributes = jarFile.getManifest().getMainAttributes();
    version = new Version(manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_VERSION));
    name = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_NAME);
    description = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_DESCRIPTION);
    // read jars/* ww  w . j  a v a  2  s .  c om*/
    Enumeration<JarEntry> jars = jarFile.entries();

    while (jars.hasMoreElements()) {
        JarEntry jar = jars.nextElement();
        JarFile moduleJarFile = null;
        OutputStream output = null;
        if (StringUtils.endsWith(jar.getName(), ".jar")) {
            try {
                InputStream input = jarFile.getInputStream(jar);
                File moduleFile = File.createTempFile(jar.getName(), "");
                output = new FileOutputStream(moduleFile);
                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = input.read(bytes)) != -1) {
                    output.write(bytes, 0, read);
                }
                moduleJarFile = new JarFile(moduleFile);
                Attributes moduleManifestAttributes = moduleJarFile.getManifest().getMainAttributes();
                String bundleName = moduleManifestAttributes.getValue(Constants.ATTR_NAME_BUNDLE_SYMBOLIC_NAME);
                String jahiaGroupId = moduleManifestAttributes.getValue(Constants.ATTR_NAME_GROUP_ID);
                if (bundleName == null || jahiaGroupId == null) {
                    throw new IOException(
                            "Jar file " + jar.getName() + " in package does not seems to be a DX bundle.");
                }
                modules.put(bundleName, new PackagedModule(bundleName, moduleManifestAttributes, moduleFile));
            } finally {
                IOUtils.closeQuietly(output);
                if (moduleJarFile != null) {
                    moduleJarFile.close();
                }
            }
        }
    }

    // we finally sort modules based on dependencies
    try {
        sortByDependencies(modules);
    } catch (CycleDetectedException e) {
        throw new JahiaRuntimeException("A cyclic dependency detected in the modules of the supplied package",
                e);
    }
}

From source file:org.mule.util.scan.ClasspathScanner.java

protected <T> Set<Class<T>> processJarUrl(URL url, String basepath, Class<T> clazz, int flags)
        throws IOException {
    Set<Class<T>> set = new HashSet<Class<T>>();
    String path = url.getFile().substring(5, url.getFile().indexOf("!"));
    // We can't URLDecoder.decode(path) since some encoded chars are allowed on file uris
    path = path.replaceAll("%20", " ");
    JarFile jar = new JarFile(path);

    for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) {
        JarEntry entry = entries.nextElement();
        if (entry.getName().startsWith(basepath) && entry.getName().endsWith(".class")) {
            try {
                String name = entry.getName();
                // Ignore anonymous and inner classes
                if (name.contains("$") && !hasFlag(flags, INCLUDE_INNER)) {
                    continue;
                }/*from w  w w . ja va 2 s.c  o m*/

                URL classURL = classLoader.getResource(name);
                InputStream classStream = classURL.openStream();
                ClassReader reader = new ClosableClassReader(classStream);

                ClassScanner visitor = getScanner(clazz);
                reader.accept(visitor, 0);
                if (visitor.isMatch()) {
                    @SuppressWarnings("unchecked")
                    Class<T> loadedClass = (Class<T>) loadClass(visitor.getClassName());
                    addClassToSet(loadedClass, set, flags);
                }
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    Throwable t = ExceptionHelper.getRootException(e);
                    logger.debug(String.format("%s: caused by: %s", e.toString(), t.toString()));
                }
            }
        }
    }
    jar.close();

    return set;
}

From source file:org.openmrs.module.ModuleFactory.java

/**
 * Execute all unrun changeSets in liquibase.xml for the given module
 * /*from   w w  w.j a v a  2  s  .  c  o  m*/
 * @param module the module being executed on
 */
private static void runLiquibase(Module module) {
    JarFile jarFile = null;
    boolean liquibaseFileExists = false;

    try {
        try {
            jarFile = new JarFile(module.getFile());
        } catch (IOException e) {
            throw new ModuleException("Unable to get jar file", module.getName(), e);
        }

        //check whether module has a liquibase.xml
        InputStream inStream = null;
        ZipEntry entry = null;
        try {
            inStream = ModuleUtil.getResourceFromApi(jarFile, module.getModuleId(), module.getVersion(),
                    MODULE_CHANGELOG_FILENAME);
            if (inStream == null) {
                // Try the old way. Loading from the root of the omod
                entry = jarFile.getEntry(MODULE_CHANGELOG_FILENAME);
            }
            liquibaseFileExists = (inStream != null) || (entry != null);
        } finally {
            IOUtils.closeQuietly(inStream);
        }
    } finally {
        try {
            if (jarFile != null) {
                jarFile.close();
            }
        } catch (IOException e) {
            log.warn("Unable to close jarfile: " + jarFile.getName());
        }
    }

    if (liquibaseFileExists) {
        try {
            // run liquibase.xml by Liquibase API
            DatabaseUpdater.executeChangelog(MODULE_CHANGELOG_FILENAME, null, null, null,
                    getModuleClassLoader(module));
        } catch (InputRequiredException ire) {
            // the user would be stepped through the questions returned here.
            throw new ModuleException("Input during database updates is not yet implemented.", module.getName(),
                    ire);
        } catch (DatabaseUpdateException e) {
            throw new ModuleException("Unable to update data model using liquibase.xml.", module.getName(), e);
        } catch (Exception e) {
            throw new ModuleException("Unable to update data model using liquibase.xml.", module.getName(), e);
        }
    }
}