List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry
public ZipArchiveEntry(ZipArchiveEntry entry) throws ZipException
From source file:com.facebook.buck.util.unarchive.UnzipTest.java
@Test public void testParentDirPaths() throws InterruptedException, IOException { try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { // It seems very unlikely that a zip file would contain ".." paths, but handle it anyways. zip.putArchiveEntry(new ZipArchiveEntry("foo/bar/")); zip.closeArchiveEntry();/*from w ww . ja v a2 s . co m*/ zip.putArchiveEntry(new ZipArchiveEntry("foo/bar/../")); zip.closeArchiveEntry(); } Path extractFolder = tmpFolder.newFolder(); ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES); assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo"))); assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo/bar"))); }
From source file:de.fischer.thotti.core.distbuilder.DistributionBuilder.java
protected void generateRunSkript(ArchiveOutputStream os) throws IOException, TemplateException, AWSRessourceNotFoundException, AWSIllegalConfigurationException { // @todo Improve Exception handling AWSAccessCredentials remoteCredentials = getRemoteUsersCredentials(); Configuration cfg = new Configuration(); cfg.setClassForTemplateLoading(this.getClass(), "/freemarker/distribution"); cfg.setLocalizedLookup(false);/* w w w . ja va2s .c om*/ cfg.setObjectWrapper(new DefaultObjectWrapper()); Map varMap = new HashMap(); varMap.put("var_classpath", cpBuilder.toString()); varMap.put("var_ak", remoteCredentials.getAccessKeyId()); varMap.put("var_sk", remoteCredentials.getSecretKey()); varMap.put("var_resultfile", NDRunner.THOTTI_RESULT_FILE); Template temp = null; temp = cfg.getTemplate("run.sh.ftl"); StringWriter out = new StringWriter(); temp.process(varMap, out); out.flush(); String content = out.getBuffer().toString().replace("\r\n", "\n"); String target = BASE_DIRECTORY + "/" + BIN_DIRECTORY + "/ndrunner"; os.putArchiveEntry(new ZipArchiveEntry(target)); IOUtils.copy(new ByteArrayInputStream(content.getBytes()), os); os.closeArchiveEntry(); }
From source file:com.cloudbees.jenkins.support.SupportPlugin.java
public static void writeBundle(OutputStream outputStream, final List<Component> components) throws IOException { StringBuilder manifest = new StringBuilder(); StringWriter errors = new StringWriter(); PrintWriter errorWriter = new PrintWriter(errors); appendManifestHeader(manifest);/*from ww w.j a va 2 s . c o m*/ List<Content> contents = appendManifestContents(manifest, errorWriter, components); contents.add(new StringContent("manifest.md", manifest.toString())); try { try (BulkChange change = new BulkChange(ContentMappings.get()); ZipArchiveOutputStream binaryOut = new ZipArchiveOutputStream( new BufferedOutputStream(outputStream, 16384))) { Optional<ContentFilter> maybeFilter = getContentFilter(); Optional<FilteredOutputStream> maybeFilteredOut = maybeFilter .map(filter -> new FilteredOutputStream(binaryOut, filter)); OutputStream textOut = maybeFilteredOut.map(OutputStream.class::cast).orElse(binaryOut); OutputStreamSelector selector = new OutputStreamSelector(() -> binaryOut, () -> textOut); IgnoreCloseOutputStream unfilteredOut = new IgnoreCloseOutputStream(binaryOut); IgnoreCloseOutputStream filteredOut = new IgnoreCloseOutputStream(selector); for (Content content : contents) { if (content == null) { continue; } final String name = maybeFilter.map(filter -> filter.filter(content.getName())) .orElseGet(content::getName); final ZipArchiveEntry entry = new ZipArchiveEntry(name); entry.setTime(content.getTime()); try { binaryOut.putArchiveEntry(entry); binaryOut.flush(); OutputStream out = content.shouldBeFiltered() ? filteredOut : unfilteredOut; if (content instanceof PrefilteredContent && maybeFilter.isPresent()) { ((PrefilteredContent) content).writeTo(out, maybeFilter.get()); } else { content.writeTo(out); } out.flush(); } catch (Throwable e) { String msg = "Could not attach ''" + name + "'' to support bundle"; logger.log(Level.WARNING, msg, e); errorWriter.println(msg); errorWriter .println("-----------------------------------------------------------------------"); errorWriter.println(); SupportLogFormatter.printStackTrace(e, errorWriter); errorWriter.println(); } finally { maybeFilteredOut.ifPresent(FilteredOutputStream::reset); selector.reset(); binaryOut.closeArchiveEntry(); } } errorWriter.close(); String errorContent = errors.toString(); if (StringUtils.isNotBlank(errorContent)) { try { binaryOut.putArchiveEntry(new ZipArchiveEntry("manifest/errors.txt")); textOut.write(errorContent.getBytes(StandardCharsets.UTF_8)); textOut.flush(); binaryOut.closeArchiveEntry(); } catch (IOException e) { logger.log(Level.WARNING, "Could not write manifest/errors.txt to zip archive", e); } } binaryOut.flush(); change.commit(); } } finally { outputStream.flush(); } }
From source file:fr.ortolang.diffusion.api.content.ContentResource.java
private ResponseBuilder handleExport(boolean followSymlink, String filename, String format, final List<String> paths, final Pattern pattern) throws UnsupportedEncodingException { ResponseBuilder builder;//from w w w .j a v a 2 s . co m switch (format) { case "zip": { LOGGER.log(Level.FINE, "exporting using format zip"); builder = Response.ok(); builder.header("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename, "utf-8") + ".zip"); builder.type("application/zip"); StreamingOutput stream = output -> { try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(output)) { for (String path : paths) { try { String key = resolveContentPath(path); ArchiveEntryFactory factory = (name, time, size) -> { ZipArchiveEntry entry = new ZipArchiveEntry(name); if (time != -1) { entry.setTime(time); } if (size != -1) { entry.setSize(size); } return entry; }; exportToArchive(key, out, factory, PathBuilder.fromPath(path), false, pattern); } catch (AccessDeniedException e) { LOGGER.log(Level.FINEST, "access denied during export to zip", e); } catch (BrowserServiceException | CoreServiceException | AliasNotFoundException | KeyNotFoundException | OrtolangException e) { LOGGER.log(Level.INFO, "unable to export path to zip", e); } catch (InvalidPathException e) { LOGGER.log(Level.FINEST, "invalid path during export to zip", e); } catch (PathNotFoundException e) { LOGGER.log(Level.FINEST, "path not found during export to zip", e); } catch (ExportToArchiveIOException e) { LOGGER.log(Level.SEVERE, "unexpected IO error during export to archive, stopping export", e); break; } } } }; builder.entity(stream); break; } case "tar": { LOGGER.log(Level.FINE, "exporting using format tar"); builder = Response.ok(); builder.header("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename, "utf-8") + ".tar.gz"); builder.type("application/x-gzip"); StreamingOutput stream = output -> { try (GzipCompressorOutputStream gout = new GzipCompressorOutputStream(output); TarArchiveOutputStream out = new TarArchiveOutputStream(gout)) { for (String path : paths) { try { String key = resolveContentPath(path); ArchiveEntryFactory factory = (name, time, size) -> { TarArchiveEntry entry = new TarArchiveEntry(name); if (time != -1) { entry.setModTime(time); } if (size != -1) { entry.setSize(size); } return entry; }; exportToArchive(key, out, factory, PathBuilder.fromPath(path), false, pattern); } catch (BrowserServiceException | CoreServiceException | AliasNotFoundException | KeyNotFoundException | OrtolangException e) { LOGGER.log(Level.INFO, "unable to export path to tar", e); } catch (InvalidPathException e) { LOGGER.log(Level.FINEST, "invalid path during export to tar", e); } catch (PathNotFoundException e) { LOGGER.log(Level.FINEST, "path not found during export to tar", e); } catch (ExportToArchiveIOException e) { LOGGER.log(Level.SEVERE, "unexpected IO error during export to archive, stopping export", e); break; } } } }; builder.entity(stream); break; } default: builder = Response.status(Status.BAD_REQUEST).entity("export format [" + format + "] is not supported"); } return builder; }
From source file:com.facebook.buck.util.unarchive.UnzipTest.java
@Test public void testDirectoryPathsOverwriteFiles() throws InterruptedException, IOException { try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { // It seems very unlikely that a zip file would contain ".." paths, but handle it anyways. zip.putArchiveEntry(new ZipArchiveEntry("foo/bar")); zip.closeArchiveEntry();/* w ww . ja v a2 s . com*/ } Path extractFolder = tmpFolder.newFolder(); Files.write(extractFolder.resolve("foo"), ImmutableList.of("whatever")); ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES); assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo"))); assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo/bar"))); }
From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java
private void writeMimetype(ArchiveOutputStream out) { String mimeType = getTemplate(epubPath + MIMETYPE); InputStream in = new ByteArrayInputStream(mimeType.getBytes()); try {// w w w .j a v a 2 s .co m out.putArchiveEntry(new ZipArchiveEntry("mimetype")); IOUtils.copy(in, out); in.close(); out.closeArchiveEntry(); } catch (IOException e) { LOG.error(e.getMessage(), e); } }
From source file:com.facebook.buck.util.unarchive.UnzipTest.java
@Test public void testStripsPrefixAndIgnoresSiblings() throws IOException { byte[] bazDotSh = "echo \"baz.sh\"\n".getBytes(Charsets.UTF_8); try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { zip.putArchiveEntry(new ZipArchiveEntry("foo")); zip.closeArchiveEntry();/*w w w .j av a 2 s . c o m*/ zip.putArchiveEntry(new ZipArchiveEntry("foo/bar/baz.txt")); zip.write(DUMMY_FILE_CONTENTS, 0, DUMMY_FILE_CONTENTS.length); zip.closeArchiveEntry(); ZipArchiveEntry exeEntry = new ZipArchiveEntry("foo/bar/baz.sh"); exeEntry.setUnixMode( (int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------"))); exeEntry.setMethod(ZipEntry.STORED); exeEntry.setSize(bazDotSh.length); zip.putArchiveEntry(exeEntry); zip.write(bazDotSh); zip.closeArchiveEntry(); zip.putArchiveEntry(new ZipArchiveEntry("sibling")); zip.closeArchiveEntry(); zip.putArchiveEntry(new ZipArchiveEntry("sibling/some/dir/and/file.txt")); zip.write(DUMMY_FILE_CONTENTS, 0, DUMMY_FILE_CONTENTS.length); zip.closeArchiveEntry(); } Path extractFolder = Paths.get("output_dir", "nested"); ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(tmpFolder.getRoot()); ArchiveFormat.ZIP.getUnarchiver().extractArchive(zipFile, filesystem, extractFolder, Optional.of(Paths.get("foo")), ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES); assertFalse(filesystem.isDirectory(extractFolder.resolve("sibling"))); assertFalse(filesystem.isDirectory(extractFolder.resolve("foo"))); assertFalse(filesystem.isDirectory(extractFolder.resolve("some"))); Path bazDotTxtPath = extractFolder.resolve("bar").resolve("baz.txt"); Path bazDotShPath = extractFolder.resolve("bar").resolve("baz.sh"); assertTrue(filesystem.isDirectory(extractFolder.resolve("bar"))); assertTrue(filesystem.isFile(bazDotTxtPath)); assertTrue(filesystem.isFile(bazDotShPath)); assertTrue(filesystem.isExecutable(bazDotShPath)); assertEquals(new String(bazDotSh), filesystem.readFileIfItExists(bazDotShPath).get()); assertEquals(new String(DUMMY_FILE_CONTENTS), filesystem.readFileIfItExists(bazDotTxtPath).get()); }
From source file:com.eucalyptus.www.X509Download.java
private static byte[] getX509Zip(User u) throws Exception { X509Certificate cloudCert = null; final X509Certificate x509; String userAccessKey = null;//www.j a va 2 s .c o m String userSecretKey = null; KeyPair keyPair = null; try { for (AccessKey k : u.getKeys()) { if (k.isActive()) { userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } } if (userAccessKey == null) { AccessKey k = u.createKey(); userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } keyPair = Certs.generateKeyPair(); x509 = Certs.generateCertificate(keyPair, u.getName()); x509.checkValidity(); u.addCertificate(x509); cloudCert = SystemCredentials.lookup(Eucalyptus.class).getCertificate(); } catch (Exception e) { LOG.fatal(e, e); throw e; } ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(byteOut); ZipArchiveEntry entry = null; String fingerPrint = Certs.getFingerPrint(keyPair.getPublic()); if (fingerPrint != null) { String baseName = X509Download.NAME_SHORT + "-" + u.getName() + "-" + fingerPrint.replaceAll(":", "").toLowerCase().substring(0, 8); zipOut.setComment("To setup the environment run: source /path/to/eucarc"); StringBuilder sb = new StringBuilder(); //TODO:GRZE:FIXME velocity String userNumber = u.getAccount().getAccountNumber(); sb.append("EUCA_KEY_DIR=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd -P)"); final Optional<String> computeUrl = remotePublicify(Compute.class); if (computeUrl.isPresent()) { sb.append(entryFor("EC2_URL", null, computeUrl)); } else { sb.append("\necho WARN: Eucalyptus URL is not configured. >&2"); ServiceBuilder<? extends ServiceConfiguration> builder = ServiceBuilders.lookup(Compute.class); ServiceConfiguration localConfig = builder.newInstance(Internets.localHostAddress(), Internets.localHostAddress(), Internets.localHostAddress(), Eucalyptus.INSTANCE.getPort()); sb.append("\nexport EC2_URL=" + ServiceUris.remotePublicify(localConfig)); } sb.append(entryFor("S3_URL", "An OSG is either not registered or not configured. S3_URL is not set. " + "Please register an OSG and/or set a valid s3 endpoint and download credentials again. " + "Or set S3_URL manually to http://OSG-IP:8773/services/objectstorage", remotePublicify(ObjectStorage.class))); sb.append(entryFor("EUARE_URL", "EUARE URL is not configured.", remotePublicify(Euare.class))); sb.append(entryFor("TOKEN_URL", "TOKEN URL is not configured.", remotePublicify(Tokens.class))); sb.append(entryFor("AWS_AUTO_SCALING_URL", "Auto Scaling service URL is not configured.", remotePublicify(AutoScaling.class))); sb.append(entryFor("AWS_CLOUDFORMATION_URL", null, remotePublicify(CloudFormation.class))); sb.append(entryFor("AWS_CLOUDWATCH_URL", "Cloud Watch service URL is not configured.", remotePublicify(CloudWatch.class))); sb.append(entryFor("AWS_ELB_URL", "Load Balancing service URL is not configured.", remotePublicify(LoadBalancing.class))); sb.append("\nexport EUSTORE_URL=" + StackConfiguration.DEFAULT_EUSTORE_URL); sb.append("\nexport EC2_PRIVATE_KEY=${EUCA_KEY_DIR}/" + baseName + "-pk.pem"); sb.append("\nexport EC2_CERT=${EUCA_KEY_DIR}/" + baseName + "-cert.pem"); sb.append("\nexport EC2_JVM_ARGS=-Djavax.net.ssl.trustStore=${EUCA_KEY_DIR}/jssecacerts"); sb.append("\nexport EUCALYPTUS_CERT=${EUCA_KEY_DIR}/cloud-cert.pem"); sb.append("\nexport EC2_ACCOUNT_NUMBER='" + u.getAccount().getAccountNumber() + "'"); sb.append("\nexport EC2_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport EC2_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport AWS_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_CREDENTIAL_FILE=${EUCA_KEY_DIR}/iamrc"); sb.append("\nexport EC2_USER_ID='" + userNumber + "'"); sb.append( "\nalias ec2-bundle-image=\"ec2-bundle-image --cert ${EC2_CERT} --privatekey ${EC2_PRIVATE_KEY} --user ${EC2_ACCOUNT_NUMBER} --ec2cert ${EUCALYPTUS_CERT}\""); sb.append( "\nalias ec2-upload-bundle=\"ec2-upload-bundle -a ${EC2_ACCESS_KEY} -s ${EC2_SECRET_KEY} --url ${S3_URL}\""); sb.append("\n"); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("eucarc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); sb = new StringBuilder(); sb.append("AWSAccessKeyId=").append(userAccessKey).append('\n'); sb.append("AWSSecretKey=").append(userSecretKey); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("iamrc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry("cloud-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(cloudCert)); zipOut.closeArchiveEntry(); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("jssecacerts")); entry.setUnixMode(0600); KeyStore tempKs = KeyStore.getInstance("jks"); tempKs.load(null); tempKs.setCertificateEntry("eucalyptus", cloudCert); ByteArrayOutputStream bos = new ByteArrayOutputStream(); tempKs.store(bos, "changeit".toCharArray()); zipOut.write(bos.toByteArray()); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-pk.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes("RSA PRIVATE KEY", Crypto.getCertificateProvider().getEncoded(keyPair.getPrivate()))); zipOut.closeArchiveEntry(); /** write the X509 certificate to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(x509)); zipOut.closeArchiveEntry(); } /** close the zip output stream and return the bytes **/ zipOut.close(); return byteOut.toByteArray(); }
From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java
private void writeMetaInfo(String tname, ArchiveOutputStream out) { String metaTemplate = getTemplate(epubPath + META_INF); if (null != tname) { metaTemplate = metaTemplate.replace("TEAMNAME", "" + tname); } else {/*from w w w .j a v a2 s . c om*/ metaTemplate = metaTemplate.replace("TEAMNAME/", ""); } InputStream in = new ByteArrayInputStream(metaTemplate.getBytes()); try { out.putArchiveEntry(new ZipArchiveEntry("META-INF/container.xml")); IOUtils.copy(in, out); in.close(); out.closeArchiveEntry(); } catch (IOException e) { LOG.error(e.getMessage(), e); } }
From source file:at.spardat.xma.xdelta.JarDelta.java
/** * Entry to new name./*w w w . j av a 2 s . c o m*/ * * @param source the source * @param name the name * @return the zip archive entry * @throws ZipException the zip exception */ public static ZipArchiveEntry entryToNewName(ZipArchiveEntry source, String name) throws ZipException { if (source.getName().equals(name)) return new ZipArchiveEntry(source); ZipArchiveEntry ret = new ZipArchiveEntry(name); byte[] extra = source.getExtra(); if (extra != null) { ret.setExtraFields(ExtraFieldUtils.parse(extra, true, ExtraFieldUtils.UnparseableExtraField.READ)); } else { ret.setExtra(ExtraFieldUtils.mergeLocalFileDataData(source.getExtraFields(true))); } ret.setInternalAttributes(source.getInternalAttributes()); ret.setExternalAttributes(source.getExternalAttributes()); ret.setExtraFields(source.getExtraFields(true)); ret.setCrc(source.getCrc()); ret.setMethod(source.getMethod()); ret.setSize(source.getSize()); return ret; }