List of usage examples for java.util.zip ZipOutputStream putNextEntry
public void putNextEntry(ZipEntry e) throws IOException
From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java
public static void splitZip(File inputFile, File outputFile, Set<String> includeEnties) throws IOException { if (outputFile.exists()) { FileUtils.deleteQuietly(outputFile); }//from ww w.j a va2 s . c o m if (null == includeEnties || includeEnties.size() < 1) { return; } FileOutputStream fos = new FileOutputStream(outputFile); ZipOutputStream jos = new ZipOutputStream(fos); final byte[] buffer = new byte[8192]; FileInputStream fis = new FileInputStream(inputFile); ZipInputStream zis = new ZipInputStream(fis); try { // loop on the entries of the jar file package and put them in the final jar ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { // do not take directories or anything inside a potential META-INF folder. if (entry.isDirectory()) { continue; } String name = entry.getName(); if (!includeEnties.contains(name)) { continue; } JarEntry newEntry; // Preserve the STORED method of the input entry. if (entry.getMethod() == JarEntry.STORED) { newEntry = new JarEntry(entry); } else { // Create a new entry so that the compressed len is recomputed. newEntry = new JarEntry(name); } // add the entry to the jar archive jos.putNextEntry(newEntry); // read the content of the entry from the input stream, and write it into the archive. int count; while ((count = zis.read(buffer)) != -1) { jos.write(buffer, 0, count); } // close the entries for this file jos.closeEntry(); zis.closeEntry(); } } finally { zis.close(); } fis.close(); jos.close(); }
From source file:eu.scape_project.planning.xml.ProjectExportAction.java
/** * new helper method that was refactored from * {@link #exportAllProjectsToZip()} It takes a list of * {@link PlanProperties} and exports it to a zip file. * //w w w .j ava 2 s .c o m * @param ppList * {@link PlanProperties} for plans to export * * @return True if export was successful, false otherwise. */ private boolean exportPPListToZip(List<PlanProperties> ppList) { if (!ppList.isEmpty()) { log.debug("number of plans to export: " + ppList.size()); String filename = "allprojects.zip"; lastProjectExportPath = OS.getTmpPath() + "export" + System.currentTimeMillis() + "/"; new File(lastProjectExportPath).mkdirs(); String binarydataTempPath = lastProjectExportPath + "binarydata/"; File binarydataTempDir = new File(binarydataTempPath); binarydataTempDir.mkdirs(); try { OutputStream out = new BufferedOutputStream(new FileOutputStream(lastProjectExportPath + 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(lastProjectExportPath + "finished.info").createNewFile(); // FacesMessages.instance().add(FacesMessage.SEVERITY_INFO, // "Export was written to: " + exportPath); log.info("Export was written to: " + lastProjectExportPath); } 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(lastProjectExportPath + "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."); } return false; } finally { // remove all binary temp files OS.deleteDirectory(binarydataTempDir); } } return true; }
From source file:gov.nih.nci.cabig.caaers.web.ae.AdditionalInformationDocumentZipDownloadController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException { Integer additionalInformationId = ServletRequestUtils.getRequiredIntParameter(request, "additionalInformationId"); List<AdditionalInformationDocument> additionalInformationDocuments = additionalInformationDocumentService .findByAdditionalInformationId(additionalInformationId); File tempFile = null;/*from w w w. j ava 2s . c om*/ ZipOutputStream zos = null; FileOutputStream fos = null; List<String> zipEntriesName = new ArrayList<String>(); try { tempFile = File.createTempFile( "additionalInformationFile" + System.currentTimeMillis() + RandomUtils.nextInt(1000), ".zip"); fos = new FileOutputStream(tempFile); zos = new ZipOutputStream(fos); for (AdditionalInformationDocument additionalInformationDocument : additionalInformationDocuments) { String name = getUniqueZipEntryName(additionalInformationDocument, zipEntriesName); zipEntriesName.add(name); ZipEntry zipEntry = new ZipEntry(name); zos.putNextEntry(zipEntry); IOUtils.copy(new FileInputStream(additionalInformationDocument.getFile()), zos); zos.closeEntry(); } zos.flush(); } catch (Exception e) { log.error("Unable to create temp file", e); return null; } finally { if (zos != null) IOUtils.closeQuietly(zos); if (fos != null) IOUtils.closeQuietly(fos); } if (tempFile != null) { FileInputStream fis = null; OutputStream out = null; try { fis = new FileInputStream(tempFile); out = response.getOutputStream(); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment; filename=" + additionalInformationId + ".zip"); response.setHeader("Content-length", String.valueOf(tempFile.length())); response.setHeader("Pragma", "private"); response.setHeader("Cache-control", "private, must-revalidate"); IOUtils.copy(fis, out); out.flush(); } catch (Exception e) { log.error("Error while reading zip file ", e); } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(out); } FileUtils.deleteQuietly(tempFile); } return null; }
From source file:fr.cirad.mgdb.exporting.markeroriented.EigenstratExportHandler.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 { // long before = System.currentTimeMillis(); File warningFile = File.createTempFile("export_warnings_", ""); FileWriter warningFileWriter = new FileWriter(warningFile); File snpFile = null;//w w w .j av a2s.c o m try { snpFile = File.createTempFile("snpFile", ""); FileWriter snpFileWriter = new FileWriter(snpFile); ZipOutputStream zos = new ZipOutputStream(outputStream); if (ByteArrayOutputStream.class.isAssignableFrom(outputStream.getClass())) zos.setLevel(ZipOutputStream.STORED); 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); } } MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule); int markerCount = markerCursor.count(); List<Individual> individuals = getIndividualsFromSamples(sModule, sampleIDs); ArrayList<String> individualList = new ArrayList<String>(); StringBuffer indFileContents = new StringBuffer(); for (int i = 0; i < sampleIDs.size(); i++) { Individual individual = individuals.get(i); if (!individualList.contains(individual.getId())) { individualList.add(individual.getId()); indFileContents .append(individual.getId() + "\t" + getIndividualGenderCode(sModule, individual.getId()) + "\t" + (individual.getPopulation() == null ? "." : individual.getPopulation()) + LINE_SEPARATOR); } } String exportName = sModule + "_" + markerCount + "variants_" + individualList.size() + "individuals"; zos.putNextEntry(new ZipEntry(exportName + ".ind")); zos.write(indFileContents.toString().getBytes()); zos.putNextEntry(new ZipEntry(exportName + ".eigenstratgeno")); int avgObjSize = (Integer) mongoTemplate .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats() .get("avgObjSize"); int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize; short nProgress = 0, nPreviousProgress = 0; long nLoadedMarkerCount = 0; while (markerCursor.hasNext()) { int nLoadedMarkerCountInLoop = 0; Map<Comparable, String> markerChromosomalPositions = new LinkedHashMap<Comparable, String>(); boolean fStartingNewChunk = true; markerCursor.batchSize(nChunkSize); while (markerCursor.hasNext() && (fStartingNewChunk || nLoadedMarkerCountInLoop % nChunkSize != 0)) { DBObject exportVariant = markerCursor.next(); DBObject refPos = (DBObject) exportVariant.get(VariantData.FIELDNAME_REFERENCE_POSITION); markerChromosomalPositions.put((Comparable) exportVariant.get("_id"), refPos.get(ReferencePosition.FIELDNAME_SEQUENCE) + ":" + refPos.get(ReferencePosition.FIELDNAME_START_SITE)); nLoadedMarkerCountInLoop++; fStartingNewChunk = false; } List<Comparable> currentMarkers = new ArrayList<Comparable>(markerChromosomalPositions.keySet()); 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()) // read data and write results into temporary files (one per sample) { Comparable variantId = variant.getId(); List<String> chromAndPos = Helper.split(markerChromosomalPositions.get(variantId), ":"); if (chromAndPos.size() == 0) LOG.warn("Chromosomal position not found for marker " + variantId); // LOG.debug(marker + "\t" + (chromAndPos.length == 0 ? "0" : chromAndPos[0]) + "\t" + 0 + "\t" + (chromAndPos.length == 0 ? 0l : Long.parseLong(chromAndPos[1])) + LINE_SEPARATOR); if (markerSynonyms != null) { Comparable syn = markerSynonyms.get(variantId); if (syn != null) variantId = syn; } snpFileWriter.write(variantId + "\t" + (chromAndPos.size() == 0 ? "0" : chromAndPos.get(0)) + "\t" + 0 + "\t" + (chromAndPos.size() == 0 ? 0l : Long.parseLong(chromAndPos.get(1))) + LINE_SEPARATOR); Map<String, List<String>> individualGenotypes = new LinkedHashMap<String, List<String>>(); Collection<VariantRunData> runs = variantsAndRuns.get(variant); if (runs != null) for (VariantRunData run : runs) for (Integer sampleIndex : run.getSampleGenotypes().keySet()) { SampleGenotype sampleGenotype = run.getSampleGenotypes().get(sampleIndex); String individualId = individuals .get(sampleIDs .indexOf(new SampleId(run.getId().getProjectId(), sampleIndex))) .getId(); Integer gq = null; try { gq = (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_GQ); } catch (Exception ignored) { } if (gq != null && gq < nMinimumGenotypeQuality) continue; Integer dp = null; try { dp = (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_DP); } catch (Exception ignored) { } if (dp != null && dp < nMinimumReadDepth) continue; String gtCode = sampleGenotype.getCode(); List<String> storedIndividualGenotypes = individualGenotypes.get(individualId); if (storedIndividualGenotypes == null) { storedIndividualGenotypes = new ArrayList<String>(); individualGenotypes.put(individualId, storedIndividualGenotypes); } storedIndividualGenotypes.add(gtCode); } for (int j = 0; j < individualList .size(); j++ /* we use this list because it has the proper ordering*/) { String individualId = individualList.get(j); List<String> genotypes = individualGenotypes.get(individualId); HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes int highestGenotypeCount = 0; String mostFrequentGenotype = null; if (genotypes != null) for (String genotype : genotypes) { if (genotype.length() == 0) continue; /* skip missing genotypes */ int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype); if (gtCount > highestGenotypeCount) { highestGenotypeCount = gtCount; mostFrequentGenotype = genotype; } genotypeCounts.put(genotype, gtCount); } List<String> alleles = mostFrequentGenotype == null ? new ArrayList<String>() : variant.getAllelesFromGenotypeCode(mostFrequentGenotype); int nOutputCode = 0; if (mostFrequentGenotype == null) nOutputCode = 9; else for (String all : Helper.split(mostFrequentGenotype, "/")) if ("0".equals(all)) nOutputCode++; if (j == 0 && variant.getKnownAlleleList().size() > 2) warningFileWriter.write("- Variant " + variant.getId() + " is multi-allelic. Make sure Eigenstrat genotype encoding specifications are suitable for you.\n"); zos.write(("" + nOutputCode).getBytes()); if (genotypeCounts.size() > 1 || alleles.size() > 2) { if (genotypeCounts.size() > 1) warningFileWriter.write("- Dissimilar genotypes found for variant " + (variantId == null ? variant.getId() : variantId) + ", individual " + individualId + ". Exporting most frequent: " + nOutputCode + "\n"); if (alleles.size() > 2) warningFileWriter.write("- More than 2 alleles found for variant " + (variantId == null ? variant.getId() : variantId) + ", individual " + individualId + ". Exporting only the first 2 alleles.\n"); } } zos.write((LINE_SEPARATOR).getBytes()); } if (progress.hasAborted()) return; nLoadedMarkerCount += nLoadedMarkerCountInLoop; nProgress = (short) (nLoadedMarkerCount * 100 / markerCount); if (nProgress > nPreviousProgress) { // if (nProgress%5 == 0) // LOG.info("============= exportData: " + nProgress + "% =============" + (System.currentTimeMillis() - before)/1000 + "s"); progress.setCurrentStepProgress(nProgress); nPreviousProgress = nProgress; } } snpFileWriter.close(); zos.putNextEntry(new ZipEntry(exportName + ".snp")); BufferedReader in = new BufferedReader(new FileReader(snpFile)); String sLine; while ((sLine = in.readLine()) != null) zos.write((sLine + "\n").getBytes()); in.close(); warningFileWriter.close(); if (warningFile.length() > 0) { zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt")); int nWarningCount = 0; in = new BufferedReader(new FileReader(warningFile)); while ((sLine = in.readLine()) != null) { zos.write((sLine + "\n").getBytes()); nWarningCount++; } LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount); in.close(); } warningFile.delete(); zos.close(); progress.setCurrentStepProgress((short) 100); } finally { if (snpFile != null && snpFile.exists()) snpFile.delete(); } }
From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java
private void zipWebInfJar(String zipName, File[] files) throws Exception { byte[] buffer = new byte[4096]; // Create a buffer for copying int bytesRead; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipName)); try {//from w w w. j a va 2 s.c o m for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.isDirectory()) { continue; } String fileName = "WEB-INF/" + f.getName(); FileInputStream in = new FileInputStream(f); // Stream to read file try { ZipEntry entry = new ZipEntry(fileName); // Make a ZipEntry out.putNextEntry(entry); // Store entry while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } finally { in.close(); } } } finally { out.close(); } }
From source file:edu.isi.wings.catalog.component.api.impl.oodt.ComponentCreationFM.java
private void addDirToArchive(ZipOutputStream zos, File srcFile) { File[] files = srcFile.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { addDirToArchive(zos, files[i]); continue; }//from w w w . j a va 2s .com try { byte[] buffer = new byte[1024]; FileInputStream fis = new FileInputStream(files[i]); zos.putNextEntry(new ZipEntry(files[i].getName())); int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); fis.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
From source file:org.saiku.plugin.resources.PentahoRepositoryResource2.java
@GET @Path("/zip") public Response getResourcesAsZip(@QueryParam("directory") String directory, @QueryParam("files") String files, @QueryParam("type") String type) { try {// ww w. j a v a 2 s . c om if (StringUtils.isBlank(directory)) return Response.ok().build(); final String fileType = type; IUserContentAccess access = contentAccessFactory.getUserContentAccess(null); if (!access.fileExists(directory) && access.hasAccess(directory, FileAccess.READ)) { throw new SaikuServiceException( "Access to Repository has failed File does not exist or no read right: " + directory); } IBasicFileFilter txtFilter = StringUtils.isBlank(type) ? null : new IBasicFileFilter() { public boolean accept(IBasicFile file) { return file.isDirectory() || file.getExtension().equals(fileType); } }; ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(bos); List<IBasicFile> basicFiles = access.listFiles(directory, txtFilter); for (IBasicFile basicFile : basicFiles) { if (!basicFile.isDirectory()) { String entry = basicFile.getName(); byte[] doc = IOUtils.toByteArray(basicFile.getContents()); ZipEntry ze = new ZipEntry(entry); zos.putNextEntry(ze); zos.write(doc); } } zos.closeEntry(); zos.close(); byte[] zipDoc = bos.toByteArray(); return Response.ok(zipDoc, MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition", "attachment; filename = " + directory + ".zip") .header("content-length", zipDoc.length).build(); } catch (Exception e) { log.error("Cannot zip resources " + files, e); String error = ExceptionUtils.getRootCauseMessage(e); return Response.serverError().entity(error).build(); } }
From source file:fr.univrouen.poste.services.ZipService.java
public void writeZip(List<PosteCandidature> posteCandidatures, OutputStream destStream) throws IOException, SQLException { ZipOutputStream out = new ZipOutputStream(destStream); for (PosteCandidature posteCandidature : posteCandidatures) { String folderName = posteCandidature.getPoste().getNumEmploi().concat("/"); folderName = folderName.concat(posteCandidature.getCandidat().getNom().concat("-")); folderName = folderName.concat(posteCandidature.getCandidat().getPrenom().concat("-")); folderName = folderName.concat(posteCandidature.getCandidat().getNumCandidat().concat("/")); for (PosteCandidatureFile posteCandidatureFile : posteCandidature.getCandidatureFiles()) { String fileName = posteCandidatureFile.getId().toString().concat("-") .concat(posteCandidatureFile.getFilename()); String folderFileName = folderName.concat(fileName); out.putNextEntry(new ZipEntry(folderFileName)); InputStream inputStream = posteCandidatureFile.getBigFile().getBinaryFile().getBinaryStream(); BufferedInputStream bufInputStream = new BufferedInputStream(inputStream, BUFFER); byte[] bytes = new byte[BUFFER]; int length; while ((length = bufInputStream.read(bytes)) >= 0) { out.write(bytes, 0, length); }//w ww . j a v a 2s . com out.closeEntry(); } } out.close(); }
From source file:net.morphbank.mbsvc3.webservices.Uploader.java
private String createZipFile() { String fileName = folderPath + "xml" + getNextReqFileNumber(folderPath) + ".zip"; String list = ""; try {//ww w . java 2 s . c o m FileOutputStream fout = new FileOutputStream(fileName); ZipOutputStream zout = new ZipOutputStream(fout); for (int i = 0; i < listOfXmlFiles.size(); i++) { String file = listOfXmlFiles.get(i); if (file.endsWith(".xml")) { list += file; FileInputStream fin = new FileInputStream(listOfXmlFiles.get(i)); ZipEntry ze = new ZipEntry(listOfXmlFiles.get(i).replaceAll(folderPath, "")); zout.putNextEntry(ze); for (int c = fin.read(); c != -1; c = fin.read()) { zout.write(c); } fin.close(); } } zout.close(); fout.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fileName.replaceAll(folderPath, ""); }
From source file:com.vmware.appfactory.recipe.controller.RecipeApiController.java
private void writeToZip(OutputStream os, Recipe recipe) throws IOException { InputStream is = null;//from w ww. ja v a 2 s. c om ZipOutputStream zos = null; try { zos = new ZipOutputStream(os); _log.debug("Opened a ZIP stream"); /* Write recipe into the ZIP stream */ String jsonFileName = toFileName(recipe.getName() + AfConstant.RECIPE_FILE_EXTENSION); _log.debug("Writing the JSON file ({})", jsonFileName); zos.putNextEntry(new ZipEntry(jsonFileName)); String json = EXPORT_OBJECT_MAPPER.writeValueAsString(recipe); zos.write(json.getBytes()); /* Copy all payload files into the temporary directory */ for (RecipeFile file : recipe.getFiles()) { if (file.getPath() != null) { try { writeRecipeFileToZip(recipe, file, zos); } catch (IOException ex) { throw new IOException("Failed to export recipe file " + file.getURI().toString(), ex); } } } /* Done with the ZIP file */ zos.finish(); zos = null; } catch (IOException ex) { IOUtils.closeQuietly(zos); IOUtils.closeQuietly(is); throw ex; } }