List of usage examples for java.util.zip ZipOutputStream putNextEntry
public void putNextEntry(ZipEntry e) throws IOException
From source file:ch.ivyteam.ivy.maven.util.ClasspathJar.java
private void writeManifest(String name, ZipOutputStream jarStream, List<String> classpathEntries) throws IOException { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().putValue("Name", name); if (mainClass != null) { manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass); }/* www. j a va 2 s .c o m*/ if (!classpathEntries.isEmpty()) { manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, StringUtils.join(classpathEntries, " ")); } jarStream.putNextEntry(new ZipEntry(MANIFEST_MF)); manifest.write(jarStream); }
From source file:net.librec.util.FileUtil.java
/** * Zip a given folder/*from w w w . ja v a 2s . com*/ * * @param dirPath a given folder: must be all files (not sub-folders) * @param filePath zipped file * @throws Exception if error occurs */ public static void zipFolder(String dirPath, String filePath) throws Exception { File outFile = new File(filePath); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outFile)); int bytesRead; byte[] buffer = new byte[1024]; CRC32 crc = new CRC32(); for (File file : listFiles(dirPath)) { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); crc.reset(); while ((bytesRead = bis.read(buffer)) != -1) { crc.update(buffer, 0, bytesRead); } bis.close(); // Reset to beginning of input stream bis = new BufferedInputStream(new FileInputStream(file)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.STORED); entry.setCompressedSize(file.length()); entry.setSize(file.length()); entry.setCrc(crc.getValue()); zos.putNextEntry(entry); while ((bytesRead = bis.read(buffer)) != -1) { zos.write(buffer, 0, bytesRead); } bis.close(); } zos.close(); LOG.debug("A zip-file is created to: " + outFile.getPath()); }
From source file:fr.simon.marquis.secretcodes.util.ExportContentProvider.java
private void saveZipFile() { File[] files = getContext().getFilesDir().listFiles(); String zipPath = getContext().getFilesDir().getAbsolutePath() + "/" + ZIP_FILE_NAME; try {/*ww w .j av a2s . c om*/ BufferedInputStream origin = null; FileOutputStream zipFile = new FileOutputStream(zipPath); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(zipFile)); byte data[] = new byte[BUFFER]; for (int i = 0; i < files.length; i++) { FileInputStream fi = new FileInputStream(files[i]); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry( files[i].getAbsolutePath().substring(files[i].getAbsolutePath().lastIndexOf("/") + 1)); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } origin.close(); } out.close(); Log.d(this.getClass().getSimpleName(), "zipFile created at " + zipPath + " with " + files.length + " files"); } catch (Exception e) { e.printStackTrace(); Log.e(this.getClass().getSimpleName(), "error while zipping at " + zipPath + " with " + files.length + " files", e); } }
From source file:fr.gael.dhus.service.job.SendLogsJob.java
@Override protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException { if (!configurationManager.getSendLogsCronConfiguration().isActive()) return;//from ww w . j av a2s .co m long start = System.currentTimeMillis(); logger.info("SCHEDULER : Send Administrative logs."); if (!DHuS.isStarted()) { logger.warn("SCHEDULER : Not run while system not fully initialized."); return; } String[] addresses = configurationManager.getSendLogsCronConfiguration().getAddresses().split(","); // Case of no addresses available: use system support if ((addresses == null) || (addresses.length == 0) || "".equals(addresses[0].trim())) { String email = configurationManager.getSupportConfiguration().getMail(); if ((email == null) || "".equals(email)) { throw new MailException("Support e-mail not configured, " + "system logs will not be send"); } addresses = new String[] { email }; } RollingFileAppender rollingFileAppender = (RollingFileAppender) ((org.apache.logging.log4j.core.Logger) LogManager .getRootLogger()).getAppenders().get("RollingFile"); if (rollingFileAppender == null) { throw new MailException("No rolling log file defined"); } String logPath = rollingFileAppender.getFileName(); if ((logPath == null) || logPath.trim().equals("")) { throw new MailException("Log file not defined"); } File logs = new File(logPath); if (!logs.exists()) { throw new MailException("Log file not present : " + logs.getPath()); } Date now = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'@'HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("GMT")); String docFilename = configurationManager.getNameConfiguration().getShortName().toLowerCase() + "-" + df.format(now); File zipLogs; try { zipLogs = File.createTempFile(docFilename, ".zip"); } catch (IOException e) { throw new MailException("Cannot create temporary zip log file.", e); } // compress logs file to zip format FileOutputStream fos; ZipOutputStream zos = null; FileInputStream fis = null; try { int length; byte[] buffer = new byte[1024]; ZipEntry entry = new ZipEntry(docFilename + ".txt"); fos = new FileOutputStream(zipLogs); zos = new ZipOutputStream(fos); fis = new FileInputStream(logs); zos.setLevel(Deflater.BEST_COMPRESSION); zos.putNextEntry(entry); while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } } catch (IOException e) { throw new MailException("An error occurred during compression " + "logs file, cannot send logs !", e); } finally { try { if (fis != null) { fis.close(); } if (zos != null) { zos.closeEntry(); zos.close(); } } catch (IOException e) { throw new MailException("An error occurred during compression " + "logs file, cannot send logs !", e); } } EmailAttachment attachment = new EmailAttachment(); attachment.setDescription( configurationManager.getNameConfiguration().getShortName() + " Logs " + now.toString()); attachment.setPath(zipLogs.getPath()); attachment.setName(zipLogs.getName()); // Prepare the addresses List<String> ads = new ArrayList<String>(); for (String email : addresses) { StringTokenizer tk = new StringTokenizer(email, ", "); while (tk.hasMoreTokens()) { String token = tk.nextToken().trim(); if (!token.isEmpty()) ads.add(token); } } for (String email : ads) { try { String server = configurationManager.getServerConfiguration().getExternalHostname(); String url = configurationManager.getServerConfiguration().getExternalUrl(); mailServer.send(email, null, null, "[" + configurationManager.getNameConfiguration().getShortName().toLowerCase() + "@" + server + "] logs of " + df.format(now), "Here is attached " + configurationManager.getNameConfiguration().getShortName() + " logs of \"" + url + "\" host.\n\n" + "Kind Regards.\nThe " + configurationManager.getNameConfiguration().getShortName() + " Team.", attachment); logger.info("Logs Sent to " + email); } catch (EmailException e) { throw new MailException("Cannot send logs to " + email, e); } } if (!zipLogs.delete()) { logger.warn("Cannot remove mail attachment: " + zipLogs.getAbsolutePath()); } logger.info("SCHEDULER : Send Administrative logs done - " + (System.currentTimeMillis() - start) + "ms"); }
From source file:game.com.HandleDownloadFolderServlet.java
private void outputZipStream(ZipOutputStream output, File file) throws FileNotFoundException, IOException { for (File currentFile : file.listFiles()) { InputStream input = null; byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; try {//from w w w .j ava 2 s . c om if (currentFile.isDirectory()) { outputZipStream(output, currentFile); } else { input = new BufferedInputStream(new FileInputStream(currentFile), DEFAULT_BUFFER_SIZE); output.putNextEntry(new ZipEntry(currentFile.getName())); for (int length = 0; (length = input.read(buffer)) > 0;) { output.write(buffer, 0, length); } output.closeEntry(); } } finally { if (input != null) { try { input.close(); } catch (Exception logOrIgnore) { logger.error(logOrIgnore.getMessage(), logOrIgnore); } } } } }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java
private MimeBodyPart zipAttachment(byte[] attach, String containedFileName, String zipFileName, String nameSuffix, String fileExtension) { MimeBodyPart messageBodyPart = null; try {/*from w w w .j a v a 2 s.c o m*/ ByteArrayOutputStream bout = new ByteArrayOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(bout); String entryName = containedFileName + nameSuffix + fileExtension; zipOut.putNextEntry(new ZipEntry(entryName)); zipOut.write(attach); zipOut.closeEntry(); zipOut.close(); messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(zipFileName + nameSuffix + ".zip"); } catch (Exception e) { // TODO: handle exception } return messageBodyPart; }
From source file:fr.cirad.mgdb.exporting.markeroriented.VcfExportHandler.java
@Override public void exportData(OutputStream outputStream, String sModule, List<SampleId> sampleIDs, ProgressIndicator progress, DBCursor markerCursor, Map<Comparable, Comparable> markerSynonyms, int nMinimumGenotypeQuality, int nMinimumReadDepth, Map<String, InputStream> readyToExportFiles) throws Exception { Integer projectId = null;/*from w ww. ja va 2 s . c o m*/ for (SampleId spId : sampleIDs) { if (projectId == null) projectId = spId.getProject(); else if (projectId != spId.getProject()) { projectId = 0; break; // more than one project are involved: no header will be written } } File warningFile = File.createTempFile("export_warnings_", ""); FileWriter warningFileWriter = new FileWriter(warningFile); MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule); int markerCount = markerCursor.count(); ZipOutputStream zos = new ZipOutputStream(outputStream); if (readyToExportFiles != null) for (String readyToExportFile : readyToExportFiles.keySet()) { zos.putNextEntry(new ZipEntry(readyToExportFile)); InputStream inputStream = readyToExportFiles.get(readyToExportFile); byte[] dataBlock = new byte[1024]; int count = inputStream.read(dataBlock, 0, 1024); while (count != -1) { zos.write(dataBlock, 0, count); count = inputStream.read(dataBlock, 0, 1024); } } LinkedHashMap<SampleId, String> sampleIDToIndividualIdMap = new LinkedHashMap<SampleId, String>(); ArrayList<String> individualList = new ArrayList<String>(); List<Individual> individuals = getIndividualsFromSamples(sModule, sampleIDs); for (int i = 0; i < sampleIDs.size(); i++) { String individualId = individuals.get(i).getId(); sampleIDToIndividualIdMap.put(sampleIDs.get(i), individualId); if (!individualList.contains(individualId)) { individualList.add(individualId); } } String exportName = sModule + "_" + markerCount + "variants_" + individualList.size() + "individuals"; zos.putNextEntry(new ZipEntry(exportName + ".vcf")); int avgObjSize = (Integer) mongoTemplate .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats().get("avgObjSize"); int nQueryChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize; VariantContextWriter writer = null; try { List<String> distinctSequenceNames = new ArrayList<String>(); String sequenceSeqCollName = MongoTemplateManager.getMongoCollectionName(Sequence.class); if (mongoTemplate.collectionExists(sequenceSeqCollName)) { DBCursor markerCursorCopy = markerCursor.copy(); markerCursorCopy.batchSize(nQueryChunkSize); while (markerCursorCopy.hasNext()) { int nLoadedMarkerCountInLoop = 0; boolean fStartingNewChunk = true; while (markerCursorCopy.hasNext() && (fStartingNewChunk || nLoadedMarkerCountInLoop % nQueryChunkSize != 0)) { DBObject exportVariant = markerCursorCopy.next(); String chr = (String) ((DBObject) exportVariant .get(VariantData.FIELDNAME_REFERENCE_POSITION)) .get(ReferencePosition.FIELDNAME_SEQUENCE); if (!distinctSequenceNames.contains(chr)) distinctSequenceNames.add(chr); } } markerCursorCopy.close(); } Collections.sort(distinctSequenceNames, new AlphaNumericStringComparator()); SAMSequenceDictionary dict = createSAMSequenceDictionary(sModule, distinctSequenceNames); writer = new CustomVCFWriter(null, zos, dict, false, false, true); // VariantContextWriterBuilder vcwb = new VariantContextWriterBuilder(); // vcwb.unsetOption(Options.INDEX_ON_THE_FLY); // vcwb.unsetOption(Options.DO_NOT_WRITE_GENOTYPES); // vcwb.setOption(Options.USE_ASYNC_IOINDEX_ON_THE_FLY); // vcwb.setOption(Options.ALLOW_MISSING_FIELDS_IN_HEADER); // vcwb.setReferenceDictionary(dict); // writer = vcwb.build(); // writer = new AsyncVariantContextWriter(writer, 3000); progress.moveToNextStep(); // done with dictionary DBCursor headerCursor = mongoTemplate .getCollection(MongoTemplateManager.getMongoCollectionName(DBVCFHeader.class)) .find(new BasicDBObject("_id." + VcfHeaderId.FIELDNAME_PROJECT, projectId)); Set<VCFHeaderLine> headerLines = new HashSet<VCFHeaderLine>(); boolean fWriteCommandLine = true, fWriteEngineHeaders = true; // default values while (headerCursor.hasNext()) { DBVCFHeader dbVcfHeader = DBVCFHeader.fromDBObject(headerCursor.next()); headerLines.addAll(dbVcfHeader.getHeaderLines()); // Add sequence header lines (not stored in our vcf header collection) BasicDBObject projection = new BasicDBObject(SequenceStats.FIELDNAME_SEQUENCE_LENGTH, true); int nSequenceIndex = 0; for (String sequenceName : distinctSequenceNames) { String sequenceInfoCollName = MongoTemplateManager.getMongoCollectionName(SequenceStats.class); boolean fCollectionExists = mongoTemplate.collectionExists(sequenceInfoCollName); if (fCollectionExists) { DBObject record = mongoTemplate.getCollection(sequenceInfoCollName).findOne( new Query(Criteria.where("_id").is(sequenceName)).getQueryObject(), projection); if (record == null) { LOG.warn("Sequence '" + sequenceName + "' not found in collection " + sequenceInfoCollName); continue; } Map<String, String> sequenceLineData = new LinkedHashMap<String, String>(); sequenceLineData.put("ID", (String) record.get("_id")); sequenceLineData.put("length", ((Number) record.get(SequenceStats.FIELDNAME_SEQUENCE_LENGTH)).toString()); headerLines.add(new VCFContigHeaderLine(sequenceLineData, nSequenceIndex++)); } } fWriteCommandLine = headerCursor.size() == 1 && dbVcfHeader.getWriteCommandLine(); // wouldn't make sense to include command lines for several runs if (!dbVcfHeader.getWriteEngineHeaders()) fWriteEngineHeaders = false; } headerCursor.close(); VCFHeader header = new VCFHeader(headerLines, individualList); header.setWriteCommandLine(fWriteCommandLine); header.setWriteEngineHeaders(fWriteEngineHeaders); writer.writeHeader(header); short nProgress = 0, nPreviousProgress = 0; long nLoadedMarkerCount = 0; HashMap<SampleId, Comparable /*phID*/> phasingIDsBySample = new HashMap<SampleId, Comparable>(); while (markerCursor.hasNext()) { if (progress.hasAborted()) return; int nLoadedMarkerCountInLoop = 0; boolean fStartingNewChunk = true; markerCursor.batchSize(nQueryChunkSize); List<Comparable> currentMarkers = new ArrayList<Comparable>(); while (markerCursor.hasNext() && (fStartingNewChunk || nLoadedMarkerCountInLoop % nQueryChunkSize != 0)) { DBObject exportVariant = markerCursor.next(); currentMarkers.add((Comparable) exportVariant.get("_id")); nLoadedMarkerCountInLoop++; fStartingNewChunk = false; } LinkedHashMap<VariantData, Collection<VariantRunData>> variantsAndRuns = MgdbDao.getSampleGenotypes( mongoTemplate, sampleIDs, currentMarkers, true, null /*new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_SEQUENCE).and(new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_START_SITE))*/); // query mongo db for matching genotypes for (VariantData variant : variantsAndRuns.keySet()) { VariantContext vc = variant.toVariantContext(variantsAndRuns.get(variant), !ObjectId.isValid(variant.getId().toString()), sampleIDToIndividualIdMap, phasingIDsBySample, nMinimumGenotypeQuality, nMinimumReadDepth, warningFileWriter, markerSynonyms == null ? variant.getId() : markerSynonyms.get(variant.getId())); try { writer.add(vc); } catch (Throwable t) { Exception e = new Exception("Unable to convert to VariantContext: " + variant.getId(), t); LOG.debug("error", e); throw e; } if (nLoadedMarkerCountInLoop > currentMarkers.size()) LOG.error("Bug: writing variant number " + nLoadedMarkerCountInLoop + " (only " + currentMarkers.size() + " variants expected)"); } nLoadedMarkerCount += nLoadedMarkerCountInLoop; nProgress = (short) (nLoadedMarkerCount * 100 / markerCount); if (nProgress > nPreviousProgress) { progress.setCurrentStepProgress(nProgress); nPreviousProgress = nProgress; } } progress.setCurrentStepProgress((short) 100); } catch (Exception e) { LOG.error("Error exporting", e); progress.setError(e.getMessage()); return; } finally { warningFileWriter.close(); if (warningFile.length() > 0) { zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt")); int nWarningCount = 0; BufferedReader in = new BufferedReader(new FileReader(warningFile)); String sLine; while ((sLine = in.readLine()) != null) { zos.write((sLine + "\n").getBytes()); nWarningCount++; } LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount); in.close(); } warningFile.delete(); if (writer != null) try { writer.close(); } catch (Throwable ignored) { } } }
From source file:eu.planets_project.pp.plato.action.ProjectExportAction.java
/** * Exports all projects into separate xml files and adds them to a zip archive. * @return null Always returns null, so user stays on same screen after action performed *///w w w . j a v a2s .c om public String exportAllProjectsToZip() { List<PlanProperties> ppList = em.createQuery("select p from PlanProperties p").getResultList(); if (!ppList.isEmpty()) { log.debug("number of plans to export: " + ppList.size()); String filename = "allprojects.zip"; String exportPath = OS.getTmpPath() + "export" + System.currentTimeMillis() + "/"; new File(exportPath).mkdirs(); String binarydataTempPath = exportPath + "binarydata/"; File binarydataTempDir = new File(binarydataTempPath); binarydataTempDir.mkdirs(); try { OutputStream out = new BufferedOutputStream(new FileOutputStream(exportPath + filename)); ZipOutputStream zipOut = new ZipOutputStream(out); for (PlanProperties pp : ppList) { log.debug("EXPORTING: " + pp.getName()); ZipEntry zipAdd = new ZipEntry(String.format("%1$03d", pp.getId()) + "-" + FileUtils.makeFilename(pp.getName()) + ".xml"); zipOut.putNextEntry(zipAdd); // export the complete project, including binary data exportComplete(pp.getId(), zipOut, binarydataTempPath); zipOut.closeEntry(); } zipOut.close(); out.close(); new File(exportPath + "finished.info").createNewFile(); FacesMessages.instance().add(FacesMessage.SEVERITY_INFO, "Export was written to: " + exportPath); log.info("Export was written to: " + exportPath); } catch (IOException e) { FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "An error occured while generating the export file."); log.error("An error occured while generating the export file.", e); File errorInfo = new File(exportPath + "error.info"); try { Writer w = new FileWriter(errorInfo); w.write("An error occured while generating the export file:"); w.write(e.getMessage()); w.close(); } catch (IOException e1) { log.error("Could not write error file."); } } finally { // remove all binary temp files OS.deleteDirectory(binarydataTempDir); } } else { FacesMessages.instance().add("No Projects found!"); } return null; }
From source file:com.esofthead.mycollab.vaadin.resources.StreamDownloadResourceSupportExtDrive.java
private void addFolderToZip(String path, Resource res, ZipOutputStream zip) throws Exception { List<Resource> lstResource; if (ResourceUtils.getType(res) == ResourceType.MyCollab) { lstResource = resourceService.getResources(res.getPath()); } else {// w w w.jav a 2s. c o m ExternalResourceService service = ResourceUtils.getExternalResourceService(ResourceUtils.getType(res)); lstResource = service.getResources(ResourceUtils.getExternalDrive(res), res.getPath()); } if (res instanceof Folder && lstResource.size() == 0) { // emptyFolder zip.putNextEntry(new ZipEntry(path + "/" + res.getName() + "/")); } else { if (res instanceof Folder) { zip.putNextEntry(new ZipEntry(path + "/" + res.getName() + "/")); } for (Resource curRes : lstResource) { if (curRes instanceof Folder) { addFolderToZip(path + "/" + res.getName(), curRes, zip); } else { addFileToZip(path + "/" + res.getName(), (Content) curRes, zip); } } } }
From source file:com.fujitsu.dc.test.unit.cell.LogTest.java
private void createZip(ZipOutputStream zos, File[] files) throws IOException { byte[] buf = new byte[1024]; InputStream is = null;/*from w w w. ja v a2 s .c o m*/ try { for (File file : files) { ZipEntry entry = new ZipEntry(file.getName()); zos.putNextEntry(entry); is = new BufferedInputStream(new FileInputStream(file)); int len = 0; while ((len = is.read(buf)) != -1) { zos.write(buf, 0, len); } } } finally { IOUtils.closeQuietly(is); } }