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.dangdang.config.service.web.mb.PropertyExportManagedBean.java

/**
 * ??ZIP/*from  w w  w  .  j  a v a  2s . c  o  m*/
 * 
 * @return
 */
public StreamedContent generateFileAll() {
    LOGGER.info("Export all config group");
    StreamedContent file = null;

    String authedNode = ZKPaths.makePath(nodeAuth.getAuthedNode(), versionMB.getSelectedVersion());
    List<String> children = nodeService.listChildren(authedNode);
    if (children != null && !children.isEmpty()) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(out);
            for (String groupName : children) {
                String groupPath = ZKPaths.makePath(authedNode, groupName);
                String fileName = ZKPaths.getNodeFromPath(groupPath) + ".properties";

                List<PropertyItemVO> items = nodeBusiness.findPropertyItems(nodeAuth.getAuthedNode(),
                        versionMB.getSelectedVersion(), groupName);
                List<String> lines = formatPropertyLines(groupName, items);
                if (!lines.isEmpty()) {
                    ZipEntry zipEntry = new ZipEntry(fileName);
                    zipOutputStream.putNextEntry(zipEntry);
                    IOUtils.writeLines(lines, "\r\n", zipOutputStream, Charsets.UTF_8.displayName());
                    zipOutputStream.closeEntry();
                }
            }

            zipOutputStream.close();
            byte[] data = out.toByteArray();
            InputStream in = new ByteArrayInputStream(data);

            String fileName = authedNode.replace('/', '-') + ".zip";
            file = new DefaultStreamedContent(in, "application/zip", fileName, Charsets.UTF_8.name());
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    return file;
}

From source file:com.asual.summer.bundle.BundleDescriptorMojo.java

public void execute() throws MojoExecutionException {

    try {/*from ww  w.j  av  a2s .c o  m*/

        String webXml = "WEB-INF/web.xml";
        File warDir = new File(buildDirectory, finalName);
        File warFile = new File(buildDirectory, finalName + ".war");
        File webXmlFile = new File(warDir, webXml);
        FileUtils.copyFile(new File(basedir, "src/main/webapp/" + webXml), webXmlFile);

        Configuration[] configurations = new Configuration[] { new WebXmlConfiguration(),
                new FragmentConfiguration() };
        WebAppContext context = new WebAppContext();
        context.setDefaultsDescriptor(null);
        context.setDescriptor(webXmlFile.getAbsolutePath());
        context.setConfigurations(configurations);

        for (Artifact artifact : artifacts) {
            JarInputStream in = new JarInputStream(new FileInputStream(artifact.getFile()));
            while (true) {
                ZipEntry entry = in.getNextEntry();
                if (entry != null) {
                    if ("META-INF/web-fragment.xml".equals(entry.getName())) {
                        Resource fragment = Resource
                                .newResource("file:" + artifact.getFile().getAbsolutePath());
                        context.getMetaData().addFragment(fragment, Resource
                                .newResource("jar:" + fragment.getURL() + "!/META-INF/web-fragment.xml"));
                        context.getMetaData().addWebInfJar(fragment);
                    }
                } else {
                    break;
                }
            }
            in.close();
        }

        for (int i = 0; i < configurations.length; i++) {
            configurations[i].preConfigure(context);
        }

        for (int i = 0; i < configurations.length; i++) {
            configurations[i].configure(context);
        }

        for (int i = 0; i < configurations.length; i++) {
            configurations[i].postConfigure(context);
        }

        Descriptor descriptor = context.getMetaData().getWebXml();
        Node root = descriptor.getRoot();

        List<Object> nodes = new ArrayList<Object>();
        List<FragmentDescriptor> fragmentDescriptors = context.getMetaData().getOrderedFragments();
        for (FragmentDescriptor fd : fragmentDescriptors) {
            for (int i = 0; i < fd.getRoot().size(); i++) {
                Object el = fd.getRoot().get(i);
                if (el instanceof Node && ((Node) el).getTag().matches("^name|ordering$")) {
                    continue;
                }
                nodes.add(el);
            }
        }
        root.addAll(nodes);

        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(warDir, webXml)));
        writer.write(root.toString());
        writer.close();

        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(warFile));
        zip(warDir, warDir, zos);
        zos.close();

    } catch (Exception e) {
        getLog().error(e.getMessage(), e);
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:ezbake.deployer.publishers.EzAzkabanPublisher.java

/**
 * This will publish the artifact to Azkaban for scheduled running.  The artifact should be of the format
 * <p/>//from  ww w.ja v a2  s  .c o  m
 * <p/>
 * The artifact at this point in time will already have included the SSL certs.
 * <p/>
 * Its up to the publisher to reorganize the tar file if needed for its PaaS
 *
 * @param artifact    The artifact to deploy
 * @param callerToken - The token of the user or application that initiated this call
 * @throws DeploymentException - On any exceptions
 */
@Override
public void publish(DeploymentArtifact artifact, EzSecurityToken callerToken) throws DeploymentException {
    File unzippedPack = null;
    File azkabanZip = null;
    ZipOutputStream zipOutputStream = null;
    String flowName;
    final BatchJobInfo jobInfo = artifact.getMetadata().getManifest().getBatchJobInfo();

    // Get the Azkaban authentication token
    final AuthenticationResult authenticatorResult;
    try {
        authenticatorResult = new AuthenticationManager(new URI(azConf.getAzkabanUrl()), azConf.getUsername(),
                azConf.getPassword()).login();
    } catch (URISyntaxException e) {
        throw new DeploymentException(e.getMessage());
    }

    if (authenticatorResult.hasError()) {
        log.error("Could not log into Azkaban: " + authenticatorResult.getError());
        throw new DeploymentException(authenticatorResult.getError());
    }

    log.info("Successfully logged into Azkaban. Now creating .zip to upload");

    try {
        // Unzip the artifact
        unzippedPack = UnzipUtil.unzip(new File(unzipDir), ByteBuffer.wrap(artifact.getArtifact()));
        log.info("Unzipped artifact to: " + unzippedPack.getAbsolutePath());

        // Create a .zip file to submit to Azkaban
        azkabanZip = File.createTempFile("ezbatch_", ".zip");
        log.info("Created temporary zip file: " + azkabanZip.getCanonicalPath());
        zipOutputStream = new ZipOutputStream(new FileOutputStream(azkabanZip));

        // Copy the configs from the artifact to the top level of the zip.  This should contain the Azkaban
        // .jobs and .properties
        final String configDir = UnzipUtil.getConfDirectory(unzippedPack).get();
        final File configDirFile = new File(configDir);
        for (File f : FileUtils.listFiles(configDirFile, TrueFileFilter.TRUE, TrueFileFilter.TRUE)) {
            zipOutputStream.putNextEntry(new ZipArchiveEntry(f.getCanonicalPath().replaceFirst(configDir, "")));
            IOUtils.copy(new FileInputStream(f), zipOutputStream);
            zipOutputStream.closeEntry();
        }
        log.info("Copied configs to the .zip");

        // Copy the jars from bin/ in the artifact to lib/ in the .zip file and other things to the jar as needed
        final String dirPrefix = unzippedPack.getAbsolutePath() + "/bin/";
        for (File f : FileUtils.listFiles(new File(dirPrefix), TrueFileFilter.TRUE, TrueFileFilter.TRUE)) {
            zipOutputStream
                    .putNextEntry(new ZipArchiveEntry(f.getCanonicalPath().replaceFirst(dirPrefix, "lib/")));

            final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(f));
            final JarOutputStream jarOutputStream = new JarOutputStream(zipOutputStream);

            JarEntry je;
            while ((je = jarInputStream.getNextJarEntry()) != null) {
                jarOutputStream.putNextEntry(je);
                IOUtils.copy(jarInputStream, jarOutputStream);
                jarOutputStream.closeEntry();
            }
            log.info("Created Jar file");

            // Add the SSL certs to the jar
            final String sslPath = UnzipUtil.getSSLPath(configDirFile).get();
            for (File sslFile : FileUtils.listFiles(new File(sslPath), TrueFileFilter.TRUE,
                    TrueFileFilter.TRUE)) {
                if (sslFile.isFile()) {
                    jarOutputStream.putNextEntry(new JarArchiveEntry("ssl/" + sslFile.getName()));
                    IOUtils.copy(new FileInputStream(sslFile), jarOutputStream);
                    jarOutputStream.closeEntry();
                }
            }
            log.info("Added SSL certs to jar");

            // Add the application.properties to the jar file so the jobs can read it
            final File appProps = new File(configDir, "application.properties");
            final Properties adjustedProperties = new Properties();
            adjustedProperties.load(new FileInputStream(appProps));
            adjustedProperties.setProperty("ezbake.security.ssl.dir", "/ssl/");
            jarOutputStream.putNextEntry(new JarArchiveEntry("application.properties"));
            adjustedProperties.store(jarOutputStream, null);
            jarOutputStream.closeEntry();

            jarOutputStream.finish();
            zipOutputStream.closeEntry();
        }

        // Check to see if there are any .job files.  If there aren't, this is an external job and we need to create
        // one for the .zip file
        final Collection<File> jobFiles = FileUtils.listFiles(configDirFile, new String[] { "job" }, false);
        if (jobFiles.isEmpty()) {
            // If there are no job files present then we need to create one for the user
            final StringBuilder sb = new StringBuilder(
                    "type=hadoopJava\n" + "job.class=ezbatch.amino.api.EzFrameworkDriver\n"
                            + "classpath=./lib/*\n" + "main.args=-d /ezbatch/amino/config");

            for (File xmlConfig : FileUtils.listFiles(configDirFile, new String[] { "xml" }, false)) {
                sb.append(" -c ").append(xmlConfig.getName());
            }

            zipOutputStream.putNextEntry(new ZipEntry("Analytic.job"));
            IOUtils.copy(new StringReader(sb.toString()), zipOutputStream);
            zipOutputStream.closeEntry();
            log.info("There was no .job file so one was created for the .zip");
            flowName = "Analytic";
        } else {
            flowName = jobInfo.getFlowName();
            if (flowName == null) {
                log.warn("Manifest did not contain flow_name. Guessing what it should be");
                flowName = FilenameUtils.getBaseName(jobFiles.toArray(new File[jobFiles.size()])[0].getName());
                log.info("Guessing the flow name should be:" + flowName);
            }
        }

        zipOutputStream.finish();
        log.info("Finished creating .zip");

        // Now that we've created the zip to upload, attempt to create a project for it to be uploaded to. Every .zip
        // file needs to be uploaded to a project, and the project may or may not already exist.
        final String projectName = ArtifactHelpers.getAppId(artifact) + "_"
                + ArtifactHelpers.getServiceId(artifact);
        final ProjectManager projectManager = new ProjectManager(authenticatorResult.getSessionId(),
                new URI(azConf.getAzkabanUrl()));
        final ManagerResult managerResult = projectManager.createProject(projectName, "EzBatch Deployed");

        // If the project already exists, it will return an error, but really it's not a problem
        if (managerResult.hasError()) {
            if (!managerResult.getMessage().contains("already exists")) {
                log.error("Could not create project: " + managerResult.getMessage());
                throw new DeploymentException(managerResult.getMessage());
            } else {
                log.info("Reusing the existing project: " + projectName);
            }
        } else {
            log.info("Created new project: " + projectName);
            log.info("Path: " + managerResult.getPath());
        }

        // Upload the .zip file to the project
        final UploadManager uploader = new UploadManager(authenticatorResult.getSessionId(),
                azConf.getAzkabanUrl(), projectName, azkabanZip);
        final UploaderResult uploaderResult = uploader.uploadZip();

        if (uploaderResult.hasError()) {
            log.error("Could not upload the zip file: " + uploaderResult.getError());
            throw new DeploymentException(uploaderResult.getError());
        }

        log.info("Successfully submitted zip file to Azkaban");

        // Schedule the jar to run.  If the start times aren't provided, it will run in 2 minutes

        final ScheduleManager scheduler = new ScheduleManager(authenticatorResult.getSessionId(),
                new URI(azConf.getAzkabanUrl()));

        // Add the optional parameters if they are present
        if (jobInfo.isSetStartDate()) {
            scheduler.setScheduleDate(jobInfo.getStartDate());
        }
        if (jobInfo.isSetStartTime()) {
            scheduler.setScheduleTime(jobInfo.getStartTime());
        }
        if (jobInfo.isSetRepeat()) {
            scheduler.setPeriod(jobInfo.getRepeat());
        }

        final SchedulerResult schedulerResult = scheduler.scheduleFlow(projectName, flowName,
                uploaderResult.getProjectId());
        if (schedulerResult.hasError()) {
            log.error("Failure to schedule job: " + schedulerResult.getError());
            throw new DeploymentException(schedulerResult.getError());
        }

        log.info("Successfully scheduled flow: " + flowName);

    } catch (Exception ex) {
        log.error("No Nos!", ex);
        throw new DeploymentException(ex.getMessage());
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        FileUtils.deleteQuietly(azkabanZip);
        FileUtils.deleteQuietly(unzippedPack);
    }
}

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);/*  w  ww.j a  v a2 s  . c o  m*/
    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.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/*from   ww w . j  a v  a 2  s  . c  o  m*/
 * @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:ch.randelshofer.cubetwister.HTMLExporter.java

public void exportToDirectory(String documentName, DocumentModel model, File dir, ProgressObserver p)
        throws IOException {
    this.documentName = documentName;
    this.model = model;
    this.dir = dir;
    this.zipFile = null;
    this.p = p;/*from  www .  j a  va2  s.  c om*/
    init();
    processHTMLTemplates(p);
    new File(dir, "applets").mkdir();
    ZipOutputStream zout = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(new File(dir, "applets/resources.xml.zip"))));
    zout.setLevel(Deflater.BEST_COMPRESSION);
    try {
        //model.writeXML(new PrintWriter(new File(dir, "applets/resources.xml")));
        zout.putNextEntry(new ZipEntry("resources.xml"));
        PrintWriter pw = new PrintWriter(zout);
        model.writeXML(pw);
        pw.flush();
        zout.closeEntry();
    } finally {
        zout.close();
    }
    p.setProgress(p.getProgress() + 1);
}

From source file:de.thorstenberger.examServer.webapp.action.PDFBulkExport.java

/**
 * Call the taskmodel-core-view application via http for every user, that has processed the given task. Streams a zip
 * archive with all rendered pdf files to <code>os</code>.
 *
 * @param tasklets/*from w w  w . ja  v  a  2  s .c  o m*/
 *          all tasklets to render
 * @param os
 *          the outputstream the zip shall be written to
 * @param pdfExporter
 * @throws IOException
 */
private void renderAllPdfs(final List<Tasklet> tasklets, final OutputStream os, final PDFExporter pdfExporter)
        throws IOException {
    // create zip with all generated pdfs
    final ZipOutputStream zos = new ZipOutputStream(os);

    // fetch pdf for every user/tasklet
    // render a pdf for every user that has a tasklet for the current task
    for (final Tasklet tasklet : tasklets) {
        final String userId = tasklet.getUserId();

        if (!tasklet.hasOrPassedStatus(Status.INPROGRESS)) {
            log.info(String.format("Skipping PDF for user %s, last try has no contents.", userId));
            continue;
        }
        log.debug("exporting pdf for " + userId);

        // add new zipentry (for next pdf)
        if (!addGeneratedPDFS(tasklet, userId, zos)) {
            final String filename = userId + ".pdf";
            final ZipEntry ze = new ZipEntry(filename);
            zos.putNextEntry(ze);
            // fetch the generated pdf from taskmodel-core-view
            pdfExporter.renderPdf(tasklet, filename, zos);
            // close this zipentry
            zos.closeEntry();
        }
    }
    zos.close();
}

From source file:com.seleniumtests.util.FileUtility.java

/**
 * Create a zip file from list of files to a temp directory. They will be added at the root of zip file
 * @param files//from   w w  w. ja  v a 2  s. co  m
 * @return the zipped file
 * @throws IOException
 */
public static File createZipArchiveFromFiles(List<File> files) throws IOException {
    final File zipArchive = File.createTempFile("temp_zip_", ".zip");
    try (final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipArchive))) {
        for (File f : files) {
            if (!f.exists()) {
                logger.warn(String.format("File %s does not exist", f.getName()));
                continue;
            }
            ZipEntry e = new ZipEntry(f.getName());
            out.putNextEntry(e);
            IOUtils.write(FileUtils.readFileToByteArray(f), out);
            out.closeEntry();
        }
    }
    return zipArchive;
}

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

private String firmarImagen(int fileName) throws IOException {

    String result = "";
    try {//from ww  w . j  av a 2s. c  om
        Path currentRelativePath = Paths.get("");
        String s = currentRelativePath.toAbsolutePath().toString();
        String theFolder = s + "/" + "archivos";

        FileOutputStream fos = new FileOutputStream(userFolderPath + "/" + Integer.toString(fileName) + ".zip");
        ZipOutputStream zos = new ZipOutputStream(fos);

        String file1Name = theFolder + "/" + Integer.toString(fileName) + ".jpg";
        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(fileName) + ".zip");
        byte[] data = Files.readAllBytes(path);
        byte[] byteArray = Base64.encodeBase64(data);
        String b64 = new String(byteArray);

        result = firma(b64, Integer.toString(fileName), "pruebita");
        System.out.println("User : " + idSimulatedUser + " ENVIADO");
        nFilesSend++;

    } catch (FileNotFoundException ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (WriterException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "http://" + result;
}