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:lu.fisch.moenagade.model.Project.java

public void jar() {
    try {//from  w ww.  j a  va  2s  . c o m
        // compile all
        if (!save())
            return;

        generateSource(true);
        if (compile()) {
            // adjust the dirname
            String bdir = getDirectoryName();
            if (!bdir.endsWith(System.getProperty("file.separator"))) {
                bdir += System.getProperty("file.separator");
            }

            // adjust the filename
            String bname = getDirectoryName();
            if (bname.endsWith(System.getProperty("file.separator"))) {
                bname = bname.substring(0, bname.length() - 1);
            }
            bname = bname.substring(bname.lastIndexOf(System.getProperty("file.separator")) + 1);

            // default class to launch
            String mc = "moenagade.Project";

            // target JVM
            String target = "1.8";

            /*
            String[] targets = new String[]{"1.1","1.2","1.3","1.5","1.6"};
            if(System.getProperty("java.version").startsWith("1.7"))
            targets = new String[]{"1.1","1.2","1.3","1.5","1.6","1.7"};
            if(System.getProperty("java.version").startsWith("1.8"))
            targets = new String[]{"1.1","1.2","1.3","1.5","1.6","1.7","1.8"};
                    
            target= (String) JOptionPane.showInputDialog(
                           frame,
                           "Please enter version of the JVM you want to target.",
                           "Target JVM",
                           JOptionPane.QUESTION_MESSAGE,
                           Moenagade.IMG_QUESTION,
                           targets,
                           "1.6");*/

            File fDir = new File(directoryName + System.getProperty("file.separator") + "bin");
            if (!fDir.exists())
                fDir.mkdir();

            // get all the files content
            Hashtable<String, String> codes = new Hashtable<>();
            String srcdir = directoryName + System.getProperty("file.separator") + "src";
            Collection files = FileUtils.listFiles(new File(srcdir), new String[] { "java" }, true);

            File[] javas = new File[files.size()];
            int i = 0;
            for (Iterator iterator = files.iterator(); iterator.hasNext();) {
                File file = (File) iterator.next();
                javas[i++] = file;
            }

            try {
                // make class files
                Runtime6.getInstance().compileToPath(javas, fDir.getAbsolutePath(), target, "");

                StringList manifest = new StringList();
                manifest.add("Manifest-Version: 1.0");
                manifest.add("Created-By: " + Moenagade.E_VERSION + " " + Moenagade.E_VERSION);
                manifest.add("Name: " + bname);
                if (mc != null) {
                    manifest.add("Main-Class: " + mc);
                }

                // compose the filename
                fDir = new File(bdir + "dist" + System.getProperty("file.separator"));
                fDir.mkdir();
                bname = bdir + "dist" + System.getProperty("file.separator") + bname + ".jar";
                String baseName = bdir;
                String libFolderName = bdir + "lib";
                String distLibFolderName = bdir + "dist" + System.getProperty("file.separator") + "lib";

                File outFile = new File(bname);
                FileOutputStream bo = new FileOutputStream(bname);
                JarOutputStream jo = new JarOutputStream(bo);

                String dirname = getDirectoryName();
                if (!dirname.endsWith(System.getProperty("file.separator"))) {
                    dirname += System.getProperty("file.separator");
                }
                // add the files to the array
                addToJar(jo, "", new File(dirname + "bin" + System.getProperty("file.separator")));
                // add the files to the array
                addToJar(jo, "", new File(dirname + "src" + System.getProperty("file.separator")),
                        new String[] { "java" });

                //manifest.add("Class-Path: "+cp+" "+cpsw);

                // adding the manifest file
                manifest.add("");
                JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
                jo.putNextEntry(je);
                String mf = manifest.getText();
                jo.write(mf.getBytes(), 0, mf.getBytes().length);

                jo.close();
                bo.close();

                // delete bin directory
                deleteDirectory(new File(getDirectoryName() + System.getProperty("file.separator") + "bin"
                        + System.getProperty("file.separator")));
                // generate java code with dispose_on_exit
                generateSource();

                JOptionPane.showMessageDialog(frame,
                        "The JAR-archive has been generated and can\nbe found in the \"dist\" directory.",
                        "Success", JOptionPane.INFORMATION_MESSAGE, Moenagade.IMG_INFO);
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
        }
    }
    /*catch (ClassNotFoundException ex)
    {
    JOptionPane.showMessageDialog(frame, "There was an error while creating the JAR-archive ...", "Error :: ClassNotFoundException", JOptionPane.ERROR_MESSAGE,Unimozer.IMG_ERROR);
    }*/
    catch (IOException ex) {
        JOptionPane.showMessageDialog(frame, "There was an error while creating the JAR-archive ...",
                "Error :: IOException", JOptionPane.ERROR_MESSAGE, Moenagade.IMG_ERROR);
        ex.printStackTrace();
    }
}

From source file:org.apache.pluto.util.assemble.io.JarStreamingAssembly.java

/**
 * Reads the source JarInputStream, copying entries to the destination JarOutputStream. 
 * The web.xml and portlet.xml are cached, and after the entire archive is copied 
 * (minus the web.xml) a re-written web.xml is generated and written to the 
 * destination JAR./*from w  w  w  .  j  a  v a  2  s .c  om*/
 * 
 * @param source the WAR source input stream
 * @param dest the WAR destination output stream
 * @param dispatchServletClass the name of the dispatch class
 * @throws IOException
 */
public static void assembleStream(JarInputStream source, JarOutputStream dest, String dispatchServletClass)
        throws IOException {

    try {
        //Need to buffer the web.xml and portlet.xml files for the rewritting
        JarEntry servletXmlEntry = null;
        byte[] servletXmlBuffer = null;
        byte[] portletXmlBuffer = null;

        JarEntry originalJarEntry;

        //Read the source archive entry by entry
        while ((originalJarEntry = source.getNextJarEntry()) != null) {

            final JarEntry newJarEntry = smartClone(originalJarEntry);
            originalJarEntry = null;

            //Capture the web.xml JarEntry and contents as a byte[], don't write it out now or
            //update the CRC or length of the destEntry.
            if (Assembler.SERVLET_XML.equals(newJarEntry.getName())) {
                servletXmlEntry = newJarEntry;
                servletXmlBuffer = IOUtils.toByteArray(source);
            }

            //Capture the portlet.xml contents as a byte[]
            else if (Assembler.PORTLET_XML.equals(newJarEntry.getName())) {
                portletXmlBuffer = IOUtils.toByteArray(source);
                dest.putNextEntry(newJarEntry);
                IOUtils.write(portletXmlBuffer, dest);
            }

            //Copy all other entries directly to the output archive
            else {
                dest.putNextEntry(newJarEntry);
                IOUtils.copy(source, dest);
            }

            dest.closeEntry();
            dest.flush();

        }

        // If no portlet.xml was found in the archive, skip the assembly step.
        if (portletXmlBuffer != null) {
            // container for assembled web.xml bytes
            final byte[] webXmlBytes;

            // Checks to make sure the web.xml was found in the archive
            if (servletXmlBuffer == null) {
                throw new FileNotFoundException(
                        "File '" + Assembler.SERVLET_XML + "' could not be found in the source input stream.");
            }

            //Create streams of the byte[] data for the updater method
            final InputStream webXmlIn = new ByteArrayInputStream(servletXmlBuffer);
            final InputStream portletXmlIn = new ByteArrayInputStream(portletXmlBuffer);
            final ByteArrayOutputStream webXmlOut = new ByteArrayOutputStream(servletXmlBuffer.length);

            //Update the web.xml
            WebXmlStreamingAssembly.assembleStream(webXmlIn, portletXmlIn, webXmlOut, dispatchServletClass);
            IOUtils.copy(webXmlIn, webXmlOut);
            webXmlBytes = webXmlOut.toByteArray();

            //If no compression is being used (STORED) we have to manually update the size and crc
            if (servletXmlEntry.getMethod() == ZipEntry.STORED) {
                servletXmlEntry.setSize(webXmlBytes.length);
                final CRC32 webXmlCrc = new CRC32();
                webXmlCrc.update(webXmlBytes);
                servletXmlEntry.setCrc(webXmlCrc.getValue());
            }

            //write out the assembled web.xml entry and contents
            dest.putNextEntry(servletXmlEntry);
            IOUtils.write(webXmlBytes, dest);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Jar stream " + source + " successfully assembled.");
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No portlet XML file was found, assembly was not required.");
            }

            //copy the original, unmodified web.xml entry to the destination
            dest.putNextEntry(servletXmlEntry);
            IOUtils.write(servletXmlBuffer, dest);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Jar stream " + source + " successfully assembled.");
            }
        }

    } finally {

        dest.flush();
        dest.close();

    }
}

From source file:com.threerings.media.tile.bundle.tools.TileSetBundler.java

/**
 * Create a tileset bundle jar file.//  w  w  w .jav a  2 s  .com
 *
 * @param target the tileset bundle file that will be created.
 * @param bundle contains the tilesets we'd like to save out to the bundle.
 * @param improv the image provider.
 * @param imageBase the base directory for getting images for non-ObjectTileSet tilesets.
 * @param keepOriginalPngs bundle up the original PNGs as PNGs instead of converting to the
 * FastImageIO raw format
 */
public static boolean createBundleJar(File target, TileSetBundle bundle, ImageProvider improv, String imageBase,
        boolean keepOriginalPngs, boolean uncompressed) throws IOException {
    // now we have to create the actual bundle file
    FileOutputStream fout = new FileOutputStream(target);
    Manifest manifest = new Manifest();
    JarOutputStream jar = new JarOutputStream(fout, manifest);
    jar.setLevel(uncompressed ? Deflater.NO_COMPRESSION : Deflater.BEST_COMPRESSION);

    try {
        // write all of the image files to the bundle, converting the
        // tilesets to trimmed tilesets in the process
        Iterator<Integer> iditer = bundle.enumerateTileSetIds();

        // Store off the updated TileSets in a separate Map so we can wait to change the
        // bundle till we're done iterating.
        HashIntMap<TileSet> toUpdate = new HashIntMap<TileSet>();
        while (iditer.hasNext()) {
            int tileSetId = iditer.next().intValue();
            TileSet set = bundle.getTileSet(tileSetId);
            String imagePath = set.getImagePath();

            // sanity checks
            if (imagePath == null) {
                log.warning("Tileset contains no image path " + "[set=" + set + "]. It ain't gonna work.");
                continue;
            }

            // if this is an object tileset, trim it
            if (!keepOriginalPngs && (set instanceof ObjectTileSet)) {
                // set the tileset up with an image provider; we
                // need to do this so that we can trim it!
                set.setImageProvider(improv);

                // we're going to trim it, so adjust the path
                imagePath = adjustImagePath(imagePath);
                jar.putNextEntry(new JarEntry(imagePath));

                try {
                    // create a trimmed object tileset, which will
                    // write the trimmed tileset image to the jar
                    // output stream
                    TrimmedObjectTileSet tset = TrimmedObjectTileSet.trimObjectTileSet((ObjectTileSet) set,
                            jar);
                    tset.setImagePath(imagePath);
                    // replace the original set with the trimmed
                    // tileset in the tileset bundle
                    toUpdate.put(tileSetId, tset);

                } catch (Exception e) {
                    e.printStackTrace(System.err);

                    String msg = "Error adding tileset to bundle " + imagePath + ", " + set.getName() + ": "
                            + e;
                    throw (IOException) new IOException(msg).initCause(e);
                }

            } else {
                // read the image file and convert it to our custom
                // format in the bundle
                File ifile = new File(imageBase, imagePath);
                try {
                    BufferedImage image = ImageIO.read(ifile);
                    if (!keepOriginalPngs && FastImageIO.canWrite(image)) {
                        imagePath = adjustImagePath(imagePath);
                        jar.putNextEntry(new JarEntry(imagePath));
                        set.setImagePath(imagePath);
                        FastImageIO.write(image, jar);
                    } else {
                        jar.putNextEntry(new JarEntry(imagePath));
                        FileInputStream imgin = new FileInputStream(ifile);
                        StreamUtil.copy(imgin, jar);
                    }
                } catch (Exception e) {
                    String msg = "Failure bundling image " + ifile + ": " + e;
                    throw (IOException) new IOException(msg).initCause(e);
                }
            }
        }
        bundle.putAll(toUpdate);

        // now write a serialized representation of the tileset bundle
        // object to the bundle jar file
        JarEntry entry = new JarEntry(BundleUtil.METADATA_PATH);
        jar.putNextEntry(entry);
        ObjectOutputStream oout = new ObjectOutputStream(jar);
        oout.writeObject(bundle);
        oout.flush();

        // finally close up the jar file and call ourself done
        jar.close();

        return true;

    } catch (Exception e) {
        // remove the incomplete jar file and rethrow the exception
        jar.close();
        if (!target.delete()) {
            log.warning("Failed to close botched bundle '" + target + "'.");
        }
        String errmsg = "Failed to create bundle " + target + ": " + e;
        throw (IOException) new IOException(errmsg).initCause(e);
    }
}

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

private synchronized void jar(Map<String, byte[]> javacresult, List<CodeGenerator> generators) {
    try {/*from  w w  w. ja v a2  s  .  c  om*/
        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 ww.  j  a  v a2s  .c  o 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.dspace.installer_edm.InstallerEDMConfEDMExport.java

/**
 * Recorre el war para escribir los archivos web.xml, la api de dspace y los jar de lucene
 *
 * @throws IOException/*from   w  w w. jav  a 2  s  . c  om*/
 * @throws TransformerException
 */
private void writeNewJar() throws IOException, TransformerException {
    final int BUFFER_SIZE = 1024;
    // directorio de trabajo
    File jarDir = new File(this.eDMExportWarJarFile.getName()).getParentFile();
    // archivo temporal del nuevo war
    File newJarFile = File.createTempFile("EDMExport", ".jar", jarDir);
    newJarFile.deleteOnExit();
    // flujo de escritura para el nuevo war
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    try {
        // recorrer los archivos del war
        Enumeration<JarEntry> entries = eDMExportWarJarFile.entries();
        // libreras de lucene
        Pattern luceneLibPattern = Pattern.compile("^WEB-INF/lib/(lucene-.+?)-\\d+.+\\.jar$");
        boolean newApiCopied = false;
        if (dspaceApi == null)
            newApiCopied = true;
        boolean replace = false;
        // recorrer
        while (entries.hasMoreElements()) {
            replace = false;
            installerEDMDisplay.showProgress('.');
            JarEntry entry = entries.nextElement();
            InputStream intputStream = null;
            // todos menos web.xml
            if (!entry.getName().equals("WEB-INF/web.xml")) {
                // api de dspace, se muestra la actual y la de dspace para pedir si se copia
                if (!newApiCopied && entry.getName().matches("^WEB-INF/lib/dspace-api-\\d+.+\\.jar$")) {
                    String response = null;
                    do {
                        installerEDMDisplay.showLn();
                        installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace.question",
                                new String[] { entry.getName(), "WEB-INF/lib/" + dspaceApi.getName(),
                                        dspaceApi.getAbsolutePath() });
                        response = br.readLine();
                        if (response == null)
                            continue;
                        response = response.trim();
                        if (response.isEmpty() || response.equalsIgnoreCase(answerYes)) {
                            replace = true;
                            break;
                        } else if (response.equalsIgnoreCase("n")) {
                            break;
                        }
                    } while (true);
                    // se reemplaza por la de dspace
                    if (replace) {
                        JarEntry newJarEntry = new JarEntry("WEB-INF/lib/" + dspaceApi.getName());
                        newJarEntry.setCompressedSize(-1);
                        jarOutputStream.putNextEntry(newJarEntry);
                        intputStream = new FileInputStream(dspaceApi);
                        newApiCopied = true;
                        if (debug) {
                            installerEDMDisplay.showLn();
                            installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace",
                                    new String[] { entry.getName(), "WEB-INF/lib/" + dspaceApi.getName(),
                                            dspaceApi.getAbsolutePath() });
                            installerEDMDisplay.showLn();
                        }
                    }
                } else {
                    // libreras de lucene
                    Matcher luceneLibMatcher = luceneLibPattern.matcher(entry.getName());
                    if (luceneLibMatcher.find()) {
                        String prefixLuceneLib = luceneLibMatcher.group(1);
                        File luceneLibFile = null;
                        String patternFile = prefixLuceneLib + "-\\d+.+\\.jar";
                        for (File file : luceneLibs) {
                            if (file.getName().matches(patternFile)) {
                                luceneLibFile = file;
                                break;
                            }
                        }
                        if (luceneLibFile != null) {
                            String response = null;
                            do {
                                installerEDMDisplay.showLn();
                                installerEDMDisplay.showQuestion(currentStepGlobal,
                                        "writeNewJar.replace.question",
                                        new String[] { entry.getName(),
                                                "WEB-INF/lib/" + luceneLibFile.getName(),
                                                luceneLibFile.getAbsolutePath() });
                                response = br.readLine();
                                if (response == null)
                                    continue;
                                response = response.trim();
                                if (response.isEmpty() || response.equalsIgnoreCase(answerYes)) {
                                    replace = true;
                                    break;
                                } else if (response.equalsIgnoreCase("n")) {
                                    break;
                                }
                            } while (true);
                            // se reemplaza por la de dspace
                            if (replace) {
                                JarEntry newJarEntry = new JarEntry("WEB-INF/lib/" + luceneLibFile.getName());
                                newJarEntry.setCompressedSize(-1);
                                jarOutputStream.putNextEntry(newJarEntry);
                                intputStream = new FileInputStream(luceneLibFile);
                                if (debug) {
                                    installerEDMDisplay.showLn();
                                    installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace",
                                            new String[] { entry.getName(),
                                                    "WEB-INF/lib/" + luceneLibFile.getName(),
                                                    luceneLibFile.getAbsolutePath() });
                                    installerEDMDisplay.showLn();
                                }
                            }
                        }
                        // si no era la api de dspace o las libreras de lucene se copia tal cual
                    } else if (!replace) {
                        JarEntry entryOld = new JarEntry(entry);
                        entryOld.setCompressedSize(-1);
                        jarOutputStream.putNextEntry(entryOld);
                        intputStream = eDMExportWarJarFile.getInputStream(entry);
                    }
                }
                if (intputStream == null) {
                    if (debug)
                        installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.notIS",
                                new String[] { entry.getName() });
                    continue;
                }
                // se lee el archivo y se copia al flujo de escritura del war
                int count;
                byte data[] = new byte[BUFFER_SIZE];
                while ((count = intputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                    jarOutputStream.write(data, 0, count);
                }
                intputStream.close();
            }
        }
        installerEDMDisplay.showLn();
        // se aade web.xml al war
        addNewWebXml(jarOutputStream);
        // cerramos el archivo jar y borramos el war
        eDMExportWarJarFile.close();
        eDMExportWarWorkFile.delete();
        // sustituimos el viejo por el temporal
        try {
            /*if (newJarFile.renameTo(eDMExportWarWorkFile) && eDMExportWarWorkFile.setExecutable(true, true)) {
            eDMExportWarWorkFile = new File(myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
            } else {
            throw new IOException();
            }*/
            if (jarOutputStream != null)
                jarOutputStream.close();
            FileUtils.moveFile(newJarFile, eDMExportWarWorkFile);
            //newJarFile.renameTo(eDMExportWarWorkFile);
            eDMExportWarWorkFile.setExecutable(true, true);
            eDMExportWarWorkFile = new File(
                    myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
        } catch (Exception io) {
            io.printStackTrace();
            throw new IOException();
        }
    } finally {
        if (jarOutputStream != null) {
            jarOutputStream.close();
        }
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public void processDownloadMails(HttpServletRequest request, HttpServletResponse response) {
    MailAccount account = getAccount(request);
    String foldername = request.getParameter("folder");
    String sout = null;//from   www.ja  v a  2 s .  c  o  m
    try {
        account.checkStoreConnected();
        StringBuffer sb = new StringBuffer();
        FolderCache mcache = account.getFolderCache(foldername);
        Message msgs[] = mcache.getAllMessages();
        String zipname = "Webtop-mails-" + getInternationalFolderName(mcache);
        response.setContentType("application/x-zip-compressed");
        response.setHeader("Content-Disposition", "inline; filename=\"" + zipname + ".zip\"");
        OutputStream out = response.getOutputStream();

        JarOutputStream jos = new java.util.jar.JarOutputStream(out);
        outputJarMailFolder(null, msgs, jos);

        int cut = foldername.length() + 1;
        cycleMailFolder(account, mcache.getFolder(), cut, jos);

        jos.close();

    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public void processGetAttachments(HttpServletRequest request, HttpServletResponse response) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pids[] = request.getParameterValues("ids");
    String providername = request.getParameter("provider");
    String providerid = request.getParameter("providerid");

    try {// w  w w  .  j a v  a2s  .c  o  m
        account.checkStoreConnected();
        FolderCache mcache = null;
        Message m = null;
        if (providername == null) {
            mcache = account.getFolderCache(pfoldername);
            long newmsguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(newmsguid);
        } else {
            mcache = fcProvided;
            m = mcache.getProvidedMessage(providername, providerid);
        }
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        String name = m.getSubject();
        if (name == null) {
            name = "attachments";
        }
        try {
            name = MailUtils.decodeQString(name);
        } catch (Exception exc) {
        }
        name += ".zip";
        //prepare hashmap to hold already used pnames
        HashMap<String, String> pnames = new HashMap<String, String>();
        ServletUtils.setFileStreamHeaders(response, "application/x-zip-compressed", DispositionType.INLINE,
                name);
        JarOutputStream jos = new java.util.jar.JarOutputStream(response.getOutputStream());
        byte[] b = new byte[64 * 1024];
        for (String pid : pids) {
            Part part = mailData.getAttachmentPart(Integer.parseInt(pid));
            String pname = part.getFileName();
            if (pname == null) {
                pname = "unknown";
            }
            /*
            try {
               pname = MailUtils.decodeQString(pname, "iso-8859-1");
            } catch (Exception exc) {
            }
            */
            //keep name and extension
            String bpname = pname;
            String extpname = null;
            int ix = pname.lastIndexOf(".");
            if (ix > 0) {
                bpname = pname.substring(0, ix);
                extpname = pname.substring(ix + 1);
            }
            //check for existing pname and find an unused name
            int xid = 0;
            String rpname = pname;
            while (pnames.containsKey(rpname)) {
                rpname = bpname + " (" + (++xid) + ")";
                if (extpname != null)
                    rpname += "." + extpname;
            }

            JarEntry je = new JarEntry(rpname);
            jos.putNextEntry(je);
            if (providername == null) {
                Folder folder = mailData.getFolder();
                if (!folder.isOpen()) {
                    folder.open(Folder.READ_ONLY);
                }
            }
            InputStream is = part.getInputStream();
            int len = 0;
            while ((len = is.read(b)) != -1) {
                jos.write(b, 0, len);
            }
            is.close();

            //remember used pname
            pnames.put(rpname, rpname);
        }
        jos.closeEntry();
        jos.flush();
        jos.close();

    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

From source file:lu.fisch.unimozer.Diagram.java

public void jar() {
    try {//from  w  w w  . java 2s. co m
        // compile all
        if (compile())
            if (save()) {

                // adjust the dirname
                String dir = getDirectoryName();
                if (!dir.endsWith(System.getProperty("file.separator"))) {
                    dir += System.getProperty("file.separator");
                }

                // adjust the filename
                String name = getDirectoryName();
                if (name.endsWith(System.getProperty("file.separator"))) {
                    name = name.substring(0, name.length() - 1);
                }
                name = name.substring(name.lastIndexOf(System.getProperty("file.separator")) + 1);

                /*String[] classNames = new String[classes.size()+1];
                Set<String> set = classes.keySet();
                Iterator<String> itr = set.iterator();
                classNames[0]=null;
                int c = 1;
                while (itr.hasNext())
                {
                    classNames[c]=itr.next();
                    c++;
                }/**/
                Vector<String> mains = getMains();
                String[] classNames = new String[mains.size()];
                for (int c = 0; c < mains.size(); c++)
                    classNames[c] = mains.get(c);
                // default class to launch
                String mc = "";
                {
                    if (classNames.length == 0) {
                        mc = "";
                        JOptionPane.showMessageDialog(printOptions,
                                "Unimozer was unable to detect a startable class\n"
                                        + "inside your project. The JAR-archive will be created\n"
                                        + "but it won't be executable!",
                                "Mainclass", JOptionPane.INFORMATION_MESSAGE, Unimozer.IMG_INFO);
                    } else if (classNames.length == 1)
                        mc = classNames[0];
                    else
                        mc = (String) JOptionPane.showInputDialog(frame,
                                "Unimozer detected more than one runnable class.\n"
                                        + "Please select which one you want to be launched\n"
                                        + "automatically with the JAR-archive.",
                                "Autostart", JOptionPane.QUESTION_MESSAGE, Unimozer.IMG_QUESTION, classNames,
                                "");
                }
                // target JVM
                String target = null;
                if (Runtime5.getInstance().usesSunJDK() && mc != null) {

                    String[] targets = new String[] { "1.1", "1.2", "1.3", "1.5", "1.6" };
                    if (System.getProperty("java.version").startsWith("1.7"))
                        targets = new String[] { "1.1", "1.2", "1.3", "1.5", "1.6", "1.7" };
                    if (System.getProperty("java.version").startsWith("1.8"))
                        targets = new String[] { "1.1", "1.2", "1.3", "1.5", "1.6", "1.7", "1.8" };

                    target = (String) JOptionPane.showInputDialog(frame,
                            "Please enter version of the JVM you want to target.", "Target JVM",
                            JOptionPane.QUESTION_MESSAGE, Unimozer.IMG_QUESTION, targets, "1.6");
                }
                // make the class-files and all
                // related stuff
                if (((Runtime5.getInstance().usesSunJDK() && target != null)
                        || (!Runtime5.getInstance().usesSunJDK())) && (mc != null))
                    if (makeInteractive(false, target, false) == true) {

                        StringList manifest = new StringList();
                        manifest.add("Manifest-Version: 1.0");
                        manifest.add("Created-By: " + Unimozer.E_VERSION + " " + Unimozer.E_VERSION);
                        manifest.add("Name: " + name);
                        if (mc != null) {
                            manifest.add("Main-Class: " + mc);
                        }

                        // compose the filename
                        File fDir = new File(dir + "dist" + System.getProperty("file.separator"));
                        fDir.mkdir();
                        name = dir + "dist" + System.getProperty("file.separator") + name + ".jar";
                        String baseName = dir;
                        String libFolderName = dir + "lib";
                        String distLibFolderName = dir + "dist" + System.getProperty("file.separator") + "lib";

                        File outFile = new File(name);
                        FileOutputStream bo = new FileOutputStream(name);
                        JarOutputStream jo = new JarOutputStream(bo);

                        String dirname = getDirectoryName();
                        if (!dirname.endsWith(System.getProperty("file.separator"))) {
                            dirname += System.getProperty("file.separator");
                        }
                        // add the files to the array
                        addToJar(jo, "", new File(dirname + "bin" + System.getProperty("file.separator")));
                        // add the files to the array
                        addToJar(jo, "", new File(dirname + "src" + System.getProperty("file.separator")),
                                new String[] { "java" });
                        /*
                        // define a filter for files that do not start with a dot
                        FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return !name.startsWith("."); } };                     
                        // get the bin directory
                        File binDir = new File(dirname+"bin"+System.getProperty("file.separator")); 
                        // get all files
                        File[] files = binDir.listFiles(filter);
                        for(int f=0;f<files.length;f++)
                        {
                            FileInputStream bi = new FileInputStream(files[f]);
                            String entry = files[f].getAbsolutePath();
                            entry = entry.substring(binDir.getAbsolutePath().length()+1);
                            JarEntry je = new JarEntry(entry);
                            jo.putNextEntry(je);
                            byte[] buf = new byte[1024];
                            int anz;
                            while ((anz = bi.read(buf)) != -1)
                            {
                                jo.write(buf, 0, anz);
                            }
                            bi.close();
                        }
                         */

                        // ask to include another direectory
                        // directory filter
                        /*
                        FilenameFilter dirFilter = new FilenameFilter() { public boolean accept(File dir, String name) { File isDir = new File(dir+System.getProperty("file.separator")+name); return isDir.isDirectory() && !name.equals("bin") && !name.equals("src") && !name.equals("dist") && !name.equals("nbproject") && !name.equals("doc"); } };
                        // get directories
                        File projectDir = new File(dirname);
                        String[] subDirs = projectDir.list(dirFilter);
                        if(subDirs.length>0)
                        {
                            String subdir = (String) JOptionPane.showInputDialog(
                               frame,
                               "Do you want to include any other resources directory?\n"+
                               "Click ?Cancel? to not include any resources directory!",
                               "JAR Packager",
                               JOptionPane.QUESTION_MESSAGE,
                               Unimozer.IMG_QUESTION,
                               subDirs,
                               null);
                            if(subdir!=null)
                            {
                                addToJar(jo,subdir+"/",new File(dirname+subdir+System.getProperty("file.separator")));
                            }
                        }
                         */

                        /*
                        Set<String> set = classes.keySet();
                        Iterator<String> itr = set.iterator();
                        int i = 0;
                        while (itr.hasNext())
                        {
                            String classname = itr.next();
                            String act = classname + ".class";
                            FileInputStream bi = new FileInputStream(dirname+"bin"+System.getProperty("file.separator")+act);
                            JarEntry je = new JarEntry(act);
                            jo.putNextEntry(je);
                            byte[] buf = new byte[1024];
                            int anz;
                            while ((anz = bi.read(buf)) != -1)
                            {
                                jo.write(buf, 0, anz);
                            }
                            bi.close();
                        }
                         */

                        // copy libs
                        File lib = new File(libFolderName);
                        File distLib = new File(distLibFolderName);
                        StringList libs = null;
                        if (lib.exists()) {
                            libs = CopyDirectory.copyFolder(lib, distLib);
                        }
                        String cp = new String();
                        if (libs != null) {
                            for (int i = 0; i < libs.count(); i++) {
                                String myLib = libs.get(i);
                                myLib = myLib.substring(baseName.length());
                                if (i != 0)
                                    cp = cp + " ";
                                cp = cp + myLib;
                            }
                            //manifest.add("Class-Path: "+cp);
                        }

                        // Let's search for the path of the swing-layout JAR file
                        String cpsw = "";
                        if (getCompleteSourceCode().contains("org.jdesktop.layout")) {
                            if (Main.classpath != null) {
                                // copy the file
                                String src = Main.classpath;
                                File f1 = new File(src);
                                String dest = distLibFolderName + System.getProperty("file.separator")
                                        + f1.getName();
                                // create folder if not exists
                                File f2 = new File(distLibFolderName);
                                if (!f2.exists())
                                    f2.mkdir();
                                // copy the file
                                InputStream in = new FileInputStream(src);
                                OutputStream out = new FileOutputStream(dest);
                                byte[] buffer = new byte[1024];
                                int length;
                                while ((length = in.read(buffer)) > 0) {
                                    out.write(buffer, 0, length);
                                }
                                in.close();
                                out.close();
                                // add the manifest entry
                                cpsw = "lib" + System.getProperty("file.separator") + f1.getName();
                            }
                        }

                        manifest.add("Class-Path: " + cp + " " + cpsw);

                        // adding the manifest file
                        manifest.add("");
                        JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
                        jo.putNextEntry(je);
                        String mf = manifest.getText();
                        jo.write(mf.getBytes(), 0, mf.getBytes().length);

                        jo.close();
                        bo.close();

                        cleanAll();

                        JOptionPane.showMessageDialog(frame, "The JAR-archive has been generated ...",
                                "Success", JOptionPane.INFORMATION_MESSAGE, Unimozer.IMG_INFO);
                    }
            }
    }
    /*catch (ClassNotFoundException ex)
    {
    JOptionPane.showMessageDialog(frame, "There was an error while creating the JAR-archive ...", "Error :: ClassNotFoundException", JOptionPane.ERROR_MESSAGE,Unimozer.IMG_ERROR);
    }*/
    catch (IOException ex) {
        JOptionPane.showMessageDialog(frame, "There was an error while creating the JAR-archive ...",
                "Error :: IOException", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
    }
}