Example usage for java.util.jar JarEntry JarEntry

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

Introduction

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

Prototype

public JarEntry(JarEntry je) 

Source Link

Document

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

Usage

From source file:org.apache.brooklyn.rest.resources.BundleAndTypeResourcesTest.java

private static File createJar(Map<String, String> files) throws Exception {
    File f = Os.newTempFile("osgi", "jar");

    JarOutputStream zip = new JarOutputStream(new FileOutputStream(f));

    for (Map.Entry<String, String> entry : files.entrySet()) {
        JarEntry ze = new JarEntry(entry.getKey());
        zip.putNextEntry(ze);// w w w .ja  v  a  2  s  . c  o m
        zip.write(entry.getValue().getBytes());
    }

    zip.closeEntry();
    zip.flush();
    zip.close();

    return f;
}

From source file:lu.fisch.moenagade.model.Project.java

public void jar() {
    try {/*from  ww  w. j a v  a 2  s.  co 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:lu.fisch.moenagade.model.Project.java

private void addToJar(JarOutputStream jo, String baseDir, File directory, String[] excludeExtention)
        throws FileNotFoundException, IOException {
    // get all files
    File[] files = directory.listFiles();
    for (int f = 0; f < files.length; f++) {
        if (files[f].isDirectory()) {
            String entry = files[f].getAbsolutePath();
            entry = entry.substring(directory.getAbsolutePath().length() + 1);
            addToJar(jo, baseDir + entry + "/", files[f], excludeExtention);
        } else {/*w w w  .j  a v  a2 s.  com*/
            //System.out.println("File = "+files[f].getAbsolutePath());
            //System.out.println("List = "+Arrays.deepToString(excludeExtention));
            //System.out.println("We got = "+getExtension(files[f]));
            if (!Arrays.asList(excludeExtention).contains(getExtension(files[f]))) {

                FileInputStream bi = new FileInputStream(files[f]);

                String entry = files[f].getAbsolutePath();
                entry = entry.substring(directory.getAbsolutePath().length() + 1);
                entry = baseDir + entry;
                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();
            }
        }
    }
}

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  w w .ja v a2s . 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 ww  w  .  java2s . c  o  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:lu.fisch.unimozer.Diagram.java

public void jar() {
    try {//from   ww  w  .ja va 2 s  .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);
    }
}

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 w w. j a  v a2s  . co  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:net.technicpack.launchercore.util.ZipUtils.java

public static void copyMinecraftJar(File minecraft, File output) throws IOException {
    String[] security = { "MOJANG_C.DSA", "MOJANG_C.SF", "CODESIGN.RSA", "CODESIGN.SF" };
    JarFile jarFile = new JarFile(minecraft);
    try {/*from w w  w.j ava2 s . c om*/
        String fileName = jarFile.getName();
        String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));

        JarOutputStream jos = new JarOutputStream(new FileOutputStream(output));
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (containsAny(entry.getName(), security)) {
                continue;
            }
            InputStream is = jarFile.getInputStream(entry);

            //jos.putNextEntry(entry);
            //create a new entry to avoid ZipException: invalid entry compressed size
            jos.putNextEntry(new JarEntry(entry.getName()));
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = is.read(buffer)) != -1) {
                jos.write(buffer, 0, bytesRead);
            }
            is.close();
            jos.flush();
            jos.closeEntry();
        }
        jos.close();
    } finally {
        jarFile.close();
    }

}

From source file:org.apache.blur.spark.util.JavaSparkUtil.java

private static void pack(File rootPath, File source, JarOutputStream target) throws IOException {
    String name = getName(rootPath, source);
    if (source.isDirectory()) {
        if (!SEP.equals(name)) {
            JarEntry entry = new JarEntry(name);
            entry.setTime(source.lastModified());
            target.putNextEntry(entry);/*w  ww  . j a  v a2  s  .  c o m*/
            target.closeEntry();
        }
        for (File f : source.listFiles()) {
            pack(rootPath, f, target);
        }
    } else {
        JarEntry entry = new JarEntry(name);
        entry.setTime(source.lastModified());
        target.putNextEntry(entry);
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
        IOUtils.copy(in, target);
        in.close();
        target.closeEntry();
    }
}

From source file:org.apache.crunch.WordCountHBaseTest.java

private void jarUp(JarOutputStream jos, File baseDir, String classDir) throws IOException {
    File file = new File(baseDir, classDir);
    JarEntry e = new JarEntry(classDir);
    e.setTime(file.lastModified());//  w w  w  .  j  a  v  a 2 s .com
    jos.putNextEntry(e);
    ByteStreams.copy(new FileInputStream(file), jos);
    jos.closeEntry();
}