Example usage for java.util.jar JarOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

From source file:org.apache.brooklyn.util.core.ClassLoaderUtilsTest.java

@Test
public void testLoadClassInOsgiWhiteListWithInvalidBundlePresent() throws Exception {
    String bundlePath = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH;
    String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
    String classname = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_SIMPLE_ENTITY;

    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), bundlePath);

    mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build();
    Bundle bundle = installBundle(mgmt, bundleUrl);

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    JarOutputStream target = new JarOutputStream(buffer, manifest);
    target.close();

    OsgiManager osgiManager = ((ManagementContextInternal) mgmt).getOsgiManager().get();
    Framework framework = osgiManager.getFramework();
    Bundle installedBundle = framework.getBundleContext().installBundle("stream://invalid",
            new ByteArrayInputStream(buffer.toByteArray()));
    assertNotNull(installedBundle);//w ww  . j a  v  a 2 s . c  om

    Class<?> clazz = bundle.loadClass(classname);
    Entity entity = createSimpleEntity(bundleUrl, clazz);

    String whileList = bundle.getSymbolicName() + ":" + bundle.getVersion();
    System.setProperty(ClassLoaderUtils.WHITE_LIST_KEY, whileList);

    ClassLoaderUtils cluMgmt = new ClassLoaderUtils(getClass(), mgmt);
    ClassLoaderUtils cluClass = new ClassLoaderUtils(clazz);
    ClassLoaderUtils cluEntity = new ClassLoaderUtils(getClass(), entity);

    assertLoadSucceeds(classname, clazz, cluMgmt, cluClass, cluEntity);
    assertLoadSucceeds(bundle.getSymbolicName() + ":" + classname, clazz, cluMgmt, cluClass, cluEntity);
}

From source file:com.glaf.core.util.ZipUtils.java

public static byte[] getZipBytes(Map<String, InputStream> dataMap) {
    byte[] bytes = null;
    try {/*from   w  w w  . j av a 2  s . c o m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        JarOutputStream jos = new JarOutputStream(bos);
        if (dataMap != null) {
            Set<Entry<String, InputStream>> entrySet = dataMap.entrySet();
            for (Entry<String, InputStream> entry : entrySet) {
                String name = entry.getKey();
                InputStream inputStream = entry.getValue();
                if (name != null && inputStream != null) {
                    BufferedInputStream bis = new BufferedInputStream(inputStream);
                    JarEntry jarEntry = new JarEntry(name);
                    jos.putNextEntry(jarEntry);

                    while ((len = bis.read(buf)) >= 0) {
                        jos.write(buf, 0, len);
                    }

                    bis.close();
                    jos.closeEntry();
                }
            }
        }
        jos.flush();
        jos.close();
        bos.flush();
        bos.close();
        bytes = baos.toByteArray();
        baos.close();
        return bytes;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:JarUtils.java

/**
 * Create a JAR file from a directory, recursing through children.
 * //from  w  w w  .j  a  v  a  2s.  com
 * @param directory in directory source
 * @param outputJar in file to output the jar data to
 * @return out File that was generated
 * @throws IOException when there is an I/O exception
 */
public File createJarFromDirectory(String directory, File outputJar) throws IOException {
    JarOutputStream jarStream = null;
    try {
        if (!outputJar.getParentFile().exists()) {
            outputJar.getParentFile().mkdirs();
        }

        jarStream = new JarOutputStream(new FileOutputStream(outputJar));
        File dir = new File(directory);

        createJarFromDirectory(dir, dir, jarStream);
    } finally {
        if (jarStream != null) {
            jarStream.close();
        }
    }
    return outputJar;
}

From source file:rubah.tools.UpdateClassGenerator.java

public void generateConversionJar(File outJar) throws IOException {

    FileOutputStream fos = new FileOutputStream(outJar);
    JarOutputStream jos = new JarOutputStream(fos, new Manifest());

    this.generateConversionClasses(jos, this.v0, this.preffixes.get(this.v1.getNamespace()));
    this.generateConversionClasses(jos, this.v1, "");

    jos.close();
    fos.close();/*from  ww  w. j a v  a2s  .c  om*/
}

From source file:org.sakaiproject.kernel.component.core.test.ComponentLoaderServiceImplTest.java

/**
 * @param file//from  w  ww  .  ja va  2  s .  c o m
 * @throws IOException
 */
private void createComponent(File f, String component) throws IOException {
    if (f.getParentFile().mkdirs()) {
        if (debug)
            LOG.debug("Created Directory " + f);
    }
    JarOutputStream jarOutput = new JarOutputStream(new FileOutputStream(f));
    JarEntry jarEntry = new JarEntry("SAKAI-INF/component.xml");
    jarOutput.putNextEntry(jarEntry);
    String componentXml = ResourceLoader.readResource(component, this.getClass().getClassLoader());
    jarOutput.write(componentXml.getBytes("UTF-8"));
    jarOutput.closeEntry();
    jarOutput.close();
}

From source file:interactivespaces.workbench.project.java.BndOsgiContainerBundleCreator.java

/**
 * Create a Jar file from a source folder.
 *
 * @param jarDestinationFile/*from   w w w .jav  a 2  s .  c om*/
 *          the jar file being created
 * @param sourceFolder
 *          the source folder containing the classes
 */
private void createJarFile(File jarDestinationFile, File sourceFolder) {
    // Create a buffer for reading the files
    byte[] buf = new byte[IO_BUFFER_SIZE];

    JarOutputStream out = null;
    try {
        // Create the jar file
        out = new JarOutputStream(new FileOutputStream(jarDestinationFile));

        writeJarFile(sourceFolder, buf, out, "");

        // Complete the jar file
        out.close();
    } catch (Exception e) {
        throw new InteractiveSpacesException(
                String.format("Failed creating jar file %s", jarDestinationFile.getAbsolutePath()), e);
    } finally {
        fileSupport.close(out, true);
    }
}

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

private Manifest jarDirectoryAndReadManifest(Manifest fromJar, Manifest fromUser, boolean mergeEntries)
        throws IOException {
    // Create a jar with a manifest we'd expect to see merged.
    Path originalJar = folder.newFile("unexpected.jar");
    JarOutputStream ignored = new JarOutputStream(Files.newOutputStream(originalJar), fromJar);
    ignored.close();

    // Now create the actual manifest
    Path manifestFile = folder.newFile("actual_manfiest.mf");
    try (OutputStream os = Files.newOutputStream(manifestFile)) {
        fromUser.write(os);/* w  w  w  . ja va2  s.  c  o m*/
    }

    Path tmp = folder.newFolder();
    Path output = tmp.resolve("example.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output,
            ImmutableSortedSet.of(originalJar), /* main class */ null, manifestFile, mergeEntries,
            /* blacklist */ ImmutableSet.of());
    ExecutionContext context = TestExecutionContext.newInstance();
    step.execute(context);

    // Now verify that the created manifest matches the expected one.
    try (JarInputStream jis = new JarInputStream(Files.newInputStream(output))) {
        return jis.getManifest();
    }
}

From source file:JarUtil.java

/**
 * Adds the given file to the specified JAR file.
 * /*from w w w .ja v  a 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.enderville.enderinstaller.util.InstallScript.java

/**
 * Repackages all the files in the tmp directory to the new minecraft.jar
 *
 * @param tmp The temp directory where mods were installed.
 * @param mcjar The location to save the new minecraft.jar.
 * @throws IOException/*from   ww w  .  java2s  .  c  o  m*/
 */
public static void repackMCJar(File tmp, File mcjar) throws IOException {
    byte[] dat = new byte[4 * 1024];

    JarOutputStream jarout = new JarOutputStream(FileUtils.openOutputStream(mcjar));

    Queue<File> queue = new LinkedList<File>();
    for (File f : tmp.listFiles()) {
        queue.add(f);
    }

    while (!queue.isEmpty()) {
        File f = queue.poll();
        if (f.isDirectory()) {
            for (File child : f.listFiles()) {
                queue.add(child);
            }
        } else {
            //TODO need a better way to do this
            String name = f.getPath().substring(tmp.getPath().length() + 1);
            //TODO is this formatting really required for jars?
            name = name.replace("\\", "/");
            if (f.isDirectory() && !name.endsWith("/")) {
                name = name + "/";
            }
            JarEntry entry = new JarEntry(name);
            jarout.putNextEntry(entry);

            FileInputStream in = new FileInputStream(f);
            int len = -1;
            while ((len = in.read(dat)) > 0) {
                jarout.write(dat, 0, len);
            }
            in.close();
        }
        jarout.closeEntry();
    }
    jarout.close();

}

From source file:com.theoryinpractise.clojure.AbstractClojureCompilerMojo.java

private File createJar(final String cp, final String mainClass) {
    try {//  ww  w . java 2s  . c  om
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, cp);
        manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass);
        File tempFile = File.createTempFile("clojuremavenplugin", "jar");
        tempFile.deleteOnExit();
        JarOutputStream target = new JarOutputStream(new FileOutputStream(tempFile), manifest);
        target.close();
        return tempFile;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}