List of usage examples for java.util.zip ZipOutputStream ZipOutputStream
public ZipOutputStream(OutputStream out)
From source file:be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java
private ZipOutputStream copyOOXMLContent(String signatureZipEntryName, OutputStream signedOOXMLOutputStream) throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException { ZipOutputStream zipOutputStream = new ZipOutputStream(signedOOXMLOutputStream); ZipInputStream zipInputStream = new ZipInputStream(this.getOfficeOpenXMLDocumentURL().openStream()); ZipEntry zipEntry;/*from w w w. j a v a 2s . c o m*/ boolean hasOriginSigsRels = false; while (null != (zipEntry = zipInputStream.getNextEntry())) { LOG.debug("copy ZIP entry: " + zipEntry.getName()); ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); if ("[Content_Types].xml".equals(zipEntry.getName())) { Document contentTypesDocument = loadDocumentNoClose(zipInputStream); Element typesElement = contentTypesDocument.getDocumentElement(); /* * We need to add an Override element. */ Element overrideElement = contentTypesDocument.createElementNS( "http://schemas.openxmlformats.org/package/2006/content-types", "Override"); overrideElement.setAttribute("PartName", "/" + signatureZipEntryName); overrideElement.setAttribute("ContentType", "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"); typesElement.appendChild(overrideElement); Element nsElement = contentTypesDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "http://schemas.openxmlformats.org/package/2006/content-types"); NodeList nodeList = XPathAPI.selectNodeList(contentTypesDocument, "/tns:Types/tns:Default[@Extension='sigs']", nsElement); if (0 == nodeList.getLength()) { /* * Add Default element for 'sigs' extension. */ Element defaultElement = contentTypesDocument.createElementNS( "http://schemas.openxmlformats.org/package/2006/content-types", "Default"); defaultElement.setAttribute("Extension", "sigs"); defaultElement.setAttribute("ContentType", "application/vnd.openxmlformats-package.digital-signature-origin"); typesElement.appendChild(defaultElement); } writeDocumentNoClosing(contentTypesDocument, zipOutputStream, false); } else if ("_rels/.rels".equals(zipEntry.getName())) { Document relsDocument = loadDocumentNoClose(zipInputStream); Element nsElement = relsDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "http://schemas.openxmlformats.org/package/2006/relationships"); NodeList nodeList = XPathAPI.selectNodeList(relsDocument, "/tns:Relationships/tns:Relationship[@Target='_xmlsignatures/origin.sigs']", nsElement); if (0 == nodeList.getLength()) { Element relationshipElement = relsDocument.createElementNS( "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship"); relationshipElement.setAttribute("Id", "rel-id-" + UUID.randomUUID().toString()); relationshipElement.setAttribute("Type", "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin"); relationshipElement.setAttribute("Target", "_xmlsignatures/origin.sigs"); relsDocument.getDocumentElement().appendChild(relationshipElement); } writeDocumentNoClosing(relsDocument, zipOutputStream, false); } else if ("_xmlsignatures/_rels/origin.sigs.rels".equals(zipEntry.getName())) { hasOriginSigsRels = true; Document originSignRelsDocument = loadDocumentNoClose(zipInputStream); Element relationshipElement = originSignRelsDocument.createElementNS( "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship"); String relationshipId = "rel-" + UUID.randomUUID().toString(); relationshipElement.setAttribute("Id", relationshipId); relationshipElement.setAttribute("Type", "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); String target = FilenameUtils.getName(signatureZipEntryName); LOG.debug("target: " + target); relationshipElement.setAttribute("Target", target); originSignRelsDocument.getDocumentElement().appendChild(relationshipElement); writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false); } else { IOUtils.copy(zipInputStream, zipOutputStream); } } if (false == hasOriginSigsRels) { /* * Add signature relationships document. */ addOriginSigsRels(signatureZipEntryName, zipOutputStream); addOriginSigs(zipOutputStream); } /* * Return. */ zipInputStream.close(); return zipOutputStream; }
From source file:com.liferay.ide.server.remote.AbstractRemoteServerPublisher.java
public IPath publishModuleDelta(String archiveName, IModuleResourceDelta[] deltas, String deletePrefix, boolean adjustGMTOffset) throws CoreException { IPath path = LiferayServerCore.getTempLocation("partial-war", archiveName); //$NON-NLS-1$ FileOutputStream outputStream = null; ZipOutputStream zip = null;/* w w w.j a v a2s .c om*/ File warfile = path.toFile(); warfile.getParentFile().mkdirs(); try { outputStream = new FileOutputStream(warfile); zip = new ZipOutputStream(outputStream); Map<ZipEntry, String> deleteEntries = new HashMap<ZipEntry, String>(); processResourceDeltas(deltas, zip, deleteEntries, deletePrefix, StringPool.EMPTY, adjustGMTOffset); for (ZipEntry entry : deleteEntries.keySet()) { zip.putNextEntry(entry); zip.write(deleteEntries.get(entry).getBytes()); } // if ((removedResources != null) && (removedResources.size() > 0)) { // writeRemovedResources(removedResources, zip); // } } catch (Exception ex) { ex.printStackTrace(); } finally { if (zip != null) { try { zip.close(); } catch (IOException localIOException1) { } } } return new Path(warfile.getAbsolutePath()); }
From source file:org.elasticsearch.plugins.PluginManagerIT.java
/** creates a plugin .zip and returns the url for testing */ private String createPlugin(final Path structure, String... properties) throws IOException { writeProperties(structure, properties); Path zip = createTempDir().resolve(structure.getFileName() + ".zip"); try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zip))) { Files.walkFileTree(structure, new SimpleFileVisitor<Path>() { @Override/* ww w.ja v a 2 s. co m*/ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { stream.putNextEntry(new ZipEntry(structure.relativize(file).toString())); Files.copy(file, stream); return FileVisitResult.CONTINUE; } }); } if (randomBoolean()) { writeSha1(zip, false); } else if (randomBoolean()) { writeMd5(zip, false); } return zip.toUri().toURL().toString(); }
From source file:msearch.filmlisten.MSFilmlisteSchreiben.java
private void xmlSchreibenStart(String datei) throws IOException, XMLStreamException { File file = new File(datei); File dir = new File(file.getParent()); if (!dir.exists()) { if (!dir.mkdirs()) { MSLog.fehlerMeldung(947623049, MSLog.FEHLER_ART_PROG, "MSearchIoXmlFilmlisteSchreiben.xmlSchreibenStart", "Kann den Pfad nicht anlegen: " + dir.toString()); }/* ww w . ja v a2 s.c om*/ } MSLog.systemMeldung(" --> Start Schreiben nach: " + datei); XMLOutputFactory outFactory = XMLOutputFactory.newInstance(); if (datei.endsWith(MSConst.FORMAT_BZ2)) { bZip2CompressorOutputStream = new BZip2CompressorOutputStream(new FileOutputStream(file), 9 /*Blocksize: 1 - 9*/); out = new OutputStreamWriter(bZip2CompressorOutputStream, MSConst.KODIERUNG_UTF); } else if (datei.endsWith(MSConst.FORMAT_ZIP)) { zipOutputStream = new ZipOutputStream(new FileOutputStream(file)); ZipEntry entry = new ZipEntry(MSConst.XML_DATEI_FILME); zipOutputStream.putNextEntry(entry); out = new OutputStreamWriter(zipOutputStream, MSConst.KODIERUNG_UTF); } else { out = new OutputStreamWriter(new FileOutputStream(file), MSConst.KODIERUNG_UTF); } writer = outFactory.createXMLStreamWriter(out); writer.writeStartDocument("UTF-8", "1.0"); writer.writeCharacters("\n");//neue Zeile writer.writeStartElement(MSConst.XML_START); writer.writeCharacters("\n");//neue Zeile }
From source file:com.nridge.core.base.std.FilUtl.java
/** * Compresses the input file into a ZIP file container. * * @param aInFileName The file name to be compressed. * @param aZipFileName The file name of the ZIP container. * @throws IOException Related to opening the file streams and * related read/write operations.//w w w.j a v a 2s . c om */ static public void zipFile(String aInFileName, String aZipFileName) throws IOException { File inFile; int byteCount; byte[] ioBuf; FileInputStream fileIn; ZipOutputStream zipOut; FileOutputStream fileOut; inFile = new File(aInFileName); if (inFile.isDirectory()) return; ioBuf = new byte[FILE_IO_BUFFER_SIZE]; fileIn = new FileInputStream(inFile); fileOut = new FileOutputStream(aZipFileName); zipOut = new ZipOutputStream(fileOut); zipOut.putNextEntry(new ZipEntry(inFile.getName())); byteCount = fileIn.read(ioBuf); while (byteCount > 0) { zipOut.write(ioBuf, 0, byteCount); byteCount = fileIn.read(ioBuf); } fileIn.close(); zipOut.closeEntry(); zipOut.close(); }
From source file:com.polyvi.xface.extension.zip.XZipExt.java
/** * ?/* ww w. jav a 2 s . c o m*/ * * @param srcFileURL * URL * @param zipFileURL * ?zip??URL * @throws FileNotFoundException * @throws IOException * @throws IllegalArgumentException */ private void zipDir(String srcFileURL, String zipFileURL) throws FileNotFoundException, IOException, IllegalArgumentException { Uri srcFileUri = getFileUri(srcFileURL); Uri dstFileUri = getFileUri(zipFileURL); if (areFilesSame(srcFileUri, dstFileUri)) { throw new IllegalArgumentException(); } prepareForZipDir(dstFileUri); ZipOutputStream zos = new ZipOutputStream(mResourceApi.openOutputStream(dstFileUri)); compressDir(srcFileUri, zos, ""); zos.close(); }
From source file:com.evolveum.midpoint.cli.ninja.action.ExportAction.java
private Writer createWriter() throws IOException { File file = getParams().getFile(); if (file != null) { if (file.exists()) { file.delete();// www.j a va2 s.c o m } file.createNewFile(); OutputStream os = new FileOutputStream(file); if (getParams().isZip()) { os = new ZipOutputStream(os); } Writer writer = new OutputStreamWriter(os, StandardCharsets.UTF_8); return new BufferedWriter(writer); } return new LogWriter(STD_OUT); }
From source file:ZipTransformTest.java
public void testFileZipEntryTransformerInStream() throws IOException { final String name = "foo"; final byte[] contents = "bar".getBytes(); File file1 = File.createTempFile("temp", null); File file2 = File.createTempFile("temp", null); try {//w w w .j a va2s . c o m // Create the ZIP file ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1)); try { zos.putNextEntry(new ZipEntry(name)); zos.write(contents); zos.closeEntry(); } finally { IOUtils.closeQuietly(zos); } // Transform the ZIP file FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(file1); out = new FileOutputStream(file2); ZipUtil.transformEntry(in, name, new FileZipEntryTransformer() { protected void transform(ZipEntry zipEntry, File in, File out) throws IOException { FileWriter fw = new FileWriter(out); fw.write("CAFEBABE"); fw.close(); } }, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } // Test the ZipUtil byte[] actual = ZipUtil.unpackEntry(file2, name); assertNotNull(actual); assertEquals("CAFEBABE", new String(actual)); } finally { FileUtils.deleteQuietly(file1); FileUtils.deleteQuietly(file2); } }
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 v a 2 s . co 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:ee.ria.xroad.common.asic.AsicContainer.java
/** * Write this container to the given output stream in ZIP format. * @param out the stream for writing container * @throws Exception if errors occurred when writing ZIP entries */// w ww . j a v a2s. c o m public void write(OutputStream out) throws Exception { try (ZipOutputStream zip = new ZipOutputStream(out)) { AsicHelper.write(this, zip); } }