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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
Source File: EJSUtil.java    From jeddict with Apache License 2.0 5 votes vote down vote up
public static void copyDynamicResource(Consumer<FileTypeStream> parserManager, String inputResource, FileObject webRoot, Function<String, String> pathResolver, ProgressHandler handler) throws IOException {
    InputStream inputStream = loadResource(inputResource);
    try (ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
        ZipEntry entry;
        while ((entry = zipInputStream.getNextEntry()) != null) {
            if(entry.isDirectory()){
                continue;
            }
            boolean skipParsing = true;
            String entryName = entry.getName();                
            if (entryName.endsWith(".ejs")) {
                skipParsing = false;
                entryName = entryName.substring(0, entryName.lastIndexOf("."));
            }
            String targetPath = pathResolver.apply(entryName);
            if (targetPath == null) {
                continue;
            }
            handler.progress(targetPath);
            FileObject target = org.openide.filesystems.FileUtil.createData(webRoot, targetPath);
            FileLock lock = target.lock();
            try (OutputStream outputStream = target.getOutputStream(lock)) {
                parserManager.accept(new FileTypeStream(entryName, zipInputStream, outputStream, skipParsing));
                zipInputStream.closeEntry();
            } finally {
                lock.releaseLock();
            }
        }
    } catch (Throwable ex) {
        Exceptions.printStackTrace(ex);
        System.out.println("InputResource : " + inputResource);
    }
}
 
Example #23
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 #24
Source File: BshClassPath.java    From beanshell with Apache License 2.0 5 votes vote down vote up
/** Search Archive for classes.
 * @param the archive file location
 * @return array of class names found
 * @throws IOException */
static String [] searchArchiveForClasses( URL url ) throws IOException {
    List<String> list = new ArrayList<>();
    ZipInputStream zip = new ZipInputStream(url.openStream());

    ZipEntry ze;
    while( zip.available() == 1 )
        if ( (ze = zip.getNextEntry()) != null
                && isClassFileName( ze.getName() ) )
            list.add( canonicalizeClassName( ze.getName() ) );
    zip.close();

    return list.toArray( new String[list.size()] );
}
 
Example #25
Source File: EJSParser.java    From jeddict with Apache License 2.0 5 votes vote down vote up
public Consumer<FileTypeStream> getParserManager(List<String> skipFile) {
    return (FileTypeStream fileType) -> {
        try {
            if (SKIP_FILE_TYPE.contains(fileType.getFileType())
                    || (skipFile != null && skipFile.contains(fileType.getFileName()))
                    || fileType.isSkipParsing()) {
                copy(fileType.getInputStream(), fileType.getOutputStream());
                if (!(fileType.getInputStream() instanceof ZipInputStream)) {
                    fileType.getInputStream().close();
                }
                fileType.getOutputStream().close();
            } else {
                Reader reader = new BufferedReader(new InputStreamReader(fileType.getInputStream(), UTF_8));
                try (Writer writer = new BufferedWriter(new OutputStreamWriter(fileType.getOutputStream(), UTF_8))) {
                    writer.write(parse(reader));
                    if (!(fileType.getInputStream() instanceof ZipInputStream)) {
                        reader.close();
                    }
                    writer.flush();
                }
            }

        } catch (ScriptException | IOException ex) {
            Exceptions.printStackTrace(ex);
            System.out.println("Error in template : " + fileType.getFileName());
        }
    };
}
 
Example #26
Source File: WingsTask.java    From wings with Apache License 2.0 5 votes vote down vote up
private void unZipIt(String zipFile, String outputFolder) {
  byte[] buffer = new byte[1024];
  try{
    File folder = new File(outputFolder);
    if(!folder.exists()){
      folder.mkdir();
    }
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry ze = zis.getNextEntry();

    while(ze!=null) {
      String fileName = ze.getName();
      File newFile = new File(outputFolder + File.separator + fileName);
      new File(newFile.getParent()).mkdirs();
      FileOutputStream fos = new FileOutputStream(newFile);             
      int len;
      while ((len = zis.read(buffer)) > 0) {
        fos.write(buffer, 0, len);
      }
      fos.close();   
      ze = zis.getNextEntry();
    }
    zis.closeEntry();
    zis.close();
  } catch(IOException ex){
    ex.printStackTrace(); 
  }
}
 
Example #27
Source File: Dependencies.java    From eclipse-wakatime with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void unzip(String zipFile, File outputDir) throws IOException {
    if(!outputDir.exists())
        outputDir.mkdirs();

    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        String fileName = ze.getName();
        File newFile = new File(outputDir, fileName);

        if (ze.isDirectory()) {
            newFile.mkdirs();
        } else {
            FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
        }

        ze = zis.getNextEntry();
    }

    zis.closeEntry();
    zis.close();
}
 
Example #28
Source File: QuickAndDirtyXlsxReader.java    From WhiteRabbit with Apache License 2.0 5 votes vote down vote up
private void processRels(ZipInputStream inputStream) throws IOException {
	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
	String line = null;
	while ((line = bufferedReader.readLine()) != null)
		for (String tag : StringUtilities.multiFindBetween(line, "<Relationship", ">")) {
			String rId = StringUtilities.findBetween(tag, "Id=\"", "\"");
			String filename = "xl/" + StringUtilities.findBetween(tag, "Target=\"", "\"");
			if (filename.contains("/sheet")) {
				Sheet sheet = new Sheet();
				add(sheet);
				rIdToSheet.put(rId, sheet);
				filenameToSheet.put(filename, sheet);
			}
		}
}
 
Example #29
Source File: DeploymentController.java    From activiti-in-action-codes with Apache License 2.0 5 votes vote down vote up
/**
 * 部署流程资源
 */
@RequestMapping(value = "/deploy")
public String deploy(@RequestParam(value = "file", required = true) MultipartFile file) {

    // 获取上传的文件名
    String fileName = file.getOriginalFilename();

    try {
        // 得到输入流(字节流)对象
        InputStream fileInputStream = file.getInputStream();

        // 文件的扩展名
        String extension = FilenameUtils.getExtension(fileName);

        // zip或者bar类型的文件用ZipInputStream方式部署
        DeploymentBuilder deployment = repositoryService.createDeployment();
        if (extension.equals("zip") || extension.equals("bar")) {
            ZipInputStream zip = new ZipInputStream(fileInputStream);
            deployment.addZipInputStream(zip);
        } else {
            // 其他类型的文件直接部署
            deployment.addInputStream(fileName, fileInputStream);
        }
        deployment.deploy();
    } catch (Exception e) {
        logger.error("error on deploy process, because of file input stream");
    }

    return "redirect:process-list";
}
 
Example #30
Source File: SiteHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String getZipRootFolder(InputStream source) throws IOException {
    String folder = null;
    try {
        ZipInputStream str = new ZipInputStream(source);
        ZipEntry entry;
        boolean first = true;
        while ((entry = str.getNextEntry()) != null) {
            if (first) {
                first = false;
                if (entry.isDirectory()) {
                    folder = entry.getName();
                } else {
                    String fileName = entry.getName();
                    int slashIndex = fileName.indexOf('/');
                    if (slashIndex != -1) {
                        String name = fileName.substring(slashIndex+1);
                        folder = fileName.substring(0, slashIndex);
                        if (name.length() == 0 || folder.length() == 0) {
                            return null;
                        }
                        folder += "/"; //NOI18N
                    } else {
                        return null;
                    }
                }
            } else {
                if (!entry.getName().startsWith(folder)) {
                    return null;
                }
            }
        }
    } finally {
        source.close();
    }
    return folder;
}