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:fll.web.GatherBugReport.java

/**
 * Add the database to the zipfile./* www .ja va  2  s .c o  m*/
 * 
 * @throws SQLException
 */
private static void addDatabase(final ZipOutputStream zipOut, final Connection connection,
        final Document challengeDocument) throws IOException, SQLException {

    ZipOutputStream dbZipOut = null;
    FileInputStream fis = null;
    try {
        final File temp = File.createTempFile("database", ".flldb");

        dbZipOut = new ZipOutputStream(new FileOutputStream(temp));
        DumpDB.dumpDatabase(dbZipOut, connection, challengeDocument);
        dbZipOut.close();

        zipOut.putNextEntry(new ZipEntry("database.flldb"));
        fis = new FileInputStream(temp);
        IOUtils.copy(fis, zipOut);
        fis.close();

        if (!temp.delete()) {
            temp.deleteOnExit();
        }

    } finally {
        IOUtils.closeQuietly(dbZipOut);
        IOUtils.closeQuietly(fis);
    }

}

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

public static void zip(final File input, final File output) throws IOException {
    final FileOutputStream out = new FileOutputStream(output);
    final ZipOutputStream zOut = new ZipOutputStream(out);
    try {//from   w  w  w . java2 s .c  o m
        zipFile("", input, zOut);
    } finally {
        zOut.close();
    }
}

From source file:de.blizzy.backup.Utils.java

public static void zipFile(File source, File target) throws IOException {
    ZipOutputStream out = null;/*from   w w w  . ja va  2s. c  o m*/
    try {
        out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target)));
        out.setLevel(Deflater.BEST_COMPRESSION);

        ZipEntry entry = new ZipEntry(source.getName());
        entry.setTime(source.lastModified());
        out.putNextEntry(entry);

        Files.copy(source.toPath(), out);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:com.compomics.pladipus.core.control.util.ZipUtils.java

/**
 * Zips an entire folder in one go//from ww  w. jav a2 s  .  c o m
 *
 * @param input the original folder
 * @param output the destination zip file
 */
static public void zipFolder(File inputFolder, File zipFile) throws UnspecifiedPladipusException, IOException {
    if (zipFile.exists()) {
        zipFile.delete();
    }
    zipFile.getParentFile().mkdirs();
    zipFile.createNewFile();
    try (FileOutputStream fileWriter = new FileOutputStream(zipFile);
            ZipOutputStream zip = new ZipOutputStream(fileWriter)) {
        addFolderToZip("", inputFolder.getAbsolutePath(), zip);
        zip.flush();
    }
}

From source file:eionet.gdem.conversion.odf.OpenDocument.java

/**
 * Method unzips the ods file, replaces content.xml and meta.xml and finally zips it together again
 * @param out OutputStream//from   ww  w  .  j a  va 2  s. co m
 * @throws Exception If an error occurs.
 */
public void createOdsFile(OutputStream out) throws Exception {

    if (strContentFile == null) {
        throw new Exception("Content file is not set!");
    }

    initOdsFiles();

    FileInputStream result_file_input = null;
    FileOutputStream zip_file_output = new FileOutputStream(strOdsOutFile);
    ZipOutputStream zip_out = new ZipOutputStream(zip_file_output);

    try {
        // unzip template ods file to temp directory
        ZipUtil.unzip(strOdsTemplateFile, strWorkingFolder);
        // copy conent file into temp directory
        Utils.copyFile(new File(strContentFile),
                new File(strWorkingFolder + File.separator + CONTENT_FILE_NAME));
        // try to transform meta with XSL, if it fails then copy meta file into temp directory
        try {
            convertMetaFile();
        } catch (Throwable t) {
            Utils.copyFile(new File(strMetaFile), new File(strWorkingFolder + File.separator + META_FILE_NAME));
        }
        // zip temp directory
        ZipUtil.zipDir(strWorkingFolder, zip_out);
        zip_out.finish();
        zip_out.close();

        // Fill outputstream
        result_file_input = new FileInputStream(strOdsOutFile);
        Streams.drain(result_file_input, out);

    } catch (IOException ioe) {
        throw new Exception("Could not create OpenDocument Spreadsheet file: " + ioe.toString());
    } finally {
        IOUtils.closeQuietly(zip_out);
        IOUtils.closeQuietly(zip_file_output);
        IOUtils.closeQuietly(result_file_input);
    }
    try {
        // delete working folder and temporary ods file
        Utils.deleteFolder(strWorkingFolder);
        Utils.deleteFile(strOdsOutFile);
    } catch (Exception ioe) {
        // TODO fix logger
        // couldn't delete temp files
    }

}

From source file:com.thoughtworks.go.plugin.infra.commons.PluginsZip.java

public void create() {
    checkFilesAccessibility(bundledPlugins, externalPlugins);
    reset();// w w w. ja  v  a  2 s. c  o  m

    MessageDigest md5Digest = DigestUtils.getMd5Digest();
    try (ZipOutputStream zos = new ZipOutputStream(
            new DigestOutputStream(new BufferedOutputStream(new FileOutputStream(destZipFile)), md5Digest))) {
        for (GoPluginDescriptor agentPlugins : agentPlugins()) {
            String zipEntryPrefix = "external/";

            if (agentPlugins.isBundledPlugin()) {
                zipEntryPrefix = "bundled/";
            }

            zos.putNextEntry(
                    new ZipEntry(zipEntryPrefix + new File(agentPlugins.pluginFileLocation()).getName()));
            Files.copy(new File(agentPlugins.pluginFileLocation()).toPath(), zos);
            zos.closeEntry();
        }
    } catch (Exception e) {
        LOG.error("Could not create zip of plugins for agent to download.", e);
    }

    md5DigestOfPlugins = Hex.encodeHexString(md5Digest.digest());
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

private void consultarFirma(int fileNameId) {
    try {/*from ww w . j a  v a2 s  .c  o m*/
        FileOutputStream fos = new FileOutputStream(
                userFolderPath + "/" + Integer.toString(fileNameId) + "Firmada.zip");
        ZipOutputStream zos = new ZipOutputStream(fos);

        String file1Name = userFolderPath + "/" + Integer.toString(fileNameId) + "Firmada.png";
        File image = new File(file1Name);

        ZipEntry zipEntry = new ZipEntry(image.getName());
        zos.putNextEntry(zipEntry);
        FileInputStream fileInputStream = new FileInputStream(image);

        byte[] buf = new byte[2048];
        int bytesRead;

        while ((bytesRead = fileInputStream.read(buf)) > 0) {
            zos.write(buf, 0, bytesRead);
        }
        zos.closeEntry();
        zos.close();
        fos.close();

        Path path = Paths.get(userFolderPath + "/" + Integer.toString(fileNameId) + "Firmada.zip");

        byte[] data = Files.readAllBytes(path);
        byte[] byteArray = Base64.encodeBase64(data);
        String b64 = new String(byteArray);

        System.out.println(consultaFirma(b64, Integer.toString(fileNameId) + "Firmada"));

        nFilesVerified++;
        System.out.println("User : " + idSimulatedUser + " FIRMA VERIFICADA");
    } catch (IOException ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        nNotFileFound++;
    } catch (IOException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        nVerifyErrors++;
    }
}

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

@Post
public Representation getConfig(Map<String, String> data) {
    try {// w  w  w . j  a  v  a  2 s. c o  m
        if (!getRequestAttributes().containsKey("client"))
            return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);

        Client client = Clients.dao.queryForId(getAttribute("client"));
        if (!Policy.get().canAccess(getSessionToken().get().getUser(), client)) {
            return clientError("FORBIDDEN", Status.CLIENT_ERROR_BAD_REQUEST);
        }

        ArrayList<String> config = new ArrayList<>();
        config.addAll(Arrays.asList(DEFAULTS));

        // create zip
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(baos);

        List<Certificate> userCert = Certificates.dao.queryForEq("client_id", client.id).stream()
                .filter(Certificate::valid).collect(Collectors.toList());

        if (!userCert.isEmpty()) {
            byte[] raw = userCert.get(0).getRaw();
            zip.putNextEntry(new ZipEntry("client.crt"));
            zip.write(raw);
            zip.putNextEntry(new ZipEntry("README"));
            zip.write(("!! You are using your own keypair. Please make sure to adjust the "
                    + "path to your private key in the config file or move the private key"
                    + " here and name it client.key").getBytes());
            config.add("cert client.crt");
            config.add("key client.key");
        } else if (client.user.certId != null && !client.user.certId.isEmpty()) {
            Representation res = addPKCS11config(data.get("platform").toLowerCase(), config, client.user);
            if (res != null)
                return res;
        }

        if (client.user.certId == null || client.user.certId.isEmpty()) {
            zip.putNextEntry(new ZipEntry("NO_KEYPAIR_DEFINED"));
            zip.write("Invalid state, no keypair has been defined.".getBytes());
        }

        return finalizeZip(config, zip, baos);
    } catch (Exception ex) {
        Logger.getLogger(getClass()).error("Failed to generate config file archive", ex);
    }

    return DEFAULT_ERROR;
}

From source file:ee.ria.xroad.common.messagelog.archive.LogArchiveCache.java

InputStream getArchiveFile() throws IOException {
    tempArchive = File.createTempFile("xroad-log-archive-zip", ".tmp", workingDir.toFile());
    try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tempArchive))) {
        addAsicContainersToArchive(out);
        addLinkingInfoToArchive(out);//from   w w  w .  j  ava  2 s.com
    } catch (Exception e) {
        handleCacheError(e);
    }

    return new FileInputStream(tempArchive);
}

From source file:org.envirocar.app.util.Util.java

/**
 * Zips a list of files into the target archive.
 * /*w  ww.  j  a  va2 s. c o  m*/
 * @param files
 *            the list of files of the target archive
 * @param target
 *            the target filename
 * @throws IOException 
 */
public static void zipNative(List<File> files, String target) throws IOException {
    ZipOutputStream zos = null;
    try {
        File targetFile = new File(target);
        FileOutputStream dest = new FileOutputStream(targetFile);

        zos = new ZipOutputStream(new BufferedOutputStream(dest));

        for (File f : files) {
            byte[] bytes = readFileContents(f).toByteArray();
            ZipEntry entry = new ZipEntry(f.getName());
            zos.putNextEntry(entry);
            zos.write(bytes);
            zos.closeEntry();
        }

    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (zos != null)
                zos.close();
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
        }
    }

}