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:net.cliseau.composer.javacor.MissingToolException.java

/**
 * Create a JAR file for startup of the unit.
 *
 * The created JAR file contains all the specified archive files and contains a
 * manifest which in particular determines the class path for the JAR file.
 * All files in startupArchiveFileNames are deleted during the execution of
 * this method.// w  w w  .  j  ava2  s.c o  m
 *
 * @param fileName Name of the file to write the result to.
 * @param startupArchiveFileNames Names of files to include in the JAR file.
 * @param startupDependencies Names of classpath entries to include in the JAR file classpath.
 * @exception IOException Thrown if file operations fail, such as creating the JAR file or reading from the input file(s).
 */
private void createJAR(final String fileName, final Collection<String> startupArchiveFileNames,
        final Collection<String> startupDependencies) throws IOException, InvalidConfigurationException {
    // Code inspired by:
    //   http://www.java2s.com/Code/Java/File-Input-Output/CreateJarfile.htm
    //   http://www.massapi.com/class/java/util/jar/Manifest.java.html

    // construct manifest with appropriate "Class-path" property
    Manifest starterManifest = new Manifest();
    Attributes starterAttributes = starterManifest.getMainAttributes();
    // Remark for those who read this code to learn something:
    // If one forgets to set the MANIFEST_VERSION attribute, then
    // silently *nothing* (except for a line break) will be written
    // to the JAR file manifest!
    starterAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    starterAttributes.put(Attributes.Name.MAIN_CLASS, getStartupName());
    starterAttributes.put(Attributes.Name.CLASS_PATH,
            StringUtils.join(startupDependencies, manifestClassPathSeparator));

    // create output JAR file
    FileOutputStream fos = new FileOutputStream(fileName);
    JarOutputStream jos = new JarOutputStream(fos, starterManifest);

    // add the entries for the starter archive's files
    for (String archFileName : startupArchiveFileNames) {
        File startupArchiveFile = new File(archFileName);
        JarEntry startupEntry = new JarEntry(startupArchiveFile.getName());
        startupEntry.setTime(startupArchiveFile.lastModified());
        jos.putNextEntry(startupEntry);

        // copy the content of the starter archive's file
        // TODO: if we used Apache Commons IO 2.1, then the following
        //       code block could be simplified as:
        //       FileUtils.copyFile(startupArchiveFile, jos);
        FileInputStream fis = new FileInputStream(startupArchiveFile);
        byte buffer[] = new byte[1024 /*bytes*/];
        while (true) {
            int nRead = fis.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            jos.write(buffer, 0, nRead);
        }
        fis.close();
        // end of FileUtils.copyFile() substitution code
        jos.closeEntry();

        startupArchiveFile.delete(); // cleanup the disk a bit
    }

    jos.close();
    fos.close();
}

From source file:co.cask.cdap.internal.app.runtime.spark.SparkRuntimeService.java

/**
 * Updates the dependency jar packaged by the {@link ApplicationBundler#createBundle(Location, Iterable,
 * Iterable)} by moving the things inside classes, lib, resources a level up as expected by spark.
 *
 * @param dependencyJar {@link Location} of the job jar to be updated
 * @param context       {@link BasicSparkContext} of this job
 *///from   w  ww. j  av  a 2  s.c  o  m
private Location updateDependencyJar(Location dependencyJar, BasicSparkContext context) throws IOException {

    final String[] prefixToStrip = { ApplicationBundler.SUBDIR_CLASSES, ApplicationBundler.SUBDIR_LIB,
            ApplicationBundler.SUBDIR_RESOURCES };

    Id.Program programId = context.getProgram().getId();

    Location updatedJar = locationFactory.create(String.format("%s.%s.%s.%s.%s.jar",
            ProgramType.SPARK.name().toLowerCase(), programId.getAccountId(), programId.getApplicationId(),
            programId.getId(), context.getRunId().getId()));

    // Creates Manifest
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0");
    JarOutputStream jarOutput = new JarOutputStream(updatedJar.getOutputStream(), manifest);

    try {
        JarInputStream jarInput = new JarInputStream(dependencyJar.getInputStream());

        try {
            JarEntry jarEntry = jarInput.getNextJarEntry();

            while (jarEntry != null) {
                boolean isDir = jarEntry.isDirectory();
                String entryName = jarEntry.getName();
                String newEntryName = entryName;

                for (String prefix : prefixToStrip) {
                    if (entryName.startsWith(prefix) && !entryName.equals(prefix)) {
                        newEntryName = entryName.substring(prefix.length());
                    }
                }

                jarEntry = new JarEntry(newEntryName);
                jarOutput.putNextEntry(jarEntry);
                if (!isDir) {
                    ByteStreams.copy(jarInput, jarOutput);
                }
                jarEntry = jarInput.getNextJarEntry();
            }
        } finally {
            jarInput.close();
            Locations.deleteQuietly(dependencyJar);
        }
    } finally {
        jarOutput.close();
    }
    return updatedJar;
}

From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java

/**
 * Writes a new {@link File} into the archive.
 *
 * @param inputFile the {@link File} to write.
 * @param jarPath   the filepath inside the archive.
 * @throws IOException//from ww w .  j  ava 2  s. c  o  m
 */
public void writeFile(File inputFile, String jarPath) throws IOException {
    // Get an input stream on the file.
    FileInputStream fis = new FileInputStream(inputFile);
    try {

        // create the zip entry
        JarEntry entry = new JarEntry(jarPath);
        entry.setTime(inputFile.lastModified());

        writeEntry(fis, entry);
    } finally {
        // close the file stream used to read the file
        fis.close();
    }
}

From source file:com.peterbochs.PeterBochsDebugger.java

public static void main(String[] args) {
    WebServiceUtil.log("peter-bochs", "start", null, null, null);
    try {// w w w .  j a  va  2 s .c om
        UIManager.setLookAndFeel("com.peterswing.white.PeterSwingWhiteLookAndFeel");
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (args.length == 0) {
        String errorMessage = "Wrong number of argument\n\n";
        errorMessage += "\nIn Linux/Mac : java -jar peter-bochs-debugger.jar bochs -f bochsrc.bxrc";
        errorMessage += "\nIn windows : java -jar peter-bochs-debugger.jar c:\\program files\\bochs2.4.3\\bochsdbg.exe -q -f bochsrc.bxrc";
        errorMessage += "\n!!! if using peter-bochs in windows, you need to pass the full path of bochs exe and -q to the parameter. (!!! relative path of bochs exe will not work)";
        errorMessage += "\n!!! to use \"experimental feature\", please add \"-debug\" to the parameter list";
        System.out.println(errorMessage);
        JOptionPane.showMessageDialog(null, errorMessage);
        System.exit(1);
    } else {
        if (args[0].equals("-version") || args[0].equals("-v")) {
            System.out.println(Global.version);
            System.exit(1);
        }
    }

    for (String str : args) {
        if (str.contains("bochsrc") || str.contains(".bxrc")) {
            bochsrc = str;
        }
    }

    String osName = System.getProperty("os.name").toLowerCase();
    if (osName.toLowerCase().contains("windows")) {
        os = OSType.win;
    } else if (osName.toLowerCase().contains("mac")) {
        os = OSType.mac;
    } else {
        os = OSType.linux;
    }
    if (os == OSType.mac) {
        com.apple.eawt.Application macApp = com.apple.eawt.Application.getApplication();
        // System.setProperty("dock:name", "Your Application Name");
        macApp.setDockIconImage(new ImageIcon(
                PeterBochsDebugger.class.getClassLoader().getResource("com/peterbochs/icons/peter.png"))
                        .getImage());
        // java.awt.PopupMenu menu = new java.awt.PopupMenu();
        // menu.add(new MenuItem("test"));
        // macApp.setDockMenu(menu);

        macApp.addApplicationListener(new MacAboutBoxHandler());
    }

    if (ArrayUtils.contains(args, "-debug")) {
        Global.debug = true;
        args = (String[]) ArrayUtils.removeElement(args, "-debug");
    } else {
        Global.debug = false;
    }

    try {
        if (PeterBochsDebugger.class.getProtectionDomain().getCodeSource().getLocation().getFile()
                .endsWith(".jar")) {
            JarFile jarFile = new JarFile(
                    PeterBochsDebugger.class.getProtectionDomain().getCodeSource().getLocation().getFile());
            if (System.getProperty("os.name").toLowerCase().contains("linux")) {
                if (System.getProperty("os.arch").contains("64")) {
                    if (Global.debug) {
                        System.out.println("Loading linux 64 bits jogl");
                    }
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libgluegen-rt.so")),
                            new File("libgluegen-rt.so"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libjogl_awt.so")),
                            new File("libjogl_awt.so"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libjogl_cg.so")),
                            new File("libjogl_cg.so"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libjogl.so")),
                            new File("libjogl.so"));
                } else {
                    if (Global.debug) {
                        System.out.println("Loading linux 32 bits jogl");
                    }
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_i586/libgluegen-rt.so")),
                            new File("libgluegen-rt.so"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_i586/libjogl_awt.so")),
                            new File("libjogl_awt.so"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_i586/libjogl_cg.so")),
                            new File("libjogl_cg.so"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/linux_i586/libjogl.so")),
                            new File("libjogl.so"));
                }
                try {
                    File f = new File(".");
                    Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libjogl.so");
                    System.out.println("Loading " + f.getAbsolutePath() + File.separator + "libjogl.so");
                    Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libjogl_awt.so");
                    Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libjogl_cg.so");
                    Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libgluegen-rt.so");
                } catch (UnsatisfiedLinkError e) {
                    e.printStackTrace();
                    System.err.println("Native code library failed to load.\n" + e);
                    System.err.println(
                            "Solution : Please add \"-Djava.library.path=.\" to start peter-bochs\n" + e);
                }
            } else if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                CommonLib.writeFile(jarFile.getInputStream(new JarEntry("com/peterbochs/exe/PauseBochs.exe")),
                        new File("PauseBochs.exe"));
                CommonLib.writeFile(jarFile.getInputStream(new JarEntry("com/peterbochs/exe/StopBochs.exe")),
                        new File("StopBochs.exe"));
                CommonLib.writeFile(jarFile.getInputStream(new JarEntry("com/peterbochs/exe/ndisasm.exe")),
                        new File("ndisasm.exe"));

                if (System.getProperty("os.arch").contains("64")) {
                    if (Global.debug) {
                        System.out.println("Loading windows 64 bits jogl");
                    }
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_amd64/jogl.dll")),
                            new File("jogl.dll"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_amd64/jogl_awt.dll")),
                            new File("jogl_awt.dll"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_amd64/jogl_cg.dll")),
                            new File("jogl_cg.dll"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_amd64/gluegen-rt.dll")),
                            new File("gluegen-rt.dll"));
                } else {
                    if (Global.debug) {
                        System.out.println("Loading windows 32 bits jogl");
                    }
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_i586/jogl.dll")),
                            new File("jogl.dll"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_i586/jogl_awt.dll")),
                            new File("jogl_awt.dll"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_i586/jogl_cg.dll")),
                            new File("jogl_cg.dll"));
                    CommonLib.writeFile(
                            jarFile.getInputStream(
                                    new JarEntry("com/peterbochs/jogl_dll/windows_i586/gluegen-rt.dll")),
                            new File("gluegen-rt.dll"));
                }
                try {
                    File f = new File(".");
                    System.load(f.getAbsolutePath() + File.separator + "jogl.dll");
                    System.load(f.getAbsolutePath() + File.separator + "jogl_awt.dll");
                    System.load(f.getAbsolutePath() + File.separator + "jogl_cg.dll");
                    System.load(f.getAbsolutePath() + File.separator + "gluegen-rt.dll");
                } catch (UnsatisfiedLinkError e) {
                    e.printStackTrace();
                    System.err.println("Native code library failed to load.\n" + e);
                    System.err.println(
                            "Solution : Please add \"-Djava.library.path=.\" to start peter-bochs\n" + e);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (ArrayUtils.contains(args, "-loadBreakpoint")) {
        Setting.getInstance().setLoadBreakpointAtStartup(true);
        args = (String[]) ArrayUtils.removeElement(args, "-loadBreakpoint");
    } else if (ArrayUtils.contains(args, "-loadbreakpoint")) {
        Setting.getInstance().setLoadBreakpointAtStartup(true);
        args = (String[]) ArrayUtils.removeElement(args, "-loadbreakpoint");
    }

    for (int x = 0; x < args.length; x++) {
        if (args[x].toLowerCase().startsWith("-osdebug")) {
            Global.osDebug = CommonLib.string2long(args[x].replaceAll("-.*=", ""));
            args = (String[]) ArrayUtils.removeElement(args, args[x]);
            x = -1;
        } else if (args[x].toLowerCase().startsWith("-profilingmemoryport")) {
            Global.profilingMemoryPort = (int) CommonLib.string2long(args[x].replaceAll("-.*=", ""));
            args = (String[]) ArrayUtils.removeElement(args, args[x]);
            x = -1;
        } else if (args[x].toLowerCase().startsWith("-profilingjmpport")) {
            Global.profilingJmpPort = (int) CommonLib.string2long(args[x].replaceAll("-.*=", ""));
            args = (String[]) ArrayUtils.removeElement(args, args[x]);
            x = -1;
        } else if (args[x].toLowerCase().startsWith("-loadelf")) {
            Global.elfPaths = args[x].replaceAll("-loadelf=", "").split(",");
            Setting.getInstance().setLoadSystemMapAtStartup(true);
            args = (String[]) ArrayUtils.removeElement(args, args[x]);
            x = -1;
        } else if (args[x].toLowerCase().startsWith("-loadmap")) {
            System.out.println("-loadmap is not deprecated, please use -loadelf.");
        }
    }

    arguments = args;

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            PeterBochsDebugger inst = new PeterBochsDebugger();
            PeterBochsDebugger.instance = inst;

            new Thread("preventSetVisibleHang thread") {
                public void run() {
                    try {
                        Thread.sleep(10000);
                        if (preventSetVisibleHang) {
                            System.out.println(
                                    "setVisible(true) cause system hang, this probably a swing bug, so force exit, please restart");
                            System.exit(-1);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();

            if (Global.debug) {
                System.out.println("setVisible(true)");
            }
            inst.setVisible(true);

            preventSetVisibleHang = false;
            if (Global.debug) {
                System.out.println("end setVisible(true)");
            }
        }
    });
}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

private static void replaceInJar(File sourceJar, String origFile, File replacementFile) throws IOException {
    String srcJarAbsPath = sourceJar.getAbsolutePath();
    String srcJarSuffix = srcJarAbsPath.substring(srcJarAbsPath.lastIndexOf(File.separator) + 1);
    String srcJarName = srcJarSuffix.split(".jar")[0];

    String destJarName = srcJarName + "-managix";
    String destJarSuffix = destJarName + ".jar";
    File destJar = new File(sourceJar.getParentFile().getAbsolutePath() + File.separator + destJarSuffix);
    //  File destJar = new File(sourceJar.getAbsolutePath() + ".modified");
    JarFile sourceJarFile = new JarFile(sourceJar);
    Enumeration<JarEntry> entries = sourceJarFile.entries();
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(destJar));
    byte[] buffer = new byte[2048];
    int read;/*w w w  . jav a 2 s  .  c o m*/
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String name = entry.getName();
        if (name.equals(origFile)) {
            continue;
        }
        InputStream jarIs = sourceJarFile.getInputStream(entry);
        jos.putNextEntry(entry);
        while ((read = jarIs.read(buffer)) != -1) {
            jos.write(buffer, 0, read);
        }
        jarIs.close();
    }
    sourceJarFile.close();
    JarEntry entry = new JarEntry(origFile);
    jos.putNextEntry(entry);
    FileInputStream fis = new FileInputStream(replacementFile);
    while ((read = fis.read(buffer)) != -1) {
        jos.write(buffer, 0, read);
    }
    fis.close();
    jos.close();
    sourceJar.delete();
    destJar.renameTo(sourceJar);
    destJar.setExecutable(true);
}

From source file:com.googlecode.mycontainer.maven.plugin.ExecMojo.java

/**
 * Create a jar with just a manifest containing a Main-Class entry for
 * SurefireBooter and a Class-Path entry for all classpath elements. Copied
 * from surefire (ForkConfiguration#createJar())
 * /*w w  w .  j a  v  a  2  s.c  o  m*/
 * @param classPath
 *            List&lt;String> of all classpath elements.
 * @return
 * @throws IOException
 */
private File createJar(List classPath, String mainClass) throws IOException {
    File file = File.createTempFile("maven-exec", ".jar");
    file.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(file);
    JarOutputStream jos = new JarOutputStream(fos);
    jos.setLevel(JarOutputStream.STORED);
    JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
    jos.putNextEntry(je);

    Manifest man = new Manifest();

    // we can't use StringUtils.join here since we need to add a '/' to
    // the end of directory entries - otherwise the jvm will ignore them.
    String cp = "";
    for (Iterator it = classPath.iterator(); it.hasNext();) {
        String el = (String) it.next();
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp += UrlUtils.getURL(new File(el)).toExternalForm() + " ";
    }

    man.getMainAttributes().putValue("Manifest-Version", "1.0");
    man.getMainAttributes().putValue("Class-Path", cp.trim());
    man.getMainAttributes().putValue("Main-Class", mainClass);

    man.write(jos);
    jos.close();

    return file;
}

From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java

/**
 * Copies the content of a Jar/Zip archive into the receiver archive.
 * <p/>An optional {@link IZipEntryFilter} allows to selectively choose which files
 * to copy over.//from w ww .ja  v a2 s.  c  o m
 *
 * @param input  the {@link InputStream} for the Jar/Zip to copy.
 * @param filter the filter or <code>null</code>
 * @throws IOException
 * @throws SignedJarBuilder.IZipEntryFilter.ZipAbortException if the {@link IZipEntryFilter} filter indicated that the write
 *                                                            must be aborted.
 */
public void writeZip(InputStream input, IZipEntryFilter filter)
        throws IOException, IZipEntryFilter.ZipAbortException {
    ZipInputStream zis = new ZipInputStream(input);

    try {
        // loop on the entries of the intermediary package and put them in the final package.
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            String name = entry.getName();

            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }

            // ignore some of the content in META-INF/ but not all
            if (name.startsWith("META-INF/")) {
                // ignore the manifest file.
                String subName = name.substring(9);
                if ("MANIFEST.MF".equals(subName)) {
                    int count;
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    while ((count = zis.read(buffer)) != -1) {
                        out.write(buffer, 0, count);
                    }
                    ByteArrayInputStream swapStream = new ByteArrayInputStream(out.toByteArray());
                    Manifest manifest = new Manifest(swapStream);
                    mManifest.getMainAttributes().putAll(manifest.getMainAttributes());
                    continue;
                }

                // special case for Maven meta-data because we really don't care about them in apks.
                if (name.startsWith("META-INF/maven/")) {
                    continue;
                }

                // check for subfolder
                int index = subName.indexOf('/');
                if (index == -1) {
                    // no sub folder, ignores signature files.
                    if (subName.endsWith(".SF") || name.endsWith(".RSA") || name.endsWith(".DSA")) {
                        continue;
                    }
                }
            }

            // if we have a filter, we check the entry against it
            if (filter != null && !filter.checkEntry(name)) {
                continue;
            }

            JarEntry newEntry;

            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }

            writeEntry(zis, newEntry);

            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
}

From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java

/**
 * Closes the Jar archive by creating the manifest, and signing the archive.
 *
 * @throws IOException//from  ww  w .ja v  a 2s  .c  o m
 * @throws SigningException
 */
public void close() throws IOException, SigningException {
    if (mManifest != null) {
        // write the manifest to the jar file
        mOutputJar.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME));
        mManifest.write(mOutputJar);

        try {
            // CERT.SF
            Signature signature = Signature.getInstance("SHA1with" + mKey.getAlgorithm());
            signature.initSign(mKey);
            if (StringUtils.isBlank(mSignFile)) {
                mOutputJar.putNextEntry(new JarEntry("META-INF/CERT.SF"));
            } else {
                mOutputJar.putNextEntry(new JarEntry("META-INF/" + mSignFile + ".SF"));
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            writeSignatureFile(baos);
            byte[] signedData = baos.toByteArray();
            mOutputJar.write(signedData);

            if (StringUtils.isBlank(mSignFile)) {
                mOutputJar.putNextEntry(new JarEntry("META-INF/CERT." + mKey.getAlgorithm()));
            } else {
                mOutputJar.putNextEntry(new JarEntry("META-INF/" + mSignFile + "." + mKey.getAlgorithm()));
            }
            // CERT.*
            writeSignatureBlock(new CMSProcessableByteArray(signedData), mCertificate, mKey);
        } catch (Exception e) {
            throw new SigningException(e);
        }
    }

    mOutputJar.close();
    mOutputJar = null;
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static void writeJarEntries(JarFile jar, JarOutputStream jos, String signatureName) throws IOException {

    for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) {
        JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
        if (!jarEntry.isDirectory()) {
            String entryName = jarEntry.getName();

            // Signature files not to write across
            String sigFileLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName, SIGNATURE_EXT)
                    .toUpperCase();//from  w  ww  .ja  v a 2s.c o  m
            String dsaSigBlockLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName,
                    DSA_SIG_BLOCK_EXT);
            String rsaSigBlockLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName,
                    RSA_SIG_BLOCK_EXT);

            // Do not write across existing manifest or matching signature files
            if ((!entryName.equalsIgnoreCase(MANIFEST_LOCATION))
                    && (!entryName.equalsIgnoreCase(sigFileLocation))
                    && (!entryName.equalsIgnoreCase(dsaSigBlockLocation))
                    && (!entryName.equalsIgnoreCase(rsaSigBlockLocation))) {
                // New JAR entry based on original
                JarEntry newJarEntry = new JarEntry(jarEntry.getName());
                newJarEntry.setMethod(jarEntry.getMethod());
                newJarEntry.setCompressedSize(jarEntry.getCompressedSize());
                newJarEntry.setCrc(jarEntry.getCrc());
                jos.putNextEntry(newJarEntry);

                InputStream jis = null;

                try {
                    jis = jar.getInputStream(jarEntry);

                    byte[] buffer = new byte[2048];
                    int read = -1;

                    while ((read = jis.read(buffer)) != -1) {
                        jos.write(buffer, 0, read);
                    }

                    jos.closeEntry();
                } finally {
                    IOUtils.closeQuietly(jis);
                }
            }
        }
    }
}

From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java

/**
 * Creates a Jar archive that includes the given list of files
 * //from  w w  w. j a  v  a 2s .  c o  m
 * @param archiveFile the name of the jar archive file
 * @param tobeJared the files to be included in the jar file
 * 
 * @return if the operation was successful
 */
public static boolean createJarArchive(File archiveFile, List<File> tobeJared) {
    try {
        byte buffer[] = new byte[BUFFER_SIZE];
        // Open archive file
        FileOutputStream stream = new FileOutputStream(archiveFile);
        JarOutputStream out = new JarOutputStream(stream, new Manifest());

        for (int i = 0; i < tobeJared.size(); i++) {
            if (tobeJared.get(i) == null || !tobeJared.get(i).exists() || tobeJared.get(i).isDirectory())
                continue; // Just in case...
            log.debug("Adding " + tobeJared.get(i).getName());

            // Add archive entry
            JarEntry jarAdd = new JarEntry(tobeJared.get(i).getName());
            jarAdd.setTime(tobeJared.get(i).lastModified());
            out.putNextEntry(jarAdd);

            // Write file to archive
            FileInputStream in = new FileInputStream(tobeJared.get(i));
            while (true) {
                int nRead = in.read(buffer, 0, buffer.length);
                if (nRead <= 0)
                    break;
                out.write(buffer, 0, nRead);
            }
            in.close();
        }

        out.close();
        stream.close();
        log.info("Adding completed OK");
        return true;
    } catch (Exception e) {
        log.error("Creating jar file failed", e);
        return false;
    }
}