java.util.zip.ZipInputStream Java Examples

The following examples show how to use java.util.zip.ZipInputStream. 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: SmallRyeBeanArchiveHandler.java    From smallrye-health with Apache License 2.0 7 votes vote down vote up
@Override
public BeanArchiveBuilder handle(String beanArchiveReference) {

    // An external form of a wildfly beans.xml URL will be something like:
    // vfs:/content/_DEFAULT___DEFAULT__1f4a3572-fc97-41f5-8fed-0e7e7f7895df.war/WEB-INF/lib/4e0a1b50-4a74-429d-b519-9eedcac11046.jar/META-INF/beans.xml
    beanArchiveReference = beanArchiveReference.substring(0, beanArchiveReference.lastIndexOf("/META-INF/beans.xml"));

    if (beanArchiveReference.endsWith(".war")) {
        // We only use this handler for libraries - WEB-INF classes are handled by ServletContextBeanArchiveHandler
        return null;
    }

    try {
        URL url = new URL(beanArchiveReference);
        try (ZipInputStream in = openStream(url)) {
            BeanArchiveBuilder builder = new BeanArchiveBuilder();
            handleLibrary(url, in, builder);
            return builder;
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #2
Source File: SignCode.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Removes base64 encoding, unzips the files and writes the new files over
 * the top of the old ones.
 */
private static void extractFilesFromApplicationString(String data, List<File> files)
        throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(data));
    try (ZipInputStream zis = new ZipInputStream(bais)) {
        byte[] buf = new byte[32 * 1024];
        for (int i = 0; i < files.size(); i ++) {
            try (FileOutputStream fos = new FileOutputStream(files.get(i))) {
                zis.getNextEntry();
                int numRead;
                while ( (numRead = zis.read(buf)) >= 0) {
                    fos.write(buf, 0 , numRead);
                }
            }
        }
    }
}
 
Example #3
Source File: ArtifactsServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldLogErrorIfFailedToSaveFileWhenAttemptHitsMaxAttempts() throws IOException {
    final File logsDir = new File("logs");
    final ByteArrayInputStream stream = new ByteArrayInputStream("".getBytes());
    String buildInstanceId = "1";
    final File destFile = new File(logsDir,
            buildInstanceId + File.separator + "generated" + File.separator + LOG_XML_NAME);
    final IOException ioException = new IOException();

    Mockito.doThrow(ioException).when(zipUtil).unzip(any(ZipInputStream.class), any(File.class));

    try (LogFixture logFixture = logFixtureFor(ArtifactsService.class, Level.DEBUG)) {
        ArtifactsService artifactsService = new ArtifactsService(resolverService, stageService, artifactsDirHolder, zipUtil);
        artifactsService.saveFile(destFile, stream, true, PUBLISH_MAX_RETRIES);
        String result;
        synchronized (logFixture) {
            result = logFixture.getLog();
        }
        assertThat(result).contains("Failed to save the file to:");
    }
}
 
Example #4
Source File: ASiCUtils.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns the next entry from the given ZipInputStream by skipping corrupted or
 * not accessible files NOTE: returns null only when the end of ZipInputStream
 * is reached
 * 
 * @param zis {@link ZipInputStream} to get next entry from
 * @return list of file name {@link String}s
 * @throws DSSException if too much tries failed
 */
public static ZipEntry getNextValidEntry(ZipInputStream zis) {
	int counter = 0;
	while (counter < MAX_MALFORMED_FILES) {
		try {
			return zis.getNextEntry();
		} catch (Exception e) {
			LOG.warn("ZIP container contains a malformed, corrupted or not accessible entry! The entry is skipped. Reason: [{}]", e.getMessage());
			// skip the entry and continue until find the next valid entry or end of the
			// stream
			counter++;
			closeEntry(zis);
		}
	}
	throw new DSSException("Unable to retrieve a valid ZipEntry (" + MAX_MALFORMED_FILES + " tries)");
}
 
Example #5
Source File: ZipUnpackerSequenceFileWriter.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected void processInputStream(InputStream stream, final FlowFile flowFile, final Writer writer) throws IOException {

    try (final ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(stream))) {
        ZipEntry zipEntry;
        while ((zipEntry = zipIn.getNextEntry()) != null) {
            if (zipEntry.isDirectory()) {
                continue;
            }
            final File file = new File(zipEntry.getName());
            final String key = file.getName();
            long fileSize = zipEntry.getSize();
            final InputStreamWritable inStreamWritable = new InputStreamWritable(zipIn, (int) fileSize);
            writer.append(new Text(key), inStreamWritable);
            logger.debug("Appending FlowFile {} to Sequence File", new Object[]{key});
        }
    }
}
 
Example #6
Source File: Zip.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public void decompress(final byte[] buf, final int offset, final int size, final OutputStream out) throws
        IOException {
    if (buf == null || buf.length == 0 || size <= 0 || offset >= buf.length || out == null) {
        return;
    }
    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(buf, offset, size));
    try {
        zis.getNextEntry();
        byte[] buffer = new byte[1024];
        int position = -1;
        while ((position = zis.read(buffer)) != -1) {
            out.write(buffer, 0, position);
        }
    } finally {
        zis.close();
    }
}
 
Example #7
Source File: JarProcessor.java    From shrinker with Apache License 2.0 6 votes vote down vote up
private List<Pair<String, byte[]>> readZipEntries(Path src) throws IOException {
    ImmutableList.Builder<Pair<String, byte[]>> list = ImmutableList.builder();
    try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(Files.readAllBytes(src)))) {
        for (ZipEntry entry = zip.getNextEntry();
             entry != null;
             entry = zip.getNextEntry()) {
            String name = entry.getName();
            if (!name.endsWith(".class")) {
                // skip
                continue;
            }
            long entrySize = entry.getSize();
            if (entrySize >= Integer.MAX_VALUE) {
                throw new OutOfMemoryError("Too large class file " + name + ", size is " + entrySize);
            }
            byte[] bytes = readByteArray(zip, (int) entrySize);
            list.add(Pair.of(name, bytes));
        }
    }
    return list.build();
}
 
Example #8
Source File: OS.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public static void ZipExplodeTo(InputStream stream, File outfolder) throws FileNotFoundException, IOException  {
	byte buffer[] = new byte[10240];
	outfolder.mkdirs();
	ZipInputStream zis = new ZipInputStream(stream);
	ZipEntry ze = zis.getNextEntry();
	while (ze != null) {
		FileOutputStream fout = new FileOutputStream(outfolder.getAbsolutePath()+File.separator+ze.getName());
		int len;
		while ((len=zis.read(buffer))>0) {
			fout.write(buffer,0,len);
		}
		fout.close();
		ze=zis.getNextEntry();
	}
	zis.closeEntry();
	zis.close();
	stream.close();
}
 
Example #9
Source File: CapabilityStatementUtilities.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts a zip file specified by the zipFilePath to a directory specified by
 * destDirectory (will be created if does not exists)
 * @param zipFilePath
 * @param destDirectory
 * @throws IOException
 */
public void unzip(String zipFilePath, String destDirectory) throws IOException {
    File destDir = new File(destDirectory);
    if (!destDir.exists()) {
        destDir.mkdir();
    }
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
    ZipEntry entry = zipIn.getNextEntry();
    // iterates over entries in the zip file
    while (entry != null) {
        String filePath = destDirectory + File.separator + entry.getName();
        if (!entry.isDirectory()) {
            // if the entry is a file, extracts it
            extractFile(zipIn, filePath);
        } else {
            // if the entry is a directory, make the directory
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}
 
Example #10
Source File: FileHelper.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
/*************ZIP file operation***************/
public static boolean readZipFile(String zipFileName, StringBuffer crc) {
	try {
		ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName));
		ZipEntry entry;
		while ((entry = zis.getNextEntry()) != null) {
			long size = entry.getSize();
			crc.append(entry.getCrc() + ", size: " + size);
        }
        zis.close();
	} catch (Exception ex) {
		Log.i(TAG,"Exception: " + ex.toString());
		return false;
	}
	return true;
}
 
Example #11
Source File: DeploymentCollectionResource.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
@Post
public String deploy(Representation entity){
	InputStream input = null;
	String processDefinitionKey = null;
	try {
		input = entity.getStream();
		if(input == null){
			throw new FoxbpmPluginException("请求中必须包含文件流", "Rest服务");
		}
		ModelService modelService = FoxBpmUtil.getProcessEngine().getModelService();
		ZipInputStream zip = new ZipInputStream(input);
		DeploymentBuilder deploymentBuilder = modelService.createDeployment();
		deploymentBuilder.addZipInputStream(zip);
		Deployment deployment = deploymentBuilder.deploy();
		setStatus(Status.SUCCESS_CREATED);
		ProcessDefinitionQuery processDefinitionQuery = modelService.createProcessDefinitionQuery();
		processDefinitionKey = processDefinitionQuery.deploymentId(deployment.getId()).singleResult().getId();
	} catch (Exception e) {
		if (e instanceof FoxBPMException) {
			throw (FoxBPMException) e;
		}
		throw new FoxBPMException(e.getMessage(), e);
	}		
	return processDefinitionKey;
}
 
Example #12
Source File: SmallRyeBeanArchiveHandler.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public BeanArchiveBuilder handle(String beanArchiveReference) {

    // An external form of a wildfly beans.xml URL will be something like:
    // vfs:/content/_DEFAULT___DEFAULT__1f4a3572-fc97-41f5-8fed-0e7e7f7895df.war/WEB-INF/lib/4e0a1b50-4a74-429d-b519-9eedcac11046.jar/META-INF/beans.xml
    beanArchiveReference = beanArchiveReference.substring(0, beanArchiveReference.lastIndexOf("/META-INF/beans.xml"));

    if (beanArchiveReference.endsWith(".war")) {
        // We only use this handler for libraries - WEB-INF classes are handled by ServletContextBeanArchiveHandler
        return null;
    }

    try {
        URL url = new URL(beanArchiveReference);
        try (ZipInputStream in = openStream(url)) {
            BeanArchiveBuilder builder = new BeanArchiveBuilder();
            handleLibrary(url, in, builder);
            return builder;
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #13
Source File: StatedRelationshipToOwlRefsetServiceTest.java    From snomed-owl-toolkit with Apache License 2.0 6 votes vote down vote up
@Test
public void convertAndReconcileStatedRelationshipsToOwlRefset() throws IOException, OWLOntologyCreationException, ConversionException {
	File baseRf2SnapshoZip = ZipUtil.zipDirectoryRemovingCommentsAndBlankLines("src/test/resources/SnomedCT_MiniRF2_Base_snapshot");
	File midCycleDeltaZip = ZipUtil.zipDirectoryRemovingCommentsAndBlankLines("src/test/resources/SnomedCT_MiniRF2_MidAuthoringCycle_delta");
	File compleOwlSnapshotZip = ZipUtil.zipDirectoryRemovingCommentsAndBlankLines("src/test/resources/SnomedCT_MiniRF2_Base_CompleteOwl_snapshot");

	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	service.convertStatedRelationshipsToOwlReRefsetAndReconcileWithPublishedArchive(new FileInputStream(baseRf2SnapshoZip), new FileInputStream(midCycleDeltaZip), new FileInputStream(compleOwlSnapshotZip), byteArrayOutputStream, "20190731");

	String owlRefset;
	try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()))) {
		ZipEntry nextEntry = zipInputStream.getNextEntry();
		assertEquals("sct2_sRefset_OWLAxiomDelta_INT_20190731.txt", nextEntry.getName());
		owlRefset = StreamUtils.copyToString(zipInputStream, Charset.forName("UTF-8"));
	}

	assertFalse("Output should not contain the snomed axiom prefix", owlRefset.contains("<http://snomed.info/id/"));
	assertEquals(
			"id\teffectiveTime\tactive\tmoduleId\trefsetId\treferencedComponentId\towlExpression\n" +
			"e35258b4-15d8-4fb2-bea5-dcc6b5e7de62\t\t1\t900000000000207008\t733073007\t8801005\tSubClassOf(ObjectIntersectionOf(:73211009 ObjectSomeValuesFrom(:roleGroup ObjectSomeValuesFrom(:100106001 :100102001))) :8801005)\n" +
			"1\t\t1\t900000000000207008\t733073007\t8801005\tSubClassOf(:8801005 :73211009)\n" +
			"2\t\t1\t900000000000207008\t733073007\t73211009\tSubClassOf(:73211009 :362969004)\n" +
			"2b75cd59-24c6-46e4-8565-0ab3da7f0ab3\t\t0\t900000000000207008\t733073007\t362969004\tEquivalentClasses(:362969004 ObjectIntersectionOf(:404684003 ObjectSomeValuesFrom(:609096000 ObjectSomeValuesFrom(:363698007 :113331007))))\n",
			owlRefset);
}
 
Example #14
Source File: FilesTest.java    From development with Apache License 2.0 6 votes vote down vote up
protected Map<String, byte[]> getZipEntries(byte[] content)
        throws IOException {
    Map<String, byte[]> result = new HashMap<String, byte[]>();
    ZipInputStream in = new ZipInputStream(
            new ByteArrayInputStream(content));
    ZipEntry entry;
    while ((entry = in.getNextEntry()) != null) {
        String path = entry.getName();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int b;
        while ((b = in.read()) != -1)
            buffer.write(b);
        assertNull("duplicate entry " + path, result.put(path, buffer
                .toByteArray()));
    }
    return result;
}
 
Example #15
Source File: RepoGen.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
private Manifest getManifest(final File file) throws IOException
{
	final ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
	try
	{
		ZipEntry entry = zis.getNextEntry();
		while (entry != null)
		{
			// read the manifest to determine the name and version number
			// System.out.println(entry.getName() + " " + entry.isDirectory());
			if ("META-INF/MANIFEST.MF".equals(entry.getName()))
				return new Manifest(zis);
			entry = zis.getNextEntry();
		}
	}
	finally
	{
		zis.close();
	}
	return null;
}
 
Example #16
Source File: BasicGameWizardIterator.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static void unZipFile(InputStream source, FileObject projectRoot) throws IOException {
    try {
        ZipInputStream str = new ZipInputStream(source);
        ZipEntry entry;
        while ((entry = str.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                FileUtil.createFolder(projectRoot, entry.getName());
            } else {
                FileObject fo = FileUtil.createData(projectRoot, entry.getName());
                if ("nbproject/project.xml".equals(entry.getName())) {
                    // Special handling for setting name of Ant-based projects; customize as needed:
                    filterProjectXML(fo, str, projectRoot.getName());
                } else {
                    writeFile(str, fo);
                }
            }
        }
    } finally {
        source.close();
    }
}
 
Example #17
Source File: AvailableGames.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
private static Map<String, URI> getGamesFromZip(final File map) {
  final Map<String, URI> availableGames = new HashMap<>();

  try (InputStream fis = new FileInputStream(map);
      ZipInputStream zis = new ZipInputStream(fis);
      URLClassLoader loader = new URLClassLoader(new URL[] {map.toURI().toURL()})) {
    ZipEntry entry = zis.getNextEntry();
    while (entry != null) {
      if (entry.getName().contains("games/") && entry.getName().toLowerCase().endsWith(".xml")) {
        final URL url = loader.getResource(entry.getName());
        if (url != null) {
          availableGames.putAll(
              getAvailableGames(URI.create(url.toString().replace(" ", "%20"))));
        }
      }
      // we have to close the loader to allow files to be deleted on windows
      zis.closeEntry();
      entry = zis.getNextEntry();
    }
  } catch (final IOException e) {
    log.log(Level.SEVERE, "Error reading zip file in: " + map.getAbsolutePath(), e);
  }
  return availableGames;
}
 
Example #18
Source File: LwjglAppletCompositeProvider.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void unZipFile(InputStream source, FileObject projectRoot) throws IOException {
    try {
        ZipInputStream str = new ZipInputStream(source);
        ZipEntry entry;
        while ((entry = str.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                FileUtil.createFolder(projectRoot, entry.getName());
            } else {
                FileObject fo = FileUtil.createData(projectRoot, entry.getName());
                writeFile(str, fo);
            }
        }
    } finally {
        source.close();
    }
}
 
Example #19
Source File: OS.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public static void ZipExplodeToHere(String zippath) throws FileNotFoundException, IOException  {
	byte buffer[] = new byte[10240];
	File zipfile = new File(zippath);
	File outfolder = new File(zipfile.getParentFile().getAbsolutePath());
	outfolder.mkdirs();
	ZipInputStream zis = new ZipInputStream(new FileInputStream(zippath));
	ZipEntry ze = zis.getNextEntry();
	while (ze != null) {
		FileOutputStream fout = new FileOutputStream(outfolder.getAbsolutePath()+File.separator+ze.getName());
		int len;
		while ((len=zis.read(buffer))>0) {
			fout.write(buffer,0,len);
		}
		fout.close();
		ze=zis.getNextEntry();
	}
	zis.closeEntry();
	zis.close();
}
 
Example #20
Source File: DitaDocumentationGeneratorTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void generateDita(@TempDir final File temporaryFolder, final TestInfo info) throws IOException {
    final File output = new File(temporaryFolder, info.getTestMethod().get().getName() + ".zip");
    new DitaDocumentationGenerator(
            new File[] {
                    copyBinaries("org.talend.test.valid", temporaryFolder, info.getTestMethod().get().getName()) },
            Locale.ROOT, log, output, true, true).run();
    assertTrue(output.exists());
    final Map<String, String> files = new HashMap<>();
    try (final ZipInputStream zip = new ZipInputStream(new FileInputStream(output))) {
        ZipEntry nextEntry;
        while ((nextEntry = zip.getNextEntry()) != null) {
            files.put(nextEntry.getName(), IO.slurp(zip));
        }
    }
    try (final BufferedReader reader = resource("generateDita1.xml")) {
        assertEquals(reader.lines().collect(joining("\n")), files.get("generateDita/test/my.dita").trim());
    }
    try (final BufferedReader reader = resource("generateDita2.xml")) {
        assertEquals(reader.lines().collect(joining("\n")), files.get("generateDita/test/my2.dita").trim());
    }
    assertEquals(4, files.size());
    // folders
    assertEquals("", files.get("generateDita/test/"));
    assertEquals("", files.get("generateDita/"));
}
 
Example #21
Source File: ResourceParentFolderAutoDeploymentStrategyTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeployResources_NoParent() {

    final Resource[] resources = new Resource[] { resourceMock1, resourceMock2, resourceMock3 };
    classUnderTest.deployResources(deploymentNameHint, resources, repositoryServiceMock);

    when(fileMock1.getParentFile()).thenReturn(null);
    when(fileMock2.getParentFile()).thenReturn(parentFile2Mock);
    when(parentFile2Mock.isDirectory()).thenReturn(false);
    when(fileMock3.getParentFile()).thenReturn(null);

    verify(repositoryServiceMock, times(3)).createDeployment();
    verify(deploymentBuilderMock, times(3)).enableDuplicateFiltering();
    verify(deploymentBuilderMock, times(1)).name(deploymentNameHint + "." + resourceName1);
    verify(deploymentBuilderMock, times(1)).name(deploymentNameHint + "." + resourceName2);
    verify(deploymentBuilderMock, times(1)).name(deploymentNameHint + "." + resourceName3);
    verify(deploymentBuilderMock, times(1)).addInputStream(eq(resourceName1), isA(InputStream.class));
    verify(deploymentBuilderMock, times(1)).addInputStream(eq(resourceName2), isA(InputStream.class));
    verify(deploymentBuilderMock, times(1)).addZipInputStream(isA(ZipInputStream.class));
    verify(deploymentBuilderMock, times(3)).deploy();
}
 
Example #22
Source File: ZipUtilsTest.java    From panda with Apache License 2.0 5 votes vote down vote up
@Test
void extract() throws IOException {
    File outputDirectory = directoryPath.toFile();

    BufferedInputStream stream = new BufferedInputStream(ZipUtils.class.getResourceAsStream("/commons/zip-utils-test.zip"));
    ZipInputStream zipStream = new ZipInputStream(stream);
    ZipUtils.extract(zipStream, outputDirectory);

    File directory = new File(outputDirectory, "directory");
    Assertions.assertTrue(directory.exists());

    Node<File> map = FileUtils.collectFiles(directory);
    Assertions.assertEquals("directory", map.getElement().getName());

    Set<String> files = map.collectLeafs(File::isFile).stream()
            .map(File::getName)
            .collect(Collectors.toSet());
    Assertions.assertEquals(Sets.newHashSet("1.txt", "2.txt"), files);
}
 
Example #23
Source File: ClsSet.java    From Box with Apache License 2.0 5 votes vote down vote up
private void load(File input) throws IOException, DecodeException {
	String name = input.getName();
	try (InputStream inputStream = new FileInputStream(input)) {
		if (name.endsWith(CLST_EXTENSION)) {
			load(inputStream);
		} else if (name.endsWith(".jar")) {
			try (ZipInputStream in = new ZipInputStream(inputStream)) {
				ZipEntry entry = in.getNextEntry();
				while (entry != null) {
					if (entry.getName().endsWith(CLST_EXTENSION) && ZipSecurity.isValidZipEntry(entry)) {
						load(in);
					}
					entry = in.getNextEntry();
				}
			}
		} else {
			throw new JadxRuntimeException("Unknown file format: " + name);
		}
	}
}
 
Example #24
Source File: DeploymentBuilderImpl.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public DeploymentBuilder addZipInputStream(ZipInputStream zipInputStream) {
  try {
    ZipEntry entry = zipInputStream.getNextEntry();
    while (entry != null) {
      if (!entry.isDirectory()) {
        String entryName = entry.getName();
        addInputStream(entryName, zipInputStream);
      }
      entry = zipInputStream.getNextEntry();
    }
  } catch (Exception e) {
    throw new ProcessEngineException("problem reading zip input stream", e);
  }
  return this;
}
 
Example #25
Source File: TestMergeContent.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testZip() throws IOException {
    final TestRunner runner = TestRunners.newTestRunner(new MergeContent());
    runner.setProperty(MergeContent.MAX_BIN_AGE, "1 sec");
    runner.setProperty(MergeContent.MERGE_FORMAT, MergeContent.MERGE_FORMAT_ZIP);

    createFlowFiles(runner);
    runner.run();

    runner.assertQueueEmpty();
    runner.assertTransferCount(MergeContent.REL_MERGED, 1);
    runner.assertTransferCount(MergeContent.REL_FAILURE, 0);
    runner.assertTransferCount(MergeContent.REL_ORIGINAL, 3);

    final MockFlowFile bundle = runner.getFlowFilesForRelationship(MergeContent.REL_MERGED).get(0);
    try (final InputStream rawIn = new ByteArrayInputStream(runner.getContentAsByteArray(bundle)); final ZipInputStream in = new ZipInputStream(rawIn)) {
        Assert.assertNotNull(in.getNextEntry());
        final byte[] part1 = IOUtils.toByteArray(in);
        Assert.assertTrue(Arrays.equals("Hello".getBytes("UTF-8"), part1));

        in.getNextEntry();
        final byte[] part2 = IOUtils.toByteArray(in);
        Assert.assertTrue(Arrays.equals(", ".getBytes("UTF-8"), part2));

        in.getNextEntry();
        final byte[] part3 = IOUtils.toByteArray(in);
        Assert.assertTrue(Arrays.equals("World!".getBytes("UTF-8"), part3));
    }
    bundle.assertAttributeEquals(CoreAttributes.MIME_TYPE.key(), "application/zip");
}
 
Example #26
Source File: CheckoutTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void unpack (String filename) throws IOException {
    File zipLarge = new File(getDataDir(), filename);
    ZipInputStream is = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipLarge)));
    ZipEntry entry;
    while ((entry = is.getNextEntry()) != null) {
        File unpacked = new File(workDir, entry.getName());
        FileChannel channel = new FileOutputStream(unpacked).getChannel();
        byte[] bytes = new byte[2048];
        try {
            int len;
            long size = entry.getSize();
            while (size > 0 && (len = is.read(bytes, 0, 2048)) > 0) {
                ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, len);
                int j = channel.write(buffer);
                size -= len;
            }
        } finally {
            channel.close();
        }
    }
    ZipEntry e = is.getNextEntry();
}
 
Example #27
Source File: LottieCompositionFactory.java    From lottie-android with Apache License 2.0 5 votes vote down vote up
/**
 * Parse an animation from src/main/assets. It is recommended to use {@link #fromRawRes(Context, int)} instead.
 * The asset file name will be used as a cache key so future usages won't have to parse the json again.
 * However, if your animation has images, you may package the json and images as a single flattened zip file in assets.
 *
 * Pass null as the cache key to skip the cache.
 *
 * @see #fromZipStreamSync(ZipInputStream, String)
 */
@WorkerThread
public static LottieResult<LottieComposition> fromAssetSync(Context context, String fileName, @Nullable String cacheKey) {
  try {
    if (fileName.endsWith(".zip")) {
      return fromZipStreamSync(new ZipInputStream(context.getAssets().open(fileName)), cacheKey);
    }
    return fromJsonInputStreamSync(context.getAssets().open(fileName), cacheKey);
  } catch (IOException e) {
    return new LottieResult<>(e);
  }
}
 
Example #28
Source File: Constructor.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    try {
        ZipInputStream in = new ZipInputStream(null);
        throw new Exception("Constructor did not check the null argument");
    } catch (NullPointerException e) {
    }
}
 
Example #29
Source File: ZipInputStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.util.zip.ZipInputStream#skip(long)
 */
public void test_skipJ() throws Exception {
    zentry = zis.getNextEntry();
    byte[] rbuf = new byte[(int) zentry.getSize()];
    zis.skip(2);
    int r = zis.read(rbuf, 0, rbuf.length);
    assertEquals("Failed to skip data", 10, r);

    zentry = zis.getNextEntry();
    zentry = zis.getNextEntry();
    long s = zis.skip(1025);
    assertEquals("invalid skip: " + s, 1025, s);

    try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipBytes))) {
        zis.getNextEntry();
        long skipLen = dataBytes.length / 2;
        assertEquals("Assert 0: failed valid skip", skipLen, zis.skip(skipLen));
        zis.skip(dataBytes.length);
        assertEquals("Assert 1: performed invalid skip", 0, zis.skip(1));
        assertEquals("Assert 2: failed zero len skip", 0, zis.skip(0));
        try {
            zis.skip(-1);
            fail("Assert 3: Expected Illegal argument exception");
        } catch (IllegalArgumentException e) {
            // Expected
        }
    }
}
 
Example #30
Source File: Processor.java    From awacs with Apache License 2.0 5 votes vote down vote up
private void processEntry(final ZipInputStream zis, final ZipEntry ze,
        final ContentHandlerFactory handlerFactory) {
    ContentHandler handler = handlerFactory.createContentHandler();
    try {

        // if (CODE2ASM.equals(command)) { // read bytecode and process it
        // // with TraceClassVisitor
        // ClassReader cr = new ClassReader(readEntry(zis, ze));
        // cr.accept(new TraceClassVisitor(null, new PrintWriter(os)),
        // false);
        // }

        boolean singleInputDocument = inRepresentation == SINGLE_XML;
        if (inRepresentation == BYTECODE) { // read bytecode and process it
            // with handler
            ClassReader cr = new ClassReader(readEntry(zis, ze));
            cr.accept(new SAXClassAdapter(handler, singleInputDocument), 0);

        } else { // read XML and process it with handler
            XMLReader reader = XMLReaderFactory.createXMLReader();
            reader.setContentHandler(handler);
            reader.parse(new InputSource(
                    singleInputDocument ? (InputStream) new ProtectedInputStream(
                            zis) : new ByteArrayInputStream(readEntry(zis,
                            ze))));

        }
    } catch (Exception ex) {
        update(ze.getName(), 0);
        update(ex, 0);
    }
}