org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream Java Examples

The following examples show how to use org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream. 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: ScatterZipOutputStream.java    From importer-exporter with Apache License 2.0 6 votes vote down vote up
void writeTo(ZipArchiveOutputStream target) throws IOException {
    entryStore.closeForWriting();
    backingStore.closeForWriting();
    String line;

    try (InputStream stream = backingStore.getInputStream();
         BufferedReader reader = new BufferedReader(new InputStreamReader(entryStore.getInputStream(), StandardCharsets.UTF_8))) {
        while ((line = reader.readLine()) != null) {
            String[] values = line.split(",");
            if (values.length != 5)
                throw new IOException("Failed to read temporary zip entry.");

            ZipArchiveEntry entry = new ZipArchiveEntry(values[0]);
            entry.setMethod(Integer.parseInt(values[1]));
            entry.setCrc(Long.parseLong(values[2]));
            entry.setCompressedSize(Long.parseLong(values[3]));
            entry.setSize(Long.parseLong(values[4]));

            try (BoundedInputStream rawStream = new BoundedInputStream(stream, entry.getCompressedSize())) {
                target.addRawArchiveEntry(entry, rawStream);
            }
        }
    } catch (NumberFormatException e) {
        throw new IOException("Failed to read temporary zip entry.", e);
    }
}
 
Example #2
Source File: GeneratorService.java    From vertx-starter with Apache License 2.0 6 votes vote down vote up
public Buffer onProjectRequested(VertxProject project) throws Exception {
  ArchiveOutputStreamFactory factory;
  ArchiveFormat archiveFormat = project.getArchiveFormat();
  if (archiveFormat == ArchiveFormat.TGZ) {
    factory = baos -> new TarArchiveOutputStream(new GzipCompressorOutputStream(baos));
  } else if (archiveFormat == ArchiveFormat.ZIP) {
    factory = baos -> new ZipArchiveOutputStream(baos);
  } else {
    throw new IllegalArgumentException("Unsupported archive format: " + archiveFormat.getFileExtension());
  }

  try (TempDir tempDir = TempDir.create();
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       ArchiveOutputStream out = factory.create(baos)) {

    createProject(project, tempDir);
    generateArchive(tempDir, out);

    out.finish();
    out.close();

    return Buffer.buffer(baos.toByteArray());
  }
}
 
Example #3
Source File: CompressUtils.java    From es with Apache License 2.0 6 votes vote down vote up
private static void addFilesToCompression(ZipArchiveOutputStream zaos, File file, String dir) throws IOException {

        ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, dir + file.getName());
        zaos.putArchiveEntry(zipArchiveEntry);

        if (file.isFile()) {
            BufferedInputStream bis = null;
            try {
                bis = new BufferedInputStream(new FileInputStream(file));
                IOUtils.copy(bis, zaos);
                zaos.closeArchiveEntry();
            } catch (IOException e) {
                throw e;
            } finally {
                IOUtils.closeQuietly(bis);
            }
        } else if (file.isDirectory()) {
            zaos.closeArchiveEntry();

            for (File childFile : file.listFiles()) {
                addFilesToCompression(zaos, childFile, dir + file.getName() + File.separator);
            }
        }
    }
 
Example #4
Source File: CompressExtension.java    From jphp with Apache License 2.0 6 votes vote down vote up
@Override
public void onRegister(CompileScope scope) {
    // register classes ...
    registerWrapperClass(scope, ArchiveEntry.class, PArchiveEntry.class);
    registerWrapperClass(scope, TarArchiveEntry.class, PTarArchiveEntry.class);
    registerWrapperClass(scope, ZipArchiveEntry.class, PZipArchiveEntry.class);

    registerWrapperClass(scope, ArchiveInputStream.class, PArchiveInput.class);
    registerWrapperClass(scope, TarArchiveInputStream.class, PTarArchiveInput.class);
    registerWrapperClass(scope, ZipArchiveInputStream.class, PZipArchiveInput.class);

    registerWrapperClass(scope, ArchiveOutputStream.class, PArchiveOutput.class);
    registerWrapperClass(scope, TarArchiveOutputStream.class, PTarArchiveOutput.class);
    registerWrapperClass(scope, ZipArchiveOutputStream.class, PZipArchiveOutput.class);

    registerClass(scope, PGzipOutputStream.class);
    registerClass(scope, PGzipInputStream.class);
    registerClass(scope, PBzip2OutputStream.class);
    registerClass(scope, PBZip2InputStream.class);
    registerClass(scope, PLz4OutputStream.class);
    registerClass(scope, PLz4InputStream.class);

    registerClass(scope, PArchive.class);
    registerClass(scope, PTarArchive.class);
    registerClass(scope, PZipArchive.class);
}
 
Example #5
Source File: ZipUtil.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 添加目录到Zip
 * @param file
 * @param out
 * @param entryPath
 */
private static void addDirectoryToZip(File file, ZipArchiveOutputStream out, String entryPath) {
    
    try {
         
        String path=entryPath + file.getName();
        if(file.isDirectory()){
            path=formatDirPath(path); //为了在压缩文件中包含空文件夹
        }
        ZipArchiveEntry entry = new ZipArchiveEntry(path);
        entry.setTime(file.lastModified());
        // entry.setSize(files[i].length());
        out.putArchiveEntry(entry);

        out.closeArchiveEntry();
    } catch (IOException e) {
      //  e.printStackTrace();
    	if (logger.isErrorEnabled()) {
         logger.error("添加目录到Zip",e);
     }
    } finally {
       
    }
}
 
Example #6
Source File: UnzipTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@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();
  }

  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")));
}
 
Example #7
Source File: UnzipTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@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();
    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")));
}
 
Example #8
Source File: LogArchiver.java    From cuba with Apache License 2.0 6 votes vote down vote up
public static void writeArchivedLogTailToStream(File logFile, OutputStream outputStream) throws IOException {
    if (!logFile.exists()) {
        throw new FileNotFoundException();
    }

    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(outputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.DEFLATED);
    zipOutputStream.setEncoding(ZIP_ENCODING);

    byte[] content = getTailBytes(logFile);

    ArchiveEntry archiveEntry = newTailArchive(logFile.getName(), content);
    zipOutputStream.putArchiveEntry(archiveEntry);
    zipOutputStream.write(content);

    zipOutputStream.closeArchiveEntry();
    zipOutputStream.close();
}
 
Example #9
Source File: FoldersServiceBean.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] exportFolder(Folder folder) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.STORED);
    zipOutputStream.setEncoding(StandardCharsets.UTF_8.name());
    String xml = createXStream().toXML(folder);
    byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8);
    ArchiveEntry zipEntryDesign = newStoredEntry("folder.xml", xmlBytes);
    zipOutputStream.putArchiveEntry(zipEntryDesign);
    zipOutputStream.write(xmlBytes);
    try {
        zipOutputStream.closeArchiveEntry();
    } catch (Exception ex) {
        throw new RuntimeException(String.format("Exception occurred while exporting folder %s.",  folder.getName()));
    }

    zipOutputStream.close();
    return byteArrayOutputStream.toByteArray();
}
 
Example #10
Source File: EntityImportExport.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] exportEntitiesToZIP(Collection<? extends Entity> entities) {
    String json = entitySerialization.toJson(entities, null, EntitySerializationOption.COMPACT_REPEATED_ENTITIES);
    byte[] jsonBytes = json.getBytes(StandardCharsets.UTF_8);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.STORED);
    zipOutputStream.setEncoding(StandardCharsets.UTF_8.name());
    ArchiveEntry singleDesignEntry = newStoredEntry("entities.json", jsonBytes);
    try {
        zipOutputStream.putArchiveEntry(singleDesignEntry);
        zipOutputStream.write(jsonBytes);
        zipOutputStream.closeArchiveEntry();
    } catch (Exception e) {
        throw new RuntimeException("Error on creating zip archive during entities export", e);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
    }
    return byteArrayOutputStream.toByteArray();
}
 
Example #11
Source File: CompressionTools.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
public static void compressZipFile(
        final File temporaryZipFile,
        final Path pathToCompress,
        final BuildListener listener)
        throws IOException {
    try (final ZipArchiveOutputStream zipArchiveOutputStream =
                 new ZipArchiveOutputStream(
                 new BufferedOutputStream(
                 new FileOutputStream(temporaryZipFile)))) {

        compressArchive(
                pathToCompress,
                zipArchiveOutputStream,
                new ArchiveEntryFactory(CompressionType.Zip),
                CompressionType.Zip,
                listener);
    }
}
 
Example #12
Source File: ExtractionToolsTest.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
@Test
public void canDecompressZipFile() {
    try {
        compressedFile = Files.createTempFile(ARCHIVE_PREFIX, ".zip");
        try (final ZipArchiveOutputStream outputStream = new ZipArchiveOutputStream(
                    new BufferedOutputStream(new FileOutputStream(compressedFile.toFile())))) {
            // Deflated is the default compression method
            zipDirectory(testDir, outputStream, ZipOutputStream.DEFLATED);
        }

        ExtractionTools.decompressFile(
                compressedFile.toFile(),
                decompressDestination.toFile(),
                CompressionType.Zip,
                null);

        assertEquals(getFileNames(testDir), getFileNames(decompressDestination));
    } catch (final IOException e) {
        fail(e.getMessage());
    }
}
 
Example #13
Source File: DownloadService.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
byte[] compressToZipFile(List<BinaryImage> allImages) {
	try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
			ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(byteOut);) {

		zipOutput.setEncoding("UTF-8");

		for (int i = 0; i < allImages.size(); i++) {
			BinaryImage image = allImages.get(i);
			String fileName = createEntryFileName(image, i + 1);
			ZipArchiveEntry entry = new ZipArchiveEntry(fileName);
			entry.setSize(image.getImageBinary().length);
			zipOutput.putArchiveEntry(entry);
			copyToOutputStream(zipOutput, image.getImageBinary());
			zipOutput.closeArchiveEntry();
		}
		zipOutput.close();
		return byteOut.toByteArray();
	} catch (Exception e) {
		LOG.error(e.getMessage(), e);
		return null;
	}
}
 
Example #14
Source File: Zipper.java    From james-project with Apache License 2.0 6 votes vote down vote up
private void storeInArchive(MailboxWithAnnotations mailboxWithAnnotations, ZipArchiveOutputStream archiveOutputStream) throws IOException {
    Mailbox mailbox = mailboxWithAnnotations.mailbox;
    List<MailboxAnnotation> annotations = mailboxWithAnnotations.annotations;

    String name = mailbox.getName();
    ZipArchiveEntry archiveEntry = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(new Directory(name), name);

    archiveEntry.addExtraField(EntryTypeExtraField.TYPE_MAILBOX);
    archiveEntry.addExtraField(new MailboxIdExtraField(mailbox.getMailboxId().serialize()));
    archiveEntry.addExtraField(new UidValidityExtraField(mailbox.getUidValidity().asLong()));

    archiveOutputStream.putArchiveEntry(archiveEntry);
    archiveOutputStream.closeArchiveEntry();

    storeAllAnnotationsInArchive(archiveOutputStream, annotations, name);
}
 
Example #15
Source File: Zipper.java    From james-project with Apache License 2.0 6 votes vote down vote up
private void storeInArchive(MessageResult message, ZipArchiveOutputStream archiveOutputStream) throws IOException {
    String entryId = message.getMessageId().serialize();
    ZipArchiveEntry archiveEntry = createMessageZipArchiveEntry(message, archiveOutputStream, entryId);

    archiveOutputStream.putArchiveEntry(archiveEntry);
    try {
        Content content = message.getFullContent();
        try (InputStream stream = content.getInputStream()) {
            IOUtils.copy(stream, archiveOutputStream);
        }
    } catch (MailboxException e) {
        LOGGER.error("Error while storing message in archive", e);
    }

    archiveOutputStream.closeArchiveEntry();
}
 
Example #16
Source File: Assembler.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the given file in the ZIP file. If the given file is a directory, then this method
 * recursively adds all files contained in this directory. This method is invoked for zipping
 * the "application/sis-console/src/main/artifact" directory and sub-directories before to zip.
 */
private void appendRecursively(final File file, String relativeFile, final ZipArchiveOutputStream out) throws IOException {
    if (file.isDirectory()) {
        relativeFile += '/';
    }
    final ZipArchiveEntry entry = new ZipArchiveEntry(file, relativeFile);
    if (file.canExecute()) {
        entry.setUnixMode(0744);
    }
    out.putArchiveEntry(entry);
    if (!entry.isDirectory()) {
        try (FileInputStream in = new FileInputStream(file)) {
            in.transferTo(out);
        }
    }
    out.closeArchiveEntry();
    if (entry.isDirectory()) {
        for (final String filename : file.list(this)) {
            appendRecursively(new File(file, filename), relativeFile.concat(filename), out);
        }
    }
}
 
Example #17
Source File: ZipAssertTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void isDirectoryShouldNotThrowWhenDirectory() throws Exception {
    try (ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(destination)) {

        ZipArchiveEntry archiveEntry = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(new Directory("any"), DIRECTORY_NAME);
        archiveOutputStream.putArchiveEntry(archiveEntry);
        archiveOutputStream.closeArchiveEntry();
        archiveOutputStream.finish();
    }

    try (ZipFile zipFile = new ZipFile(destination)) {
        assertThatCode(() -> assertThatZip(zipFile)
                .containsOnlyEntriesMatching(
                    hasName(DIRECTORY_NAME)
                        .isDirectory()))
            .doesNotThrowAnyException();
    }
}
 
Example #18
Source File: ZipAssertTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void containsOnlyExtraFieldsShouldNotThrowWhenUnexpectedField() throws Exception {
    try (ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(destination)) {

        ZipArchiveEntry archiveEntry = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(new File("any"), ENTRY_NAME);
        archiveEntry.addExtraField(EXTRA_FIELD);
        archiveOutputStream.putArchiveEntry(archiveEntry);
        IOUtils.copy(new ByteArrayInputStream(ENTRY_CONTENT), archiveOutputStream);
        archiveOutputStream.closeArchiveEntry();

        archiveOutputStream.finish();
    }

    try (ZipFile zipFile = new ZipFile(destination)) {
        assertThatCode(() -> assertThatZip(zipFile)
            .containsOnlyEntriesMatching(
                hasName(ENTRY_NAME)
                    .containsExtraFields()))
            .doesNotThrowAnyException();
    }
}
 
Example #19
Source File: ZipAssertTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void containsOnlyExtraFieldsShouldNotThrowWhenContainingExpectedExtraFields() throws Exception {
    try (ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(destination)) {

        ZipArchiveEntry archiveEntry = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(new File("any"), ENTRY_NAME);
        archiveEntry.addExtraField(EXTRA_FIELD);
        archiveOutputStream.putArchiveEntry(archiveEntry);
        IOUtils.copy(new ByteArrayInputStream(ENTRY_CONTENT), archiveOutputStream);
        archiveOutputStream.closeArchiveEntry();

        archiveOutputStream.finish();
    }

    try (ZipFile zipFile = new ZipFile(destination)) {
        assertThatCode(() -> assertThatZip(zipFile)
            .containsOnlyEntriesMatching(
                hasName(ENTRY_NAME)
                    .containsExtraFields(EXTRA_FIELD)))
            .doesNotThrowAnyException();
    }
}
 
Example #20
Source File: ExtractionToolsTest.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
@Test
public void canDecompressZipFileWithStoredCompressionMethod() {
    try {
        compressedFile = Files.createTempFile(ARCHIVE_PREFIX, ".zip");
        try (final ZipArchiveOutputStream outputStream = new ZipArchiveOutputStream(
                    new BufferedOutputStream(new FileOutputStream(compressedFile.toFile())))) {
            zipDirectory(testDir, outputStream, ZipOutputStream.STORED);
        }

        ExtractionTools.decompressFile(
                compressedFile.toFile(),
                decompressDestination.toFile(),
                CompressionType.Zip,
                null);

        assertEquals(getFileNames(testDir), getFileNames(decompressDestination));
    } catch (final IOException e) {
        fail(e.getMessage());
    }
}
 
Example #21
Source File: ZipOutputFile.java    From importer-exporter with Apache License 2.0 6 votes vote down vote up
ZipOutputFile(String contentFile, Path zipFile, Path tempDir, int threads, EventDispatcher eventDispatcher, Object eventChannel) throws IOException {
    super(contentFile, zipFile);

    out = new ZipArchiveOutputStream(zipFile.toFile());
    scatterStreams = ConcurrentHashMap.newKeySet();

    int minThreads = Math.max(2, Runtime.getRuntime().availableProcessors());
    int maxThreads = Math.max(minThreads, threads);
    ScatterGatherBackingStoreSupplier supplier = () -> new FileBasedScatterGatherBackingStore(Files.createTempFile(tempDir, "zip", ".tmp").toFile());

    scatterZipPool = new WorkerPool<>("scatter_zip_pool", minThreads, maxThreads, PoolSizeAdaptationStrategy.AGGRESSIVE,
            () -> {
                try {
                    return new ScatterZipWorker(supplier, eventDispatcher);
                } catch (IOException e) {
                    log.error("Failed to create scatter zip writer.");
                    log.error(e.getClass().getTypeName() + ": " + e.getMessage());
                    return null;
                }
            },
            maxThreads);

    scatterZipPool.setEventSource(eventChannel);
    scatterZipPool.prestartCoreWorkers();
}
 
Example #22
Source File: ZipUtil.java    From AndroidRobot with Apache License 2.0 6 votes vote down vote up
public void compress(File[] files, File zipFile) throws IOException {
	if (files == null) {
		return;
	}
	ZipArchiveOutputStream out = new ZipArchiveOutputStream(zipFile);
	out.setUseZip64(Zip64Mode.AsNeeded);
	// 将每个文件用ZipArchiveEntry封装
	for (File file : files) {
		if (file == null) {
			continue;
		}
		compressOneFile(file, out, "");
	}
	if (out != null) {
		out.close();
	}
}
 
Example #23
Source File: ArchiveUtils.java    From support-diagnostics with Apache License 2.0 6 votes vote down vote up
public static boolean createZipArchive(String dir, String archiveFileName)  {

      try {
         File srcDir = new File(dir);
         String filename = dir + "-" + archiveFileName + ".zip";

         FileOutputStream fout = new FileOutputStream(filename);
         ZipArchiveOutputStream taos = new ZipArchiveOutputStream(fout);
         archiveResultsZip(archiveFileName, taos, srcDir, "", true);
         taos.close();

         logger.info(Constants.CONSOLE, "Archive: " + filename + " was created");

      } catch (Exception ioe) {
         logger.error( "Couldn't create archive.", ioe);
         return false;
      }
      return true;

   }
 
Example #24
Source File: cfZIP.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
protected void defaultParameters( String _tag ) throws cfmBadFileException {
	defaultAttribute( "RECURSE", "true" );
	defaultAttribute( "COMPRESSIONLEVEL", ZipArchiveOutputStream.DEFLATED );
	defaultAttribute( "PREFIX", "" );
	defaultAttribute( "OVERWRITE", "true" );
	defaultAttribute( "FLATTEN", "false" );
	defaultAttribute( "CHARSET", System.getProperty( "file.encoding" ) );

	parseTagHeader( _tag );

	if ( containsAttribute( "ATTRIBUTECOLLECTION" ) )
		return;

	if ( !containsAttribute( "ACTION" ) )
		throw newBadFileException( "Missing ACTION", "You need to specify a ACTION - valid actions are CREATE/ZIP, LIST or EXTRACT/UNZIP" );

	if ( !containsAttribute( "ZIPFILE" ) && !containsAttribute( "FILE" ) )
		throw newBadFileException( "Missing ZIPFILE/FILE", "You need to specify a ZIPFILE/FILE" );

}
 
Example #25
Source File: DeletedMessageZipperTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void zipShouldTerminateZipArchiveStreamWhenGettingException() throws Exception {
    doThrow(new IOException("mocked exception")).when(zipper).putMessageToEntry(any(), any(), any());
    AtomicReference<ZipArchiveOutputStream> zipOutputStreamReference = new AtomicReference<>();
    when(zipper.newZipArchiveOutputStream(any())).thenAnswer(spyZipOutPutStream(zipOutputStreamReference));

    try {
        zipper.zip(CONTENT_LOADER, Stream.of(DELETED_MESSAGE, DELETED_MESSAGE_2), new ByteArrayOutputStream());
    } catch (Exception e) {
        // ignored
    }

    verify(zipOutputStreamReference.get(), times(1)).finish();
    verify(zipOutputStreamReference.get(), times(1)).close();
}
 
Example #26
Source File: Zipper.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void archive(List<MailboxWithAnnotations> mailboxes, Stream<MessageResult> messages, OutputStream destination) throws IOException {
    try (ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(destination)) {
        storeMailboxes(mailboxes, archiveOutputStream);
        storeMessages(messages, archiveOutputStream);
        archiveOutputStream.finish();
    }
}
 
Example #27
Source File: Zipper.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void storeInArchive(MailboxAnnotation annotation, String directory, ZipArchiveOutputStream archiveOutputStream) throws IOException {
    String entryId = directory + "/" + annotation.getKey().asString();
    ZipArchiveEntry archiveEntry = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(new File(entryId), entryId);
    archiveEntry.addExtraField(EntryTypeExtraField.TYPE_MAILBOX_ANNOTATION);
    archiveOutputStream.putArchiveEntry(archiveEntry);

    annotation.getValue().ifPresent(value -> {
        try (PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(archiveOutputStream, Charsets.UTF_8), AUTO_FLUSH)) {
            printWriter.print(value);
        }
    });

    archiveOutputStream.closeArchiveEntry();
}
 
Example #28
Source File: OutstreamZipFile.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new temporary ZIP file in the target folder.
 *
 * @param parentDirName
 *            Parent directory of new zip file
 * @param zipFileName
 *            New zip file to be created
 *
 * @throws IOException
 */
public OutstreamZipFile(String parentDirName, String zipFileName) throws IOException {
    File parentDir = new File(parentDirName + "/");
    if (parentDir.isDirectory()) {
        tempZipFile = new File(parentDir, zipFileName + TMP + ".zip");
        tempZipFile.createNewFile();
        if (tempZipFile.canWrite()) {
            zos = new ZipArchiveOutputStream(new BufferedOutputStream(new FileOutputStream(
                    tempZipFile)));
            zipFile = new File(parentDir, zipFileName + ".zip");
        }
    }
}
 
Example #29
Source File: Zipper.java    From james-project with Apache License 2.0 5 votes vote down vote up
private ZipArchiveEntry createMessageZipArchiveEntry(MessageResult message, ZipArchiveOutputStream archiveOutputStream, String entryId) throws IOException {
    ZipArchiveEntry archiveEntry = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(new File(entryId), entryId);

    archiveEntry.addExtraField(EntryTypeExtraField.TYPE_MESSAGE);
    archiveEntry.addExtraField(new SizeExtraField(message.getSize()));
    archiveEntry.addExtraField(new UidExtraField(message.getUid().asLong()));
    archiveEntry.addExtraField(new MessageIdExtraField(message.getMessageId().serialize()));
    archiveEntry.addExtraField(new MailboxIdExtraField(message.getMailboxId().serialize()));
    archiveEntry.addExtraField(new InternalDateExtraField(message.getInternalDate()));
    archiveEntry.addExtraField(new FlagsExtraField(message.getFlags()));
    return archiveEntry;
}
 
Example #30
Source File: Zipper.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void storeAllAnnotationsInArchive(ZipArchiveOutputStream archiveOutputStream, List<MailboxAnnotation> annotations, String name) throws IOException {
    if (!annotations.isEmpty()) {
        String annotationsDirectoryPath = name + "/" + ANNOTATION_DIRECTORY;
        ZipArchiveEntry annotationDirectory = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(
            new Directory(annotationsDirectoryPath), annotationsDirectoryPath);
        annotationDirectory.addExtraField(EntryTypeExtraField.TYPE_MAILBOX_ANNOTATION_DIR);
        archiveOutputStream.putArchiveEntry(annotationDirectory);
        archiveOutputStream.closeArchiveEntry();
        annotations.forEach(Throwing.consumer(annotation ->
            storeInArchive(annotation, annotationsDirectoryPath, archiveOutputStream)));
    }
}