Example usage for java.util.zip ZipOutputStream ZipOutputStream

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

Introduction

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

Prototype

public ZipOutputStream(OutputStream out) 

Source Link

Document

Creates a new ZIP output stream.

Usage

From source file:com.googlecode.dex2jar.v3.DexExceptionHandlerImpl.java

public void dumpException(DexFileReader reader, File errorFile) throws IOException {
    for (Map.Entry<Method, Exception> e : exceptions.entrySet()) {
        System.err.println("Error:" + e.getKey().toString() + "->" + e.getValue().getMessage());
    }/*from   w w w .  j  a v a2 s .  c o m*/

    final ZipOutputStream errorZipOutputStream = new ZipOutputStream(FileUtils.openOutputStream(errorFile));
    errorZipOutputStream.putNextEntry(new ZipEntry("summary.txt"));
    final PrintWriter fw = new PrintWriter(new OutputStreamWriter(errorZipOutputStream, "UTF-8"));
    fw.println(getVersionString());
    fw.println("there are " + exceptions.size() + " error methods");
    fw.print("options: ");
    if ((readerConfig & DexFileReader.SKIP_DEBUG) == 0) {
        fw.print(" -d");
    }
    fw.println();
    fw.flush();
    errorZipOutputStream.closeEntry();
    final Out out = new Out() {

        @Override
        public void pop() {

        }

        @Override
        public void push() {

        }

        @Override
        public void s(String s) {
            fw.println(s);
        }

        @Override
        public void s(String format, Object... arg) {
            fw.println(String.format(format, arg));
        }
    };
    final int[] count = new int[] { 0 };
    reader.accept(new EmptyVisitor() {

        @Override
        public DexClassVisitor visit(int accessFlags, String className, String superClass,
                String[] interfaceNames) {
            return new EmptyVisitor() {

                @Override
                public DexMethodVisitor visitMethod(final int accessFlags, final Method method) {
                    if (exceptions.containsKey(method)) {
                        return new EmptyVisitor() {

                            @Override
                            public DexCodeVisitor visitCode() {
                                try {
                                    errorZipOutputStream.putNextEntry(new ZipEntry("t" + count[0]++ + ".txt"));
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                                Exception exception = exceptions.get(method);
                                exception.printStackTrace(fw);
                                out.s("");
                                out.s("DexMethodVisitor mv=cv.visitMethod(%s, %s);",
                                        Escape.methodAcc(accessFlags), Escape.v(method));
                                out.s("DexCodeVisitor code = mv.visitCode();");
                                return new ASMifierCodeV(out);
                            }

                            @Override
                            public void visitEnd() {
                                out.s("mv.visitEnd();");
                                fw.flush();
                                try {
                                    errorZipOutputStream.closeEntry();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        };
                    }
                    return null;
                }

            };
        }

    }, readerConfig);
    errorZipOutputStream.close();

}

From source file:com.l2jserver.service.core.logging.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 * //from w  w  w  . j  av  a  2s . co  m
 * @param file
 *            file to truncate
 */
protected void truncate(File file) {
    LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");

    // Linux systems doesn't provide file creation time, so we have to hope
    // that log files
    // were not modified manually after server starup
    // We can use here Windowns-only solution but that suck :(
    if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
        File backupRoot = new File(getBackupDir());
        if (!backupRoot.exists() && !backupRoot.mkdirs()) {
            throw new Error("Can't create backup dir for backup storage");
        }

        SimpleDateFormat df;
        try {
            df = new SimpleDateFormat(getBackupDateFormat());
        } catch (Exception e) {
            throw new Error("Invalid date formate for backup files: " + getBackupDateFormat(), e);
        }
        String date = df.format(new Date(file.lastModified()));

        File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");

        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            ZipEntry entry = new ZipEntry(file.getName());
            entry.setMethod(ZipEntry.DEFLATED);
            entry.setCrc(FileUtils.checksumCRC32(file));
            zos.putNextEntry(entry);
            fis = FileUtils.openInputStream(file);

            byte[] buffer = new byte[1024];
            int readed;
            while ((readed = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, readed);
            }

        } catch (Exception e) {
            throw new Error("Can't create zip file", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    // not critical error
                    LogLog.warn("Can't close zip file", e);
                }
            }

            if (fis != null) {
                try {
                    // not critical error
                    fis.close();
                } catch (IOException e) {
                    LogLog.warn("Can't close zipped file", e);
                }
            }
        }

        if (!file.delete()) {
            throw new Error("Can't delete old log file " + file.getAbsolutePath());
        }
    }
}

From source file:com.adobe.communities.ugc.migration.export.GenericExportServlet.java

@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    if (!request.getRequestParameterMap().containsKey("path")) {
        throw new ServletException("No path specified for export. Exiting.");
    }// w ww . ja va2s  . c o  m
    final String path = StringUtils.stripEnd(request.getRequestParameter("path").getString(), "/");
    final Resource resource = request.getResourceResolver().getResource(path);
    if (resource == null) {
        throw new ServletException("Could not find a valid resource for export");
    }
    File outFile = null;
    try {
        outFile = File.createTempFile(UUID.randomUUID().toString(), ".zip");
        if (!outFile.canWrite()) {
            throw new ServletException("Cannot write to specified output file");
        }
        response.setContentType("application/octet-stream");
        final String headerKey = "Content-Disposition";
        final String headerValue = "attachment; filename=\"export.zip\"";
        response.setHeader(headerKey, headerValue);

        FileOutputStream fos = new FileOutputStream(outFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        zip = new ZipOutputStream(bos);
        OutputStream outStream = null;
        InputStream inStream = null;
        try {
            exportContent(resource, path);
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            // obtains response's output stream
            outStream = response.getOutputStream();
            inStream = new FileInputStream(outFile);
            // copy from file to output
            IOUtils.copy(inStream, outStream);
        } catch (final IOException e) {
            throw new ServletException(e);
        } catch (final Exception e) {
            throw new ServletException(e);
        } finally {
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(inStream);
            IOUtils.closeQuietly(outStream);
        }
    } finally {
        if (outFile != null) {
            outFile.delete();
        }
    }
}

From source file:com.genericworkflownodes.knime.workflowexporter.export.impl.GuseKnimeWorkflowExporter.java

@Override
public void export(final Workflow workflow, final File destination) throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(/*www .  j  a va  2s .  c  o m*/
                "exporting using " + getShortDescription() + " to [" + destination.getAbsolutePath() + "]");
    }
    final StringBuilder builder = new StringBuilder();
    generateWorkflowXml(workflow, builder);

    final ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(destination));
    zipOutputStream.putNextEntry(new ZipEntry("workflow.xml"));

    zipOutputStream.write(formatXml(builder.toString()).getBytes());

    zipOutputStream.closeEntry();
    zipOutputStream.close();
}

From source file:free.yhc.netmbuddy.share.ExporterPlaylist.java

@Override
public Err execute() {
    JSONObject jsonPl = Json.playlistToJson(_mPlid);
    JSONObject jsonMeta = Json.createMetaJson(Type.PLAYLIST);
    JSONObject jo = new JSONObject();

    if (null == jsonPl)
        return Err.PARAMETER;

    eAssert(null != jsonMeta);//from  w  w w  .j a  v a  2 s .  c o  m
    try {
        jo.put(Json.FMETA, jsonMeta);
        jo.put(Json.FPLAYLIST, jsonPl);
    } catch (JSONException e) {
        return Err.UNKNOWN;
    }

    String shareName = "";
    try {
        shareName = FileUtils.pathNameEscapeString(Utils.getResString(R.string.playlist) + "_"
                + jsonPl.getString(Json.FTITLE) + "." + Policy.SHARE_FILE_EXTENTION);
    } catch (JSONException e) {
        return Err.UNKNOWN;
    }

    ZipOutputStream zos;
    try {
        zos = new ZipOutputStream(new FileOutputStream(_mFout));
    } catch (FileNotFoundException e) {
        return Err.IO_FILE;
    }

    Err err = exportShareJson(zos, jo, shareName);
    try {
        zos.close();
    } catch (IOException e) {
        return Err.IO_FILE;
    }

    return err;
}

From source file:com.aionemu.commons.log4j.appenders.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 *
 * @param file file to truncate//ww w.j  a v a  2  s.  co m
 */
protected void truncate(File file) {
    LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");

    // Linux systems doesn't provide file creation time, so we have to hope
    // that log files
    // were not modified manually after server starup
    // We can use here Windowns-only solution but that suck :(
    if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
        File backupRoot = new File(getBackupDir());
        if (!backupRoot.exists() && !backupRoot.mkdirs()) {
            throw new AppenderInitializationError("Can't create backup dir for backup storage");
        }

        SimpleDateFormat df;
        try {
            df = new SimpleDateFormat(getBackupDateFormat());
        } catch (Exception e) {
            throw new AppenderInitializationError(
                    "Invalid date formate for backup files: " + getBackupDateFormat(), e);
        }
        String date = df.format(new Date(file.lastModified()));

        File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");

        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            ZipEntry entry = new ZipEntry(file.getName());
            entry.setMethod(ZipEntry.DEFLATED);
            entry.setCrc(FileUtils.checksumCRC32(file));
            zos.putNextEntry(entry);
            fis = FileUtils.openInputStream(file);

            byte[] buffer = new byte[1024];
            int readed;
            while ((readed = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, readed);
            }

        } catch (Exception e) {
            throw new AppenderInitializationError("Can't create zip file", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    // not critical error
                    LogLog.warn("Can't close zip file", e);
                }
            }

            if (fis != null) {
                try {
                    // not critical error
                    fis.close();
                } catch (IOException e) {
                    LogLog.warn("Can't close zipped file", e);
                }
            }
        }

        if (!file.delete()) {
            throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath());
        }
    }
}

From source file:com.eviware.soapui.impl.wsdl.support.FileAttachment.java

public void cacheFileLocally(File file) throws FileNotFoundException, IOException {
    // write attachment-data to tempfile
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    ZipOutputStream out = new ZipOutputStream(data);
    out.putNextEntry(new ZipEntry(config.getName()));

    InputStream in = new FileInputStream(file);
    long sz = file.length();
    config.setSize(sz);/*from ww  w .j a v a  2  s.  c om*/

    Tools.writeAll(out, in);

    in.close();
    out.closeEntry();
    out.finish();
    out.close();
    data.close();

    config.setData(data.toByteArray());
}

From source file:com.sangupta.jerry.util.ZipUtils.java

/**
 * Compresses the provided file into ZIP format adding a '.ZIP' at the end
 * of the filename./* w w w.ja va  2s .c  om*/
 * 
 * @param filePath
 *            the file path that needs to be compressed
 * 
 * @return returns the absolute path of the ZIP file.
 */
public String createZipFile(String filePath) {
    LOGGER.debug("Starting compression of " + filePath);

    String zipFilename = filePath + ".zip";
    LOGGER.debug("Creating zip file at " + zipFilename);

    byte[] buf = new byte[1024];

    ZipOutputStream stream = null;
    FileInputStream input = null;
    try {
        // Create the ZIP file
        stream = new ZipOutputStream(new FileOutputStream(zipFilename));

        // Compress the file
        File file = new File(filePath);
        input = new FileInputStream(file);

        // Add ZIP entry to output stream.
        stream.putNextEntry(new ZipEntry(file.getName()));

        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = input.read(buf)) > 0) {
            stream.write(buf, 0, len);
        }

        // Complete the entry
        stream.closeEntry();
    } catch (IOException e) {
        LOGGER.error("Unable to compress file " + filePath, e);
    } finally {
        IOUtils.closeQuietly(input);

        // Complete the ZIP file
        IOUtils.closeQuietly(stream);
    }

    return zipFilename;
}

From source file:fedora.server.storage.translation.AtomDOSerializer.java

/**
 * {@inheritDoc}//from  w  ww .j  a  va  2s.  c  o  m
 */
public void serialize(DigitalObject obj, OutputStream out, String encoding, int transContext)
        throws ObjectIntegrityException, StreamIOException, UnsupportedEncodingException {
    m_obj = obj;
    m_encoding = (encoding == null || encoding == "") ? "UTF-8" : encoding;
    m_transContext = transContext;
    m_pid = PID.getInstance(m_obj.getPid());
    m_feed = abdera.newFeed();

    if (m_format.equals(ATOM_ZIP1_1)) {
        m_zout = new ZipOutputStream(out);
    }

    addObjectProperties();
    m_feed.setIcon("http://www.fedora-commons.org/images/logo_vertical_transparent_200_251.png");
    addDatastreams();

    if (m_format.equals(ATOM_ZIP1_1)) {
        try {
            m_zout.putNextEntry(new ZipEntry("atommanifest.xml"));
            m_feed.writeTo("prettyxml", m_zout);
            m_zout.closeEntry();
            m_zout.close();
        } catch (IOException e) {
            throw new StreamIOException(e.getMessage(), e);
        }
    } else {
        try {
            m_feed.writeTo("prettyxml", out);
        } catch (IOException e) {
            throw new StreamIOException(e.getMessage(), e);
        }
    }
}

From source file:se.crisp.codekvast.agent.daemon.worker.impl.ZipFileDataExporterImpl.java

private void doExportDataTo(File exportFile) throws DataExportException {
    log.debug("Exporting data to {} ...", exportFile);

    File tmpFile = createTempFile(exportFile);

    try (ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(tmpFile)))) {
        String uuid = UUID.randomUUID().toString();
        zip.setComment(format("Export of Codekvast local warehouse for %s at %s, uuid=%s",
                config.getEnvironment(), Instant.now(), uuid));

        Charset charset = Charset.forName("UTF-8");
        doExportMetaInfo(zip, charset,/*ww  w  . j a  va  2  s .  c  o m*/
                ExportFileMetaInfo.builder().uuid(uuid).schemaVersion(SCHEMA_VERSION)
                        .daemonVersion(config.getDaemonVersion()).daemonVcsId(config.getDaemonVcsId())
                        .daemonHostname(getHostname()).environment(config.getEnvironment()).build());

        CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(zip, charset));
        doExportDatabaseTable(zip, csvWriter, "applications", "id", "name", "version", "createdAtMillis");
        doExportDatabaseTable(zip, csvWriter, "methods", "id", "visibility", "signature", "createdAtMillis",
                "declaringType", "exceptionTypes", "methodName", "modifiers", "packageName", "parameterTypes",
                "returnType");
        doExportDatabaseTable(zip, csvWriter, "jvms", "id", "uuid", "startedAtMillis", "dumpedAtMillis",
                "jvmDataJson");
        doExportDatabaseTable(zip, csvWriter, "invocations", "applicationId", "methodId", "jvmId",
                "invokedAtMillis", "invocationCount", "status");

        zip.finish();
    } catch (Exception e) {
        throw new DataExportException("Cannot create " + exportFile, e);
    }

    if (!tmpFile.renameTo(exportFile)) {
        tmpFile.delete();
        throw new DataExportException(format("Cannot rename %s to %s", tmpFile, exportFile));
    }
}