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:com.replaymod.replaystudio.io.ReplayOutputStream.java

/**
 * Creates a new replay output stream which will write its packets and the specified meta data
 * in a zip output stream according to the MCPR format.
 *
 * @param studio The studio/* w  w  w.j  a v a2  s. c  om*/
 * @param out The actual output stream
 * @param metaData The meta data written to the output
 * @throws IOException If an exception occurred while writing the first entry to the zip output stream
 */
public ReplayOutputStream(Studio studio, OutputStream out, ReplayMetaData metaData) throws IOException {
    this.session = new StudioSession(studio, false);
    this.codec = new StudioCodec(session);
    if (metaData == null) {
        metaData = new ReplayMetaData();
        metaData.setSingleplayer(false);
        metaData.setServerName(studio.getName() + " v" + studio.getVersion());
        metaData.setDate(System.currentTimeMillis());
    }
    metaData.setFileFormat("MCPR");
    metaData.setFileFormatVersion(1);
    metaData.setGenerator("ReplayStudio v" + studio.getVersion());
    this.metaData = metaData;

    this.out = zipOut = new ZipOutputStream(out);

    zipOut.putNextEntry(new ZipEntry("recording.tmcpr"));

}

From source file:gov.nih.nci.caintegrator.common.Cai2Util.java

private static void addFile(File curFile, ZipOutputStream out, int index) throws IOException {
    byte[] tmpBuf = new byte[BUFFER_SIZE];
    FileInputStream in = new FileInputStream(curFile);
    String relativePathName = curFile.getPath().substring(index);
    out.putNextEntry(new ZipEntry(relativePathName));
    int len;/*ww w  . ja  v a  2  s  .  c  o m*/
    while ((len = in.read(tmpBuf)) > 0) {
        out.write(tmpBuf, 0, len);
    }
    // Complete the entry
    out.closeEntry();
    in.close();
}

From source file:edu.harvard.med.screensaver.service.cherrypicks.CherryPickRequestPlateMapFilesBuilder.java

@SuppressWarnings("unchecked")
private InputStream doBuildZip(CherryPickRequest cherryPickRequest, Set<CherryPickAssayPlate> forPlates)
        throws IOException {
    ByteArrayOutputStream zipOutRaw = new ByteArrayOutputStream();
    ZipOutputStream zipOut = new ZipOutputStream(zipOutRaw);
    MultiMap/*<String,SortedSet<CherryPick>>*/ files2CherryPicks = buildCherryPickFiles(cherryPickRequest,
            forPlates);/* ww  w .  j av a  2  s .  c  o m*/
    buildReadme(cherryPickRequest, zipOut);
    buildDistinctPlateCopyFile(cherryPickRequest, forPlates, zipOut);
    PrintWriter out = new CSVPrintWriter(new OutputStreamWriter(zipOut), NEWLINE);
    for (Iterator iter = files2CherryPicks.keySet().iterator(); iter.hasNext();) {
        String fileName = (String) iter.next();
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOut.putNextEntry(zipEntry);
        writeHeadersRow(out);
        for (LabCherryPick cherryPick : (SortedSet<LabCherryPick>) files2CherryPicks.get(fileName)) {
            writeCherryPickRow(out, cherryPick);
        }
        out.flush();
    }
    out.close();
    return new ByteArrayInputStream(zipOutRaw.toByteArray());
}

From source file:S3DataManager.java

public static void zipSource(final String directory, final ZipOutputStream out, final String prefixToTrim)
        throws Exception {
    if (!Paths.get(directory).startsWith(Paths.get(prefixToTrim))) {
        throw new Exception(zipSourceError + "prefixToTrim: " + prefixToTrim + ", directory: " + directory);
    }//from  ww w. ja v  a  2s.co  m

    File dir = new File(directory);
    String[] dirFiles = dir.list();
    if (dirFiles == null) {
        throw new Exception("Invalid directory path provided: " + directory);
    }
    byte[] buffer = new byte[1024];
    int bytesRead;

    for (int i = 0; i < dirFiles.length; i++) {
        File f = new File(dir, dirFiles[i]);
        if (f.isDirectory()) {
            if (f.getName().equals(".git") == false) {
                zipSource(f.getPath() + File.separator, out, prefixToTrim);
            }
        } else {
            FileInputStream inputStream = new FileInputStream(f);
            try {
                String path = trimPrefix(f.getPath(), prefixToTrim);

                ZipEntry entry = new ZipEntry(path);
                out.putNextEntry(entry);
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            } finally {
                inputStream.close();
            }
        }
    }
}

From source file:com.heliosdecompiler.helios.tasks.DecompileAndSaveTask.java

@Override
public void run() {
    File file = FileChooserUtil.chooseSaveLocation(Settings.LAST_DIRECTORY.get().asString(),
            Collections.singletonList("zip"));
    if (file == null)
        return;/*from   w  ww  . ja v  a2 s. c o  m*/
    if (file.exists()) {
        boolean delete = SWTUtil.promptForYesNo(Constants.REPO_NAME + " - Overwrite existing file",
                "The selected file already exists. Overwrite?");
        if (!delete) {
            return;
        }
    }

    AtomicReference<Transformer> transformer = new AtomicReference<>();

    Display display = Display.getDefault();
    display.asyncExec(() -> {
        Shell shell = new Shell(Display.getDefault());
        FillLayout layout = new FillLayout();
        layout.type = SWT.VERTICAL;
        shell.setLayout(layout);
        Transformer.getAllTransformers(t -> {
            return t instanceof Decompiler || t instanceof Disassembler;
        }).forEach(t -> {
            Button button = new Button(shell, SWT.RADIO);
            button.setText(t.getName());
            button.addSelectionListener(new SelectionAdapter() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    transformer.set(t);
                }
            });
        });
        Button ok = new Button(shell, SWT.NONE);
        ok.setText("OK");
        ok.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.close();
                shell.dispose();
                synchronized (transformer) {
                    transformer.notify();
                }
            }
        });
        shell.pack();
        SWTUtil.center(shell);
        shell.open();
    });

    synchronized (transformer) {
        try {
            transformer.wait();
        } catch (InterruptedException e) {
            ExceptionHandler.handle(e);
        }
    }

    FileOutputStream fileOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        file.createNewFile();
        fileOutputStream = new FileOutputStream(file);
        zipOutputStream = new ZipOutputStream(fileOutputStream);
        Set<String> written = new HashSet<>();
        for (Pair<String, String> pair : data) {
            LoadedFile loadedFile = Helios.getLoadedFile(pair.getValue0());
            if (loadedFile != null) {
                String innerName = pair.getValue1();
                byte[] bytes = loadedFile.getAllData().get(innerName);
                if (bytes != null) {
                    if (loadedFile.getClassNode(pair.getValue1()) != null) {
                        StringBuilder buffer = new StringBuilder();
                        transformer.get().transform(loadedFile.getClassNode(pair.getValue1()), bytes, buffer);
                        String name = innerName.substring(0, innerName.length() - 6) + ".java";
                        if (written.add(name)) {
                            zipOutputStream.putNextEntry(new ZipEntry(name));
                            zipOutputStream.write(buffer.toString().getBytes(StandardCharsets.UTF_8));
                            zipOutputStream.closeEntry();
                        } else {
                            SWTUtil.showMessage("Duplicate entry occured: " + name);
                        }
                    } else {
                        if (written.add(pair.getValue1())) {
                            zipOutputStream.putNextEntry(new ZipEntry(pair.getValue1()));
                            zipOutputStream.write(loadedFile.getAllData().get(pair.getValue1()));
                            zipOutputStream.closeEntry();
                        } else {
                            SWTUtil.showMessage("Duplicate entry occured: " + pair.getValue1());
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }
}

From source file:de.fu_berlin.inf.dpp.core.zip.FileZipper.java

private static void internalZipFiles(List<FileWrapper> files, File archive, boolean compress,
        boolean includeDirectories, long totalSize, ZipListener listener)
        throws IOException, OperationCanceledException {

    byte[] buffer = new byte[BUFFER_SIZE];

    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(archive), BUFFER_SIZE);

    ZipOutputStream zipStream = new ZipOutputStream(outputStream);

    zipStream.setLevel(compress ? Deflater.DEFAULT_COMPRESSION : Deflater.NO_COMPRESSION);

    boolean cleanup = true;
    boolean isCanceled = false;

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();//from w  w w  .j  a  v  a  2 s .  c  om

    long totalRead = 0L;

    try {
        for (FileWrapper file : files) {
            String entryName = includeDirectories ? file.getPath() : file.getName();

            if (listener != null) {
                isCanceled = listener.update(file.getPath());
            }

            log.trace("compressing file: " + entryName);

            zipStream.putNextEntry(new ZipEntry(entryName));

            InputStream in = null;

            try {
                int read = 0;
                in = file.getInputStream();
                while (-1 != (read = in.read(buffer))) {

                    if (isCanceled) {
                        throw new OperationCanceledException(
                                "compressing of file '" + entryName + "' was canceled");
                    }

                    zipStream.write(buffer, 0, read);

                    totalRead += read;

                    if (listener != null) {
                        listener.update(totalRead, totalSize);
                    }

                }
            } finally {
                IOUtils.closeQuietly(in);
            }
            zipStream.closeEntry();
        }
        cleanup = false;
    } finally {
        IOUtils.closeQuietly(zipStream);
        if (cleanup && archive != null && archive.exists() && !archive.delete()) {
            log.warn("could not delete archive file: " + archive);
        }
    }

    stopWatch.stop();

    log.debug(String.format("created archive %s I/O: [%s]", archive.getAbsolutePath(),
            CoreUtils.throughput(archive.length(), stopWatch.getTime())));

}

From source file:com.music.scheduled.BackupJob.java

private void zipBackup(String baseFileName) throws IOException {
    FileOutputStream fos = new FileOutputStream(baseFileName + ".zip");
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));

    File entryFile = new File(baseFileName + ".sql");
    FileInputStream fi = new FileInputStream(entryFile);
    InputStream origin = new BufferedInputStream(fi, ZIP_BUFFER);
    ZipEntry entry = new ZipEntry("data.sql");
    zos.putNextEntry(entry);/*from w w  w  . j a va2 s.c  om*/
    int count;
    byte[] data = new byte[ZIP_BUFFER];
    while ((count = origin.read(data, 0, ZIP_BUFFER)) != -1) {
        zos.write(data, 0, count);
    }
    origin.close();
    zos.close();

    entryFile.delete();
}

From source file:com.replaymod.sponge.recording.AbstractRecorder.java

@Override
public void endRecording(OutputStream out, ReplayMetaData metaData) throws IllegalStateException, IOException {
    if (metaData == null) {
        Preconditions.checkState(rawOutputs.remove(out),
                "Specified output is unknown or meta data is missing.");
        out.flush();//from  w w w.  j a  v  a2  s . c o m
        out.close();
    } else {
        ZipOutputStream zipOut = outputs.remove(out);
        if (zipOut == null) {
            throw new IllegalStateException("Specified output is unknown or contains raw data.");
        }

        zipOut.closeEntry();

        zipOut.putNextEntry(new ZipEntry("metaData.json"));
        zipOut.write(toJson(metaData).getBytes());
        zipOut.closeEntry();

        zipOut.flush();
        zipOut.close();
    }
}

From source file:com.marklogic.contentpump.OutputArchive.java

public long write(String outputPath, byte[] bytes) throws IOException {

    if (null == outputPath) {
        throw new NullPointerException("null path");
    }/* w  w w.  jav a 2  s  .  com*/
    if (null == bytes) {
        throw new NullPointerException("null content bytes");
    }

    long total = bytes.length;
    ZipEntry entry = new ZipEntry(outputPath);

    if (outputStream == null) {
        newOutputStream();
    }

    if (currentFileBytes > 0 && currentFileBytes + total > Integer.MAX_VALUE) {
        if (currentEntries % 2 == 0) {
            //the file overflowed is metadata, create new zip
            newOutputStream();
        } else {
            //the file overflowed is doc, keep it in current zip
            LOG.warn("too many bytes in current package:" + currPath);
        }
    }

    try {
        outputStream.putNextEntry(entry);
        outputStream.write(bytes);
        outputStream.closeEntry();
    } catch (ZipException e) {
        LOG.warn("Exception caught: " + e.getMessage() + entry.getName());
        return 0;
    }

    currentFileBytes += total;
    currentEntries++;

    return total;

}

From source file:be.neutrinet.ispng.vpn.api.VPNClientConfig.java

protected Representation finalizeZip(List<String> config, ZipOutputStream zip, ByteArrayOutputStream baos)
        throws Exception {
    String file = "";
    for (String s : config) {
        file += s + '\n';
    }/*from  ww  w. java  2 s.c  o m*/

    if (caCert == null) {
        caCert = IOUtils.toByteArray(new FileInputStream(VPN.cfg.getProperty("ca.crt")));
    }

    ZipEntry configFile = new ZipEntry("neutrinet.ovpn");
    configFile.setCreationTime(FileTime.from(Instant.now()));
    zip.putNextEntry(configFile);
    zip.write(file.getBytes());
    zip.putNextEntry(new ZipEntry("ca.crt"));
    zip.write(caCert);

    zip.close();

    ByteArrayRepresentation rep = new ByteArrayRepresentation(baos.toByteArray());
    rep.setMediaType(MediaType.APPLICATION_ZIP);
    rep.setSize(baos.size());
    rep.setCharacterSet(CharacterSet.UTF_8);
    rep.setDisposition(new Disposition(Disposition.TYPE_ATTACHMENT));
    return rep;
}