List of usage examples for java.util.zip ZipOutputStream flush
public void flush() throws IOException
From source file:org.opentestsystem.authoring.testspecbank.service.impl.FileManagerServiceImpl.java
@Override public void buildZipFromDirectory(final File sourceDirectory, final String targetZipFileName) { FileOutputStream fos = null;// w w w .ja v a2s .com BufferedOutputStream bos = null; ZipOutputStream zipOutputStream = null; try { // create zip output file stream fos = new FileOutputStream(tempFileDirectory + targetZipFileName); bos = new BufferedOutputStream(fos); zipOutputStream = new ZipOutputStream(bos); // for each downloaded file... for (final File file : sourceDirectory.listFiles()) { FileInputStream fis = null; try { // create new zip entry fis = new FileInputStream(file); zipOutputStream.putNextEntry(new ZipEntry(file.getName())); // write file contents to zip final byte[] buf = new byte[BUFFER_SIZE]; int readLen = 0; while ((readLen = fis.read(buf)) > 0) { zipOutputStream.write(buf, 0, readLen); } } catch (final IOException e) { throw new LocalizedException("localFile.zip.entry.fail", new String[] { file.getName() }); } finally { if (fis != null) { fis.close(); } zipOutputStream.closeEntry(); } } } catch (final IOException e) { throw new LocalizedException("localFile.zip.fail", new String[] { targetZipFileName }); } finally { try { if (zipOutputStream != null) { zipOutputStream.flush(); zipOutputStream.close(); } if (bos != null) { bos.flush(); bos.close(); } if (fos != null) { fos.flush(); fos.close(); } } catch (final IOException e) { throw new LocalizedException("localFile.zip.fail", new String[] { targetZipFileName }); } } }
From source file:org.staxcel.internal.SpreadSheetImpl.java
/** * Zip all source files into target zip file * //from w w w . j a v a2 s. c om * @param targetFile * @param baseFolder * @param sourceFilesList * @throws IOException */ private void zipContent(File targetFile, File baseFolder, ArrayList<File> sourceFilesList) throws IOException { BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(targetFile)); ZipOutputStream zipOut = new ZipOutputStream(fOut); String baseFolderPath = baseFolder.getAbsolutePath(); int blockSize = getDefaultBlockSize(); byte[] byteArray = new byte[blockSize]; for (int index = 0; index < sourceFilesList.size(); ++index) { File entryFile = sourceFilesList.get(index); String name = entryFile.getAbsolutePath().substring(baseFolderPath.length()); System.out.println("name is : " + name); ZipEntry zipEntry = new ZipEntry(name); zipOut.putNextEntry(zipEntry); long inputFileSize = entryFile.length(); InputStream fIn = new BufferedInputStream(new FileInputStream(entryFile)); int length = 0; while (inputFileSize > 0) { length = inputFileSize >= blockSize ? blockSize : (int) inputFileSize; inputFileSize = inputFileSize - length; fIn.read(byteArray, 0, length); zipOut.write(byteArray, 0, length); } fIn.close(); } zipOut.flush(); zipOut.close(); fOut.flush(); fOut.close(); }
From source file:com.flexive.core.storage.GenericDivisionExporter.java
/** * Dump a generic table to XML/*from w w w . ja va2 s .c o m*/ * * @param tableName name of the table * @param stmt an open statement * @param out output stream * @param sb an available and valid StringBuilder * @param xmlTag name of the xml tag to write per row * @param idColumn (optional) id column to sort results * @param onlyBinaries process binary fields (else these will be ignored) * @throws SQLException on errors * @throws IOException on errors */ private void dumpTable(String tableName, Statement stmt, OutputStream out, StringBuilder sb, String xmlTag, String idColumn, boolean onlyBinaries) throws SQLException, IOException { ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName + (StringUtils.isEmpty(idColumn) ? "" : " ORDER BY " + idColumn + " ASC")); final ResultSetMetaData md = rs.getMetaData(); String value, att; boolean hasSubTags; while (rs.next()) { hasSubTags = false; if (!onlyBinaries) { sb.setLength(0); sb.append(" <").append(xmlTag); } for (int i = 1; i <= md.getColumnCount(); i++) { value = null; att = md.getColumnName(i).toLowerCase(); switch (md.getColumnType(i)) { case java.sql.Types.DECIMAL: case java.sql.Types.NUMERIC: case java.sql.Types.BIGINT: if (!onlyBinaries) { value = String.valueOf(rs.getBigDecimal(i)); if (rs.wasNull()) value = null; } break; case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: if (!onlyBinaries) { value = String.valueOf(rs.getLong(i)); if (rs.wasNull()) value = null; } break; case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: case java.sql.Types.REAL: if (!onlyBinaries) { value = String.valueOf(rs.getDouble(i)); if (rs.wasNull()) value = null; } break; case java.sql.Types.TIMESTAMP: case java.sql.Types.DATE: if (!onlyBinaries) { final Timestamp ts = rs.getTimestamp(i); if (rs.wasNull()) value = null; else value = FxFormatUtils.getDateTimeFormat().format(ts); } break; case java.sql.Types.BIT: case java.sql.Types.CHAR: case java.sql.Types.BOOLEAN: if (!onlyBinaries) { value = rs.getBoolean(i) ? "1" : "0"; if (rs.wasNull()) value = null; } break; case java.sql.Types.CLOB: case java.sql.Types.BLOB: case java.sql.Types.LONGVARBINARY: case java.sql.Types.LONGVARCHAR: case java.sql.Types.VARBINARY: case java.sql.Types.VARCHAR: case java.sql.Types.BINARY: case SQL_LONGNVARCHAR: case SQL_NCHAR: case SQL_NCLOB: case SQL_NVARCHAR: hasSubTags = true; break; default: LOG.warn("Unhandled type [" + md.getColumnType(i) + "] for [" + tableName + "." + att + "]"); } if (value != null && !onlyBinaries) sb.append(' ').append(att).append("=\"").append(value).append("\""); } if (hasSubTags) { if (!onlyBinaries) sb.append(">\n"); for (int i = 1; i <= md.getColumnCount(); i++) { switch (md.getColumnType(i)) { case java.sql.Types.VARBINARY: case java.sql.Types.LONGVARBINARY: case java.sql.Types.BLOB: case java.sql.Types.BINARY: if (idColumn == null) throw new IllegalArgumentException("Id column required to process binaries!"); String binFile = FOLDER_BINARY + "/BIN_" + String.valueOf(rs.getLong(idColumn)) + "_" + i + ".blob"; att = md.getColumnName(i).toLowerCase(); if (onlyBinaries) { if (!(out instanceof ZipOutputStream)) throw new IllegalArgumentException( "out has to be a ZipOutputStream to store binaries!"); ZipOutputStream zip = (ZipOutputStream) out; InputStream in = rs.getBinaryStream(i); if (rs.wasNull()) break; ZipEntry ze = new ZipEntry(binFile); zip.putNextEntry(ze); byte[] buffer = new byte[4096]; int read; while ((read = in.read(buffer)) != -1) zip.write(buffer, 0, read); in.close(); zip.closeEntry(); zip.flush(); } else { InputStream in = rs.getBinaryStream(i); //need to fetch to see if it is empty if (rs.wasNull()) break; in.close(); sb.append(" <").append(att).append(">").append(binFile).append("</").append(att) .append(">\n"); } break; case java.sql.Types.CLOB: case SQL_LONGNVARCHAR: case SQL_NCHAR: case SQL_NCLOB: case SQL_NVARCHAR: case java.sql.Types.LONGVARCHAR: case java.sql.Types.VARCHAR: if (!onlyBinaries) { value = rs.getString(i); if (rs.wasNull()) break; att = md.getColumnName(i).toLowerCase(); sb.append(" <").append(att).append('>'); escape(sb, value); sb.append("</").append(att).append(">\n"); } break; } } if (!onlyBinaries) sb.append(" </").append(xmlTag).append(">\n"); } else { if (!onlyBinaries) sb.append("/>\n"); } if (!onlyBinaries) write(out, sb); } }
From source file:org.niord.core.message.MessageExportService.java
/** * Exports the messages search result to the output stream * @param result the search result/*from w w w .jav a2 s. co m*/ * @param os the output stream */ public void export(PagedSearchResultVo<SystemMessageVo> result, OutputStream os) { long t0 = System.currentTimeMillis(); try { ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(os)); // Rewrite links in message description to remove "/rest/repo/file/" prefix result.getData().forEach( m -> m.rewriteRepoPath("\"/rest/repo/file/" + m.getRepoPath(), "\"" + m.getRepoPath())); // Write the messages file to the Zip file log.debug("Adding messages.json to zip archive"); out.putNextEntry(new ZipEntry("messages.json")); ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); String messages = mapper.writeValueAsString(result); IOUtils.write(messages, out, "utf-8"); out.closeEntry(); // Write the messages-preview.html file into the archive. // Can be used to preview the messages by someone unzipping the archive String html = messagesPreviewHtmlFile.replace("<<MESSAGES-JSON>>", StringEscapeUtils.escapeJavaScript(messages)); log.debug("Adding messages-preview.html to zip archive"); out.putNextEntry(new ZipEntry("messages-preview.html")); IOUtils.write(html, out, "utf-8"); out.closeEntry(); // Write the message attachments and thumbnail files to the Zip file Set<String> folderCache = new HashSet<>(); result.getData().stream().filter(m -> m.getAttachments() != null && !m.getAttachments().isEmpty()) .forEach(m -> { exportAttachments(m, out, folderCache); exportThumbnail(m, out, folderCache); }); out.flush(); out.close(); log.info("Created Zip export archive in " + (System.currentTimeMillis() - t0) + " ms"); } catch (Exception e) { throw new WebApplicationException("Error generating ZIP archive for messages", e); } }
From source file:org.sakaiproject.metaobj.shared.mgt.impl.StructuredArtifactDefinitionManagerImpl.java
/** * This method will export a form into a stream. It has the ability to turn off checking * for the export form permission.//from w ww . j a v a 2s. c o m * @param formId String * @param os OutputStream * @param checkPermission boolean * @throws IOException */ public void packageFormForExport(String formId, OutputStream os, boolean checkPermission) throws IOException { if (checkPermission) { getAuthzManager().checkPermission(SharedFunctionConstants.EXPORT_ARTIFACT_DEF, getToolId()); } CheckedOutputStream checksum = new CheckedOutputStream(os, new Adler32()); ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(checksum)); StructuredArtifactDefinitionBean bean = loadHome(formId); writeSADtoZip(bean, zos, ""); zos.finish(); zos.flush(); }
From source file:org.etudes.mneme.impl.ExportQtiServiceImpl.java
/** * Write Xml document to zip package// ww w.j av a 2 s . c o m * * @param zip * @param fileTitle * @param document */ protected void writeDocumentToZip(ZipOutputStream zip, String subFolder, String fileTitle, Document document) { try { if (subFolder != null) zip.putNextEntry(new ZipEntry(subFolder)); zip.putNextEntry(new ZipEntry(fileTitle)); zip.write(Xml.writeDocumentToString(document).getBytes("UTF-8")); zip.closeEntry(); zip.flush(); } catch (IOException e) { M_log.warn("zipSubmissionsQuestion: zipping question: " + e.toString()); } }
From source file:org.auscope.portal.server.web.controllers.JobListController.java
/** * Sends the contents of one or more job files as a ZIP archive to the * client.//from w w w. j a v a 2 s . co m * * @param request The servlet request including a jobId parameter and a * files parameter with the filenames separated by comma * @param response The servlet response receiving the data * * @return null on success or the joblist view with an error parameter on * failure. */ @RequestMapping("/downloadAsZip.do") public ModelAndView downloadAsZip(HttpServletRequest request, HttpServletResponse response) { String jobIdStr = request.getParameter("jobId"); String filesParam = request.getParameter("files"); GeodesyJob job = null; String errorString = null; if (jobIdStr != null) { try { int jobId = Integer.parseInt(jobIdStr); job = jobManager.getJobById(jobId); } catch (NumberFormatException e) { logger.error("Error parsing job ID!"); } } if (job != null && filesParam != null) { String[] fileNames = filesParam.split(","); logger.debug("Archiving " + fileNames.length + " file(s) of job " + jobIdStr); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=\"jobfiles.zip\""); try { boolean readOneOrMoreFiles = false; ZipOutputStream zout = new ZipOutputStream(response.getOutputStream()); for (String fileName : fileNames) { File f = new File(job.getOutputDir() + File.separator + fileName); if (!f.canRead()) { // if a file could not be read we go ahead and try the // next one. logger.error("File " + f.getPath() + " not readable!"); } else { byte[] buffer = new byte[16384]; int count = 0; zout.putNextEntry(new ZipEntry(fileName)); FileInputStream fin = new FileInputStream(f); while ((count = fin.read(buffer)) != -1) { zout.write(buffer, 0, count); } zout.closeEntry(); readOneOrMoreFiles = true; } } if (readOneOrMoreFiles) { zout.finish(); zout.flush(); zout.close(); return null; } else { zout.close(); errorString = new String("Could not access the files!"); logger.error(errorString); } } catch (IOException e) { errorString = new String("Could not create ZIP file: " + e.getMessage()); logger.error(errorString); } } // We only end up here in case of an error so return a suitable message if (errorString == null) { if (job == null) { errorString = new String("Invalid job specified!"); logger.error(errorString); } else if (filesParam == null) { errorString = new String("No filename(s) provided!"); logger.error(errorString); } else { // should never get here errorString = new String("Something went wrong."); logger.error(errorString); } } return new ModelAndView("joblist", "error", errorString); }
From source file:se.unlogic.hierarchy.foregroundmodules.imagegallery.GalleryModule.java
@WebPublic(alias = "download") public SimpleForegroundModuleResponse downloadGallery(HttpServletRequest req, HttpServletResponse res, User user, URIParser uriParser) throws SQLException, URINotFoundException { Gallery gallery = null;/*from w ww . j av a2 s . co m*/ if (uriParser.size() < 3 || (gallery = this.galleryDao.get(uriParser.get(2))) == null) { throw new URINotFoundException(uriParser); } // check if path is valid File dir = new File(gallery.getUrl()); if (!dir.canRead()) { throw new URINotFoundException(uriParser); } log.info("User " + user + " downloading gallery " + gallery + "..."); long startTime = System.currentTimeMillis(); File[] files = dir.listFiles(fileFilter); ZipOutputStream zipOutputStream = null; try { res.setContentType("application/zip"); res.setHeader("Content-Disposition", "inline; filename=\"" + FileUtils.toValidHttpFilename(gallery.getName()) + ".zip\""); res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate"); zipOutputStream = new ZipOutputStream(res.getOutputStream()); zipOutputStream.setLevel(ZipOutputStream.STORED); ZipUtils.addFiles(files, zipOutputStream); zipOutputStream.flush(); log.info("Sent gallery " + gallery + " containing " + files.length + " files to user " + user + " in " + TimeUtils.millisecondsToString(System.currentTimeMillis() - startTime)); } catch (IOException e) { log.info("Error sending gallery " + gallery + " to user " + user); } finally { StreamUtils.closeStream(zipOutputStream); } return null; }
From source file:com.orange.mmp.midlet.MidletManager.java
/** * Builds a ZIP archive with the appropriate name * @param mobile/*w w w. j a va 2s .c o m*/ * @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:password.pwm.http.servlet.ConfigManagerServlet.java
private void outputZipDebugFile(final PwmRequest pwmRequest, final ZipOutputStream zipOutput, final String pathPrefix) throws IOException, PwmUnrecoverableException { final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final PwmSession pwmSession = pwmRequest.getPwmSession(); { // kick off health check so that it might be faster later.. Thread healthThread = new Thread() { public void run() { pwmApplication.getHealthMonitor().getHealthRecords(); }//from w w w .ja v a 2 s . co m }; healthThread .setName(Helper.makeThreadName(pwmApplication, ConfigManagerServlet.class) + "-HealthCheck"); healthThread.setDaemon(true); healthThread.start(); } final StoredConfiguration storedConfiguration = readCurrentConfiguration(pwmRequest); storedConfiguration.resetAllPasswordValues( "value removed from " + PwmConstants.PWM_APP_NAME + "-Support configuration export"); { zipOutput.putNextEntry(new ZipEntry(pathPrefix + PwmConstants.DEFAULT_CONFIG_FILE_FILENAME)); storedConfiguration.resetAllPasswordValues( "value removed from " + PwmConstants.PWM_APP_NAME + "-Support configuration export"); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); storedConfiguration.toXml(outputStream); zipOutput.write(outputStream.toByteArray()); zipOutput.closeEntry(); zipOutput.flush(); } { zipOutput.putNextEntry(new ZipEntry(pathPrefix + "configuration-debug.txt")); zipOutput.write(storedConfiguration.toString(true).getBytes(PwmConstants.DEFAULT_CHARSET)); zipOutput.closeEntry(); zipOutput.flush(); } { final String aboutJson = JsonUtil.serialize(AdminServlet.makeInfoBean(pwmApplication), JsonUtil.Flag.PrettyPrint); zipOutput.putNextEntry(new ZipEntry(pathPrefix + "about.json")); zipOutput.write(aboutJson.getBytes(PwmConstants.DEFAULT_CHARSET)); zipOutput.closeEntry(); zipOutput.flush(); } { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); pwmApplication.getAuditManager().outputVaultToCsv(baos, pwmRequest.getLocale(), true); zipOutput.putNextEntry(new ZipEntry(pathPrefix + "audit.csv")); zipOutput.write(baos.toByteArray()); zipOutput.closeEntry(); zipOutput.flush(); } { zipOutput.putNextEntry(new ZipEntry(pathPrefix + "info.json")); final LinkedHashMap<String, Object> outputMap = new LinkedHashMap<>(); { // services info final LinkedHashMap<String, Object> servicesMap = new LinkedHashMap<>(); for (final PwmService service : pwmApplication.getPwmServices()) { final LinkedHashMap<String, Object> serviceOutput = new LinkedHashMap<>(); serviceOutput.put("name", service.getClass().getSimpleName()); serviceOutput.put("status", service.status()); serviceOutput.put("health", service.healthCheck()); serviceOutput.put("serviceInfo", service.serviceInfo()); servicesMap.put(service.getClass().getSimpleName(), serviceOutput); } outputMap.put("services", servicesMap); } // java threads outputMap.put("threads", Thread.getAllStackTraces()); final String recordJson = JsonUtil.serializeMap(outputMap, JsonUtil.Flag.PrettyPrint); zipOutput.write(recordJson.getBytes(PwmConstants.DEFAULT_CHARSET)); zipOutput.closeEntry(); zipOutput.flush(); } if (pwmApplication.getApplicationPath() != null) { try { zipOutput.putNextEntry(new ZipEntry(pathPrefix + "fileMd5sums.json")); final Map<String, String> fileChecksums = BuildChecksumMaker .readDirectorySums(pwmApplication.getApplicationPath()); final String json = JsonUtil.serializeMap(fileChecksums, JsonUtil.Flag.PrettyPrint); zipOutput.write(json.getBytes(PwmConstants.DEFAULT_CHARSET)); zipOutput.closeEntry(); zipOutput.flush(); } catch (Exception e) { LOGGER.error(pwmSession, "unable to generate fileMd5sums during zip debug building: " + e.getMessage()); } } { zipOutput.putNextEntry(new ZipEntry(pathPrefix + "debug.log")); final int maxCount = 100 * 1000; final int maxSeconds = 30 * 1000; final LocalDBLogger.SearchParameters searchParameters = new LocalDBLogger.SearchParameters( PwmLogLevel.TRACE, maxCount, null, null, maxSeconds, null); final LocalDBLogger.SearchResults searchResults = pwmApplication.getLocalDBLogger() .readStoredEvents(searchParameters); int counter = 0; while (searchResults.hasNext()) { final PwmLogEvent event = searchResults.next(); zipOutput.write(event.toLogString().getBytes(PwmConstants.DEFAULT_CHARSET)); zipOutput.write("\n".getBytes(PwmConstants.DEFAULT_CHARSET)); counter++; if (counter % 100 == 0) { zipOutput.flush(); } } zipOutput.closeEntry(); } { zipOutput.putNextEntry(new ZipEntry(pathPrefix + "health.json")); final Set<HealthRecord> records = pwmApplication.getHealthMonitor().getHealthRecords(); final String recordJson = JsonUtil.serializeCollection(records, JsonUtil.Flag.PrettyPrint); zipOutput.write(recordJson.getBytes(PwmConstants.DEFAULT_CHARSET)); zipOutput.closeEntry(); zipOutput.flush(); } }