List of usage examples for java.util.zip ZipFile getInputStream
public InputStream getInputStream(ZipEntry entry) throws IOException
From source file:no.uio.medicine.virsurveillance.parsers.CSVsGBDdata.java
public void parse(String deathFolder) throws IOException { File f = new File(deathFolder); Runtime runtime = Runtime.getRuntime(); if (f.isDirectory()) { String[] filesInDir = f.list(); for (String fil : filesInDir) { if (fil.endsWith(".zip")) { ZipFile zipFile = new ZipFile(deathFolder + "/" + fil); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { System.out.println( "Used memory: " + (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024) + " Free memory: " + (runtime.freeMemory()) / (1024 * 1024)); ZipEntry entry = entries.nextElement(); InputStream stream = zipFile.getInputStream(entry); BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8")); CSVParser parser = CSVFormat.RFC4180.withDelimiter(',').withIgnoreEmptyLines().withHeader() .parse(br);//from ww w . j a va2 s . com List<CSVRecord> records = parser.getRecords(); System.out.println("Reading records: " + zipFile.getName() + "/" + entry); /*for (int i=0;i<records.size();i++) { CSVRecord csvRecord = records.get(i);*/ for (CSVRecord csvRecord : records) { if (csvRecord.isMapped("age_group_id")) { //age group 22 corresponds to all ages if (csvRecord.get("age_group_id").equalsIgnoreCase("22")) { String location = null; String year = null; String sex = null; String cause = null; String number = null; String metric = null; if (csvRecord.isMapped("location_code")) { location = csvRecord.get("location_code"); } if (csvRecord.isMapped("year")) { year = csvRecord.get("year"); } if (csvRecord.isMapped("sex_id")) { //1=male, 2 = female if (csvRecord.get("sex_id").equalsIgnoreCase(("1"))) { sex = "m"; } else if (csvRecord.get("sex_id").equalsIgnoreCase("2")) { sex = "f"; } } if (csvRecord.isMapped("cause_name")) { cause = csvRecord.get("cause_name"); } if (csvRecord.isMapped("mean")) { number = csvRecord.get("mean"); } if (csvRecord.isMapped("metric") && csvRecord.isMapped("unit")) { metric = csvRecord.get("metric") + "-" + csvRecord.get("unit"); } if (location != null && year != null && sex != null && cause != null && number != null && metric != null) { try { sqlM.addSanitaryIssueToCountry(location, year, sex, cause, metric, number); } catch (SQLException ex) { Logger.getLogger(CSVsGBDdata.class.getName()).log(Level.SEVERE, null, ex); } } } } } parser.close(); stream.close(); br.close(); } zipFile.close(); } } } else { System.out.println("Not a directory"); } }
From source file:com.openmeap.file.FileOperationManagerImpl.java
@Override public void unzipFile(ZipFile zipFile, String destinationDir) throws FileOperationException { try {/*from ww w. j a v a2s . c o m*/ int BUFFER = 1024; BufferedOutputStream dest = null; BufferedInputStream is = null; OutputStream fos = null; ZipEntry entry; Enumeration e = zipFile.entries(); while (e.hasMoreElements()) { try { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipFile.getInputStream(entry)); String newFile = destinationDir + File.separator + entry.getName(); if (entry.isDirectory()) { continue; // skip directories, resource manager will create for us } else { fos = write(newFile); dest = new BufferedOutputStream(fos, BUFFER); Utils.pipeInputStreamIntoOutputStream(is, dest); } } finally { if (dest != null) { dest.close(); } if (fos != null) { fos.close(); } if (is != null) { is.close(); } } } } catch (IOException ioe) { throw new FileOperationException(ioe); } }
From source file:io.fabric8.forge.camel.commands.CamelNewComponentsCommand.java
private String findComponentFQCN(String component, String selectedVersion) { String result = null;//from w w w. j a v a2 s.c o m InputStream stream = null; try { File tmp = File.createTempFile("camel-dep", "jar"); URL url = new URL(String.format("https://repo1.maven.org/maven2/org/apache/camel/%s/%s/%s-%s.jar", component, selectedVersion, component, selectedVersion)); FileUtils.copyURLToFile(url, tmp); ZipFile zipFile = new ZipFile(tmp); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getName().startsWith("META-INF/services/org/apache/camel/component/") && !entry.isDirectory()) { stream = zipFile.getInputStream(entry); Properties prop = new Properties(); prop.load(stream); result = prop.getProperty("class"); break; } } } catch (Exception e) { throw new RuntimeException("Unable to inspect added component", e); } finally { if (stream != null) { try { stream.close(); } catch (Exception e) { } } } return result; }
From source file:net.minecraftforge.fml.server.FMLServerHandler.java
@Override public void addModAsResource(ModContainer container) { String langFile = "assets/" + container.getModId().toLowerCase() + "/lang/en_US.lang"; File source = container.getSource(); InputStream stream = null;// w ww.j a v a 2 s.c om ZipFile zip = null; try { if (source.isDirectory() && (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment")) { stream = new FileInputStream(new File(source.toURI().resolve(langFile).getPath())); } else { zip = new ZipFile(source); ZipEntry entry = zip.getEntry(langFile); if (entry == null) throw new FileNotFoundException(); stream = zip.getInputStream(entry); } LanguageMap.inject(stream); } catch (IOException e) { // hush } catch (Exception e) { FMLLog.getLogger().error(e); } finally { IOUtils.closeQuietly(stream); try { if (zip != null) zip.close(); } catch (IOException e) { // shush } } }
From source file:com.t3.persistence.PackedFile.java
/** * Returns an InputStream that corresponds to the zip file path specified. * This method should be called only for binary file contents such as * images (assets and thumbnails).// w ww. j av a2s .c o m * For character-based data, use {@link #getFileAsReader(String)} * instead. * * @param path zip file archive path entry * @return InputStream representing the data stream * @throws IOException */ public InputStream getFileAsInputStream(String path) throws IOException { File explodedFile = getExplodedFile(path); if ((!file.exists() && !tmpFile.exists() && !explodedFile.exists()) || removedFileSet.contains(path)) throw new FileNotFoundException(path); if (explodedFile.exists()) return FileUtil.getFileAsInputStream(explodedFile); ZipEntry entry = new ZipEntry(path); ZipFile zipFile = getZipFile(); InputStream in = null; try { in = zipFile.getInputStream(entry); if (in != null) { String type = FileUtil.getContentType(in); if (log.isDebugEnabled() && type != null) log.debug("FileUtil.getContentType() returned " + type); return in; } } catch (Exception ex) { // Don't need to close 'in' since zipFile.close() will do so } throw new FileNotFoundException(path); }
From source file:org.openmrs.module.clinicalsummary.rule.EvaluableSummaryRuleProvider.java
/** * @see org.openmrs.logic.rule.provider.RuleProvider#afterStartup() *///from w w w . ja v a2 s. c om @Override public void afterStartup() { if (log.isDebugEnabled()) log.debug("Registering clinical summary rules ..."); try { ModuleClassLoader moduleClassLoader = ModuleFactory.getModuleClassLoader(CLINICAL_SUMMARY_MODULE); for (URL url : moduleClassLoader.getURLs()) { String filename = url.getFile(); if (StringUtils.contains(filename, CLINICAL_SUMMARY_MODULE_API)) { ZipFile zipFile = new ZipFile(filename); for (Enumeration list = zipFile.entries(); list.hasMoreElements();) { ZipEntry entry = (ZipEntry) list.nextElement(); String zipFileName = FilenameUtils.getBaseName(entry.getName()); String zipFileExtension = FilenameUtils.getExtension(entry.getName()); if (StringUtils.endsWith(zipFileName, RULE_CLASS_SUFFIX) && StringUtils.equals(zipFileExtension, CLASS_SUFFIX)) { EvaluableRuleVisitor visitor = new EvaluableRuleVisitor(); ClassReader classReader = new ClassReader(zipFile.getInputStream(entry)); classReader.accept(visitor, false); } } zipFile.close(); } } } catch (IOException e) { log.error("Processing rule classes failed. Rule might not get registered."); } }
From source file:net.sf.zekr.engine.translation.TranslationData.java
private void loadAndVerify() throws TranslationException { ZipFile zf = null; try {/*w w w .jav a 2 s. c o m*/ logger.info("Loading translation pack " + this + "..."); zf = new ZipFile(archiveFile); ZipEntry ze = zf.getEntry(file); if (ze == null) { logger.error("Load failed. No proper entry found in \"" + archiveFile.getName() + "\"."); return; } byte[] textBuf = new byte[(int) ze.getSize()]; if (!verify(zf.getInputStream(ze), textBuf)) logger.warn("Unauthorized translation data pack: " + this); // throw new TranslationException("INVALID_TRANSLATION_SIGNATURE", new String[] { name }); refineText(new String(textBuf, encoding)); logger.log("Translation pack " + this + " loaded successfully."); } catch (IOException e) { logger.error("Problem while loading translation pack " + this + "."); logger.log(e); throw new TranslationException(e); } finally { try { zf.close(); } catch (Exception e) { // do nothing } } }
From source file:org.openmrs.module.amrsreports.rule.MohEvaluableRuleProvider.java
/** * @see org.openmrs.logic.rule.provider.RuleProvider#afterStartup() *//*from www.ja v a2s .com*/ @Override public void afterStartup() { if (log.isDebugEnabled()) log.debug("Registering AMRS reports summary rules ..."); try { ModuleClassLoader moduleClassLoader = ModuleFactory.getModuleClassLoader(AMRS_REPORT_MODULE); for (URL url : moduleClassLoader.getURLs()) { String filename = url.getFile(); if (StringUtils.contains(filename, AMRS_REPORT_MODULE_API)) { ZipFile zipFile = new ZipFile(filename); for (Enumeration list = zipFile.entries(); list.hasMoreElements();) { ZipEntry entry = (ZipEntry) list.nextElement(); String zipFileName = FilenameUtils.getBaseName(entry.getName()); String zipFileExtension = FilenameUtils.getExtension(entry.getName()); if (StringUtils.endsWith(zipFileName, RULE_CLASS_SUFFIX) && StringUtils.equals(zipFileExtension, CLASS_SUFFIX)) { MohEvaluableRuleVisitor visitor = new MohEvaluableRuleVisitor(); ClassReader classReader = new ClassReader(zipFile.getInputStream(entry)); classReader.accept(visitor, false); } } zipFile.close(); } } } catch (IOException e) { log.error("Processing rule classes failed. Rule might not get registered."); } }
From source file:com.dibsyhex.apkdissector.ZipReader.java
public void getZipContents(String name) { try {/* www .j av a 2 s .com*/ File file = new File(name); FileInputStream fileInputStream = new FileInputStream(file); ZipInputStream zipInputStream = new ZipInputStream(fileInputStream); //System.out.println(zipInputStream.available()); //System.out.println("Reading each entries in details:"); ZipFile zipFile = new ZipFile(file); ZipEntry zipEntry; response.displayLog("Begining to extract"); while ((zipEntry = zipInputStream.getNextEntry()) != null) { String filename = "extracts" + File.separator + file.getName() + File.separator + zipEntry.getName(); System.out.println(filename); response.displayLog(filename); File extractDirectory = new File(filename); //Create the directories new File(extractDirectory.getParent()).mkdirs(); //Now write the contents InputStream inputStream = zipFile.getInputStream(zipEntry); OutputStream outputStream = new FileOutputStream(extractDirectory); FileUtils.copyInputStreamToFile(inputStream, extractDirectory); //Decode the xml files if (filename.endsWith(".xml")) { //First create a temp file at a location temp/extract/... File temp = new File("temp" + File.separator + extractDirectory); new File(temp.getParent()).mkdirs(); //Create an object of XML Decoder XmlDecoder xmlDecoder = new XmlDecoder(); InputStream inputStreamTemp = new FileInputStream(extractDirectory); byte[] buf = new byte[80000];//increase int bytesRead = inputStreamTemp.read(buf); String xml = xmlDecoder.decompressXML(buf); //System.out.println(xml); FileUtils.writeStringToFile(temp, xml); //Now rewrite the files at the original locations FileUtils.copyFile(temp, extractDirectory); } } response.displayLog("Extraction Done !"); System.out.println(" DONE ! "); zipInputStream.close(); } catch (Exception e) { System.out.println(e.toString()); response.displayError(e.toString()); } }
From source file:com.enioka.jqm.tools.LibraryCache.java
private void loadCache(Node node, JobDef jd, EntityManager em) throws JqmPayloadException { jqmlogger.debug("Resolving classpath for job definition " + jd.getApplicationName()); File jarFile = new File(FilenameUtils.concat(new File(node.getRepo()).getAbsolutePath(), jd.getJarPath())); File jarDir = jarFile.getParentFile(); File libDir = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "lib")); File libDirExtracted = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "libFromJar")); File pomFile = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "pom.xml")); // POM file should be deleted if it comes from the jar file. Otherwise, it would stay into place and modifications to the internal // pom would be ignored. boolean pomFromJar = false; // 1st: if no pom, no lib dir => find a pom inside the JAR. (& copy it, we will read later) if (!pomFile.exists() && !libDir.exists()) { jqmlogger.trace("No pom inside jar directory. Checking for a pom inside the jar file"); InputStream is = null;/*from w w w . j a v a 2s .c o m*/ FileOutputStream os = null; try { ZipFile zf = new ZipFile(jarFile); Enumeration<? extends ZipEntry> zes = zf.entries(); while (zes.hasMoreElements()) { ZipEntry ze = zes.nextElement(); if (ze.getName().endsWith("pom.xml")) { is = zf.getInputStream(ze); os = new FileOutputStream(pomFile); IOUtils.copy(is, os); pomFromJar = true; break; } } zf.close(); } catch (Exception e) { throw new JqmPayloadException("Could not handle pom inside jar", e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } // 2nd: no pom, no pom inside jar, no lib dir => find a lib dir inside the jar if (!pomFile.exists() && !libDir.exists()) { jqmlogger.trace("Checking for a lib directory inside jar"); InputStream is = null; FileOutputStream os = null; ZipFile zf = null; FileUtils.deleteQuietly(libDirExtracted); try { zf = new ZipFile(jarFile); Enumeration<? extends ZipEntry> zes = zf.entries(); while (zes.hasMoreElements()) { ZipEntry ze = zes.nextElement(); if (ze.getName().startsWith("lib/") && ze.getName().endsWith(".jar")) { if (!libDirExtracted.isDirectory() && !libDirExtracted.mkdir()) { throw new JqmPayloadException("Could not extract libraries from jar"); } is = zf.getInputStream(ze); os = new FileOutputStream(FilenameUtils.concat(libDirExtracted.getAbsolutePath(), FilenameUtils.getName(ze.getName()))); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } } catch (Exception e) { throw new JqmPayloadException("Could not handle internal lib directory", e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); try { zf.close(); } catch (Exception e) { jqmlogger.warn("could not close jar file", e); } } // If libs were extracted, put in cache and return if (libDirExtracted.isDirectory()) { FileFilter fileFilter = new WildcardFileFilter("*.jar"); File[] files = libDirExtracted.listFiles(fileFilter); URL[] libUrls = new URL[files.length]; try { for (int i = 0; i < files.length; i++) { libUrls[i] = files[i].toURI().toURL(); } } catch (Exception e) { throw new JqmPayloadException("Could not handle internal lib directory", e); } // Put in cache putInCache(libUrls, jd.getApplicationName()); return; } } // 3rd: if pom, use pom! if (pomFile.exists() && !libDir.exists()) { jqmlogger.trace("Reading a pom file"); // Retrieve resolver configuration List<GlobalParameter> repolist = em .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :repo", GlobalParameter.class) .setParameter("repo", "mavenRepo").getResultList(); List<GlobalParameter> settings = em .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :k", GlobalParameter.class) .setParameter("k", "mavenSettingsCL").getResultList(); List<GlobalParameter> settingFiles = em .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :k", GlobalParameter.class) .setParameter("k", "mavenSettingsFile").getResultList(); boolean withCentral = false; String withCustomSettings = null; String withCustomSettingsFile = null; if (settings.size() == 1 && settingFiles.isEmpty()) { jqmlogger.trace("Custom settings file will be used: " + settings.get(0).getValue()); withCustomSettings = settings.get(0).getValue(); } if (settingFiles.size() == 1) { jqmlogger.trace("Custom settings file will be used: " + settingFiles.get(0).getValue()); withCustomSettingsFile = settingFiles.get(0).getValue(); } // Configure resolver ConfigurableMavenResolverSystem resolver = Maven.configureResolver(); if (withCustomSettings != null && withCustomSettingsFile == null) { resolver.fromClassloaderResource(withCustomSettings); } if (withCustomSettingsFile != null) { resolver.fromFile(withCustomSettingsFile); } for (GlobalParameter gp : repolist) { if (gp.getValue().contains("repo1.maven.org")) { withCentral = true; } resolver = resolver.withRemoteRepo(MavenRemoteRepositories .createRemoteRepository(gp.getId().toString(), gp.getValue(), "default") .setUpdatePolicy(MavenUpdatePolicy.UPDATE_POLICY_NEVER)); } resolver.withMavenCentralRepo(withCentral); // Resolve File[] depFiles = null; try { depFiles = resolver.loadPomFromFile(pomFile).importRuntimeDependencies().resolve() .withTransitivity().asFile(); } catch (IllegalArgumentException e) { // Happens when no dependencies inside pom, which is a weird use of the feature... jqmlogger.trace("No dependencies inside pom.xml file - no libs will be used", e); depFiles = new File[0]; } // Extract results int size = 0; for (File artifact : depFiles) { if (!"pom".equals(FilenameUtils.getExtension(artifact.getName()))) { size++; } } URL[] tmp = new URL[size]; int i = 0; for (File artifact : depFiles) { if ("pom".equals(FilenameUtils.getExtension(artifact.getName()))) { continue; } try { tmp[i] = artifact.toURI().toURL(); } catch (MalformedURLException e) { throw new JqmPayloadException("Incorrect dependency in POM file", e); } i++; } // Put in cache putInCache(tmp, jd.getApplicationName()); // Cleanup if (pomFromJar && !pomFile.delete()) { jqmlogger.warn("Could not delete the temp pom file extracted from the jar."); } return; } // 4: if lib, use lib... (lib has priority over pom) if (libDir.exists()) { jqmlogger.trace( "Using the lib directory " + libDir.getAbsolutePath() + " as the source for dependencies"); FileFilter fileFilter = new WildcardFileFilter("*.jar"); File[] files = libDir.listFiles(fileFilter); URL[] tmp = new URL[files.length]; for (int i = 0; i < files.length; i++) { try { tmp[i] = files[i].toURI().toURL(); } catch (MalformedURLException e) { throw new JqmPayloadException("incorrect file inside lib directory", e); } } // Put in cache putInCache(tmp, jd.getApplicationName()); return; } throw new JqmPayloadException( "There is no lib dir or no pom.xml inside the directory containing the jar or inside the jar. The jar cannot be launched."); }