List of usage examples for java.util.zip ZipOutputStream close
public void close() throws IOException
From source file:com.matze5800.paupdater.Functions.java
public static void addFilesToExistingZip(File zipFile, File[] files) throws IOException { File tempFile = new File(Environment.getExternalStorageDirectory() + "/pa_updater", "temp_kernel.zip"); tempFile.delete();/*w ww . ja v a 2 s . c o m*/ boolean renameOk = zipFile.renameTo(tempFile); if (!renameOk) { throw new RuntimeException( "could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath()); } byte[] buf = new byte[1024]; ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile)); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = zin.getNextEntry(); while (entry != null) { String name = entry.getName(); boolean notInFiles = true; for (File f : files) { if (f.getName().equals(name)) { notInFiles = false; break; } } if (notInFiles) { out.putNextEntry(new ZipEntry(name)); int len; while ((len = zin.read(buf)) > 0) { out.write(buf, 0, len); } } entry = zin.getNextEntry(); } zin.close(); for (int i = 0; i < files.length; i++) { InputStream in = new FileInputStream(files[i]); out.putNextEntry(new ZipEntry(files[i].getName())); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); tempFile.delete(); }
From source file:ServerJniTest.java
@Test public void testDocumentRoot() throws Exception { File dir = null;//from w w w.ja v a 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:hd3gtv.embddb.network.DataBlock.java
byte[] getBytes(Protocol protocol) throws IOException { checkIfNotEmpty();/*from w w w .j a va2 s.c o m*/ ByteArrayOutputStream byte_array_out_stream = new ByteArrayOutputStream(Protocol.BUFFER_SIZE); DataOutputStream dos = new DataOutputStream(byte_array_out_stream); dos.write(Protocol.APP_SOCKET_HEADER_TAG); dos.writeInt(Protocol.VERSION); /** * Start header name */ dos.writeByte(0); byte[] request_name_data = request_name.getBytes(Protocol.UTF8); dos.writeInt(request_name_data.length); dos.write(request_name_data); /** * Start datas payload */ dos.writeByte(1); /** * Get datas from zip */ ZipOutputStream zos = new ZipOutputStream(dos); zos.setLevel(3); entries.forEach(entry -> { try { entry.toZip(zos); } catch (IOException e) { log.error("Can't add to zip", e); } }); zos.flush(); zos.finish(); zos.close(); dos.flush(); dos.close(); byte[] result = byte_array_out_stream.toByteArray(); if (log.isTraceEnabled()) { log.trace("Make raw datas for " + request_name + Hexview.LINESEPARATOR + Hexview.tracelog(result)); } return result; }
From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java
/** Compress the files in the backup folder for a project. * @param projectId The project ID/*from w w w .ja va 2 s . co m*/ * @throws IOException Any exception when reading/writing data. */ public static void compressBackupFolder(final String projectId) throws IOException { String backupPath = getBackupPath(projectId); if (!Files.isDirectory(Paths.get(backupPath))) { // No such directory, so nothing to do. return; } String projectSlug = makeSlug(projectId); // The name of the ZIP file that does/will contain all // backups for this project. Path zipFilePath = Paths.get(backupPath).resolve(projectSlug + ".zip"); // A temporary ZIP file. Any existing content in the zipFilePath // will be copied into this, followed by any other files in // the directory that have not yet been added. Path tempZipFilePath = Paths.get(backupPath).resolve("temp" + ".zip"); File tempZipFile = tempZipFilePath.toFile(); if (!tempZipFile.exists()) { tempZipFile.createNewFile(); } ZipOutputStream tempZipOut = new ZipOutputStream(new FileOutputStream(tempZipFile)); File existingZipFile = zipFilePath.toFile(); if (existingZipFile.exists()) { ZipFile zipIn = new ZipFile(existingZipFile); Enumeration<? extends ZipEntry> entries = zipIn.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); logger.debug("compressBackupFolder copying: " + e.getName()); tempZipOut.putNextEntry(e); if (!e.isDirectory()) { copy(zipIn.getInputStream(e), tempZipOut); } tempZipOut.closeEntry(); } zipIn.close(); } File dir = new File(backupPath); File[] files = dir.listFiles(); for (File source : files) { if (!source.getName().toLowerCase().endsWith(".zip")) { logger.debug("compressBackupFolder compressing and " + "deleting file: " + source.toString()); if (zipFile(tempZipOut, source)) { source.delete(); } } } tempZipOut.flush(); tempZipOut.close(); tempZipFile.renameTo(existingZipFile); }
From source file:com.serotonin.mango.rt.maint.work.ReportWorkItem.java
private void addFileAttachment(EmailContent emailContent, String name, File file) { if (file != null) { if (reportConfig.isZipData()) { try { File zipFile = File.createTempFile("tempZIP", ".zip"); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); zipOut.putNextEntry(new ZipEntry(name)); FileInputStream in = new FileInputStream(file); StreamUtils.transfer(in, zipOut); in.close();/*from w ww . j av a2 s .c om*/ zipOut.closeEntry(); zipOut.close(); emailContent.addAttachment(new EmailAttachment.FileAttachment(name + ".zip", zipFile)); filesToDelete.add(zipFile); } catch (IOException e) { LOG.error("Failed to create zip file", e); } } else emailContent.addAttachment(new EmailAttachment.FileAttachment(name, file)); filesToDelete.add(file); } }
From source file:com.wabacus.WabacusFacade.java
private static void tarFileToZip(String originFilePath, String zipFilePath) { if (Tools.isEmpty(originFilePath) || Tools.isEmpty(zipFilePath)) return;// www . j a va 2 s . c om int idx = originFilePath.lastIndexOf(File.separator); String fileName = idx > 0 ? originFilePath.substring(idx + File.separator.length()) : originFilePath;//??? idx = fileName.lastIndexOf("_"); if (idx > 0) fileName = fileName.substring(idx + 1).trim(); try { FileOutputStream fout = new FileOutputStream(zipFilePath); ZipOutputStream zipout = new ZipOutputStream(fout); FileInputStream fis = new FileInputStream(originFilePath); zipout.putNextEntry(new ZipEntry(fileName)); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { zipout.write(buffer, 0, len); } zipout.closeEntry(); fis.close(); zipout.close(); fout.close(); } catch (Exception e) { throw new WabacusRuntimeException("" + originFilePath + "zip", e); } }
From source file:md.archivers.ZIPArchiver.java
private void zipDirectory(File zipFile, File directory) throws FileNotFoundException, IOException { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); FileInputStream fin = null;/*from w ww. j av a 2s. com*/ for (File d : directory.listFiles()) { for (File f : d.listFiles()) { zos.putNextEntry(new ZipEntry(createNameForZip(f))); try { fin = new FileInputStream(f); IOUtils.copy(fin, zos); } finally { if (fin != null) fin.close(); } zos.closeEntry(); } } zos.close(); }
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 ww. j a v a 2s. 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:com.jbrisbin.vpc.jobsched.batch.BatchMessageConverter.java
public Message toMessage(Object object, MessageProperties props) throws MessageConversionException { if (object instanceof BatchMessage) { BatchMessage batch = (BatchMessage) object; props.setCorrelationId(batch.getId().getBytes()); props.setContentType("application/zip"); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ZipOutputStream zout = new ZipOutputStream(bout); for (Map.Entry<String, String> msg : batch.getMessages().entrySet()) { ZipEntry zentry = new ZipEntry(msg.getKey()); try { zout.putNextEntry(zentry); zout.write(msg.getValue().getBytes()); zout.closeEntry();//from w ww . j av a 2 s .c o m } catch (IOException e) { throw new MessageConversionException(e.getMessage(), e); } } try { zout.flush(); zout.close(); } catch (IOException e) { throw new MessageConversionException(e.getMessage(), e); } return new Message(bout.toByteArray(), props); } else { throw new MessageConversionException( "Cannot convert object " + String.valueOf(object) + " using " + getClass().toString()); } }
From source file:com.jd.survey.web.reports.ReportController.java
/** * Exports survey data to a comma delimited values file * @param surveyDefinitionId// ww w . j a v a 2s. 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); } }