List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry
public ZipArchiveEntry(ZipArchiveEntry entry) throws ZipException
From source file:org.dspace.content.packager.AbstractMETSDisseminator.java
/** * Add Bitstreams associated with a given DSpace Object into an * existing ZipArchiveOutputStream/*from w w w . j ava 2 s . co m*/ * @param context DSpace Context * @param dso The DSpace Object * @param params Parameters to the Packager script * @param zip Zip output */ protected void addBitstreamsToZip(Context context, DSpaceObject dso, PackageParameters params, ZipArchiveOutputStream zip) throws PackageValidationException, AuthorizeException, SQLException, IOException { // how to handle unauthorized bundle/bitstream: String unauth = (params == null) ? null : params.getProperty("unauthorized"); // copy all non-meta bitstreams into zip if (dso.getType() == Constants.ITEM) { Item item = (Item) dso; //get last modified time long lmTime = ((Item) dso).getLastModified().getTime(); Bundle bundles[] = item.getBundles(); for (int i = 0; i < bundles.length; i++) { if (includeBundle(bundles[i])) { // unauthorized bundle? if (!AuthorizeManager.authorizeActionBoolean(context, bundles[i], Constants.READ)) { if (unauth != null && (unauth.equalsIgnoreCase("skip"))) { log.warn("Skipping Bundle[\"" + bundles[i].getName() + "\"] because you are not authorized to read it."); continue; } else { throw new AuthorizeException( "Not authorized to read Bundle named \"" + bundles[i].getName() + "\""); } } Bitstream[] bitstreams = bundles[i].getBitstreams(); for (int k = 0; k < bitstreams.length; k++) { boolean auth = AuthorizeManager.authorizeActionBoolean(context, bitstreams[k], Constants.READ); if (auth || (unauth != null && unauth.equalsIgnoreCase("zero"))) { String zname = makeBitstreamURL(bitstreams[k], params); ZipArchiveEntry ze = new ZipArchiveEntry(zname); if (log.isDebugEnabled()) { log.debug(new StringBuilder().append("Writing CONTENT stream of bitstream(") .append(bitstreams[k].getID()).append(") to Zip: ").append(zname) .append(", size=").append(bitstreams[k].getSize()).toString()); } if (lmTime != 0) { ze.setTime(lmTime); } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged { ze.setTime(DEFAULT_MODIFIED_DATE); } ze.setSize(auth ? bitstreams[k].getSize() : 0); zip.putArchiveEntry(ze); if (auth) { InputStream input = bitstreams[k].retrieve(); Utils.copy(input, zip); input.close(); } else { log.warn("Adding zero-length file for Bitstream, SID=" + String.valueOf(bitstreams[k].getSequenceID()) + ", not authorized for READ."); } zip.closeArchiveEntry(); } else if (unauth != null && unauth.equalsIgnoreCase("skip")) { log.warn("Skipping Bitstream, SID=" + String.valueOf(bitstreams[k].getSequenceID()) + ", not authorized for READ."); } else { throw new AuthorizeException("Not authorized to read Bitstream, SID=" + String.valueOf(bitstreams[k].getSequenceID())); } } } } } // Coll, Comm just add logo bitstream to content if there is one else if (dso.getType() == Constants.COLLECTION || dso.getType() == Constants.COMMUNITY) { Bitstream logoBs = dso.getType() == Constants.COLLECTION ? ((Collection) dso).getLogo() : ((Community) dso).getLogo(); if (logoBs != null) { String zname = makeBitstreamURL(logoBs, params); ZipArchiveEntry ze = new ZipArchiveEntry(zname); if (log.isDebugEnabled()) { log.debug("Writing CONTENT stream of bitstream(" + String.valueOf(logoBs.getID()) + ") to Zip: " + zname + ", size=" + String.valueOf(logoBs.getSize())); } ze.setSize(logoBs.getSize()); //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged ze.setTime(DEFAULT_MODIFIED_DATE); zip.putArchiveEntry(ze); Utils.copy(logoBs.retrieve(), zip); zip.closeArchiveEntry(); } } }
From source file:org.eclipse.cbi.maven.plugins.macsigner.SignMojo.java
/** * Creates a zip file.//from w ww . ja v a 2 s . c o m * @param dir The Directory of the files to be zipped. * @param zip An output stream to write the file * @throws IOException */ private void createZip(File dir, ZipArchiveOutputStream zip) throws IOException { Deque<File> dir_stack = new LinkedList<File>(); dir_stack.push(dir); // base path is the parent of the "Application.app" folder // it will be used to make "Application.app" the top-level folder in the zip String base_path = getParentDirAbsolutePath(dir); // verify that "dir" actually id the ".app" folder if (!dir.getName().endsWith(".app")) throw new IOException("Please verify the configuration. Directory does not end with '.app': " + dir); while (!dir_stack.isEmpty()) { File file = dir_stack.pop(); File[] files = file.listFiles(); for (File f : files) { String name = f.getAbsolutePath().substring(base_path.length()); getLog().debug("Found: " + name); if (f.isFile() && isInContentsFolder(name)) { getLog().debug("Adding to zip file for signing: " + f); ZipArchiveEntry entry = new ZipArchiveEntry(name); zip.putArchiveEntry(entry); if (f.canExecute()) { //work around to track the relative file names // of those that need to be set as executable on unZip executableFiles.add(name); } InputStream is = new FileInputStream(f); copyInputStreamToOutputStream(is, zip); is.close(); zip.closeArchiveEntry(); } else if (f.isDirectory() && isInContentsFolder(name)) { //add directory entry dir_stack.push(f); } else { getLog().debug(f + " was not included in the zip file to be signed."); } } } }
From source file:org.eclipse.jgit.archive.ZipFormat.java
public void putEntry(ArchiveOutputStream out, String path, FileMode mode, ObjectLoader loader) throws IOException { // ZipArchiveEntry detects directories by checking // for '/' at the end of the filename. if (path.endsWith("/") && mode != FileMode.TREE) //$NON-NLS-1$ throw new IllegalArgumentException( MessageFormat.format(ArchiveText.get().pathDoesNotMatchMode, path, mode)); if (!path.endsWith("/") && mode == FileMode.TREE) //$NON-NLS-1$ path = path + "/"; //$NON-NLS-1$ final ZipArchiveEntry entry = new ZipArchiveEntry(path); if (mode == FileMode.TREE) { out.putArchiveEntry(entry);/*from ww w . ja v a 2s . co m*/ out.closeArchiveEntry(); return; } if (mode == FileMode.REGULAR_FILE) { // ok } else if (mode == FileMode.EXECUTABLE_FILE || mode == FileMode.SYMLINK) { entry.setUnixMode(mode.getBits()); } else { // Unsupported mode (e.g., GITLINK). throw new IllegalArgumentException(MessageFormat.format(ArchiveText.get().unsupportedMode, mode)); } entry.setSize(loader.getSize()); out.putArchiveEntry(entry); loader.copyTo(out); out.closeArchiveEntry(); }
From source file:org.eclipse.tracecompass.internal.tmf.ui.project.wizards.importtrace.ZipLeveledStructureProvider.java
/** * Creates a new container zip entry with the specified name, iff it has * not already been created. If the parent of the given element does not * already exist it will be recursively created as well. * @param pathname The path representing the container * @return The element represented by this pathname (it may have already existed) *//*from w w w. j ava 2s. c om*/ protected ZipArchiveEntry createContainer(IPath pathname) { ZipArchiveEntry existingEntry = directoryEntryCache.get(pathname); if (existingEntry != null) { return existingEntry; } ZipArchiveEntry parent; if (pathname.segmentCount() == 0) { return null; } else if (pathname.segmentCount() == 1) { parent = root; } else { parent = createContainer(pathname.removeLastSegments(1)); } ZipArchiveEntry newEntry = new ZipArchiveEntry(pathname.toString()); directoryEntryCache.put(pathname, newEntry); List<ZipArchiveEntry> childList = new ArrayList<>(); children.put(newEntry, childList); List<ZipArchiveEntry> parentChildList = children.get(parent); NonNullUtils.checkNotNull(parentChildList).add(newEntry); return newEntry; }
From source file:org.eclipse.winery.generators.ia.Generator.java
/** * Recursive Helper function for packageProject() * //from w ww .j ava 2 s.c o m * @param folderOrFile to add into the archive * @param baseDir * @param zos ArchiveOutputStream to add the files to */ private void addFilesRecursively(File folderOrFile, String baseDir, ArchiveOutputStream zos) { if (folderOrFile.isFile()) { String nameOfFileInZip = folderOrFile.getAbsolutePath().replace(baseDir, ""); Generator.logger.trace("Adding " + folderOrFile + " as " + nameOfFileInZip); ArchiveEntry archiveEntry = new ZipArchiveEntry(nameOfFileInZip); try (InputStream is = new FileInputStream(folderOrFile)) { zos.putArchiveEntry(archiveEntry); IOUtils.copy(is, zos); zos.closeArchiveEntry(); } catch (Exception e) { e.printStackTrace(); } } else { Generator.logger.trace("Adding folder " + folderOrFile); for (File childFile : folderOrFile.listFiles()) { this.addFilesRecursively(childFile, baseDir, zos); } } }
From source file:org.eclipse.winery.repository.export.CSARExporter.java
/** * Writes a complete CSAR containing all necessary things reachable from the given service * template//from www . j ava 2 s . co m * * @param id the id of the service template to export * @param out the outputstream to write to * @throws JAXBException */ public void writeCSAR(TOSCAComponentId entryId, OutputStream out) throws ArchiveException, IOException, XMLStreamException, JAXBException { CSARExporter.logger.trace("Starting CSAR export with {}", entryId.toString()); Map<RepositoryFileReference, String> refMap = new HashMap<RepositoryFileReference, String>(); Collection<String> definitionNames = new ArrayList<>(); final ArchiveOutputStream zos = new ArchiveStreamFactory().createArchiveOutputStream("zip", out); TOSCAExportUtil exporter = new TOSCAExportUtil(); Map<String, Object> conf = new HashMap<>(); ExportedState exportedState = new ExportedState(); TOSCAComponentId currentId = entryId; do { String defName = CSARExporter.getDefinitionsPathInsideCSAR(currentId); definitionNames.add(defName); zos.putArchiveEntry(new ZipArchiveEntry(defName)); Collection<TOSCAComponentId> referencedIds; try { referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, null); } catch (IllegalStateException e) { // thrown if something went wrong inside the repo out.close(); // we just rethrow as there currently is no error stream. throw e; } zos.closeArchiveEntry(); exportedState.flagAsExported(currentId); exportedState.flagAsExportRequired(referencedIds); currentId = exportedState.pop(); } while (currentId != null); // if we export a ServiceTemplate, data for the self-service portal might exist if (entryId instanceof ServiceTemplateId) { this.addSelfServiceMetaData((ServiceTemplateId) entryId, refMap); } // now, refMap contains all files to be added to the CSAR // write manifest directly after the definitions to have it more at the beginning of the ZIP // rather than having it at the very end this.addManifest(entryId, definitionNames, refMap, zos); // used for generated XSD schemas TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer; try { transformer = tFactory.newTransformer(); } catch (TransformerConfigurationException e1) { CSARExporter.logger.debug(e1.getMessage(), e1); throw new IllegalStateException("Could not instantiate transformer", e1); } // write all referenced files for (RepositoryFileReference ref : refMap.keySet()) { String archivePath = refMap.get(ref); archivePath = replaceBPMN4Tosca2BPELPath(archivePath, ref.getFileName(), entryId); ref = replaceBPMN4Tosca2BPELRef(archivePath, ref); CSARExporter.logger.trace("Creating {}", archivePath); ArchiveEntry archiveEntry = new ZipArchiveEntry(archivePath); zos.putArchiveEntry(archiveEntry); if (ref instanceof DummyRepositoryFileReferenceForGeneratedXSD) { CSARExporter.logger.trace("Special treatment for generated XSDs"); Document document = ((DummyRepositoryFileReferenceForGeneratedXSD) ref).getDocument(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(zos); try { transformer.transform(source, result); } catch (TransformerException e) { CSARExporter.logger.debug("Could not serialize generated xsd", e); } } else { try (InputStream is = Repository.INSTANCE.newInputStream(ref)) { IOUtils.copy(is, zos); } catch (Exception e) { CSARExporter.logger.error("Could not copy file content to ZIP outputstream", e); } } zos.closeArchiveEntry(); } this.addNamespacePrefixes(zos); deleteFiles(tempFiles.toArray(new File[tempFiles.size()])); zos.finish(); zos.close(); }
From source file:org.eclipse.winery.repository.export.CSARExporter.java
/** * Writes the configured mapping namespaceprefix -> namespace to the archive * /*from ww w .j a va 2s. co m*/ * This is kind of a quick hack. TODO: during the import, the prefixes should be extracted using * JAXB and stored in the NamespacesResource * * @throws IOException */ private void addNamespacePrefixes(ArchiveOutputStream zos) throws IOException { Configuration configuration = Repository.INSTANCE.getConfiguration(new NamespacesId()); if (configuration instanceof PropertiesConfiguration) { // Quick hack: direct serialization only works for PropertiesConfiguration PropertiesConfiguration pconf = (PropertiesConfiguration) configuration; ArchiveEntry archiveEntry = new ZipArchiveEntry(CSARExporter.PATH_TO_NAMESPACES_PROPERTIES); zos.putArchiveEntry(archiveEntry); try { pconf.save(zos); } catch (ConfigurationException e) { CSARExporter.logger.debug(e.getMessage(), e); zos.write("#Could not export properties".getBytes()); zos.write(("#" + e.getMessage()).getBytes()); } zos.closeArchiveEntry(); } }
From source file:org.eclipse.winery.repository.export.CSARExporter.java
private void addManifest(TOSCAComponentId id, Collection<String> definitionNames, Map<RepositoryFileReference, String> refMap, ArchiveOutputStream out) throws IOException { String entryDefinitionsReference = CSARExporter.getDefinitionsPathInsideCSAR(id); out.putArchiveEntry(new ZipArchiveEntry("TOSCA-Metadata/TOSCA.meta")); PrintWriter pw = new PrintWriter(out); // Setting Versions pw.println("TOSCA-Meta-Version: 1.0"); pw.println("CSAR-Version: 1.0"); String versionString = "Created-By: Winery " + Prefs.INSTANCE.getVersion(); pw.println(versionString);//from ww w. j av a 2 s.co m // Winery currently is unaware of tDefinitions, therefore, we use the // name of the service template pw.println("Entry-Definitions: " + entryDefinitionsReference); pw.println(); assert (definitionNames.contains(entryDefinitionsReference)); for (String name : definitionNames) { pw.println("Name: " + name); pw.println("Content-Type: " + org.eclipse.winery.common.constants.MimeTypes.MIMETYPE_TOSCA_DEFINITIONS); pw.println(); } // Setting other files, mainly files belonging to artifacts for (RepositoryFileReference ref : refMap.keySet()) { String archivePath = refMap.get(ref); if (archivePath.endsWith(".bpmn4tosca") || archivePath.endsWith("file.json")) { String bpelName = getPlanName(archivePath); String newFileName = getNewFileNameByPlanName(archivePath, bpelName); pw.println("Name: " + newFileName); pw.println("Content-Type: application/octet-stream"); } else { pw.println("Name: " + archivePath); String mimeType; if (ref instanceof DummyRepositoryFileReferenceForGeneratedXSD) { mimeType = MimeTypes.MIMETYPE_XSD; } else { mimeType = Repository.INSTANCE.getMimeType(ref); } pw.println("Content-Type: " + mimeType); } pw.println(); } pw.flush(); out.closeArchiveEntry(); }
From source file:org.eclipse.winery.repository.export.ZipExporter.java
/** * Writes a complete CSAR containing all necessary things reachable from the given service * template/*from w w w .ja v a 2 s. c om*/ * * @param id the id of the service template to export * @param out the outputstream to write to * @throws JAXBException */ public void writeZip(TOSCAComponentId entryId, OutputStream out) throws ArchiveException, IOException, XMLStreamException, JAXBException { ZipExporter.logger.trace("Starting CSAR export with {}", entryId.toString()); Map<RepositoryFileReference, String> refMap = new HashMap<RepositoryFileReference, String>(); Collection<String> definitionNames = new ArrayList<>(); final ArchiveOutputStream zos = new ArchiveStreamFactory().createArchiveOutputStream("zip", out); TOSCAExportUtil exporter = new TOSCAExportUtil(); Map<String, Object> conf = new HashMap<>(); ExportedState exportedState = new ExportedState(); TOSCAComponentId currentId = entryId; do { logger.info("begin to scan class:" + System.currentTimeMillis()); Reflections reflections = new Reflections("org.eclipse.winery.repository.ext"); Set<Class<? extends ExportFileGenerator>> implenmetions = reflections .getSubTypesOf(org.eclipse.winery.repository.ext.export.custom.ExportFileGenerator.class); logger.info("end to scan class:" + System.currentTimeMillis()); Iterator<Class<? extends ExportFileGenerator>> it = implenmetions.iterator(); Collection<TOSCAComponentId> referencedIds = null; String defName = ZipExporter.getDefinitionsPathInsideCSAR(currentId); definitionNames.add(defName); zos.putArchiveEntry(new ZipArchiveEntry(defName)); try { referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, null); } catch (IllegalStateException e) { // thrown if something went wrong inside the repo out.close(); // we just rethrow as there currently is no error stream. throw e; } zos.closeArchiveEntry(); while (it.hasNext()) { Class<? extends ExportFileGenerator> exportClass = it.next(); logger.trace("the " + exportClass.toString() + "begin to write file"); try { if (!Modifier.isAbstract(exportClass.getModifiers())) { ExportFileGenerator fileGenerator = exportClass.newInstance(); referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, fileGenerator); } } catch (InstantiationException e) { logger.error("export error occur while instancing " + exportClass.toString(), e); out.close(); } catch (IllegalAccessException e) { logger.error("export error occur", e); out.close(); } } exportedState.flagAsExported(currentId); exportedState.flagAsExportRequired(referencedIds); currentId = exportedState.pop(); } while (currentId != null); // if we export a ServiceTemplate, data for the self-service portal might exist if (entryId instanceof ServiceTemplateId) { this.addSelfServiceMetaData((ServiceTemplateId) entryId, refMap); addCsarMeta((ServiceTemplateId) entryId, zos); } // write custom file CustomizedFileInfos customizedResult = null; if (entryId instanceof ServiceTemplateId) { customizedResult = this.exportCustomFiles((ServiceTemplateId) entryId, zos); } // write manifest directly after the definitions to have it more at the beginning of the ZIP // rather than having it at the very end this.addManifest(entryId, definitionNames, refMap, zos); this.addManiYamlfest(entryId, exporter.getYamlExportDefResultList(), refMap, zos, exporter); this.addCheckSumFest( getCheckSums(exporter.getYamlExportDefResultList(), customizedResult.getCustomizedFileResults()), zos); // used for generated XSD schemas TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer; try { transformer = tFactory.newTransformer(); } catch (TransformerConfigurationException e1) { ZipExporter.logger.debug(e1.getMessage(), e1); throw new IllegalStateException("Could not instantiate transformer", e1); } // write all referenced files for (RepositoryFileReference ref : refMap.keySet()) { String archivePath = refMap.get(ref); ZipExporter.logger.trace("Creating {}", archivePath); ArchiveEntry archiveEntry = new ZipArchiveEntry("xml/" + archivePath); zos.putArchiveEntry(archiveEntry); if (ref instanceof DummyRepositoryFileReferenceForGeneratedXSD) { ZipExporter.logger.trace("Special treatment for generated XSDs"); Document document = ((DummyRepositoryFileReferenceForGeneratedXSD) ref).getDocument(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(zos); try { transformer.transform(source, result); } catch (TransformerException e) { ZipExporter.logger.debug("Could not serialize generated xsd", e); } } else { try (InputStream is = Repository.INSTANCE.newInputStream(ref)) { IOUtils.copy(is, zos); } catch (Exception e) { ZipExporter.logger.error("Could not copy file content to ZIP outputstream", e); } } // add plan files/artifact templantes to yaml folder updatePlanDef(archivePath, ref, zos, customizedResult.getPlanInfos()); zos.closeArchiveEntry(); } addPlan2Zip(customizedResult.getPlanInfos(), zos); this.addNamespacePrefixes(zos); zos.finish(); zos.close(); }
From source file:org.eclipse.winery.repository.export.ZipExporter.java
private void addPlan2Zip(Map<String, RepositoryFileReference> map, ArchiveOutputStream zos) throws IOException { for (RepositoryFileReference ref : map.values()) { ArchiveEntry archiveEntry = new ZipArchiveEntry("plan/" + ref.getFileName()); zos.putArchiveEntry(archiveEntry); try (InputStream is = Repository.INSTANCE.newInputStream(ref)) { IOUtils.copy(is, zos);/*from w ww . j a v a 2s . c o m*/ } catch (Exception e) { ZipExporter.logger.error("Could not copy file content to ZIP outputstream", e); } zos.closeArchiveEntry(); } }