Example usage for java.util.zip ZipOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

From source file:com.mweagle.tereus.commands.evaluation.common.LambdaUtils.java

public String createFunction(final String logicalResourceName, final String lambdaSourceRoot,
        final String bucketName, final String s3KeyName)
        throws IOException, InterruptedException, NoSuchAlgorithmException {

    // Build it, zip it, and upload it.  Return:
    /*/*w w  w.  j  av  a 2s.c  om*/
    {
      "S3Bucket" : String,
      "S3Key" : String,
      "S3ObjectVersion" : "TODO - not yet implemented"
    }
    */
    this.logger.info("Looking for source {} relative to {}", lambdaSourceRoot, templateRoot);
    final String lambdaDir = this.templateRoot.resolve(lambdaSourceRoot).normalize().toAbsolutePath()
            .toString();
    final Path lambdaPath = Paths.get(lambdaDir);

    // Build command?
    final Optional<String> buildCommand = lambdaBuildCommand(lambdaDir);
    if (buildCommand.isPresent()) {
        this.logger.info("{} Lambda source: {}", buildCommand.get(), lambdaDir);
        try {
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec(buildCommand.get(), null, new File(lambdaDir));
            this.logger.info("Waiting for `{}` to complete", buildCommand.get());

            final int buildExitCode = pr.waitFor();
            if (0 != buildExitCode) {
                logger.error("Failed to `{}`: {}", buildCommand.get(), buildExitCode);
                throw new IOException(buildCommand.get() + " failed for: " + lambdaDir);
            }
        } catch (Exception ex) {
            final String processPath = System.getenv("PATH");
            this.logger.error("`{}` failed. Confirm that PATH contains the required executable.",
                    buildCommand.get());
            this.logger.error("$PATH: {}", processPath);
            throw ex;
        }
    } else {
        this.logger.debug("No additional Lambda build file detected");
    }

    Path lambdaSource = null;
    boolean cleanupLambdaSource = false;
    MessageDigest md = MessageDigest.getInstance("SHA-256");

    try {
        final BiPredicate<Path, java.nio.file.attribute.BasicFileAttributes> matcher = (path, fileAttrs) -> {
            final String fileExtension = com.google.common.io.Files.getFileExtension(path.toString());
            return (fileExtension.toLowerCase().compareTo("jar") == 0);
        };

        // Find/compress the Lambda source
        // If there is a JAR file in the source root, then use that for the upload
        List<Path> jarFiles = Files.find(lambdaPath, 1, matcher).collect(Collectors.toList());

        if (!jarFiles.isEmpty()) {
            Preconditions.checkArgument(jarFiles.size() == 1, "More than 1 JAR file detected in directory: {}",
                    lambdaDir);
            lambdaSource = jarFiles.get(0);
            md.update(Files.readAllBytes(lambdaSource));
        } else {
            lambdaSource = Files.createTempFile("lambda-", ".zip");
            this.logger.info("Zipping lambda source code: {}", lambdaSource.toString());
            final FileOutputStream os = new FileOutputStream(lambdaSource.toFile());
            final ZipOutputStream zipOS = new ZipOutputStream(os);
            createStableZip(zipOS, lambdaPath, lambdaPath, md);
            zipOS.close();
            this.logger.info("Compressed filesize: {} bytes", lambdaSource.toFile().length());
            cleanupLambdaSource = true;
        }

        // Upload it
        final String sourceHash = Hex.encodeHexString(md.digest());
        this.logger.info("Lambda source hash: {}", sourceHash);
        if (!s3KeyName.isEmpty()) {
            this.logger.warn(
                    "User supplied S3 keyname overrides content-addressable name. Automatic updates disabled.");
        }
        final String keyName = !s3KeyName.isEmpty() ? s3KeyName
                : String.format("%s-lambda-%s.%s", logicalResourceName, sourceHash,
                        com.google.common.io.Files.getFileExtension(lambdaSource.toString()));
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("S3Bucket", new JsonPrimitive(bucketName));
        jsonObject.add("S3Key", new JsonPrimitive(keyName));

        // Upload it to s3...
        final FileInputStream fis = new FileInputStream(lambdaSource.toFile());
        try (S3Resource resource = new S3Resource(bucketName, keyName, fis,
                Optional.of(lambdaSource.toFile().length()))) {
            this.logger.info("Source payload S3 URL: {}", resource.getS3Path());

            if (resource.exists()) {
                this.logger.info("Source {} already uploaded to S3", keyName);
            } else if (!this.dryRun) {
                Optional<String> result = resource.upload();
                this.logger.info("Uploaded Lambda source to: {}", result.get());
                resource.setReleased(true);
            } else {
                this.logger.info("Dry run requested (-n/--noop). Lambda payload upload bypassed.");
            }
        }
        final Gson serializer = new GsonBuilder().disableHtmlEscaping().enableComplexMapKeySerialization()
                .create();
        return serializer.toJson(jsonObject);
    } finally {
        if (cleanupLambdaSource) {
            this.logger.debug("Deleting temporary file: {}", lambdaSource.toString());
            Files.deleteIfExists(lambdaSource);
        }
    }
}

From source file:org.fenixedu.start.controller.StartController.java

private ResponseEntity<byte[]> build(Map<String, byte[]> project, ProjectRequest request) throws IOException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(stream);

    for (Map.Entry<String, byte[]> mapEntry : project.entrySet()) {
        ZipEntry entry = new ZipEntry(request.getArtifactId() + "/" + mapEntry.getKey());
        zip.putNextEntry(entry);/*from   w w  w  .j a  v  a2 s. c o m*/
        zip.write(mapEntry.getValue());
        zip.closeEntry();
    }

    zip.close();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/zip");
    headers.add("Content-Disposition", "attachment; filename=\"" + request.getArtifactId() + ".zip\"");
    return new ResponseEntity<>(stream.toByteArray(), headers, HttpStatus.OK);
}

From source file:org.pdfgal.pdfgalweb.utils.impl.ZipUtilsImpl.java

@Override
public String zipFiles(final List<String> urisList, final String fileName)
        throws FileNotFoundException, IOException {

    String generatedFileName = null;

    if (CollectionUtils.isNotEmpty(urisList) && StringUtils.isNotEmpty(fileName)) {

        // Autogeneration of file name
        generatedFileName = this.fileUtils.getAutogeneratedName(fileName + ".zip");

        // ZIP file is created.
        final FileOutputStream fos = new FileOutputStream(generatedFileName);
        final ZipOutputStream zos = new ZipOutputStream(fos);

        // Files are added to ZIP.
        for (final String uri : urisList) {
            if (StringUtils.isNotEmpty(uri)) {
                this.addToZipFile(uri, zos, fileName);
            }/*w  w  w .  j  a v  a  2s  .  c om*/
        }

        zos.close();
        fos.close();
    }

    return generatedFileName;
}

From source file:es.urjc.mctwp.bbeans.research.image.DownloadBean.java

public String accDownloadPatientImages() {
    LoadPatient cmd = (LoadPatient) getCommand(LoadPatient.class);
    cmd.setPatientId(getSession().getPatient().getCode());
    cmd = (LoadPatient) runCommand(cmd);

    if (cmd != null && cmd.getResult() != null) {
        Patient patient = cmd.getResult();

        try {/*  w ww .j a va 2  s.  co m*/
            if (patient.getStudies() != null) {
                ZipOutputStream zos = prepareZOS(patientHeader + patient.getCode());
                downloadPatienImages(patient, zos, null);
                if (zos != null)
                    zos.close();
                completeResponse();
            }
        } catch (IOException e) {
            setErrorMessage(e.getLocalizedMessage());
            e.printStackTrace();
        }
    }

    return null;
}

From source file:com.ftb2om2.util.Zipper.java

public void createOSZ(String mp3Path, String outputPath, List<Difficulty> difficulty) throws IOException {
    FileOutputStream fos = new FileOutputStream(
            outputPath + "\\" + FilenameUtils.getBaseName(mp3Path) + ".osz");
    ZipOutputStream zos = new ZipOutputStream(fos);

    addToZip(mp3Path, "Audio.mp3", zos);

    difficulty.forEach(file -> {/*from   w  ww  .ja v  a 2s .c  om*/
        try {
            addToZip(outputPath + "\\" + file.getDifficultyName() + ".osu", file.getDifficultyName() + ".osu",
                    zos);
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    });

    zos.close();
    fos.close();
}

From source file:com.solidmaps.webapp.service.ApostilamentosServiceImpl.java

private FileSystemResource generateZip(CompanyEntity companyEntity) {

    String fileName = FILE_PATH + "Apostilamento-" + companyEntity.getCnpj() + ".zip";
    FileOutputStream fos = null;//from w ww  .j a v  a  2s . co  m

    try {

        fos = new FileOutputStream(fileName);
        ZipOutputStream zos = new ZipOutputStream(fos);
        this.addToZip(zos, fileFederal);
        this.addToZip(zos, fileCivil);
        this.addToZip(zos, fileExercito);

        zos.closeEntry();
        zos.close();

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

    FileSystemResource fileSystemResource = new FileSystemResource(fileName);

    return fileSystemResource;
}

From source file:nl.nn.adapterframework.webcontrol.action.BrowseExecute.java

protected boolean performAction(Adapter adapter, ReceiverBase receiver, String action, IMessageBrowser mb,
        String messageId, String selected[], HttpServletRequest request, HttpServletResponse response) {
    PlatformTransactionManager transactionManager = ibisManager.getTransactionManager();
    log.debug("retrieved transactionManager [" + ClassUtils.nameOf(transactionManager) + "]["
            + transactionManager + "] from ibismanager [" + ibisManager + "]");

    log.debug("performing action [" + action + "]");
    try {//  www.j  a  va  2 s  .  c o  m

        if ("deletemessage".equalsIgnoreCase(action)) {
            if (StringUtils.isNotEmpty(messageId)) {
                deleteMessage(mb, messageId, transactionManager);
            }
        }

        if ("delete selected".equalsIgnoreCase(action)) {
            for (int i = 0; i < selected.length; i++) {
                try {
                    deleteMessage(mb, selected[i], transactionManager);
                } catch (Throwable e) {
                    error(", ", "errors.generic", "Could not delete message with id [" + selected[i] + "]", e);
                }
            }
        }

        if ("resendmessage".equalsIgnoreCase(action)) {
            if (StringUtils.isNotEmpty(messageId)) {
                receiver.retryMessage(messageId);
            }
        }

        if ("resend selected".equalsIgnoreCase(action)) {
            for (int i = 0; i < selected.length; i++) {
                try {
                    receiver.retryMessage(selected[i]);
                } catch (Throwable e) {
                    error(", ", "errors.generic", "Could not resend message with id [" + selected[i] + "]", e);
                }
            }
        }

        if ("exportmessage".equalsIgnoreCase(action)) {
            String filename = "messages-" + AppConstants.getInstance().getProperty("instance.name", "") + "-"
                    + Misc.getHostname() + ".zip";
            if (StringUtils.isNotEmpty(messageId)) {
                if (Download.redirectForDownload(request, response, "application/x-zip-compressed", filename)) {
                    return true;
                }
                ZipOutputStream zipOutputStream = StreamUtil.openZipDownload(response, filename);
                exportMessage(mb, messageId, receiver, zipOutputStream);
                zipOutputStream.close();
                return true;
            }
        }

        if ("export selected".equalsIgnoreCase(action)) {
            String filename = "messages-" + AppConstants.getInstance().getProperty("instance.name", "") + "-"
                    + Misc.getHostname() + ".zip";
            if (Download.redirectForDownload(request, response, "application/x-zip-compressed", filename)) {
                return true;
            }
            ZipOutputStream zipOutputStream = StreamUtil.openZipDownload(response, filename);
            for (int i = 0; i < selected.length; i++) {
                exportMessage(mb, selected[i], receiver, zipOutputStream);
            }
            zipOutputStream.close();
            return true;
        }

    } catch (Throwable e) {
        error(", ", "errors.generic", "Error occurred performing action [" + action + "]", e);
    }
    return false;
}

From source file:eu.europa.ejusticeportal.dss.controller.action.DownloadSignedPdf.java

/**
 * @param sf/*from  w  w  w .java2s . c o  m*/
 * @param response
 * @throws IOException 
 */
private void writeZip(SignedForm sf, HttpServletResponse response, String fileName) throws IOException {
    ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
    ZipEntry ze = new ZipEntry(fileName);
    zos.putNextEntry(ze);
    zos.write(sf.getDocument());
    ze = new ZipEntry(fileName + ".xml");
    zos.putNextEntry(ze);
    zos.write(sf.getDetachedSignature());
    zos.closeEntry();
    zos.close();
}

From source file:es.urjc.mctwp.bbeans.research.image.DownloadBean.java

public String accDownloadTaskImages() {
    Task tsk = getSession().getTask();//from www  . j a va2 s . co  m

    try {
        if (tsk != null) {

            //Get images of task
            FindImagesByTask cmd = (FindImagesByTask) getCommand(FindImagesByTask.class);
            cmd.setTask(tsk);
            cmd = (FindImagesByTask) runCommand(cmd);

            if (cmd != null && cmd.getResult() != null) {
                ZipOutputStream zos = prepareZOS(taskHeader + tsk.getCode());
                downloadImages(cmd.getResult(), zos, taskHeader + tsk.getCode());
                if (zos != null)
                    zos.close();
                completeResponse();
            }
        }
    } catch (IOException e) {
        setErrorMessage(e.getLocalizedMessage());
        e.printStackTrace();
    }

    return null;
}

From source file:com.c4om.autoconf.ulysses.configanalyzer.packager.ZipConfigurationPackager.java

/**
 * This implementation compresses files into a ZIP file
 * @see com.c4om.autoconf.ulysses.interfaces.configanalyzer.packager.CompressedFileConfigurationPackager#compressFiles(java.io.File, java.util.List, java.io.File)
 */// w ww. ja v a  2  s.  co m
@Override
protected void compressFiles(File actualRootFolder, List<String> entries, File zipFile)
        throws FileNotFoundException, IOException {
    //We use the FileUtils method so that necessary directories are automatically created.
    FileOutputStream zipFOS = FileUtils.openOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(zipFOS);
    for (String entry : entries) {
        ZipEntry ze = new ZipEntry(entry);
        zos.putNextEntry(ze);
        FileInputStream sourceFileIN = new FileInputStream(
                actualRootFolder.getAbsolutePath() + File.separator + entry);
        IOUtils.copy(sourceFileIN, zos);
        sourceFileIN.close();
    }
    zos.closeEntry();
    zos.close();
}