Example usage for java.util.jar JarEntry JarEntry

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

Introduction

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

Prototype

public JarEntry(JarEntry je) 

Source Link

Document

Creates a new JarEntry with fields taken from the specified JarEntry object.

Usage

From source file:org.nuclos.server.customcode.codegenerator.NuclosJavaCompilerComponent.java

private synchronized void jar(Map<String, byte[]> javacresult, List<CodeGenerator> generators) {
    try {// w w w . j  a v a 2  s.com
        final boolean oldExists = moveJarToOld();
        if (javacresult.size() > 0) {
            final Set<String> entries = new HashSet<String>();
            final JarOutputStream jos = new JarOutputStream(
                    new BufferedOutputStream(new FileOutputStream(JARFILE)), getManifest());

            try {
                for (final String key : javacresult.keySet()) {
                    entries.add(key);
                    byte[] bytecode = javacresult.get(key);

                    // create entry for directory (required for classpath scanning)
                    if (key.contains("/")) {
                        String dir = key.substring(0, key.lastIndexOf('/') + 1);
                        if (!entries.contains(dir)) {
                            entries.add(dir);
                            jos.putNextEntry(new JarEntry(dir));
                            jos.closeEntry();
                        }
                    }

                    // call postCompile() (weaving) on compiled sources
                    for (CodeGenerator generator : generators) {
                        if (!oldExists || generator.isRecompileNecessary()) {
                            for (JavaSourceAsString src : generator.getSourceFiles()) {
                                final String name = src.getFQName();
                                if (key.startsWith(name.replaceAll("\\.", "/"))) {
                                    LOG.debug("postCompile (weaving) " + key);
                                    bytecode = generator.postCompile(key, bytecode);
                                    // Can we break here???
                                    // break outer;
                                }
                            }
                        }
                    }
                    jos.putNextEntry(new ZipEntry(key));
                    LOG.debug("writing to " + key + " to jar " + JARFILE);
                    jos.write(bytecode);
                    jos.closeEntry();
                }

                if (oldExists) {
                    final JarInputStream in = new JarInputStream(
                            new BufferedInputStream(new FileInputStream(JARFILE_OLD)));
                    final byte[] buffer = new byte[2048];
                    try {
                        int size;
                        JarEntry entry;
                        while ((entry = in.getNextJarEntry()) != null) {
                            if (!entries.contains(entry.getName())) {
                                jos.putNextEntry(entry);
                                LOG.debug("copying " + entry.getName() + " from old jar " + JARFILE_OLD);
                                while ((size = in.read(buffer, 0, buffer.length)) != -1) {
                                    jos.write(buffer, 0, size);
                                }
                                jos.closeEntry();
                            }
                            in.closeEntry();
                        }
                    } finally {
                        in.close();
                    }
                }
            } finally {
                jos.close();
            }
        }
    } catch (IOException ex) {
        throw new NuclosFatalException(ex);
    }
}

From source file:org.olat.core.util.i18n.I18nManager.java

/**
 * Create a jar file that contains the translations for the given languages.
 * <p>/*w  w  w . jav a2s.  co  m*/
 * Note that this file is created in a temporary place in olatdata/tmp. It is
 * in the responsibility of the caller of this method to remove the file when
 * not needed anymore.
 * 
 * @param languageKeys
 * @param fileName the name of the file.
 * @return The file handle to the created file or NULL if no such file could
 *         be created (e.g. there already exists a file with this file name)
 */
public File createLanguageJarFile(Collection<String> languageKeys, String fileName) {
    // Create file olatdata temporary directory
    File file = new File(WebappHelper.getTmpDir() + "/" + fileName);
    file.getParentFile().mkdirs();

    FileOutputStream stream = null;
    JarOutputStream out = null;
    try {
        // Open stream for jar file
        stream = new FileOutputStream(file);
        out = new JarOutputStream(stream, new Manifest());
        // Use now as last modified date of resources
        long now = System.currentTimeMillis();
        // Add all languages
        for (String langKey : languageKeys) {
            Locale locale = getLocaleOrNull(langKey);
            // Add all bundles in the current language
            for (String bundleName : I18nModule.getBundleNamesContainingI18nFiles()) {
                Properties propertyFile = getPropertiesWithoutResolvingRecursively(locale, bundleName);
                String entryFileName = bundleName.replace(".", "/") + "/" + I18N_DIRNAME + "/"
                        + buildI18nFilename(locale);
                // Create jar entry for this path, name and last modified
                JarEntry jarEntry = new JarEntry(entryFileName);
                jarEntry.setTime(now);
                // Write properties to jar file
                out.putNextEntry(jarEntry);
                propertyFile.store(out, null);
                if (isLogDebugEnabled()) {
                    logDebug("Adding file::" + entryFileName + " + to jar", null);
                }
            }
        }
        logDebug("Finished writing jar file::" + file.getAbsolutePath(), null);
    } catch (Exception e) {
        logError("Could not write jar file", e);
        return null;
    } finally {
        try {
            out.close();
            stream.close();
        } catch (IOException e) {
            logError("Could not close stream of jar file", e);
            return null;
        }
    }
    return file;
}

From source file:org.reficio.p2.FeatureBuilder.java

private void addToJar(JarOutputStream jar, File content) throws IOException {
    for (File f : FileUtils.listFiles(content, null, true)) {
        String fname = f.getPath().replace("\\", "/");
        if (f.isDirectory()) {
            if (!fname.endsWith("/")) {
                fname = fname + "/";
            }// ww w .  j  a v a  2  s.  com
            JarEntry entry = new JarEntry(fname);
            entry.setTime(f.lastModified());
            jar.putNextEntry(entry);
            jar.closeEntry();
        } else {
            //must be a file
            JarEntry entry = new JarEntry(fname);
            entry.setTime(f.lastModified());
            jar.putNextEntry(entry);
            jar.write(IOUtils.toByteArray(new FileInputStream(f)));
            jar.closeEntry();
        }

    }
}

From source file:org.roda.core.util.ZipUtility.java

/**
 * Creates ZIP file with the files inside directory <code>contentsDir</code> .
 * //from  www  .  ja  v  a2 s . co m
 * @param newZipFile
 *          the ZIP file to create
 * @param contentsDir
 *          the directory containing the files to compress.
 * @return the created ZIP file.
 * @throws IOException
 *           if something goes wrong with creation of the ZIP file or the
 *           reading of the files to compress.
 */
public static File createZIPFile(File newZipFile, File contentsDir) throws IOException {

    List<File> contentAbsoluteFiles = FileUtility.listFilesRecursively(contentsDir);

    FileOutputStream zipStream = new FileOutputStream(newZipFile);
    JarOutputStream jarOutputStream = new JarOutputStream(new BufferedOutputStream(zipStream));

    // Create a buffer for reading the files
    byte[] buffer = new byte[BUFFER_SIZE];

    Iterator<File> iterator = contentAbsoluteFiles.iterator();
    while (iterator.hasNext()) {
        File absoluteFile = iterator.next();
        String relativeFile = getFilePathRelativeTo(absoluteFile, contentsDir);

        FileInputStream inputStream = new FileInputStream(absoluteFile);
        BufferedInputStream in = new BufferedInputStream(inputStream);

        // Add ZIP entry to output stream.
        jarOutputStream.putNextEntry(new JarEntry(relativeFile));

        LOGGER.trace("Adding {}", relativeFile);

        int length;
        while ((length = in.read(buffer)) > 0) {
            jarOutputStream.write(buffer, 0, length);
        }

        // Complete the entry
        jarOutputStream.closeEntry();
        in.close();
        inputStream.close();
    }

    // Complete the ZIP file
    jarOutputStream.close();
    zipStream.close();

    return newZipFile;
}

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

/**
 * @param file// w w w .  j a  va  2  s.c  om
 * @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:org.sonatype.nexus.plugins.p2.repository.metadata.AbstractP2MetadataSource.java

private static StorageFileItem compressMetadataItem(final Repository repository, final String path,
        final StorageFileItem metadataXml) throws IOException {
    final Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

    // this is a special one: once cached (hence consumed), temp file gets deleted
    final FileContentLocator fileContentLocator = new FileContentLocator("application/java-archive");

    try (OutputStream buffer = fileContentLocator.getOutputStream();
            ZipOutputStream out = new ZipOutputStream(buffer);
            InputStream in = metadataXml.getInputStream()) {
        out.putNextEntry(new JarEntry(metadataXml.getName()));
        IOUtils.copy(in, out);/*ww w.ja va2 s  .com*/
    }

    final DefaultStorageFileItem result = new DefaultStorageFileItem(repository, new ResourceStoreRequest(path),
            true /* isReadable */, false /* isWritable */, fileContentLocator);
    return result;
}

From source file:org.sourcepit.common.maven.testing.ArtifactRepositoryFacade.java

private static File createStubJar(File dir) throws IOException {
    final File jarFile = File.createTempFile("stub", ".jar", dir);

    JarOutputStream jarOut = null;
    try {//from ww w.ja v a  2  s .com
        jarOut = new JarOutputStream(new FileOutputStream(jarFile));

        final JarEntry mfEntry = new JarEntry(JarFile.MANIFEST_NAME);
        jarOut.putNextEntry(mfEntry);

        final Manifest mf = new Manifest();
        mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1");
        mf.write(jarOut);

        jarOut.closeEntry();
    } finally {
        IOUtils.closeQuietly(jarOut);
    }

    return jarFile;
}

From source file:org.sourcepit.osgifier.core.packaging.BundleLocalizationWriter.java

public static Map<String, LocalizedData> write(final JarOutputStream out, Manifest manifest,
        BundleLocalization localization) throws IOException {
    final BundleLocalizationWriter<JarOutputStream> writer = new BundleLocalizationWriter<JarOutputStream>() {
        @Override/*from  w ww  . j  a v a 2 s .  c  o m*/
        protected JarOutputStream openStream(String path) throws IOException {
            out.putNextEntry(new JarEntry(path));
            return out;
        }

        @Override
        protected void closeStream(JarOutputStream out, String path) throws IOException {
            out.closeEntry();
        }
    };
    return writer.write(manifest, localization);
}

From source file:org.sourcepit.osgifier.core.packaging.Repackager.java

private void rePackageJarFile(File srcJarFile, final Manifest manifest, BundleLocalization localization,
        final JarOutputStream destJarOut, Collection<String> pathFilters) throws IOException {
    destJarOut.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME));
    writeManifest(manifest, destJarOut);
    destJarOut.closeEntry();//ww  w  . java  2 s .  c  o m

    if (localization != null) {
        final Set<String> paths = BundleLocalizationWriter.write(destJarOut, manifest, localization).keySet();
        pathFilters = pathFilters == null ? new HashSet<String>() : new HashSet<String>(pathFilters);
        for (String path : paths) {
            pathFilters.add("!" + path);
        }
    }

    final PathMatcher pathMatcher = pathFilters == null ? DEFAULT_CONTENT_MATCHER
            : createJarContentMatcher(pathFilters);

    new IOOperation<JarInputStream>(jarIn(buffIn(fileIn(srcJarFile)))) {
        @Override
        protected void run(JarInputStream srcJarIn) throws IOException {
            copyJarContents(srcJarIn, destJarOut, pathMatcher);
        }
    }.run();
}

From source file:org.sourcepit.osgifier.core.packaging.Repackager.java

private void copyJarContents(JarInputStream srcJarIn, final JarOutputStream destJarOut,
        PathMatcher contentMatcher) throws IOException {
    final Set<String> processedEntires = new HashSet<String>();

    JarEntry srcEntry = srcJarIn.getNextJarEntry();
    while (srcEntry != null) {
        final String entryName = srcEntry.getName();
        if (contentMatcher.isMatch(entryName)) {
            if (processedEntires.add(entryName)) {
                destJarOut.putNextEntry(new JarEntry(srcEntry.getName()));
                IOUtils.copy(srcJarIn, destJarOut);
                destJarOut.closeEntry();
            } else {
                logger.warn("Ignored duplicate jar entry: " + entryName);
            }//w  ww .j a  va  2s .  c om
        }
        srcJarIn.closeEntry();
        srcEntry = srcJarIn.getNextJarEntry();
    }
}