List of usage examples for java.util.zip ZipOutputStream ZipOutputStream
public ZipOutputStream(OutputStream out)
From source file:ZipTransformTest.java
public void testByteArrayTransformerInStream() throws IOException { final String name = "foo"; final byte[] contents = "bar".getBytes(); File file1 = File.createTempFile("temp", null); File file2 = File.createTempFile("temp", null); try {/* www . j a va2 s . c o m*/ // Create the ZIP file ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1)); try { zos.putNextEntry(new ZipEntry(name)); zos.write(contents); zos.closeEntry(); } finally { IOUtils.closeQuietly(zos); } // Transform the ZIP file FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(file1); out = new FileOutputStream(file2); ZipUtil.transformEntry(in, name, new ByteArrayZipEntryTransformer() { protected byte[] transform(ZipEntry zipEntry, byte[] input) throws IOException { String s = new String(input); assertEquals(new String(contents), s); return s.toUpperCase().getBytes(); } }, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } // Test the ZipUtil byte[] actual = ZipUtil.unpackEntry(file2, name); assertNotNull(actual); assertEquals(new String(contents).toUpperCase(), new String(actual)); } finally { FileUtils.deleteQuietly(file1); FileUtils.deleteQuietly(file2); } }
From source file:controller.GaleriaController.java
@br.com.caelum.vraptor.Path("galeria/zipGaleria/{galeriaId}") public Download zipGaleria(long galeriaId) { validator.ensure(sessao.getIdsPermitidosDeGalerias().contains(galeriaId), new SimpleMessage("galeria", "Acesso negado")); Galeria galeria = new Galeria(); galeria.setId(galeriaId);/*from ww w . java 2 s. com*/ List<Imagem> imagens = imagemDao.listByGaleria(galeria); validator.addIf(imagens == null || imagens.isEmpty(), new SimpleMessage("galeria", "Galeria vazia")); validator.onErrorRedirectTo(UsuarioController.class).viewGaleria(galeriaId); List<Path> paths = new ArrayList<>(); for (Imagem imagem : imagens) { String realPath = servletContext.getRealPath("/"); java.nio.file.Path imagemPath = new File(realPath + "/" + UPLOAD_DIR + "/" + imagem.getFileName()) .toPath(); paths.add(imagemPath); } byte buffer[] = new byte[2048]; try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos)) { zos.setMethod(ZipOutputStream.DEFLATED); zos.setLevel(5); for (Path path : paths) { try (FileInputStream fis = new FileInputStream(path.toFile()); BufferedInputStream bis = new BufferedInputStream(fis)) { String pathFileName = path.getFileName().toString(); zos.putNextEntry(new ZipEntry(pathFileName)); int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { zos.write(buffer, 0, bytesRead); } zos.closeEntry(); zos.flush(); } catch (IOException e) { result.include("mensagem", "Erro no download do zip"); result.forwardTo(UsuarioController.class).viewGaleria(galeriaId); return null; } } zos.finish(); byte[] zip = baos.toByteArray(); Download download = new ByteArrayDownload(zip, "application/zip", sessao.getUsuario().getNome() + ".zip"); return download; //zipDownload = new ZipDownload(sessao.getUsuario().getNome() + ".zip", paths); //return zipDownloadBuilder.build(); } catch (IOException e) { result.include("mensagem", "Erro no download do zip"); result.forwardTo(UsuarioController.class).viewGaleria(galeriaId); return null; } }
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: /*//from ww w . j av a 2 s . 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:ServerJniTest.java
@Test public void testDocumentRoot() throws Exception { File dir = null;/*from w ww.j a v a 2 s. c om*/ long handle = 0; try { dir = Files.createTempDir(); // prepare data FileUtils.writeStringToFile(new File(dir, "test.txt"), STATIC_FILE_DATA); FileUtils.writeStringToFile(new File(dir, "foo.boo"), STATIC_FILE_DATA); File zipFile = new File(dir, "test.zip"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipper = new ZipOutputStream(baos); zipper.putNextEntry(new ZipEntry("test/zipped.txt")); zipper.write(STATIC_ZIP_DATA.getBytes("UTF-8")); zipper.close(); FileUtils.writeByteArrayToFile(zipFile, baos.toByteArray()); String sout = wiltoncall("server_create", GSON.toJson(ImmutableMap.builder() .put("views", TestGateway.views()).put("tcpPort", TCP_PORT) .put("documentRoots", ImmutableList.builder().add(ImmutableMap.builder().put("resource", "/static/files") .put("dirPath", dir.getAbsolutePath()) .put("mimeTypes", ImmutableList.builder() .add(ImmutableMap.builder().put("extension", "boo") .put("mime", "text/x-boo").build()) .build()) .build()) .add(ImmutableMap.builder().put("resource", "/static") .put("zipPath", zipFile.getAbsolutePath()) .put("zipInnerPrefix", "test/").build()) .build()) .build())); Map<String, Long> shamap = GSON.fromJson(sout, LONG_MAP_TYPE); handle = shamap.get("serverHandle"); assertEquals(HELLO_RESP, httpGet(ROOT_URL + "hello")); // deliberated repeated requests assertEquals(STATIC_FILE_DATA, httpGet(ROOT_URL + "static/files/test.txt")); assertEquals(STATIC_FILE_DATA, httpGet(ROOT_URL + "static/files/test.txt")); assertEquals(STATIC_FILE_DATA, httpGet(ROOT_URL + "static/files/test.txt")); assertEquals("text/plain", httpGetHeader(ROOT_URL + "static/files/test.txt", "Content-Type")); assertEquals(STATIC_FILE_DATA, httpGet(ROOT_URL + "static/files/foo.boo")); assertEquals("text/x-boo", httpGetHeader(ROOT_URL + "static/files/foo.boo", "Content-Type")); assertEquals(STATIC_ZIP_DATA, httpGet(ROOT_URL + "static/zipped.txt")); assertEquals(STATIC_ZIP_DATA, httpGet(ROOT_URL + "static/zipped.txt")); assertEquals(STATIC_ZIP_DATA, httpGet(ROOT_URL + "static/zipped.txt")); } finally { stopServerQuietly(handle); deleteDirQuietly(dir); } }
From source file:com.orange.mmp.midlet.MidletManager.java
/** * Builds a ZIP archive with the appropriate name * @param mobile/*from w ww .ja va2 s . com*/ * @param signMidlet * @param output * @return The ZIP filename * @throws IOException * @throws MMPException */ public String computeZip(Mobile mobile, Boolean signMidlet, OutputStream output) throws IOException, MMPException { //Compute Zip ZipOutputStream zipOS = new ZipOutputStream(output); try { //Get default service Service service = ServiceManager.getInstance().getDefaultService(); //Create fake ticket DeliveryTicket ticket = new DeliveryTicket(); ticket.setServiceId(service.getId()); //Get navigation widget (main scene) Widget appWidget = WidgetManager.getInstance().getWidget(ticket.getServiceId(), mobile.getBranchId()); if (appWidget == null) appWidget = WidgetManager.getInstance().getWidget(ticket.getServiceId()); if (appWidget == null) throw new IOException("application " + ticket.getServiceId() + " not found"); ByteArrayOutputStream tmpOS = null; //Add JAD zipOS.putNextEntry( new ZipEntry(appWidget.getName() + com.orange.mmp.midlet.Constants.JAD_FILE_EXTENSION)); tmpOS = getJad(ticket.getId(), mobile, signMidlet, service); tmpOS.writeTo(zipOS); zipOS.closeEntry(); //Add JAR zipOS.putNextEntry( new ZipEntry(appWidget.getName() + com.orange.mmp.midlet.Constants.JAR_FILE_EXTENSION)); tmpOS = getJar(service.getId(), mobile, signMidlet); tmpOS.writeTo(zipOS); zipOS.closeEntry(); zipOS.flush(); String[] tmpVersion = appWidget.getVersion().toString().split("\\."); if (tmpVersion.length > 2) { return appWidget.getName() + "_V" + tmpVersion[0] + "." + tmpVersion[1] + appWidget.getBranchId() + "." + tmpVersion[2]; } return appWidget.getName() + "_V" + appWidget.getVersion() + "_" + appWidget.getBranchId(); } finally { try { zipOS.close(); } catch (IOException ioe) { } } }
From source file:csns.web.controller.DownloadController.java
@RequestMapping(value = "/download", params = "assignmentId") public String downloadAssignmentFiles(@RequestParam Long assignmentId, HttpServletResponse response, ModelMap models) throws IOException { Assignment assignment = assignmentDao.getAssignment(assignmentId); String name = assignment.getAlias().replaceAll(replaceRegex, "_"); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=" + name + ".zip"); ZipOutputStream zip = new ZipOutputStream(response.getOutputStream()); for (Submission submission : assignment.getSubmissions()) { String dir = submission.getStudent().getLastName() + "." + submission.getStudent().getFirstName(); addToZip(zip, dir, submission.getFiles()); }//from w w w .j a va 2s.co m zip.close(); return null; }
From source file:com.amalto.core.jobox.util.JoboxUtil.java
public static void zip(File file, String zipFilePath) throws IOException { if (zipFilePath == null) { zipFilePath = file.getAbsolutePath() + ".zip"; //$NON-NLS-1$ }/* ww w . j ava 2 s . c o m*/ ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath)); try { if (file.isDirectory()) { JoboxUtil.zipContents(file, file.getName(), zos); } else { try { JoboxUtil.zip(file, file.getName(), zos); } catch (Exception e) { throw new JoboxException(e); } } } finally { zos.close(); } }
From source file:au.org.ala.biocache.service.DownloadService.java
/** * Writes the supplied download to the supplied output stream. It will include all the appropriate citations etc. * /*from ww w .j ava 2s . c o m*/ * @param dd * @param requestParams * @param ip * @param out * @param includeSensitive * @param fromIndex * @throws Exception */ private void writeQueryToStream(DownloadDetailsDTO dd, DownloadRequestParams requestParams, String ip, OutputStream out, boolean includeSensitive, boolean fromIndex, boolean limit) throws Exception { String filename = requestParams.getFile(); String originalParams = requestParams.toString(); //Use a zip output stream to include the data and citation together in the download ZipOutputStream zop = new ZipOutputStream(out); String suffix = requestParams.getFileType().equals("shp") ? "zip" : requestParams.getFileType(); zop.putNextEntry(new java.util.zip.ZipEntry(filename + "." + suffix)); //put the facets if ("all".equals(requestParams.getQa())) { requestParams.setFacets(new String[] { "assertions", "data_resource_uid" }); } else { requestParams.setFacets(new String[] { "data_resource_uid" }); } Map<String, Integer> uidStats = null; try { if (fromIndex) uidStats = searchDAO.writeResultsFromIndexToStream(requestParams, zop, includeSensitive, dd, limit); else uidStats = searchDAO.writeResultsToStream(requestParams, zop, 100, includeSensitive, dd); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { unregisterDownload(dd); } zop.closeEntry(); //add the Readme for the data field descriptions zop.putNextEntry(new java.util.zip.ZipEntry("README.html")); zop.write(("For more information about the fields that are being downloaded please consult <a href='" + dataFieldDescriptionURL + "'>Download Fields</a>.").getBytes()); //add the readme for the Shape file header mappings if necessary if (dd.getHeaderMap() != null) { zop.putNextEntry(new java.util.zip.ZipEntry("Shape-README.html")); zop.write( ("The name of features is limited to 10 characters. Listed below are the mappings of feature name to download field:") .getBytes()); zop.write(("<table><td><b>Feature</b></td><td><b>Download Field<b></td>").getBytes()); for (String key : dd.getHeaderMap().keySet()) { zop.write(("<tr><td>" + key + "</td><td>" + dd.getHeaderMap().get(key) + "</td></tr>").getBytes()); } zop.write(("</table>").getBytes()); //logger.debug("JSON::: " + objectMapper.writeValueAsString(dd)); } //Add the data citation to the download if (uidStats != null && !uidStats.isEmpty() && citationsEnabled) { //add the citations for the supplied uids zop.putNextEntry(new java.util.zip.ZipEntry("citation.csv")); try { getCitations(uidStats, zop, requestParams.getSep(), requestParams.getEsc()); } catch (Exception e) { logger.error(e.getMessage(), e); } zop.closeEntry(); } else { logger.debug("Not adding citation. Enabled: " + citationsEnabled + " uids: " + uidStats); } zop.flush(); zop.close(); //now construct the sourceUrl for the log event String sourceUrl = originalParams.contains("qid:") ? webservicesRoot + "?" + requestParams.toString() : webservicesRoot + "?" + originalParams; //logger.debug("UID stats : " + uidStats); //log the stats to ala logger LogEventVO vo = new LogEventVO(1002, requestParams.getReasonTypeId(), requestParams.getSourceTypeId(), requestParams.getEmail(), requestParams.getReason(), ip, null, uidStats, sourceUrl); logger.log(RestLevel.REMOTE, vo); }
From source file:org.messic.server.api.APISong.java
@Transactional public void getSongsZip(User user, List<Long> desiredSongs, OutputStream os) throws IOException { ZipOutputStream zos = new ZipOutputStream(os); // level - the compression level (0-9) zos.setLevel(9);//from ww w. j a v a 2 s . c o m HashMap<String, String> songs = new HashMap<String, String>(); for (Long songSid : desiredSongs) { MDOSong song = daoSong.get(user.getLogin(), songSid); if (song != null) { // add file // extract the relative name for entry purpose String entryName = song.getLocation(); if (songs.get(entryName) == null) { // not repeated songs.put(entryName, "ok"); ZipEntry ze = new ZipEntry(entryName); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(song.calculateAbsolutePath(daoSettings.getSettings())); int len; byte buffer[] = new byte[1024]; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); } } } zos.close(); }
From source file:it.reply.orchestrator.service.ToscaServiceImpl.java
/** * Utility to zip an inputStream.//from w w w . java 2s .c om * */ public static void zip(@Nonnull InputStream fileStream, @Nonnull Path outputPath) throws IOException { FileUtil.touch(outputPath); try (ZipOutputStream zipOutputStream = new ZipOutputStream( new BufferedOutputStream(Files.newOutputStream(outputPath)))) { zipOutputStream.putNextEntry(new ZipEntry("definition.yml")); ByteStreams.copy(fileStream, zipOutputStream); zipOutputStream.closeEntry(); zipOutputStream.flush(); } }