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:com.izforge.izpack.compiler.packager.impl.Packager.java

/**
 * Write Packs to primary jar or each to a separate jar.
 *//*from  ww  w  . j  a  v  a 2  s  .c  o m*/
protected void writePacks() throws Exception {
    final int num = packsList.size();
    sendMsg("Writing " + num + " Pack" + (num > 1 ? "s" : "") + " into installer");

    // Map to remember pack number and bytes offsets of back references
    Map<File, Object[]> storedFiles = new HashMap<File, Object[]>();

    // Pack200 files map
    Map<Integer, File> pack200Map = new HashMap<Integer, File>();
    int pack200Counter = 0;

    // Force UTF-8 encoding in order to have proper ZipEntry names.
    primaryJarStream.setEncoding("utf-8");

    // First write the serialized files and file metadata data for each pack
    // while counting bytes.

    int packNumber = 0;
    IXMLElement root = new XMLElementImpl("packs");

    for (PackInfo packInfo : packsList) {
        Pack pack = packInfo.getPack();
        pack.nbytes = 0;
        if ((pack.id == null) || (pack.id.length() == 0)) {
            pack.id = pack.name;
        }

        // create a pack specific jar if required
        // REFACTOR : Repare web installer
        // REFACTOR : Use a mergeManager for each packages that will be added to the main merger

        //            if (packJarsSeparate) {
        // See installer.Unpacker#getPackAsStream for the counterpart
        //                String name = baseFile.getName() + ".pack-" + pack.id + ".jar";
        //                packStream = IoHelper.getJarOutputStream(name, baseFile.getParentFile());
        //            }

        sendMsg("Writing Pack " + packNumber + ": " + pack.name, PackagerListener.MSG_VERBOSE);

        // Retrieve the correct output stream
        org.apache.tools.zip.ZipEntry entry = new org.apache.tools.zip.ZipEntry(
                RESOURCES_PATH + "packs/pack-" + pack.id);
        primaryJarStream.putNextEntry(entry);
        primaryJarStream.flush(); // flush before we start counting

        ByteCountingOutputStream dos = new ByteCountingOutputStream(outputStream);
        ObjectOutputStream objOut = new ObjectOutputStream(dos);

        // We write the actual pack files
        objOut.writeInt(packInfo.getPackFiles().size());

        for (PackFile packFile : packInfo.getPackFiles()) {
            boolean addFile = !pack.loose;
            boolean pack200 = false;
            File file = packInfo.getFile(packFile);

            if (file.getName().toLowerCase().endsWith(".jar") && info.isPack200Compression()
                    && isNotSignedJar(file)) {
                packFile.setPack200Jar(true);
                pack200 = true;
            }

            // use a back reference if file was in previous pack, and in
            // same jar
            Object[] info = storedFiles.get(file);
            if (info != null && !packJarsSeparate) {
                packFile.setPreviousPackFileRef((String) info[0], (Long) info[1]);
                addFile = false;
            }

            objOut.writeObject(packFile); // base info

            if (addFile && !packFile.isDirectory()) {
                long pos = dos.getByteCount(); // get the position

                if (pack200) {
                    /*
                     * Warning!
                     * 
                     * Pack200 archives must be stored in separated streams, as the Pack200 unpacker
                     * reads the entire stream...
                     *
                     * See http://java.sun.com/javase/6/docs/api/java/util/jar/Pack200.Unpacker.html
                     */
                    pack200Map.put(pack200Counter, file);
                    objOut.writeInt(pack200Counter);
                    pack200Counter = pack200Counter + 1;
                } else {
                    FileInputStream inStream = new FileInputStream(file);
                    long bytesWritten = IoHelper.copyStream(inStream, objOut);
                    inStream.close();
                    if (bytesWritten != packFile.length()) {
                        throw new IOException("File size mismatch when reading " + file);
                    }
                }

                storedFiles.put(file, new Object[] { pack.id, pos });
            }

            // even if not written, it counts towards pack size
            pack.nbytes += packFile.size();
        }

        // Write out information about parsable files
        objOut.writeInt(packInfo.getParsables().size());

        for (ParsableFile parsableFile : packInfo.getParsables()) {
            objOut.writeObject(parsableFile);
        }

        // Write out information about executable files
        objOut.writeInt(packInfo.getExecutables().size());
        for (ExecutableFile executableFile : packInfo.getExecutables()) {
            objOut.writeObject(executableFile);
        }

        // Write out information about updatecheck files
        objOut.writeInt(packInfo.getUpdateChecks().size());
        for (UpdateCheck updateCheck : packInfo.getUpdateChecks()) {
            objOut.writeObject(updateCheck);
        }

        // Cleanup
        objOut.flush();
        if (!compressor.useStandardCompression()) {
            outputStream.close();
        }

        primaryJarStream.closeEntry();

        // close pack specific jar if required
        if (packJarsSeparate) {
            primaryJarStream.closeAlways();
        }

        IXMLElement child = new XMLElementImpl("pack", root);
        child.setAttribute("nbytes", Long.toString(pack.nbytes));
        child.setAttribute("name", pack.name);
        if (pack.id != null) {
            child.setAttribute("id", pack.id);
        }
        root.addChild(child);

        packNumber++;
    }

    // Now that we know sizes, write pack metadata to primary jar.
    primaryJarStream.putNextEntry(new org.apache.tools.zip.ZipEntry(RESOURCES_PATH + "packs.info"));
    ObjectOutputStream out = new ObjectOutputStream(primaryJarStream);
    out.writeInt(packsList.size());

    for (PackInfo packInfo : packsList) {
        out.writeObject(packInfo.getPack());
    }
    out.flush();
    primaryJarStream.closeEntry();

    // Pack200 files
    Pack200.Packer packer = createAgressivePack200Packer();
    for (Integer key : pack200Map.keySet()) {
        File file = pack200Map.get(key);
        primaryJarStream
                .putNextEntry(new org.apache.tools.zip.ZipEntry(RESOURCES_PATH + "packs/pack200-" + key));
        JarFile jar = new JarFile(file);
        packer.pack(jar, primaryJarStream);
        jar.close();
        primaryJarStream.closeEntry();
    }
}

From source file:com.wavemaker.common.util.ThrowawayFileClassLoader.java

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {

    if (this.classPath == null) {
        throw new ClassNotFoundException("invalid search root: " + this.classPath);
    } else if (name == null) {
        throw new ClassNotFoundException(MessageResource.NULL_CLASS.getMessage());
    }// w  w w.  j  ava 2 s .  co  m

    String classNamePath = name.replace('.', '/') + ".class";

    byte[] fileBytes = null;
    try {
        InputStream is = null;
        JarFile jarFile = null;

        for (Resource entry : this.classPath) {
            if (entry.getFilename().toLowerCase().endsWith(".jar")) {
                jarFile = new JarFile(entry.getFile());
                ZipEntry ze = jarFile.getEntry(classNamePath);

                if (ze != null) {
                    is = jarFile.getInputStream(ze);
                    break;
                } else {
                    jarFile.close();
                }
            } else {

                Resource classFile = entry.createRelative(classNamePath);
                if (classFile.exists()) {
                    is = classFile.getInputStream();
                    break;
                }
            }
        }

        if (is != null) {
            try {
                fileBytes = IOUtils.toByteArray(is);
                is.close();
            } finally {
                if (jarFile != null) {
                    jarFile.close();
                }
            }
        }
    } catch (IOException e) {
        throw new ClassNotFoundException(e.getMessage(), e);
    }

    if (name.contains(".")) {
        String packageName = name.substring(0, name.lastIndexOf('.'));
        if (getPackage(packageName) == null) {
            definePackage(packageName, "", "", "", "", "", "", null);
        }
    }

    Class<?> ret;
    if (fileBytes == null) {
        ret = ClassLoaderUtils.loadClass(name, this.parentClassLoader);
    } else {
        ret = defineClass(name, fileBytes, 0, fileBytes.length);
    }

    if (ret == null) {
        throw new ClassNotFoundException(
                "Couldn't find class " + name + " in expected classpath: " + this.classPath);
    }

    return ret;
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private void indexJar(URL url, File jar) throws IOException {
    JarFile jarFile = new JarFile(jar);
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        cachedFiles.put(entry.getName(), url);
    }/*from  w  w  w.  j  a  v  a2  s  .c o m*/
    jarFile.close();
    cachedJars.put(url, jar);
}

From source file:org.rhq.enterprise.server.plugin.pc.perspective.PerspectiveServerPluginManager.java

private void deployEmbeddedWars(ServerPluginEnvironment env) {
    String name = null;/*from  ww w.j  a v a 2 s.  c  o m*/
    try {
        JarFile pluginJarFile = new JarFile(env.getPluginUrl().getFile());
        try {
            for (JarEntry entry : Collections.list(pluginJarFile.entries())) {
                name = entry.getName();
                if (name.toLowerCase().endsWith(".war")) {
                    deployWar(env, entry.getName(), pluginJarFile.getInputStream(entry));
                }
            }
        } finally {
            pluginJarFile.close();
        }
    } catch (Exception e) {
        Throwable t = (e instanceof MBeanException) ? e.getCause() : e;
        log.error("Failed to deploy " + env.getPluginKey().getPluginName() + "#" + name, t);
    }
}

From source file:framework.JarResourceStore.java

public synchronized byte[] read(String pResourceName) {
    JarFile jar = null;
    try {// w  ww. j  av  a2s . c o  m
        jar = new JarFile(URLDecoder.decode(filename, "utf-8"));
        JarEntry jarEntry = jar.getJarEntry(pResourceName);
        if (jarEntry != null) {

            InputStream inputStream = jar.getInputStream(jarEntry);
            try {
                return IOUtils.toByteArray(inputStream);
            } finally {
                inputStream.close();
            }
        }
    } catch (IOException e) {
        Loggers.RELOADER.error(e.getMessage(), e);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e2) {
                Loggers.RELOADER.error(e2.getMessage(), e2);
            }
        }
    }
    return null;
}

From source file:com.github.jengelman.gradle.plugins.integration.TestFile.java

public Manifest getManifest() {
    assertIsFile();/*from  w w  w .  ja  v a2s  . c om*/
    try {
        JarFile jarFile = new JarFile(this);
        try {
            return jarFile.getManifest();
        } finally {
            jarFile.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.util.InstallUtil.java

private Properties getDefaultProperties() throws IOException {
    String os = System.getProperty("os.name");

    String jar = ServerUtil.getPath() + "/install/installer.jar";
    String fileName = "data/installDefaultValues.properties";

    if (os.startsWith("Linux")) {
        fileName = "data/installDefaultValuesNoUI.properties";
    }//from  www .  ja v a  2 s. com

    JarFile jarFile = new JarFile(jar);
    JarEntry entry = jarFile.getJarEntry(fileName);
    InputStream input = jarFile.getInputStream(entry);

    Properties p = new Properties();
    p.load(input);

    jarFile.close();
    return p;
}

From source file:com.izforge.izpack.compiler.packager.impl.Packager.java

private boolean isNotSignedJar(File file) throws IOException {
    JarFile jar = new JarFile(file);
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (entry.getName().startsWith("META-INF") && entry.getName().endsWith(".SF")) {
            jar.close();
            return false;
        }/*  w w w.ja v a  2 s .c o  m*/
    }
    jar.close();
    return true;
}

From source file:com.l2jserver.service.game.scripting.impl.ecj.EclipseCompilerScriptClassLoader.java

/**
 * AddsLibrary jar//from   w  ww  .j  a va2 s  . co  m
 * 
 * @param file
 *            jar file to add
 * @throws IOException
 *             if any I/O error occur
 */
@Override
public void addLibrary(File file) throws IOException {
    URL fileURL = file.toURI().toURL();
    addURL(fileURL);

    JarFile jarFile = new JarFile(file);

    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();

        String name = entry.getName();
        if (name.endsWith(".class")) {
            name = name.substring(0, name.length() - 6);
            name = name.replace('/', '.');
            libraryClasses.add(name);
        }
    }

    jarFile.close();
}

From source file:org.apache.felix.webconsole.internal.core.InstallAction.java

private String getSymbolicName(File bundleFile) {
    JarFile jar = null;
    try {/*from  w  w w  .  jav  a 2 s.  c o  m*/
        jar = new JarFile(bundleFile);
        Manifest m = jar.getManifest();
        if (m != null) {
            return m.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
        }
    } catch (IOException ioe) {
        getLog().log(LogService.LOG_WARNING, "Cannot extract symbolic name of bundle file " + bundleFile, ioe);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }

    // fall back to "not found"
    return null;
}