List of usage examples for java.util.zip ZipOutputStream write
public void write(int b) throws IOException
From source file:org.cloudfoundry.tools.io.zip.ZipArchiveTest.java
@Before public void setup() throws Exception { MockitoAnnotations.initMocks(this); this.zipFile = this.temporaryFolder.newFile("zipfile.zip"); ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(this.zipFile)); try {//from www.j ava2s .c o m zipOutputStream.putNextEntry(new ZipEntry("/a/b/c.txt")); zipOutputStream.write("c".getBytes()); zipOutputStream.putNextEntry(new ZipEntry("/d/")); zipOutputStream.putNextEntry(new ZipEntry("/d/e/")); zipOutputStream.putNextEntry(new ZipEntry("/d/f/")); zipOutputStream.putNextEntry(new ZipEntry("/d/f/g.txt")); zipOutputStream.putNextEntry(new ZipEntry("/d/f/h/")); zipOutputStream.write("g".getBytes()); } finally { zipOutputStream.close(); } this.zip = new ZipArchive(new LocalFolder(this.zipFile.getParentFile()).getFile(this.zipFile.getName())); }
From source file:com.espringtran.compressor4j.processor.Bzip2Processor.java
/** * Compress data// www. ja v a 2s .com * * @param fileCompressor * FileCompressor object * @return * @throws Exception */ @Override public byte[] compressData(FileCompressor fileCompressor) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BZip2CompressorOutputStream cos = new BZip2CompressorOutputStream(baos); ZipOutputStream zos = new ZipOutputStream(cos); try { zos.setLevel(fileCompressor.getLevel().getValue()); zos.setMethod(ZipOutputStream.DEFLATED); zos.setComment(fileCompressor.getComment()); for (BinaryFile binaryFile : fileCompressor.getMapBinaryFile().values()) { zos.putNextEntry(new ZipEntry(binaryFile.getDesPath())); zos.write(binaryFile.getData()); zos.closeEntry(); } zos.flush(); zos.finish(); } catch (Exception e) { FileCompressor.LOGGER.error("Error on compress data", e); } finally { zos.close(); cos.close(); baos.close(); } return baos.toByteArray(); }
From source file:com.espringtran.compressor4j.processor.GzipProcessor.java
/** * Compress data/*from w ww . ja v a 2s. c om*/ * * @param fileCompressor * FileCompressor object * @return * @throws Exception */ @Override public byte[] compressData(FileCompressor fileCompressor) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GzipCompressorOutputStream cos = new GzipCompressorOutputStream(baos); ZipOutputStream zos = new ZipOutputStream(cos); try { zos.setLevel(fileCompressor.getLevel().getValue()); zos.setMethod(ZipOutputStream.DEFLATED); zos.setComment(fileCompressor.getComment()); for (BinaryFile binaryFile : fileCompressor.getMapBinaryFile().values()) { zos.putNextEntry(new ZipEntry(binaryFile.getDesPath())); zos.write(binaryFile.getData()); zos.closeEntry(); } zos.flush(); zos.finish(); } catch (Exception e) { FileCompressor.LOGGER.error("Error on compress data", e); } finally { zos.close(); cos.close(); baos.close(); } return baos.toByteArray(); }
From source file:com.googlecode.dex2jar.v3.Dex2jar.java
private void saveTo(byte[] data, String name, Object dist) throws IOException { if (dist instanceof ZipOutputStream) { ZipOutputStream zos = (ZipOutputStream) dist; ZipEntry entry = new ZipEntry(name + ".class"); int i = name.lastIndexOf('/'); if (i > 0) { check(name.substring(0, i), zos); }// w ww. ja va2 s .c o m zos.putNextEntry(entry); zos.write(data); zos.closeEntry(); } else { File dir = (File) dist; FileUtils.writeByteArrayToFile(new File(dir, name + ".class"), data); } }
From source file:com.replaymod.sponge.recording.AbstractRecorder.java
@Override public void endRecording(OutputStream out, ReplayMetaData metaData) throws IllegalStateException, IOException { if (metaData == null) { Preconditions.checkState(rawOutputs.remove(out), "Specified output is unknown or meta data is missing."); out.flush();/*from w w w.ja v a2 s .c o m*/ out.close(); } else { ZipOutputStream zipOut = outputs.remove(out); if (zipOut == null) { throw new IllegalStateException("Specified output is unknown or contains raw data."); } zipOut.closeEntry(); zipOut.putNextEntry(new ZipEntry("metaData.json")); zipOut.write(toJson(metaData).getBytes()); zipOut.closeEntry(); zipOut.flush(); zipOut.close(); } }
From source file:ServerJniTest.java
@Test public void testDocumentRoot() throws Exception { File dir = null;/*from ww w.ja va 2 s. co m*/ 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:be.neutrinet.ispng.vpn.api.VPNClientConfig.java
@Post public Representation getConfig(Map<String, String> data) { try {/* w ww. jav a2 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:io.lightlink.excel.StreamingExcelTransformer.java
public void doExport(InputStream template, OutputStream out, ExcelStreamVisitor visitor) throws IOException { try {/*from w ww . java 2s . c om*/ ZipInputStream zipIn = new ZipInputStream(template); ZipOutputStream zipOut = new ZipOutputStream(out); ZipEntry entry; Map<String, byte[]> sheets = new HashMap<String, byte[]>(); while ((entry = zipIn.getNextEntry()) != null) { String name = entry.getName(); if (name.startsWith("xl/sharedStrings.xml")) { byte[] bytes = IOUtils.toByteArray(zipIn); zipOut.putNextEntry(new ZipEntry(name)); zipOut.write(bytes); sharedStrings = processSharedStrings(bytes); } else if (name.startsWith("xl/worksheets/sheet")) { byte[] bytes = IOUtils.toByteArray(zipIn); sheets.put(name, bytes); } else if (name.equals("xl/calcChain.xml")) { // skip this file, let excel recreate it } else if (name.equals("xl/workbook.xml")) { zipOut.putNextEntry(new ZipEntry(name)); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); Writer writer = new OutputStreamWriter(zipOut, "UTF-8"); byte[] bytes = IOUtils.toByteArray(zipIn); saxParser.parse(new ByteArrayInputStream(bytes), new WorkbookTemplateHandler(writer)); writer.flush(); } else { zipOut.putNextEntry(new ZipEntry(name)); IOUtils.copy(zipIn, zipOut); } } for (Map.Entry<String, byte[]> sheetEntry : sheets.entrySet()) { String name = sheetEntry.getKey(); byte[] bytes = sheetEntry.getValue(); zipOut.putNextEntry(new ZipEntry(name)); processSheet(bytes, zipOut, visitor); } zipIn.close(); template.close(); zipOut.close(); out.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.toString(), e); } }
From source file:com.jd.survey.web.reports.ReportController.java
/** * Exports survey data to a comma delimited values file * @param surveyDefinitionId//from w w w .j a v a2 s .co m * @param principal * @param response */ @Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" }) @RequestMapping(value = "/{id}", params = "csv", produces = "text/html") public void surveyCSVExport(@PathVariable("id") Long surveyDefinitionId, Principal principal, HttpServletRequest httpServletRequest, HttpServletResponse response) { try { User user = userService.user_findByLogin(principal.getName()); if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); response.sendRedirect("../accessDenied"); //throw new AccessDeniedException("Unauthorized access attempt"); } String columnName; SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId); List<Map<String, Object>> surveys = reportDAO.getSurveyData(surveyDefinitionId); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append( "\"id\",\"Survey Name\",\"User Login\",\"Submission Date\",\"Creation Date\",\"Last Update Date\","); for (SurveyDefinitionPage page : surveyDefinition.getPages()) { for (Question question : page.getQuestions()) { if (question.getType().getIsMatrix()) { for (QuestionRowLabel questionRowLabel : question.getRowLabels()) { for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) { stringBuilder.append("\" p" + page.getOrder() + "q" + question.getOrder() + "r" + questionRowLabel.getOrder() + "c" + questionColumnLabel.getOrder() + "\","); } } continue; } if (question.getType().getIsMultipleValue()) { for (QuestionOption questionOption : question.getOptions()) { stringBuilder.append("\" p" + page.getOrder() + "q" + question.getOrder() + "o" + questionOption.getOrder() + "\","); } continue; } stringBuilder.append("\"p" + page.getOrder() + "q" + question.getOrder() + "\","); } } stringBuilder.deleteCharAt(stringBuilder.length() - 1); //delete the last comma stringBuilder.append("\n"); for (Map<String, Object> record : surveys) { stringBuilder.append(record.get("survey_id") == null ? "" : "\"" + record.get("survey_id").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("type_name") == null ? "" : "\"" + record.get("type_name").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("login") == null ? "" : "\"" + record.get("login").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("submission_date") == null ? "" : "\"" + record.get("creation_date").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("creation_date") == null ? "" : "\"" + record.get("last_update_date").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("last_update_date") == null ? "" : "\"" + record.get("last_update_date").toString().replace("\"", "\"\"") + "\","); for (SurveyDefinitionPage page : surveyDefinition.getPages()) { for (Question question : page.getQuestions()) { if (question.getType().getIsMatrix()) { for (QuestionRowLabel questionRowLabel : question.getRowLabels()) { for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) { columnName = "p" + page.getOrder() + "q" + question.getOrder() + "r" + questionRowLabel.getOrder() + "c" + questionColumnLabel.getOrder(); stringBuilder.append(record.get(columnName) == null ? "," : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\","); } } continue; } if (question.getType().getIsMultipleValue()) { for (QuestionOption questionOption : question.getOptions()) { columnName = "p" + page.getOrder() + "q" + question.getOrder() + "o" + questionOption.getOrder(); stringBuilder.append(record.get(columnName) == null ? "," : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\","); } continue; } columnName = "p" + page.getOrder() + "q" + question.getOrder(); stringBuilder.append(record.get(columnName) == null ? "," : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\","); } } stringBuilder.deleteCharAt(stringBuilder.length() - 1); //delete the last comma stringBuilder.append("\n"); } //Zip file manipulations Code ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipEntry zipentry; ZipOutputStream zipfile = new ZipOutputStream(bos); zipentry = new ZipEntry("survey" + surveyDefinition.getId() + ".csv"); zipfile.putNextEntry(zipentry); zipfile.write(stringBuilder.toString().getBytes("UTF-8")); zipfile.close(); //response.setContentType("text/html; charset=utf-8"); response.setContentType("application/octet-stream"); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); response.setHeader("Content-Disposition", "inline;filename=survey" + surveyDefinition.getId() + ".zip"); ServletOutputStream servletOutputStream = response.getOutputStream(); //servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8")); servletOutputStream.write(bos.toByteArray()); servletOutputStream.flush(); } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(e); } }
From source file:ee.ria.xroad.proxy.clientproxy.AsicContainerClientRequestProcessor.java
private void writeContainers(List<MessageRecord> requests, String queryId, AsicContainerNameGenerator nameGen, ZipOutputStream zos, String type) throws Exception { for (MessageRecord record : requests) { String filename = nameGen.getArchiveFilename(queryId, type); zos.putNextEntry(new ZipEntry(filename)); zos.write(record.toAsicContainer().getBytes()); zos.closeEntry();// w w w. j a va2 s. c o m } }