Example usage for java.util.jar JarOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry ze) throws IOException 

Source Link

Document

Begins writing a new JAR file entry and positions the stream to the start of the entry data.

Usage

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

/**
 * Create a jar file that contains the translations for the given languages.
 * <p>/*from w  ww  . jav  a 2 s.  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:com.sonicle.webtop.mail.Service.java

private void cycleMailFolder(MailAccount account, Folder folder, int cut, JarOutputStream jos)
        throws Exception {
    for (Folder child : folder.list()) {
        String fullname = child.getFullName();
        String relname = fullname.substring(cut).replace(folder.getSeparator(), '/');

        jos.putNextEntry(new JarEntry(relname + "/"));
        jos.closeEntry();//w  ww . j  a v a 2s.co m

        cycleMailFolder(account, child, cut, jos);

        FolderCache mcache = account.getFolderCache(fullname);
        Message msgs[] = mcache.getAllMessages();
        if (msgs.length > 0)
            outputJarMailFolder(relname, msgs, jos);
    }
}

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

private void outputJarMailFolder(String foldername, Message msgs[], JarOutputStream jos) throws Exception {
    int digits = (msgs.length > 0 ? (int) Math.log10(msgs.length) + 1 : 1);
    for (int i = 0; i < msgs.length; ++i) {
        Message msg = msgs[i];//from   w ww  .j  a va2s  . co m
        String subject = msg.getSubject();
        if (subject != null)
            subject = subject.replace('/', '_').replace('\\', '_').replace(':', '-');
        else
            subject = "";
        java.util.Date date = msg.getReceivedDate();
        if (date == null)
            date = new java.util.Date();

        String fname = LangUtils.zerofill(i + 1, digits) + " - " + subject + ".eml";
        String fullname = null;
        if (foldername != null && !foldername.isEmpty())
            fullname = foldername + "/" + fname;
        else
            fullname = fname;
        JarEntry je = new JarEntry(fullname);
        je.setTime(date.getTime());
        jos.putNextEntry(je);
        msg.writeTo(jos);
        jos.closeEntry();
    }
    jos.flush();
}

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 {/*from w  ww  .  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 www. j a v  a  2s . com*/
        // 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);
    }
}