Example usage for java.util.zip ZipOutputStream closeEntry

List of usage examples for java.util.zip ZipOutputStream closeEntry

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

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

@Override
public void run() {
    File file = FileChooserUtil.chooseSaveLocation(Settings.LAST_DIRECTORY.get().asString(),
            Arrays.asList("zip"));
    if (file == null)
        return;//from w  w  w  . ja  v a  2  s .c om
    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.syncExec(() -> {
        Shell shell = new Shell(Display.getDefault());
        Combo combo = new Combo(shell, SWT.DROP_DOWN | SWT.BORDER);
        List<Transformer> transformers = new ArrayList<>();
        transformers.addAll(Decompiler.getAllDecompilers());
        transformers.addAll(Disassembler.getAllDisassemblers());
        for (Transformer t : transformers) {
            combo.add(t.getName());
        }
        shell.pack();
        shell.open();
        System.out.println(Arrays.toString(combo.getItems()));
    });

    // TODO: Ask for list of decompilers

    FileOutputStream fileOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        fileOutputStream = new FileOutputStream(file);
        zipOutputStream = new ZipOutputStream(fileOutputStream);
        for (Pair<String, String> pair : data) {
            StringBuilder buffer = new StringBuilder();
            LoadedFile loadedFile = Helios.getLoadedFile(pair.getValue0());
            if (loadedFile != null) {
                String innerName = pair.getValue1();
                byte[] bytes = loadedFile.getData().get(innerName);
                if (bytes != null) {
                    Decompiler.getById("cfr-decompiler").decompile(null, bytes, buffer);
                    zipOutputStream.putNextEntry(
                            new ZipEntry(innerName.substring(0, innerName.length() - 6) + ".java"));
                    zipOutputStream.write(buffer.toString().getBytes(StandardCharsets.UTF_8));
                    zipOutputStream.closeEntry();
                }
            }
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }
}

From source file:fll.subjective.SubjectiveFrame.java

/**
 * Save out to the same file that things were read in.
 * /*from w ww  . ja va2 s.co  m*/
 * @throws IOException if an error occurs writing to the file
 */
public void save() throws IOException {
    if (validateData()) {

        final ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(_file));
        final Writer writer = new OutputStreamWriter(zipOut, Utilities.DEFAULT_CHARSET);

        zipOut.putNextEntry(new ZipEntry("challenge.xml"));
        XMLUtils.writeXML(_challengeDocument, writer, Utilities.DEFAULT_CHARSET.name());
        zipOut.closeEntry();
        zipOut.putNextEntry(new ZipEntry("score.xml"));
        XMLUtils.writeXML(_scoreDocument, writer, Utilities.DEFAULT_CHARSET.name());
        zipOut.closeEntry();

        zipOut.close();
    }
}

From source file:cn.edu.sdust.silence.itransfer.filemanage.FileManager.java

private void zip_folder(File file, ZipOutputStream zout) throws IOException {
    byte[] data = new byte[BUFFER];
    int read;/*from  w w w .  j  av  a2  s .  c om*/

    if (file.isFile()) {
        ZipEntry entry = new ZipEntry(file.getName());
        zout.putNextEntry(entry);
        BufferedInputStream instream = new BufferedInputStream(new FileInputStream(file));

        while ((read = instream.read(data, 0, BUFFER)) != -1)
            zout.write(data, 0, read);

        zout.closeEntry();
        instream.close();

    } else if (file.isDirectory()) {
        String[] list = file.list();
        int len = list.length;

        for (int i = 0; i < len; i++)
            zip_folder(new File(file.getPath() + "/" + list[i]), zout);
    }
}

From source file:edu.isi.wings.catalog.component.api.impl.oodt.ComponentCreationFM.java

private void addDirToArchive(ZipOutputStream zos, File srcFile) {
    File[] files = srcFile.listFiles();
    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            addDirToArchive(zos, files[i]);
            continue;
        }//from  w  w w.j  av a 2 s .  co  m
        try {
            byte[] buffer = new byte[1024];
            FileInputStream fis = new FileInputStream(files[i]);
            zos.putNextEntry(new ZipEntry(files[i].getName()));
            int length;
            while ((length = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, length);
            }
            zos.closeEntry();
            fis.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java

protected void exportLocales(ZipOutputStream zos, String path) throws WPBIOException {
    try {/*from  w w w. java2  s.c om*/
        WPBProject project = dataStorage.get(WPBProject.PROJECT_KEY, WPBProject.class);
        Map<String, Object> map = new HashMap<String, Object>();
        exporter.export(project, map);
        String metadataXml = path + "metadata.xml";
        ZipEntry metadataZe = new ZipEntry(metadataXml);
        zos.putNextEntry(metadataZe);
        exportToXMLFormat(map, zos);
        zos.closeEntry();

    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("Cannot export uri's to Zip", e);
    }
}

From source file:nl.nn.adapterframework.pipes.CompressPipe.java

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    try {//  w ww .  j  ava  2  s  .co  m
        Object result;
        InputStream in;
        OutputStream out;
        boolean zipMultipleFiles = false;
        if (messageIsContent) {
            if (input instanceof byte[]) {
                in = new ByteArrayInputStream((byte[]) input);
            } else {
                in = new ByteArrayInputStream(input.toString().getBytes());
            }
        } else {
            if (compress && StringUtils.contains((String) input, ";")) {
                zipMultipleFiles = true;
                in = null;
            } else {
                in = new FileInputStream((String) input);
            }
        }
        if (resultIsContent) {
            out = new ByteArrayOutputStream();
            result = out;
        } else {
            String outFilename = null;
            if (messageIsContent) {
                outFilename = FileUtils.getFilename(getParameterList(), session, (File) null, filenamePattern);
            } else {
                outFilename = FileUtils.getFilename(getParameterList(), session, new File((String) input),
                        filenamePattern);
            }
            File outFile = new File(outputDirectory, outFilename);
            result = outFile.getAbsolutePath();
            out = new FileOutputStream(outFile);
        }
        if (zipMultipleFiles) {
            ZipOutputStream zipper = new ZipOutputStream(out);
            StringTokenizer st = new StringTokenizer((String) input, ";");
            while (st.hasMoreElements()) {
                String fn = st.nextToken();
                String zipEntryName = getZipEntryName(fn, session);
                zipper.putNextEntry(new ZipEntry(zipEntryName));
                in = new FileInputStream(fn);
                try {
                    int readLength = 0;
                    byte[] block = new byte[4096];
                    while ((readLength = in.read(block)) > 0) {
                        zipper.write(block, 0, readLength);
                    }
                } finally {
                    in.close();
                    zipper.closeEntry();
                }
            }
            zipper.close();
            out = zipper;
        } else {
            if (compress) {
                if ("gz".equals(fileFormat) || fileFormat == null && resultIsContent) {
                    out = new GZIPOutputStream(out);
                } else {
                    ZipOutputStream zipper = new ZipOutputStream(out);
                    String zipEntryName = getZipEntryName(input, session);
                    zipper.putNextEntry(new ZipEntry(zipEntryName));
                    out = zipper;
                }
            } else {
                if ("gz".equals(fileFormat) || fileFormat == null && messageIsContent) {
                    in = new GZIPInputStream(in);
                } else {
                    ZipInputStream zipper = new ZipInputStream(in);
                    String zipEntryName = getZipEntryName(input, session);
                    if (zipEntryName.equals("")) {
                        // Use first entry found
                        zipper.getNextEntry();
                    } else {
                        // Position the stream at the specified entry
                        ZipEntry zipEntry = zipper.getNextEntry();
                        while (zipEntry != null && !zipEntry.getName().equals(zipEntryName)) {
                            zipEntry = zipper.getNextEntry();
                        }
                    }
                    in = zipper;
                }
            }
            try {
                int readLength = 0;
                byte[] block = new byte[4096];
                while ((readLength = in.read(block)) > 0) {
                    out.write(block, 0, readLength);
                }
            } finally {
                out.close();
                in.close();
            }
        }
        return new PipeRunResult(getForward(), getResultMsg(result));
    } catch (Exception e) {
        PipeForward exceptionForward = findForward(EXCEPTIONFORWARD);
        if (exceptionForward != null) {
            log.warn(getLogPrefix(session) + "exception occured, forwarded to [" + exceptionForward.getPath()
                    + "]", e);
            String originalMessage;
            if (input instanceof String) {
                originalMessage = (String) input;
            } else {
                originalMessage = "Object of type " + input.getClass().getName();
            }
            String resultmsg = new ErrorMessageFormatter().format(getLogPrefix(session), e, this,
                    originalMessage, session.getMessageId(), 0);
            return new PipeRunResult(exceptionForward, resultmsg);
        }
        throw new PipeRunException(this, "Unexpected exception during compression", e);
    }
}

From source file:org.candlepin.sync.Exporter.java

private void addFileToArchive(ZipOutputStream out, int charsToDropFromName, File file)
        throws IOException, FileNotFoundException {
    log.debug("Adding file to archive: " + file.getAbsolutePath().substring(charsToDropFromName));
    out.putNextEntry(new ZipEntry(file.getAbsolutePath().substring(charsToDropFromName)));
    FileInputStream in = null;/*from   www.j a  va2s  .c o  m*/
    try {
        in = new FileInputStream(file);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:fr.gael.dhus.service.job.SendLogsJob.java

@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    if (!configurationManager.getSendLogsCronConfiguration().isActive())
        return;/* ww  w  .  j a va 2  s  .  c  om*/
    long start = System.currentTimeMillis();
    logger.info("SCHEDULER : Send Administrative logs.");
    if (!DHuS.isStarted()) {
        logger.warn("SCHEDULER : Not run while system not fully initialized.");
        return;
    }

    String[] addresses = configurationManager.getSendLogsCronConfiguration().getAddresses().split(",");
    // Case of no addresses available: use system support
    if ((addresses == null) || (addresses.length == 0) || "".equals(addresses[0].trim())) {
        String email = configurationManager.getSupportConfiguration().getMail();
        if ((email == null) || "".equals(email)) {
            throw new MailException("Support e-mail not configured, " + "system logs will not be send");
        }
        addresses = new String[] { email };
    }

    RollingFileAppender rollingFileAppender = (RollingFileAppender) ((org.apache.logging.log4j.core.Logger) LogManager
            .getRootLogger()).getAppenders().get("RollingFile");
    if (rollingFileAppender == null) {
        throw new MailException("No rolling log file defined");
    }

    String logPath = rollingFileAppender.getFileName();

    if ((logPath == null) || logPath.trim().equals("")) {
        throw new MailException("Log file not defined");
    }

    File logs = new File(logPath);
    if (!logs.exists()) {
        throw new MailException("Log file not present : " + logs.getPath());
    }

    Date now = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'@'HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    String docFilename = configurationManager.getNameConfiguration().getShortName().toLowerCase() + "-"
            + df.format(now);

    File zipLogs;
    try {
        zipLogs = File.createTempFile(docFilename, ".zip");
    } catch (IOException e) {
        throw new MailException("Cannot create temporary zip log file.", e);
    }

    // compress logs file to zip format
    FileOutputStream fos;
    ZipOutputStream zos = null;
    FileInputStream fis = null;
    try {
        int length;
        byte[] buffer = new byte[1024];
        ZipEntry entry = new ZipEntry(docFilename + ".txt");

        fos = new FileOutputStream(zipLogs);
        zos = new ZipOutputStream(fos);
        fis = new FileInputStream(logs);

        zos.setLevel(Deflater.BEST_COMPRESSION);
        zos.putNextEntry(entry);
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
    } catch (IOException e) {
        throw new MailException("An error occurred during compression " + "logs file, cannot send logs !", e);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (zos != null) {
                zos.closeEntry();
                zos.close();
            }
        } catch (IOException e) {
            throw new MailException("An error occurred during compression " + "logs file, cannot send logs !",
                    e);
        }
    }

    EmailAttachment attachment = new EmailAttachment();
    attachment.setDescription(
            configurationManager.getNameConfiguration().getShortName() + " Logs " + now.toString());
    attachment.setPath(zipLogs.getPath());
    attachment.setName(zipLogs.getName());

    // Prepare the addresses
    List<String> ads = new ArrayList<String>();
    for (String email : addresses) {
        StringTokenizer tk = new StringTokenizer(email, ", ");
        while (tk.hasMoreTokens()) {
            String token = tk.nextToken().trim();
            if (!token.isEmpty())
                ads.add(token);
        }
    }
    for (String email : ads) {
        try {
            String server = configurationManager.getServerConfiguration().getExternalHostname();
            String url = configurationManager.getServerConfiguration().getExternalUrl();

            mailServer.send(email, null, null,
                    "[" + configurationManager.getNameConfiguration().getShortName().toLowerCase() + "@"
                            + server + "] logs of " + df.format(now),
                    "Here is attached " + configurationManager.getNameConfiguration().getShortName()
                            + " logs of \"" + url + "\" host.\n\n" + "Kind Regards.\nThe "
                            + configurationManager.getNameConfiguration().getShortName() + " Team.",
                    attachment);
            logger.info("Logs Sent to " + email);
        } catch (EmailException e) {
            throw new MailException("Cannot send logs to " + email, e);
        }
    }

    if (!zipLogs.delete()) {
        logger.warn("Cannot remove mail attachment: " + zipLogs.getAbsolutePath());
    }

    logger.info("SCHEDULER : Send Administrative logs done - " + (System.currentTimeMillis() - start) + "ms");
}

From source file:fr.ippon.wip.config.ZipConfiguration.java

/**
 * Create a zip archive from a configuration.
 * // ww  w. j av a2s .com
 * @param configuration
 *            the configuration to zip
 * @param out
 *            the stream to be used
 */
public void zip(WIPConfiguration configuration, ZipOutputStream out) {
    XMLConfigurationDAO xmlConfigurationDAO = new XMLConfigurationDAO(FileUtils.getTempDirectoryPath());

    /*
     * a configuration with the same name may already has been unzipped in
     * the temp directory, so we try to delete it for avoiding name
     * modification (see ConfigurationDAO.correctConfigurationName).
     */
    xmlConfigurationDAO.delete(configuration);
    xmlConfigurationDAO.create(configuration);

    String configName = configuration.getName();

    try {
        int[] types = new int[] { XMLConfigurationDAO.FILE_NAME_CLIPPING,
                XMLConfigurationDAO.FILE_NAME_TRANSFORM, XMLConfigurationDAO.FILE_NAME_CONFIG };
        for (int type : types) {
            File file = xmlConfigurationDAO.getConfigurationFile(configName, type);
            ZipEntry entry = new ZipEntry(file.getName());
            out.putNextEntry(entry);
            copy(FileUtils.openInputStream(file), out);
            out.closeEntry();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.baasbox.db.async.ExportJob.java

@Override
public void run() {
    FileOutputStream dest = null;
    ZipOutputStream zip = null;
    FileOutputStream tempJsonOS = null;
    FileInputStream in = null;/*from   ww  w.  j  av a  2 s  .c om*/
    try {
        //File f = new File(this.fileName);
        File f = File.createTempFile("export", ".temp");

        dest = new FileOutputStream(f);
        zip = new ZipOutputStream(dest);

        File tmpJson = File.createTempFile("export", ".json");
        tempJsonOS = new FileOutputStream(tmpJson);
        DbHelper.exportData(this.appcode, tempJsonOS);
        BaasBoxLogger.info(String.format("Writing %d bytes ", tmpJson.length()));
        tempJsonOS.close();

        ZipEntry entry = new ZipEntry("export.json");
        zip.putNextEntry(entry);
        in = new FileInputStream(tmpJson);
        final int BUFFER = BBConfiguration.getImportExportBufferSize();
        byte buffer[] = new byte[BUFFER];

        int length;
        while ((length = in.read(buffer)) > 0) {
            zip.write(buffer, 0, length);
        }
        zip.closeEntry();
        in.close();

        File manifest = File.createTempFile("manifest", ".txt");
        FileUtils.writeStringToFile(manifest,
                BBInternalConstants.IMPORT_MANIFEST_VERSION_PREFIX + BBConfiguration.getApiVersion());

        ZipEntry entryManifest = new ZipEntry("manifest.txt");
        zip.putNextEntry(entryManifest);
        zip.write(FileUtils.readFileToByteArray(manifest));
        zip.closeEntry();

        tmpJson.delete();
        manifest.delete();

        File finaldestination = new File(this.fileName);
        FileUtils.moveFile(f, finaldestination);

    } catch (Exception e) {
        BaasBoxLogger.error(ExceptionUtils.getMessage(e));
    } finally {
        try {
            if (zip != null)
                zip.close();
            if (dest != null)
                dest.close();
            if (tempJsonOS != null)
                tempJsonOS.close();
            if (in != null)
                in.close();

        } catch (Exception ioe) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(ioe));
        }
    }
}