Example usage for java.util.zip ZipEntry ZipEntry

List of usage examples for java.util.zip ZipEntry ZipEntry

Introduction

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

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:de.pksoftware.springstrap.sapi.util.WebappZipper.java

/**
  * Zip it//from   w  w w. j ava2  s.  c o  m
  * @param zipFile output ZIP file location
  */
public void addResource(String resourcePath, boolean fromContext) {
    byte[] buffer = new byte[1024];

    try {
        logger.info("Adding resource: {}", resourcePath);

        PathMatchingResourcePatternResolver resolver;

        if (fromContext) {
            resolver = new ServletContextResourcePatternResolver(servletContext);
        } else {
            resolver = new PathMatchingResourcePatternResolver();
        }

        // Ant-style path matching
        Resource[] resources = resolver.getResources(resourcePath);

        for (Resource resource : resources) {
            String fileAbsolute = resource.getURL().toString();
            String fileRelative = null;
            boolean addFile = false;

            if (fromContext) {
                //File comes from webapp folder
                fileRelative = "www" + servletContext.getContextPath()
                        + ((ServletContextResource) resource).getPath();
                if (!fileRelative.endsWith("/")) {
                    addFile = true;
                }

            } else {
                //Files comes from webjar
                int jarSeparatorIndex = fileAbsolute.indexOf("!/");

                if (jarSeparatorIndex != -1) {
                    String relativeFileName = fileAbsolute.substring(jarSeparatorIndex);

                    Pattern pathPattern = Pattern.compile("\\!\\/webjar(\\/[a-z0-9_]+)+\\/www\\/");
                    Matcher pathMatcher = pathPattern.matcher(relativeFileName);
                    if (pathMatcher.find()) {
                        fileRelative = pathMatcher.replaceFirst("www" + servletContext.getContextPath() + "/");
                        addFile = true;
                    }
                }
            }

            if (addFile && null != fileRelative) {
                logger.debug("Adding File: {} => {}", fileAbsolute, fileRelative);

                if (null != files.get(fileRelative)) {
                    continue;
                }

                if (fileRelative.startsWith("temp")) {
                    logger.error(fileAbsolute);
                }

                files.put(fileRelative, resource);

                ZipEntry ze = new ZipEntry(fileRelative);
                zos.putNextEntry(ze);

                InputStream in = null;
                try {
                    in = resource.getInputStream();

                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                } catch (FileNotFoundException fio) {
                    logger.error(fio.getMessage());
                } finally {
                    if (null != in) {
                        in.close();
                    }
                }
            }
        }

        zos.closeEntry();
        //remember close it

        logger.info("Done");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:org.pdfgal.pdfgalweb.utils.impl.ZipUtilsImpl.java

/**
 * Adds a new file to the {@link ZipOutputStream}.
 * /*  w w  w  . j a  v a  2  s  .c  om*/
 * @param fileName
 * @param zos
 * @param originalFileName
 * @throws FileNotFoundException
 * @throws IOException
 */
private void addToZipFile(final String fileName, final ZipOutputStream zos, final String originalFileName)
        throws IOException {

    // File is opened.
    final File file = new File(fileName);

    // File is renamed.
    final String newName = fileName.substring(fileName.indexOf(originalFileName), fileName.length());
    final File renamedFile = new File(newName);
    file.renameTo(renamedFile);

    // File is included into ZIP.
    final FileInputStream fis = new FileInputStream(renamedFile);
    final ZipEntry zipEntry = new ZipEntry(newName);
    zos.putNextEntry(zipEntry);

    final byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zos.write(bytes, 0, length);
    }

    // Closing elements.
    zos.closeEntry();
    fis.close();

    // File is deleted
    this.fileUtils.delete(newName);
}

From source file:com.wolvereness.overmapped.asm.ByteClass.java

public Pair<ZipEntry, byte[]> call(final Map<Signature, Signature> signatures,
        final Map<String, String> classMaps, final Map<String, ByteClass> classes,
        final Map<Signature, Integer> flags, final boolean correctEnums) throws Exception {
    final ClassWriter writer = new ClassWriter(0);
    reader.accept(new FlagSetter(new RemappingClassAdapter(correctEnums ? new EnumCorrection(writer) : writer,
            new SignatureRemapper(classMaps, signatures, classes)), flags), ClassReader.EXPAND_FRAMES);

    return new ImmutablePair<ZipEntry, byte[]>(new ZipEntry(classMaps.get(token) + FILE_POSTFIX),
            writer.toByteArray());//from  w ww  . j a va 2s .  c o  m
}

From source file:com.microsoft.tfs.client.common.ui.framework.diagnostics.export.ExportRunnable.java

private void processDataProviders(final DataProviderCollection exportableCollection,
        final ZipOutputStream zipout, final IProgressMonitor monitor) throws IOException {
    final ZipEntry entry = new ZipEntry(DATA_FILENAME);
    zipout.putNextEntry(entry);/*from ww w.  j ava2  s  . c  om*/
    final PrintWriter pw = new PrintWriter(zipout);

    final DataCategory[] categories = exportableCollection.getSortedCategories();

    for (int i = 0; i < categories.length; i++) {
        final DataProviderWrapper[] providersForCurrentCategory = exportableCollection
                .getSortedProvidersForCategory(categories[i]);

        for (int j = 0; j < providersForCurrentCategory.length; j++) {
            if (monitor.isCanceled()) {
                return;
            }

            /*
             * Do not use localized data - this is for consumption by our
             * support staff
             */
            final String data = (String) Adapters.get(providersForCurrentCategory[j].getDataNOLOC(),
                    String.class, false);
            if (data != null) {
                final String messageFormat =
                        //@formatter:off
                        Messages.getString("ExportRunnable.CategoryOutputFormat", //$NON-NLS-1$
                                DiagnosticLocale.SUPPORT_LOCALE);
                //@formatter:on
                final String message = MessageFormat.format(messageFormat, categories[i].getLabelNOLOC(),
                        providersForCurrentCategory[j].getDataProviderInfo().getLabelNOLOC());

                pw.println(message);
                pw.println();
                pw.println(data);
                pw.println();
            }

            monitor.worked(1);
        }
    }

    pw.flush();
}

From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java

@FXML
public void initialize() {
    this.rootItem = new TreeItem<>(new TreeNode("[root]"));
    this.root.setRoot(this.rootItem);
    this.root.setCellFactory(new TreeCellFactory<>(node -> {
        if (node.getParent() == null) {
            ContextMenu export = new ContextMenu();

            MenuItem exportItem = new MenuItem("Export");

            export.setOnAction(e -> {
                File file = messageHandler.chooseFile().withInitialDirectory(new File("."))
                        .withTitle(Message.GENERIC_CHOOSE_EXPORT_LOCATION_JAR.format())
                        .withExtensionFilter(new FileFilter(Message.FILETYPE_JAVA_ARCHIVE.format(), "*.jar"),
                                true)//ww w  . j  a  v a2 s . c o  m
                        .promptSave();

                OpenedFile openedFile = (OpenedFile) node.getMetadata().get(OpenedFile.OPENED_FILE);

                Map<String, byte[]> clone = new HashMap<>(openedFile.getContents());

                backgroundTaskHelper.submit(
                        new BackgroundTask(Message.TASK_SAVING_FILE.format(node.getDisplayName()), true, () -> {
                            try {
                                if (!file.exists()) {
                                    if (!file.createNewFile()) {
                                        throw new IOException("Could not create export file");
                                    }
                                }

                                try (ZipOutputStream zipOutputStream = new ZipOutputStream(
                                        new FileOutputStream(file))) {
                                    for (Map.Entry<String, byte[]> ent : clone.entrySet()) {
                                        ZipEntry zipEntry = new ZipEntry(ent.getKey());
                                        zipOutputStream.putNextEntry(zipEntry);
                                        zipOutputStream.write(ent.getValue());
                                        zipOutputStream.closeEntry();
                                    }
                                }

                                messageHandler.handleMessage(Message.GENERIC_EXPORTED.format());
                            } catch (IOException ex) {
                                messageHandler.handleException(Message.ERROR_IOEXCEPTION_OCCURRED.format(), ex);
                            }
                        }));
            });

            export.getItems().add(exportItem);
            return export;
        }
        return null;
    }));

    root.addEventHandler(KeyEvent.KEY_RELEASED, event -> {
        if (event.getCode() == KeyCode.ENTER) {
            TreeItem<TreeNode> selected = this.root.getSelectionModel().getSelectedItem();
            if (selected != null) {
                if (selected.getChildren().size() != 0) {
                    selected.setExpanded(!selected.isExpanded());
                } else {
                    getParentController().getAllFilesViewerController().handleClick(selected.getValue());
                }
            }
        }
    });

    Tooltip tooltip = new Tooltip();
    StringBuilder search = new StringBuilder();

    List<TreeItem<TreeNode>> searchContext = new ArrayList<>();
    AtomicInteger searchIndex = new AtomicInteger();

    root.focusedProperty().addListener((observable, oldValue, newValue) -> {
        if (!newValue) {
            tooltip.hide();
            search.setLength(0);
        }
    });

    root.boundsInLocalProperty().addListener((observable, oldValue, newValue) -> {
        Bounds bounds = root.localToScreen(newValue);
        tooltip.setAnchorX(bounds.getMinX());
        tooltip.setAnchorY(bounds.getMinY());
    });

    root.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
        if (tooltip.isShowing() && event.getCode() == KeyCode.UP) {
            if (searchIndex.decrementAndGet() < 0) {
                searchIndex.set(searchContext.size() - 1);
            }
        } else if (tooltip.isShowing() && event.getCode() == KeyCode.DOWN) {
            if (searchIndex.incrementAndGet() >= searchContext.size()) {
                searchIndex.set(0);
            }
        } else {
            return;
        }
        event.consume();

        root.scrollTo(root.getRow(searchContext.get(searchIndex.get())));
        root.getSelectionModel().select(searchContext.get(searchIndex.get()));
    });

    root.addEventHandler(KeyEvent.KEY_TYPED, event -> {
        if (event.getCharacter().charAt(0) == '\b') {
            if (search.length() > 0) {
                search.setLength(search.length() - 1);
            }
        } else if (event.getCharacter().charAt(0) == '\u001B') { //esc
            tooltip.hide();
            search.setLength(0);
            return;
        } else if (search.length() > 0
                || (search.length() == 0 && StringUtils.isAlphanumeric(event.getCharacter()))) {
            search.append(event.getCharacter());
            if (!tooltip.isShowing()) {
                tooltip.show(root.getScene().getWindow());
            }
        }

        if (!tooltip.isShowing())
            return;

        String str = search.toString();
        tooltip.setText("Search for: " + str);

        searchContext.clear();

        ArrayDeque<TreeItem<TreeNode>> deque = new ArrayDeque<>();
        deque.addAll(rootItem.getChildren());

        while (!deque.isEmpty()) {
            TreeItem<TreeNode> item = deque.poll();
            if (item.getValue().getDisplayName().contains(str)) {
                searchContext.add(item);
            }
            if (item.isExpanded() && item.getChildren().size() > 0)
                deque.addAll(item.getChildren());
        }

        searchIndex.set(0);
        if (searchContext.size() > 0) {
            root.scrollTo(root.getRow(searchContext.get(0)));
            root.getSelectionModel().select(searchContext.get(0));
        }
    });

    openedFileController.loadedFiles().addListener((MapChangeListener<String, OpenedFile>) change -> {
        if (change.getValueAdded() != null) {
            updateTree(change.getValueAdded());
        }
        if (change.getValueRemoved() != null) {
            this.rootItem.getChildren()
                    .removeIf(ti -> ti.getValue().equals(change.getValueRemoved().getRoot()));
        }
    });
}

From source file:com.cenrise.test.azkaban.Utils.java

private static void zipFile(final String path, final File input, final ZipOutputStream zOut)
        throws IOException {
    if (input.isDirectory()) {
        final File[] files = input.listFiles();
        if (files != null) {
            for (final File f : files) {
                final String childPath = path + input.getName() + (f.isDirectory() ? "/" : "");
                zipFile(childPath, f, zOut);
            }/*from  w  ww .ja  v a 2s .  co  m*/
        }
    } else {
        final String childPath = path + (path.length() > 0 ? "/" : "") + input.getName();
        final ZipEntry entry = new ZipEntry(childPath);
        zOut.putNextEntry(entry);
        final InputStream fileInputStream = new BufferedInputStream(new FileInputStream(input));
        try {
            IOUtils.copy(fileInputStream, zOut);
        } finally {
            fileInputStream.close();
        }
    }
}

From source file:net.sf.jabref.exporter.OpenDocumentSpreadsheetCreator.java

private static void addResourceFile(String name, String resource, ZipOutputStream out) throws IOException {
    ZipEntry zipEntry = new ZipEntry(name);
    out.putNextEntry(zipEntry);/*from   www. ja  v a  2 s.c  o  m*/
    OpenDocumentSpreadsheetCreator.addFromResource(resource, out);
    out.closeEntry();
}

From source file:com.joliciel.talismane.parser.ParsingConstrainerImpl.java

@Override
public void onCompleteParse() {
    if (this.transitionSystem == null)
        this.transitionSystem = TalismaneSession.getTransitionSystem();

    if (this.file != null) {
        try {/*from w  w  w .  j  av  a  2  s .  com*/
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file, false));
            zos.putNextEntry(new ZipEntry("ParsingConstrainer.obj"));
            ObjectOutputStream oos = new ObjectOutputStream(zos);
            try {
                oos.writeObject(this);
            } finally {
                oos.flush();
            }
            zos.flush();
            zos.close();
        } catch (IOException ioe) {
            LogUtils.logError(LOG, ioe);
            throw new RuntimeException(ioe);
        }
    }
}

From source file:com.sqli.liferay.imex.util.xml.ZipUtils.java

private void zipEntries(ZipOutputStream out, File file, File inputDir) throws IOException {
    String name;//from  w w  w. ja v a 2  s.c o  m
    if (file.equals(inputDir)) {
        name = "";
    } else {
        name = file.getPath().substring(inputDir.getPath().length() + 1);
    }
    if (File.separatorChar == '\\') {
        name = name.replace("\\", "/");
    }

    log.debug("Adding: " + name);

    if (file.isDirectory()) {
        for (File child : file.listFiles()) {
            zipEntries(out, child, inputDir);
        }
    } else {
        ZipEntry entry = new ZipEntry(name);
        out.putNextEntry(entry);
        IOUtils.copy(FileUtils.openInputStream(file), out);
    }
}

From source file:fll.web.GatherBugReport.java

/**
 * Add the web application and tomcat logs to the zipfile.
 *///  w  w w  .j a v  a2 s  .  c  om
private static void addLogFiles(final ZipOutputStream zipOut, final ServletContext application)
        throws IOException {

    // get logs from the webapp
    final File fllAppDir = new File(application.getRealPath("/"));
    final File[] webLogs = fllAppDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String name) {
            return name.startsWith("fllweb.log");
        }
    });
    if (null != webLogs) {
        for (final File f : webLogs) {
            if (f.isFile()) {
                FileInputStream fis = null;
                try {
                    zipOut.putNextEntry(new ZipEntry(f.getName()));
                    fis = new FileInputStream(f);
                    IOUtils.copy(fis, zipOut);
                    fis.close();
                } finally {
                    IOUtils.closeQuietly(fis);
                }
            }
        }
    }

    // get tomcat logs
    final File webappsDir = fllAppDir.getParentFile();
    LOGGER.trace("Webapps dir: " + webappsDir.getAbsolutePath());
    final File tomcatDir = webappsDir.getParentFile();
    LOGGER.trace("Tomcat dir: " + tomcatDir.getAbsolutePath());
    final File tomcatLogDir = new File(tomcatDir, "logs");
    LOGGER.trace("tomcat log dir: " + tomcatLogDir.getAbsolutePath());
    final File[] tomcatLogs = tomcatLogDir.listFiles();
    if (null != tomcatLogs) {
        for (final File f : tomcatLogs) {
            if (f.isFile()) {
                FileInputStream fis = null;
                try {
                    zipOut.putNextEntry(new ZipEntry(f.getName()));
                    fis = new FileInputStream(f);
                    IOUtils.copy(fis, zipOut);
                    fis.close();
                } finally {
                    IOUtils.closeQuietly(fis);
                }
            }
        }
    }

}