Java Code Examples for org.apache.commons.compress.archivers.ArchiveOutputStream#putArchiveEntry()

The following examples show how to use org.apache.commons.compress.archivers.ArchiveOutputStream#putArchiveEntry() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GeneratorService.java    From vertx-starter with Apache License 2.0 6 votes vote down vote up
private void addFile(Path rootPath, Path filePath, ArchiveOutputStream stream) throws IOException {
  String relativePath = rootPath.relativize(filePath).toString();
  if (relativePath.length() == 0) return;
  String entryName = jarFileWorkAround(leadingDot(relativePath));
  ArchiveEntry entry = stream.createArchiveEntry(filePath.toFile(), entryName);
  if (EXECUTABLES.contains(entryName)) {
    if (entry instanceof ZipArchiveEntry) {
      ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) entry;
      zipArchiveEntry.setUnixMode(0744);
    } else if (entry instanceof TarArchiveEntry) {
      TarArchiveEntry tarArchiveEntry = (TarArchiveEntry) entry;
      tarArchiveEntry.setMode(0100744);
    }
  }
  stream.putArchiveEntry(entry);
  if (filePath.toFile().isFile()) {
    try (InputStream i = Files.newInputStream(filePath)) {
      IOUtils.copy(i, stream);
    }
  }
  stream.closeArchiveEntry();
}
 
Example 2
Source File: CompressExample.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
public static void makeOnlyZip() throws IOException, ArchiveException{
	File f1 = new File("D:/compresstest.txt");
       File f2 = new File("D:/test1.xml");
       
       final OutputStream out = new FileOutputStream("D:/中文名字.zip");
       ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, out);
       
       os.putArchiveEntry(new ZipArchiveEntry(f1.getName()));
       IOUtils.copy(new FileInputStream(f1), os);
       os.closeArchiveEntry();

       os.putArchiveEntry(new ZipArchiveEntry(f2.getName()));
       IOUtils.copy(new FileInputStream(f2), os);
       os.closeArchiveEntry();
       os.close();
}
 
Example 3
Source File: ZipTest.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
public void testApache() throws IOException, ArchiveException {
	log.debug("testApache()");
	File zip = File.createTempFile("apache_", ".zip");
	
	// Create zip
	FileOutputStream fos = new FileOutputStream(zip);
	ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("zip", fos);
	aos.putArchiveEntry(new ZipArchiveEntry("coñeta"));
	aos.closeArchiveEntry();
	aos.close();
	
	// Read zip
	FileInputStream fis = new FileInputStream(zip);
	ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream("zip", fis);
	ZipArchiveEntry zae = (ZipArchiveEntry) ais.getNextEntry();
	assertEquals(zae.getName(), "coñeta");
	ais.close();
}
 
Example 4
Source File: CompressionTools.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
private static void compressArchive(
        final Path pathToCompress,
        final ArchiveOutputStream archiveOutputStream,
        final ArchiveEntryFactory archiveEntryFactory,
        final CompressionType compressionType,
        final BuildListener listener)
        throws IOException {
    final List<File> files = addFilesToCompress(pathToCompress, listener);

    LoggingHelper.log(listener, "Compressing directory '%s' as a '%s' archive",
            pathToCompress.toString(),
            compressionType.name());

    for (final File file : files) {
        final String newTarFileName = pathToCompress.relativize(file.toPath()).toString();
        final ArchiveEntry archiveEntry = archiveEntryFactory.create(file, newTarFileName);
        archiveOutputStream.putArchiveEntry(archiveEntry);

        try (final FileInputStream fileInputStream = new FileInputStream(file)) {
            IOUtils.copy(fileInputStream, archiveOutputStream);
        }

        archiveOutputStream.closeArchiveEntry();
    }
}
 
Example 5
Source File: ZipEdgeArchiveBuilder.java    From datacollector with Apache License 2.0 6 votes vote down vote up
protected void addArchiveEntry(
    ArchiveOutputStream archiveOutput,
    Object fileContent,
    String pipelineId,
    String fileName
) throws IOException {
  File pipelineFile = File.createTempFile(pipelineId, fileName);
  FileOutputStream pipelineOutputStream = new FileOutputStream(pipelineFile);
  ObjectMapperFactory.get().writeValue(pipelineOutputStream, fileContent);
  pipelineOutputStream.flush();
  pipelineOutputStream.close();
  ZipArchiveEntry archiveEntry = new ZipArchiveEntry(
      pipelineFile,
      DATA_PIPELINES_FOLDER + pipelineId + "/" + fileName
  );
  archiveEntry.setSize(pipelineFile.length());
  archiveOutput.putArchiveEntry(archiveEntry);
  IOUtils.copy(new FileInputStream(pipelineFile), archiveOutput);
  archiveOutput.closeArchiveEntry();
}
 
Example 6
Source File: TarEdgeArchiveBuilder.java    From datacollector with Apache License 2.0 6 votes vote down vote up
protected void addArchiveEntry(
    ArchiveOutputStream archiveOutput,
    Object fileContent,
    String pipelineId,
    String fileName
) throws IOException {
  File pipelineFile = File.createTempFile(pipelineId, fileName);
  FileOutputStream pipelineOutputStream = new FileOutputStream(pipelineFile);
  ObjectMapperFactory.get().writeValue(pipelineOutputStream, fileContent);
  pipelineOutputStream.flush();
  pipelineOutputStream.close();
  TarArchiveEntry archiveEntry = new TarArchiveEntry(
      pipelineFile,
      DATA_PIPELINES_FOLDER + pipelineId + "/" + fileName
  );
  archiveEntry.setSize(pipelineFile.length());
  archiveOutput.putArchiveEntry(archiveEntry);
  IOUtils.copy(new FileInputStream(pipelineFile), archiveOutput);
  archiveOutput.closeArchiveEntry();
}
 
Example 7
Source File: AzkabanJobHelper.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@edu.umd.cs.findbugs.annotations.SuppressWarnings(
    value = "OBL_UNSATISFIED_OBLIGATION",
    justification = "Lombok construct of @Cleanup is handing this, but not detected by FindBugs")
private static void addFilesToZip(File zipFile, List<File> filesToAdd) throws IOException {
  try {
    @Cleanup
    OutputStream archiveStream = new FileOutputStream(zipFile);
    @Cleanup
    ArchiveOutputStream archive =
        new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, archiveStream);

    for (File fileToAdd : filesToAdd) {
      ZipArchiveEntry entry = new ZipArchiveEntry(fileToAdd.getName());
      archive.putArchiveEntry(entry);

      @Cleanup
      BufferedInputStream input = new BufferedInputStream(new FileInputStream(fileToAdd));
      IOUtils.copy(input, archive);
      archive.closeArchiveEntry();
    }

    archive.finish();
  } catch (ArchiveException e) {
    throw new IOException("Issue with creating archive", e);
  }
}
 
Example 8
Source File: RemoteApiBasedDockerProvider.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
private static void addToTar(ArchiveOutputStream tar, File file, String fileNameAndPath) throws IOException {
    if (!file.exists() || !file.canRead()) {
        throw new FileNotFoundException(String.format("Cannot read file %s. Are you sure it exists?",
                file.getAbsolutePath()));
    }
    if (file.isDirectory()) {
        for (File fileInDirectory : file.listFiles()) {
            if (!fileNameAndPath.endsWith("/")) {
                fileNameAndPath = fileNameAndPath + "/";
            }
            addToTar(tar, fileInDirectory, fileNameAndPath + fileInDirectory.getName());
        }
    } else {
        ArchiveEntry entry = tar.createArchiveEntry(file, fileNameAndPath);
        tar.putArchiveEntry(entry);
        try (FileInputStream fis = new FileInputStream(file)) {
            IOUtils.copy(fis, tar);
        }
        tar.closeArchiveEntry();
    }
}
 
Example 9
Source File: OMDBCheckpointServlet.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
private static void includeFile(File file, String entryName,
    ArchiveOutputStream archiveOutputStream)
    throws IOException {
  ArchiveEntry archiveEntry =
      archiveOutputStream.createArchiveEntry(file, entryName);
  archiveOutputStream.putArchiveEntry(archiveEntry);
  try (FileInputStream fis = new FileInputStream(file)) {
    IOUtils.copy(fis, archiveOutputStream);
  }
  archiveOutputStream.closeArchiveEntry();
}
 
Example 10
Source File: AbstractBaseArchiver.java    From cantor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static void writeArchiveEntry(final ArchiveOutputStream archive, final String name, final byte[] bytes) throws IOException {
    final TarArchiveEntry entry = new TarArchiveEntry(name);
    entry.setSize(bytes.length);
    archive.putArchiveEntry(entry);
    archive.write(bytes);
    archive.closeArchiveEntry();
}
 
Example 11
Source File: ArchiveWorkItemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager manager) {
    String archive = (String) workItem.getParameter("Archive");
    List<File> files = (List<File>) workItem.getParameter("Files");

    try {
        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        OutputStream outputStream = new FileOutputStream(new File(archive));
        ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar",
                                                                                      outputStream);

        if (files != null) {
            for (File file : files) {
                final TarArchiveEntry entry = new TarArchiveEntry("testdata/test1.xml");
                entry.setModTime(0);
                entry.setSize(file.length());
                entry.setUserId(0);
                entry.setGroupId(0);
                entry.setMode(0100000);
                os.putArchiveEntry(entry);
                IOUtils.copy(new FileInputStream(file),
                             os);
            }
        }
        os.closeArchiveEntry();
        os.close();
        manager.completeWorkItem(workItem.getId(),
                                 null);
    } catch (Exception e) {
        handleException(e);
        manager.abortWorkItem(workItem.getId());
    }
}
 
Example 12
Source File: CompressExample.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
public static void makeZip() throws IOException, ArchiveException{
		File f1 = new File("D:/compresstest.txt");
        File f2 = new File("D:/test1.xml");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        //ArchiveOutputStream ostemp = new ArchiveStreamFactory().createArchiveOutputStream("zip", baos);
        ZipArchiveOutputStream ostemp = new ZipArchiveOutputStream(baos);
        ostemp.setEncoding("GBK");
        ostemp.putArchiveEntry(new ZipArchiveEntry(f1.getName()));
        IOUtils.copy(new FileInputStream(f1), ostemp);
        ostemp.closeArchiveEntry();
        ostemp.putArchiveEntry(new ZipArchiveEntry(f2.getName()));
        IOUtils.copy(new FileInputStream(f2), ostemp);
        ostemp.closeArchiveEntry();
        ostemp.finish();
        ostemp.close();

//      final OutputStream out = new FileOutputStream("D:/testcompress.zip");
        final OutputStream out = new FileOutputStream("D:/中文名字.zip");
        ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
        os.putArchiveEntry(new ZipArchiveEntry("打包.zip"));
        baos.writeTo(os);
        os.closeArchiveEntry();
        baos.close();
        os.finish();
        os.close();
	}
 
Example 13
Source File: TarContainerPacker.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
static void includeFile(File file, String entryName,
    ArchiveOutputStream archiveOutput) throws IOException {
  ArchiveEntry entry = archiveOutput.createArchiveEntry(file, entryName);
  archiveOutput.putArchiveEntry(entry);
  try (InputStream input = new FileInputStream(file)) {
    IOUtils.copy(input, archiveOutput);
  }
  archiveOutput.closeArchiveEntry();
}
 
Example 14
Source File: ZipFiles.java    From ankush with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Zip file.
 *
 * @param filePath the file path
 * @return the string
 */
public String zipFile(String filePath) {
	try {
		/* Create Output Stream that will have final zip files */
		OutputStream zipOutput = new FileOutputStream(new File(filePath
				+ ".zip"));
		/*
		 * Create Archive Output Stream that attaches File Output Stream / and
		 * specifies type of compression
		 */
		ArchiveOutputStream logicalZip = new ArchiveStreamFactory()
				.createArchiveOutputStream(ArchiveStreamFactory.ZIP, zipOutput);
		/* Create Archieve entry - write header information */
		logicalZip.putArchiveEntry(new ZipArchiveEntry(FilenameUtils.getName(filePath)));
		/* Copy input file */
		IOUtils.copy(new FileInputStream(new File(filePath)), logicalZip);
		/* Close Archieve entry, write trailer information */
		logicalZip.closeArchiveEntry();

		/* Finish addition of entries to the file */
		logicalZip.finish();
		/* Close output stream, our files are zipped */
		zipOutput.close();
	} catch (Exception e) {
		System.err.println(e.getMessage());
		return null;
	}
	return filePath + ".zip";
}
 
Example 15
Source File: ExecMojo.java    From tomee with Apache License 2.0 4 votes vote down vote up
private void addToJar(final ArchiveOutputStream os, final Class<?> clazz) throws IOException {
    final String name = clazz.getName().replace('.', '/') + ".class";
    os.putArchiveEntry(new JarArchiveEntry(name));
    IOUtils.copy(getClass().getResourceAsStream('/' + name), os);
    os.closeArchiveEntry();
}
 
Example 16
Source File: ExecMojo.java    From tomee with Apache License 2.0 4 votes vote down vote up
private void createExecutableJar() throws Exception {
    mkdirs(execFile.getParentFile());

    final Properties config = new Properties();
    config.put("distribution", distributionName);
    config.put("workingDir", runtimeWorkingDir);
    config.put("command", DEFAULT_SCRIPT.equals(script) ? (skipArchiveRootFolder ? "" : catalinaBase.getName() + "/") + DEFAULT_SCRIPT : script);
    final List<String> jvmArgs = generateJVMArgs();

    final String catalinaOpts = toString(jvmArgs, " ");
    config.put("catalinaOpts", catalinaOpts);
    config.put("timestamp", Long.toString(System.currentTimeMillis()));
    // java only
    final String cp = getAdditionalClasspath();
    if (cp != null) {
        config.put("additionalClasspath", cp);
    }
    config.put("shutdownCommand", tomeeShutdownCommand);
    int i = 0;
    boolean encodingSet = catalinaOpts.contains("-Dfile.encoding");
    for (final String jvmArg : jvmArgs) {
        config.put("jvmArg." + i++, jvmArg);
        encodingSet = encodingSet || jvmArg.contains("-Dfile.encoding");
    }
    if (!encodingSet) { // forcing encoding for launched process to be able to read conf files
        config.put("jvmArg." + i, "-Dfile.encoding=UTF-8");
    }

    if (preTasks != null) {
        config.put("preTasks", toString(preTasks, ","));
    }
    if (postTasks != null) {
        config.put("postTasks", toString(postTasks, ","));
    }
    config.put("waitFor", Boolean.toString(waitFor));

    // create an executable jar with main runner and zipFile
    final FileOutputStream fileOutputStream = new FileOutputStream(execFile);
    final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.JAR, fileOutputStream);

    { // distrib
        os.putArchiveEntry(new JarArchiveEntry(distributionName));
        final FileInputStream in = new FileInputStream(zipFile);
        try {
            IOUtils.copy(in, os);
            os.closeArchiveEntry();
        } finally {
            IOUtil.close(in);
        }
    }

    { // config
        os.putArchiveEntry(new JarArchiveEntry("configuration.properties"));
        final StringWriter writer = new StringWriter();
        config.store(writer, "");
        IOUtils.copy(new ByteArrayInputStream(writer.toString().getBytes("UTF-8")), os);
        os.closeArchiveEntry();
    }

    { // Manifest
        final Manifest manifest = new Manifest();

        final Manifest.Attribute mainClassAtt = new Manifest.Attribute();
        mainClassAtt.setName("Main-Class");
        mainClassAtt.setValue(runnerClass);
        manifest.addConfiguredAttribute(mainClassAtt);

        final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
        manifest.write(baos);

        os.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF"));
        IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), os);
        os.closeArchiveEntry();
    }

    { // Main + utility
        for (final Class<?> clazz : asList(
                ExecRunner.class,
                Files.class, Files.PatternFileFilter.class, Files.DeleteThread.class,
                Files.FileRuntimeException.class, Files.FileDoesNotExistException.class, Files.NoopOutputStream.class,
                LoaderRuntimeException.class,
                Pipe.class, IO.class, Zips.class, JarLocation.class,
                RemoteServer.class, RemoteServer.CleanUpThread.class,
                OpenEJBRuntimeException.class, Join.class, QuickServerXmlParser.class,
                Options.class, Options.NullLog.class, Options.TomEEPropertyAdapter.class, Options.NullOptions.class,
                Options.Log.class, JavaSecurityManagers.class)) {
            addToJar(os, clazz);
        }
    }
    addClasses(additionalClasses, os);
    addClasses(preTasks, os);
    addClasses(postTasks, os);

    IOUtil.close(os);
    IOUtil.close(fileOutputStream);
}
 
Example 17
Source File: CompressedApplicationInputStreamTest.java    From vespa with Apache License 2.0 4 votes vote down vote up
private static void writeFileToTar(ArchiveOutputStream taos, File file) throws IOException {
    taos.putArchiveEntry(taos.createArchiveEntry(file, file.getName()));
    ByteStreams.copy(new FileInputStream(file), taos);
    taos.closeArchiveEntry();
}
 
Example 18
Source File: CompressedFileReference.java    From vespa with Apache License 2.0 4 votes vote down vote up
private static void writeFileToTar(ArchiveOutputStream taos, File baseDir, File file) throws IOException {
    log.log(Level.FINE, () -> "Adding file to tar: " + baseDir.toPath().relativize(file.toPath()).toString());
    taos.putArchiveEntry(taos.createArchiveEntry(file, baseDir.toPath().relativize(file.toPath()).toString()));
    ByteStreams.copy(new FileInputStream(file), taos);
    taos.closeArchiveEntry();
}