Example usage for java.util.zip ZipFile OPEN_READ

List of usage examples for java.util.zip ZipFile OPEN_READ

Introduction

In this page you can find the example usage for java.util.zip ZipFile OPEN_READ.

Prototype

int OPEN_READ

To view the source code for java.util.zip ZipFile OPEN_READ.

Click Source Link

Document

Mode flag to open a zip file for reading.

Usage

From source file:it.readbeyond.minstrel.librarian.FormatHandlerAbstractZIP.java

protected void extractCover(File f, Format format, String publicationID) {
    String destinationName = publicationID + "." + format.getName() + ".png";
    String entryName = format.getMetadatum("internalPathCover");

    if ((entryName == null) || (entryName.equals(""))) {
        format.addMetadatum("relativePathThumbnail", "");
        return;/*from   w  ww  .  j  a  v  a  2s  .c  om*/
    }

    try {
        ZipFile zipFile = new ZipFile(f, ZipFile.OPEN_READ);
        ZipEntry entry = zipFile.getEntry(entryName);
        File destFile = new File(this.thumbnailDirectoryPath, "orig-" + destinationName);
        String destinationPath = destFile.getAbsolutePath();

        BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
        int numberOfBytesRead;
        byte data[] = new byte[BUFFER_SIZE];

        FileOutputStream fos = new FileOutputStream(destFile);
        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);

        while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) {
            dest.write(data, 0, numberOfBytesRead);
        }
        dest.flush();
        dest.close();
        is.close();
        fos.close();

        // create thumbnail
        FileInputStream fis = new FileInputStream(destinationPath);
        Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, this.thumbnailWidth, this.thumbnailHeight, false);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] imageData = baos.toByteArray();

        // write thumbnail to file 
        File destFile2 = new File(this.thumbnailDirectoryPath, destinationName);
        String destinationPath2 = destFile2.getAbsolutePath();
        FileOutputStream fos2 = new FileOutputStream(destFile2);
        fos2.write(imageData, 0, imageData.length);
        fos2.flush();
        fos2.close();
        baos.close();

        // close ZIP
        zipFile.close();

        // delete original cover
        destFile.delete();

        // set relativePathThumbnail
        format.addMetadatum("relativePathThumbnail", destinationName);

    } catch (Exception e) {
        // nop 
    }
}

From source file:it.readbeyond.minstrel.librarian.FormatHandlerEPUB.java

private String getOPFPath(File f) {
    String ret = null;/*from  w w  w  .ja v  a  2 s  .com*/
    try {
        ZipFile zipFile = new ZipFile(f, ZipFile.OPEN_READ);
        ZipEntry containerEntry = zipFile.getEntry(EPUB_CONTAINER_PATH);
        if (containerEntry != null) {
            InputStream is = zipFile.getInputStream(containerEntry);
            parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
            parser.setInput(is, null);
            parser.nextTag();
            ret = parseContainer();
            is.close();
        }
        zipFile.close();
    } catch (Exception e) {
        // nop
    }
    return ret;
}

From source file:net.sf.jabref.importer.ImportCustomizationDialog.java

/**
 *
 * @param frame/*  w  w  w.  j a  v a  2s .c  o  m*/
 */
public ImportCustomizationDialog(final JabRefFrame frame) {
    super(frame, Localization.lang("Manage custom imports"), false);

    ImportTableModel tableModel = new ImportTableModel();
    customImporterTable = new JTable(tableModel);
    TableColumnModel cm = customImporterTable.getColumnModel();
    cm.getColumn(0).setPreferredWidth(COL_0_WIDTH);
    cm.getColumn(1).setPreferredWidth(COL_1_WIDTH);
    cm.getColumn(2).setPreferredWidth(COL_2_WIDTH);
    cm.getColumn(3).setPreferredWidth(COL_3_WIDTH);
    JScrollPane sp = new JScrollPane(customImporterTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    customImporterTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    customImporterTable.setPreferredScrollableViewportSize(getSize());
    if (customImporterTable.getRowCount() > 0) {
        customImporterTable.setRowSelectionInterval(0, 0);
    }

    JButton addFromFolderButton = new JButton(Localization.lang("Add from folder"));
    addFromFolderButton.addActionListener(e -> {
        CustomImporter importer = new CustomImporter();
        importer.setBasePath(FileDialogs.getNewDir(frame,
                new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)), Collections.emptyList(),
                Localization.lang("Select Classpath of New Importer"), JFileChooser.CUSTOM_DIALOG, false));
        String chosenFileStr = null;
        if (importer.getBasePath() != null) {
            chosenFileStr = FileDialogs.getNewFile(frame, importer.getFileFromBasePath(),
                    Collections.singletonList(".class"), Localization.lang("Select new ImportFormat subclass"),
                    JFileChooser.CUSTOM_DIALOG, false);
        }
        if (chosenFileStr != null) {
            try {
                importer.setClassName(pathToClass(importer.getFileFromBasePath(), new File(chosenFileStr)));
                importer.setName(importer.getInstance().getFormatName());
                importer.setCliId(importer.getInstance().getId());
                addOrReplaceImporter(importer);
                customImporterTable.revalidate();
                customImporterTable.repaint();
            } catch (Exception exc) {
                JOptionPane.showMessageDialog(frame,
                        Localization.lang("Could not instantiate %0", chosenFileStr));
            } catch (NoClassDefFoundError exc) {
                JOptionPane.showMessageDialog(frame, Localization.lang(
                        "Could not instantiate %0. Have you chosen the correct package path?", chosenFileStr));
            }

        }
    });
    addFromFolderButton
            .setToolTipText(Localization.lang("Add a (compiled) custom ImportFormat class from a class path.")
                    + "\n" + Localization.lang("The path need not be on the classpath of JabRef."));

    JButton addFromJarButton = new JButton(Localization.lang("Add from jar"));
    addFromJarButton.addActionListener(e -> {
        String basePath = FileDialogs.getNewFile(frame,
                new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)), Arrays.asList(".zip", ".jar"),
                Localization.lang("Select a Zip-archive"), JFileChooser.CUSTOM_DIALOG, false);

        if (basePath != null) {
            try (ZipFile zipFile = new ZipFile(new File(basePath), ZipFile.OPEN_READ)) {
                ZipFileChooser zipFileChooser = new ZipFileChooser(this, zipFile);
                zipFileChooser.setVisible(true);
                customImporterTable.revalidate();
                customImporterTable.repaint(10);
            } catch (IOException exc) {
                LOGGER.info("Could not open Zip-archive.", exc);
                JOptionPane.showMessageDialog(frame, Localization.lang("Could not open %0", basePath) + "\n"
                        + Localization.lang("Have you chosen the correct package path?"));
            } catch (NoClassDefFoundError exc) {
                LOGGER.info("Could not instantiate Zip-archive reader.", exc);
                JOptionPane.showMessageDialog(frame, Localization.lang("Could not instantiate %0", basePath)
                        + "\n" + Localization.lang("Have you chosen the correct package path?"));
            }
        }
    });
    addFromJarButton
            .setToolTipText(Localization.lang("Add a (compiled) custom ImportFormat class from a Zip-archive.")
                    + "\n" + Localization.lang("The Zip-archive need not be on the classpath of JabRef."));

    JButton showDescButton = new JButton(Localization.lang("Show description"));
    showDescButton.addActionListener(e -> {
        int row = customImporterTable.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(frame, Localization.lang("Please select an importer."));
        } else {
            CustomImporter importer = ((ImportTableModel) customImporterTable.getModel()).getImporter(row);
            try {
                ImportFormat importFormat = importer.getInstance();
                JOptionPane.showMessageDialog(frame, importFormat.getDescription());
            } catch (IOException | ClassNotFoundException | InstantiationException
                    | IllegalAccessException exc) {
                LOGGER.warn("Could not instantiate importer " + importer.getName(), exc);
                JOptionPane.showMessageDialog(frame, Localization.lang("Could not instantiate %0 %1",
                        importer.getName() + ":\n", exc.getMessage()));
            }
        }
    });

    JButton removeButton = new JButton(Localization.lang("Remove"));
    removeButton.addActionListener(e -> {
        int row = customImporterTable.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(frame, Localization.lang("Please select an importer."));
        } else {
            customImporterTable.removeRowSelectionInterval(row, row);
            Globals.prefs.customImports
                    .remove(((ImportTableModel) customImporterTable.getModel()).getImporter(row));
            Globals.IMPORT_FORMAT_READER.resetImportFormats();
            customImporterTable.revalidate();
            customImporterTable.repaint();
        }
    });

    Action closeAction = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dispose();
        }
    };

    JButton closeButton = new JButton(Localization.lang("Close"));
    closeButton.addActionListener(closeAction);

    JButton helpButton = new HelpAction(HelpFile.CUSTOM_IMPORTS).getHelpButton();

    // Key bindings:
    JPanel mainPanel = new JPanel();
    ActionMap am = mainPanel.getActionMap();
    InputMap im = mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
    am.put("close", closeAction);
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(sp, BorderLayout.CENTER);
    JPanel buttons = new JPanel();
    ButtonBarBuilder bb = new ButtonBarBuilder(buttons);
    buttons.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    bb.addGlue();
    bb.addButton(addFromFolderButton);
    bb.addButton(addFromJarButton);
    bb.addButton(showDescButton);
    bb.addButton(removeButton);
    bb.addButton(closeButton);
    bb.addUnrelatedGap();
    bb.addButton(helpButton);
    bb.addGlue();

    getContentPane().add(mainPanel, BorderLayout.CENTER);
    getContentPane().add(buttons, BorderLayout.SOUTH);
    this.setSize(getSize());
    pack();
    this.setLocationRelativeTo(frame);
    new FocusRequester(customImporterTable);
}

From source file:JarUtil.java

/**
 * Extracts the given jar-file to the specified directory. The target
 * directory will be cleaned before the jar-file will be extracted.
 * //from   ww w .  j  av  a2 s  .  c om
 * @param jarFile
 *            The jar file which should be unpacked
 * @param targetDir
 *            The directory to which the jar-content should be extracted.
 * @throws FileNotFoundException
 *             when the jarFile does not exist
 * @throws IOException
 *             when a file could not be written or the jar-file could not
 *             read.
 */
public static void unjar(File jarFile, File targetDir) throws FileNotFoundException, IOException {
    // clear target directory:
    if (targetDir.exists()) {
        targetDir.delete();
    }
    // create new target directory:
    targetDir.mkdirs();
    // read jar-file:
    String targetPath = targetDir.getAbsolutePath() + File.separatorChar;
    byte[] buffer = new byte[1024 * 1024];
    JarFile input = new JarFile(jarFile, false, ZipFile.OPEN_READ);
    Enumeration<JarEntry> enumeration = input.entries();
    for (; enumeration.hasMoreElements();) {
        JarEntry entry = enumeration.nextElement();
        if (!entry.isDirectory()) {
            // do not copy anything from the package cache:
            if (entry.getName().indexOf("package cache") == -1) {
                String path = targetPath + entry.getName();
                File file = new File(path);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileOutputStream out = new FileOutputStream(file);
                InputStream in = input.getInputStream(entry);
                int read;
                while ((read = in.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
                in.close();
                out.close();
            }
        }
    }

}

From source file:org.structr.core.module.ModuleService.java

private Module loadResource(String resource) throws IOException {

    // create module
    DefaultModule ret = new DefaultModule(resource);
    Set<String> classes = ret.getClasses();

    if (resource.endsWith(".jar") || resource.endsWith(".war")) {

        ZipFile zipFile = new ZipFile(new File(resource), ZipFile.OPEN_READ);

        // conventions that might be useful here:
        // ignore entries beginning with meta-inf/
        // handle entries beginning with images/ as IMAGE
        // handle entries beginning with pages/ as PAGES
        // handle entries ending with .jar as libraries, to be deployed to WEB-INF/lib
        // handle other entries as potential page and/or entity classes
        // .. to be extended
        // (entries that end with "/" are directories)
        for (Enumeration<? extends ZipEntry> entries = zipFile.entries(); entries.hasMoreElements();) {

            ZipEntry entry = entries.nextElement();
            String entryName = entry.getName();

            if (entryName.endsWith(".class")) {

                String fileEntry = entry.getName().replaceAll("[/]+", ".");

                // add class entry to Module
                classes.add(fileEntry.substring(0, fileEntry.length() - 6));

            }//from w w  w.ja  va 2s  . co  m

        }

        zipFile.close();

    } else if (resource.endsWith(classesDir)) {

        addClassesRecursively(new File(resource), classesDir, classes);

    } else if (resource.endsWith(testClassesDir)) {

        addClassesRecursively(new File(resource), testClassesDir, classes);
    }

    return ret;
}

From source file:JarUtil.java

/**
 * Extracts the given resource from a jar-file to the specified directory.
 * /*from w w  w .ja v  a 2  s  .  c o  m*/
 * @param jarFile
 *            The jar file which should be unpacked
 * @param resource
 *            The name of a resource in the jar
 * @param targetDir
 *            The directory to which the jar-content should be extracted.
 * @throws FileNotFoundException
 *             when the jarFile does not exist
 * @throws IOException
 *             when a file could not be written or the jar-file could not
 *             read.
 */
public static void unjar(File jarFile, String resource, File targetDir)
        throws FileNotFoundException, IOException {
    // clear target directory:
    if (targetDir.exists()) {
        targetDir.delete();
    }
    // create new target directory:
    targetDir.mkdirs();
    // read jar-file:
    String targetPath = targetDir.getAbsolutePath() + File.separatorChar;
    byte[] buffer = new byte[1024 * 1024];
    JarFile input = new JarFile(jarFile, false, ZipFile.OPEN_READ);
    Enumeration<JarEntry> enumeration = input.entries();
    for (; enumeration.hasMoreElements();) {
        JarEntry entry = enumeration.nextElement();
        if (!entry.isDirectory()) {
            // do not copy anything from the package cache:
            if (entry.getName().equals(resource)) {
                String path = targetPath + entry.getName();
                File file = new File(path);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileOutputStream out = new FileOutputStream(file);
                InputStream in = input.getInputStream(entry);
                int read;
                while ((read = in.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
                in.close();
                out.close();
            }
        }
    }
}

From source file:org.openhab.ui.cometvisu.internal.util.ClientInstaller.java

/**
 * Download the latest release and extract it to the configured COMETVISU_WEBFOLDER
 *//*from w w w  .j ava 2  s .  c o  m*/
public void downloadLatestRelease() {
    // request the download URL for the latest CometVisu release from the github API
    Map<String, Object> latestRelease = getLatestRelease();
    List<Map<String, Object>> assets = (ArrayList<Map<String, Object>>) latestRelease.get("assets");

    Map<String, Object> releaseAsset = null;
    for (Object assetObj : assets) {
        Map<String, Object> asset = (Map<String, Object>) assetObj;
        if (((String) asset.get("content_type")).equalsIgnoreCase("application/zip")) {
            releaseAsset = asset;
            break;
        }
    }
    if (releaseAsset == null) {
        logger.error("no zip download file found for release {}", latestRelease.get("name"));
    } else {
        File releaseFile = new File("release.zip");
        try {
            URL url = new URL((String) releaseAsset.get("browser_download_url"));

            FileUtils.copyURLToFile(url, releaseFile);

            ZipFile zip = new ZipFile(releaseFile, ZipFile.OPEN_READ);

            extractFolder("cometvisu/release/", zip, Config.COMETVISU_WEBFOLDER);
        } catch (IOException e) {
            logger.error("error opening release zip file {}", e.getMessage(), e);
        } finally {
            if (releaseFile.exists()) {
                releaseFile.delete();
            }
        }
    }
}

From source file:JarUtil.java

/**
 * Reads the package-names from the given jar-file.
 * /*from w ww  . ja v  a2s. co  m*/
 * @param jarFile
 *            the jar file
 * @return an array with all found package-names
 * @throws IOException
 *             when the jar-file could not be read
 */
public static String[] getPackageNames(File jarFile) throws IOException {
    HashMap<String, String> packageNames = new HashMap<String, String>();
    JarFile input = new JarFile(jarFile, false, ZipFile.OPEN_READ);
    Enumeration<JarEntry> enumeration = input.entries();
    for (; enumeration.hasMoreElements();) {
        JarEntry entry = enumeration.nextElement();
        String name = entry.getName();
        if (name.endsWith(".class")) {
            int endPos = name.lastIndexOf('/');
            boolean isWindows = false;
            if (endPos == -1) {
                endPos = name.lastIndexOf('\\');
                isWindows = true;
            }
            name = name.substring(0, endPos);
            name = name.replace('/', '.');
            if (isWindows) {
                name = name.replace('\\', '.');
            }
            packageNames.put(name, name);
        }
    }
    return (String[]) packageNames.values().toArray(new String[packageNames.size()]);
}

From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileUtilities.java

public void decompressZip(File inputZipPath, File zipPath) {
    int BUFFER = 2048;
    List<File> zipFiles = new ArrayList<File>();

    try {/*  w  w  w . j  a  va2  s .  c  om*/
        zipPath.mkdir();
    } catch (SecurityException e) {
        jlog.fatal("Security exception when creating " + zipPath.getName());

    }
    ZipFile zipFile = null;
    boolean isZip = true;

    // Open Zip file for reading (should be in temppath)
    try {
        zipFile = new ZipFile(inputZipPath, ZipFile.OPEN_READ);
    } catch (IOException e) {
        jlog.fatal("IO exception in " + inputZipPath.getName());
    }

    // Create an enumeration of the entries in the zip file
    Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
    if (isZip) {
        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // Get a zip file entry
            ZipEntry entry = zipFileEntries.nextElement();

            String currentEntry = entry.getName();
            File destFile = null;

            // destFile should be pointing to temppath\%date%\
            try {
                destFile = new File(zipPath.getAbsolutePath(), currentEntry);
                destFile = new File(zipPath.getAbsolutePath(), destFile.getName());
            } catch (NullPointerException e) {
                jlog.fatal("File not found" + destFile.getName());
            }

            // If the entry is a .zip add it to the list so that it can be extracted
            if (currentEntry.endsWith(".zip")) {
                zipFiles.add(destFile);
            }

            try {
                // Extract file if not a directory
                if (!entry.isDirectory()) {
                    // Stream the zip entry
                    BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));

                    int currentByte;
                    // establish buffer for writing file
                    byte data[] = new byte[BUFFER];
                    FileOutputStream fos = null;

                    // Write the current file to disk
                    try {
                        fos = new FileOutputStream(destFile);
                    }

                    catch (FileNotFoundException e) {
                        jlog.fatal("File not found " + destFile.getName());
                    }

                    catch (SecurityException e) {
                        jlog.fatal("Access denied to " + destFile.getName());
                    }

                    BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

                    // read and write until last byte is encountered
                    while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, currentByte);
                    }
                    dest.flush();
                    dest.close();
                    is.close();

                }
            }

            catch (IOException ioe) {
                jlog.fatal("IO exception in  " + zipFile.getName());
            }
        }
        try {
            zipFile.close();
        } catch (IOException e) {
            jlog.fatal("IO exception when closing  " + zipFile.getName());
        }
    }

    // Recursively decompress the list of zip files
    for (File f : zipFiles) {
        decompressZip(f, zipPath);
    }

    return;
}

From source file:de.elomagic.maven.http.HTTPMojo.java

/**
 * @todo Must may be refactored. Only a prototype
 * @param file//from   w  ww.j a va2s . co  m
 * @param destDirectory
 * @throws MojoExecutionException
 */
private void unzipToFile(final File file, final File destDirectory) throws Exception {
    getLog().info("Extracting downloaded file to folder \"" + destDirectory + "\".");

    int filesCount = 0;

    // create the destination directory structure (if needed)
    destDirectory.mkdirs();

    // open archive for reading
    try (ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ)) {
        // For every zip archive entry do
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = zipFileEntries.nextElement();
            getLog().debug("Extracting entry: " + entry);

            //create destination file
            // TODO Check entry path on path injections
            File destFile = new File(destDirectory, entry.getName());

            //create parent directories if needed
            File parentDestFile = destFile.getParentFile();
            parentDestFile.mkdirs();

            if (!entry.isDirectory()) {
                BufferedInputStream bufIS = new BufferedInputStream(zipFile.getInputStream(entry));

                // write the current file to disk
                Files.copy(bufIS, destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                filesCount++;
            }
        }
    }

    getLog().info(filesCount + " files extracted.");
}