List of usage examples for java.util.zip ZipFile close
public void close() throws IOException
From source file:org.signserver.anttasks.PostProcessModulesTask.java
/** * Replacer for the postprocess-jar Ant macro. * /*w w w.j a v a 2 s .c o m*/ * @param replaceincludes Ant list of all files in the jar to replace in * @param src Source jar file * @param destfile Destination jar file * @param properties Properties to replace from * @param self The Task (used for logging) * @throws IOException in case of error */ protected void replaceInJar(String replaceincludes, String src, String destfile, Map properties, Task self) throws IOException { try { self.log("Replace " + replaceincludes + " in " + src + " to " + destfile, Project.MSG_VERBOSE); File srcFile = new File(src); if (!srcFile.exists()) { throw new FileNotFoundException(srcFile.getAbsolutePath()); } // Expand properties of all files in replaceIncludes HashSet<String> replaceFiles = new HashSet<String>(); String[] rfiles = replaceincludes.split(","); for (int i = 0; i < rfiles.length; i++) { rfiles[i] = rfiles[i].trim(); } replaceFiles.addAll(Arrays.asList(rfiles)); self.log("Files to replace: " + replaceFiles, Project.MSG_INFO); // Open source zip file ZipFile zipSrc = new ZipFile(srcFile); ZipOutputStream zipDest = new ZipOutputStream(new FileOutputStream(destfile)); // For each entry in the source file copy them to dest file and postprocess if necessary Enumeration<? extends ZipEntry> entries = zipSrc.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); if (entry.isDirectory()) { // Just put the directory zipDest.putNextEntry(entry); } else { // If we should postprocess the entry if (replaceFiles.contains(name)) { name += (" [REPLACE]"); self.log(name, Project.MSG_VERBOSE); // Create a new zip entry for the file ZipEntry newEntry = new ZipEntry(entry.getName()); newEntry.setComment(entry.getComment()); newEntry.setExtra(entry.getExtra()); zipDest.putNextEntry(newEntry); // Read the old document StringBuffer oldDocument = stringBufferFromFile(zipSrc.getInputStream(entry)); self.log("Before replace ********\n" + oldDocument.toString() + "\n", Project.MSG_DEBUG); // Do properties substitution StrSubstitutor sub = new StrSubstitutor(properties); StringBuffer newerDocument = commentReplacement(oldDocument, properties); String newDocument = sub.replace(newerDocument); self.log("After replace ********\n" + newDocument.toString() + "\n", Project.MSG_DEBUG); // Write the new document byte[] newBytes = newDocument.getBytes("UTF-8"); entry.setSize(newBytes.length); copy(new ByteArrayInputStream(newBytes), zipDest); } else { // Just copy the entry to dest zip file name += (" []"); self.log(name, Project.MSG_VERBOSE); zipDest.putNextEntry(entry); copy(zipSrc.getInputStream(entry), zipDest); } zipDest.closeEntry(); } } zipSrc.close(); zipDest.close(); } catch (IOException ex) { throw new BuildException(ex); } }
From source file:org.wise.portal.presentation.web.controllers.admin.ImportProjectController.java
private Project importProject(String zipFilename, byte[] fileBytes) throws Exception { // upload the zipfile to curriculum_base_dir String curriculumBaseDir = wiseProperties.getProperty("curriculum_base_dir"); // make sure the curriculum_base_dir exists if (!new File(curriculumBaseDir).exists()) { throw new Exception("Curriculum upload directory \"" + curriculumBaseDir + "\" does not exist. Please verify the path you specified for curriculum_base_dir in wise.properties."); }/*from ww w. java2s . c o m*/ // save the upload zip file in the curriculum folder. String sep = "/"; long timeInMillis = Calendar.getInstance().getTimeInMillis(); String filename = zipFilename.substring(0, zipFilename.indexOf(".zip")); String newFilename = filename; if (new File(curriculumBaseDir + sep + filename).exists()) { // if this directory already exists, add a date time in milliseconds to the filename to make it unique newFilename = filename + "-" + timeInMillis; } String newFileFullPath = curriculumBaseDir + sep + newFilename + ".zip"; // copy the zip file inside curriculum_base_dir temporarily File uploadedFile = new File(newFileFullPath); uploadedFile.createNewFile(); FileCopyUtils.copy(fileBytes, uploadedFile); // make a new folder where the contents of the zip should go String newFileFullDir = curriculumBaseDir + sep + newFilename; File newFileFullDirFile = new File(newFileFullDir); newFileFullDirFile.mkdir(); Integer projectVersion = 0; // unzip the zip file try { ZipFile zipFile = new ZipFile(newFileFullPath); Enumeration entries = zipFile.entries(); int i = 0; // index used later to check for first folder in the zip file while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.getName().startsWith("__MACOSX")) { // if this entry starts with __MACOSX, this zip file was created by a user using mac's "compress" feature. // ignore it. continue; } if (entry.isDirectory()) { // first check to see if the user has changed the zip file name and therefore the zipfile name // is no longer the same as the name of the first folder in the top-level of the zip file. // if this is the case, import will fail, so throw an error. if (i == 0) { if (!entry.getName().startsWith(filename)) { throw new Exception( "Zip file name \"" + entry.getName() + "\" does not match folder name \"" + filename + "\". Do not change zip filename"); } i++; } // Assume directories are stored parents first then children. System.out.println("Extracting directory: " + entry.getName()); // This is not robust, just for demonstration purposes. (new File(entry.getName().replace(filename, newFileFullDir))).mkdir(); continue; } if ("wise4.project.json".equals(entry.getName().substring(entry.getName().lastIndexOf(sep) + 1))) { projectVersion = 4; } else if ("project.json".equals(entry.getName().substring(entry.getName().lastIndexOf(sep) + 1))) { projectVersion = 5; } System.out.println("Extracting file: " + entry.getName()); copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream( new FileOutputStream(entry.getName().replaceFirst(filename, newFileFullDir)))); } zipFile.close(); } catch (IOException ioe) { System.err.println("Unhandled exception during project import. Project was not properly imported."); ioe.printStackTrace(); throw ioe; } // remove the temp zip file uploadedFile.delete(); // now create a project in the db String path = ""; String name = ""; // get the project path and name from zip file try { if (projectVersion == 4) { path = sep + newFilename + sep + "wise4.project.json"; String projectJSONFilePath = newFileFullDir + sep + "wise4.project.json"; String projectJSONStr = FileUtils.readFileToString(new File(projectJSONFilePath)); JSONObject projectJSONObj = new JSONObject(projectJSONStr); name = projectJSONObj.getString("title"); } else if (projectVersion == 5) { path = sep + newFilename + sep + "project.json"; String projectJSONFilePath = newFileFullDir + sep + "project.json"; String projectJSONStr = FileUtils.readFileToString(new File(projectJSONFilePath)); JSONObject projectJSONObj = new JSONObject(projectJSONStr); name = projectJSONObj.getJSONObject("metadata").getString("title"); } else if (projectVersion == 0) { System.err.println("Could not determine project version during project import."); return null; } } catch (Exception e) { // there was an error getting project title. name = "Undefined"; } User signedInUser = ControllerUtil.getSignedInUser(); ModuleParameters mParams = new ModuleParameters(); mParams.setUrl(path); Curnit curnit = curnitService.createCurnit(mParams); ProjectParameters pParams = new ProjectParameters(); pParams.setCurnitId(curnit.getId()); pParams.setOwner(signedInUser); pParams.setProjectname(name); pParams.setProjectType(ProjectType.LD); pParams.setWiseVersion(projectVersion); ProjectMetadata metadata = null; // see if a file called wise4.project-meta.json exists. if yes, try parsing it. try { metadata = new ProjectMetadataImpl(); if (projectVersion == 4) { String projectMetadataFilePath = newFileFullDir + sep + "wise4.project-meta.json"; String projectMetadataStr = FileUtils.readFileToString(new File(projectMetadataFilePath)); JSONObject metadataJSONObj = new JSONObject(projectMetadataStr); metadata.populateFromJSON(metadataJSONObj); } else if (projectVersion == 5) { String projectFilePath = newFileFullDir + sep + "project.json"; String projectStr = FileUtils.readFileToString(new File(projectFilePath)); JSONObject projectJSONObj = new JSONObject(projectStr); JSONObject metadataJSONObj = projectJSONObj.getJSONObject("metadata"); metadata.populateFromJSON(metadataJSONObj); } } catch (Exception e) { // if there is any error during the parsing of the metadata, set the metadata to null System.err.println("Error parsing metadata while import project."); e.printStackTrace(); metadata = null; } // If metadata is null at this point, either wise4.project-meta.json was not // found in the zip file, or there was an error parsing. // Set a new fresh metadata object if (metadata == null) { metadata = new ProjectMetadataImpl(); metadata.setTitle(name); } pParams.setMetadata(metadata); return projectService.createProject(pParams); }
From source file:org.openmrs.web.filter.initialization.TestInstallUtil.java
/** * Extracts .omod files from the specified {@link InputStream} and copies them to the module * repository of the test application data directory, the method always closes the InputStream * before returning/*from ww w.j av a 2 s . c o m*/ * * @param in the {@link InputStream} for the zip file */ @SuppressWarnings("rawtypes") protected static boolean addZippedTestModules(InputStream in) { ZipFile zipFile = null; FileOutputStream out = null; File tempFile = null; boolean successfullyAdded = true; try { tempFile = File.createTempFile("modules", null); out = new FileOutputStream(tempFile); IOUtils.copy(in, out); zipFile = new ZipFile(tempFile); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { if (log.isDebugEnabled()) { log.debug("Skipping directory: " + entry.getName()); } continue; } String fileName = entry.getName(); if (fileName.endsWith(".omod")) { //Convert the names of .omod files located in nested directories so that they get //created under the module repo directory when being copied if (fileName.contains(System.getProperty("file.separator"))) { fileName = new File(entry.getName()).getName(); } if (log.isDebugEnabled()) { log.debug("Extracting module file: " + fileName); } //use the module repository folder GP value if specified String moduleRepositoryFolder = FilterUtil .getGlobalPropertyValue(ModuleConstants.REPOSITORY_FOLDER_PROPERTY); if (StringUtils.isBlank(moduleRepositoryFolder)) { moduleRepositoryFolder = ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT; } //At this point 'OpenmrsConstants.APPLICATION_DATA_DIRECTORY' is still null so we need check //for the app data directory defined in the runtime props file if any otherwise the logic in //the OpenmrsUtil.getDirectoryInApplicationDataDirectory(String) will default to the other String appDataDirectory = Context.getRuntimeProperties() .getProperty(OpenmrsConstants.APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY); if (StringUtils.isNotBlank(appDataDirectory)) { OpenmrsUtil.setApplicationDataDirectory(appDataDirectory); } File moduleRepository = OpenmrsUtil .getDirectoryInApplicationDataDirectory(moduleRepositoryFolder); //delete all previously added modules in case of prior test installations FileUtils.cleanDirectory(moduleRepository); OpenmrsUtil.copyFile(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(new File(moduleRepository, fileName)))); } else { if (log.isDebugEnabled()) { log.debug("Ignoring file that is not a .omod '" + fileName); } } } } catch (IOException e) { log.error("An error occured while copying modules to the test system:", e); successfullyAdded = false; } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { log.error("Failed to close zip file: ", e); } } if (tempFile != null) { tempFile.delete(); } } return successfullyAdded; }
From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.ArchiveExpander.java
private void expandZip(final File expandDir, final Archive archive, final QcContext context) throws IOException { ZipFile zipFile = null; BufferedOutputStream out = null; try {/* w ww . j a v a 2s . co m*/ zipFile = new ZipFile(archive.fullArchivePathAndName()); // write each entry to the archive directory final Enumeration zipEnum = zipFile.entries(); boolean foundArchiveDir = false; while (zipEnum.hasMoreElements()) { final ZipEntry entry = (ZipEntry) zipEnum.nextElement(); if (!entry.isDirectory()) { String entryName = entry.getName(); final File entryFile = new File(entryName); // extract out just the filename of the entry if (entryFile.getCanonicalPath().lastIndexOf(File.separator) != -1) { entryName = entryFile.getCanonicalPath() .substring(entryFile.getCanonicalPath().lastIndexOf(File.separator)); } // the file to write is the archive dir plus just the filename final File archiveFile = new File(expandDir, entryName); InputStream in = zipFile.getInputStream(entry); FileOutputStream fout = new FileOutputStream(archiveFile); //noinspection IOResourceOpenedButNotSafelyClosed out = new BufferedOutputStream(fout); copyInputStream(in, out); in = null; out = null; fout.close(); fout = null; } else { // if find a directory that isn't the archive name, add warning for weird archive structure if (!entry.getName().equals(archive.getArchiveName()) && !entry.getName().equals(archive.getArchiveName() + "/")) { context.addWarning(new StringBuilder().append("Archive '") .append("' has a non-standard directory '").append(entry.getName()).append("'.") .append("Archive files should be contained inside a single directory with the archive name as its name.") .toString()); } else { foundArchiveDir = true; } } } if (!foundArchiveDir) { context.addWarning( "Archive files should be contained inside a single directory with the archive name as its name."); } } finally { IOUtils.closeQuietly(out); if (zipFile != null) { zipFile.close(); } } }
From source file:org.geoserver.kml.KMLReflectorTest.java
protected void doTestRasterPlacemark(boolean doPlacemarks) throws Exception { // the style selects a single feature final String requestUrl = "wms/kml?layers=" + getLayerId(MockData.BASIC_POLYGONS) + "&styles=&mode=download&kmscore=0&format_options=kmplacemark:" + doPlacemarks + "&format=" + KMZMapOutputFormat.MIME_TYPE; MockHttpServletResponse response = getAsServletResponse(requestUrl); assertEquals(KMZMapOutputFormat.MIME_TYPE, response.getContentType()); ZipFile zipFile = null; try {/*from w ww . j ava2 s .c om*/ // create the kmz File tempDir = org.geoserver.data.util.IOUtils.createRandomDirectory("./target", "kmplacemark", "test"); tempDir.deleteOnExit(); File zip = new File(tempDir, "kmz.zip"); zip.deleteOnExit(); FileOutputStream output = new FileOutputStream(zip); FileUtils.writeByteArrayToFile(zip, getBinary(response)); output.flush(); output.close(); assertTrue(zip.exists()); // unzip and test it zipFile = new ZipFile(zip); ZipEntry entry = zipFile.getEntry("wms.kml"); assertNotNull(entry); assertNotNull(zipFile.getEntry("images/layers_0.png")); // unzip the wms.kml to file byte[] buffer = new byte[1024]; int len; InputStream inStream = zipFile.getInputStream(entry); File temp = File.createTempFile("test_out", "kmz", tempDir); temp.deleteOnExit(); BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(temp)); while ((len = inStream.read(buffer)) >= 0) outStream.write(buffer, 0, len); inStream.close(); outStream.close(); // read in the wms.kml and check its contents Document document = dom(new BufferedInputStream(new FileInputStream(temp))); // print(document); assertEquals("kml", document.getDocumentElement().getNodeName()); if (doPlacemarks) { assertEquals(getFeatureSource(MockData.BASIC_POLYGONS).getFeatures().size(), document.getElementsByTagName("Placemark").getLength()); XMLAssert.assertXpathEvaluatesTo("3", "count(//kml:Placemark//kml:Point)", document); } else { assertEquals(0, document.getElementsByTagName("Placemark").getLength()); } } finally { if (zipFile != null) { zipFile.close(); } } }
From source file:org.opendatakit.survey.android.tasks.DownloadFormsTask.java
private String explodeZips(FormDetails fd, File tempMediaPath, int count, int total) { String message = ""; File[] zips = tempMediaPath.listFiles(new FileFilter() { @Override// w w w .j a va 2 s . c o m public boolean accept(File pathname) { String name = pathname.getName(); return pathname.isFile() && name.substring(name.lastIndexOf('.') + 1).equals("zip"); } }); int zipCount = 0; for (File zipfile : zips) { ZipFile f = null; zipCount++; try { f = new ZipFile(zipfile, ZipFile.OPEN_READ); Enumeration<? extends ZipEntry> entries = f.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File tempFile = new File(tempMediaPath, entry.getName()); String formattedString = appContext.getString(R.string.form_download_unzipping, fd.formID, zipfile.getName(), Integer.valueOf(zipCount).toString(), Integer.valueOf(zips.length).toString(), entry.getName()); publishProgress(formattedString, Integer.valueOf(count).toString(), Integer.valueOf(total).toString()); if (entry.isDirectory()) { tempFile.mkdirs(); } else { tempFile.getParentFile().mkdirs(); int bufferSize = 8192; InputStream in = new BufferedInputStream(f.getInputStream(entry), bufferSize); OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile, false), bufferSize); // this is slow in the debugger.... int value; while ((value = in.read()) != -1) { out.write(value); } out.flush(); out.close(); in.close(); } WebLogger.getLogger(appName).i(t, "Extracted ZipEntry: " + entry.getName()); } } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); if (e.getCause() != null) { message += e.getCause().getMessage(); } else { message += e.getMessage(); } } finally { if (f != null) { try { f.close(); } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); WebLogger.getLogger(appName).e(t, "Closing of ZipFile failed: " + e.toString()); } } } } return (message.equals("") ? null : message); }
From source file:com.simpligility.maven.plugins.android.phase09package.ApkMojo.java
private void updateWithMetaInf(ZipOutputStream zos, File jarFile, Set<String> entries, boolean metaInfOnly) throws IOException { ZipFile zin = new ZipFile(jarFile); for (Enumeration<? extends ZipEntry> en = zin.entries(); en.hasMoreElements();) { ZipEntry ze = en.nextElement(); if (ze.isDirectory()) { continue; }/* w ww.jav a 2 s. c o m*/ String zn = ze.getName(); if (metaInfOnly) { if (!zn.startsWith("META-INF/")) { continue; } if (!this.apkMetaInf.isIncluded(zn)) { continue; } } boolean resourceTransformed = false; if (transformers != null) { for (ResourceTransformer transformer : transformers) { if (transformer.canTransformResource(zn)) { getLog().info("Transforming " + zn + " using " + transformer.getClass().getName()); InputStream is = zin.getInputStream(ze); transformer.processResource(zn, is, null); is.close(); resourceTransformed = true; break; } } } if (!resourceTransformed) { // Avoid duplicates that aren't accounted for by the resource transformers if (metaInfOnly && this.extractDuplicates && !entries.add(zn)) { continue; } InputStream is = zin.getInputStream(ze); final ZipEntry ne; if (ze.getMethod() == ZipEntry.STORED) { ne = new ZipEntry(ze); } else { ne = new ZipEntry(zn); } zos.putNextEntry(ne); copyStreamWithoutClosing(is, zos); is.close(); zos.closeEntry(); } } zin.close(); }
From source file:com.seajas.search.contender.service.modifier.FeedModifierService.java
/** * Retrieve the content of a result feed URL. * //from ww w. ja va2 s .c o m * @param uri * @param encodingOverride * @param userAgent * @param resultHeaders * @return Reader */ private Reader getContent(final URI uri, final String encodingOverride, final String userAgent, final Map<String, String> resultHeaders) { Reader result = null; String contentType = null; // Retrieve the feed try { InputStream inputStream = null; if (uri.getScheme().equalsIgnoreCase("ftp") || uri.getScheme().equalsIgnoreCase("ftps")) { FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient(); try { ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21); if (StringUtils.hasText(uri.getUserInfo())) { if (uri.getUserInfo().contains(":")) ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")), uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1)); else ftpClient.login(uri.getUserInfo(), ""); inputStream = ftpClient.retrieveFileStream(uri.getPath()); } } finally { ftpClient.disconnect(); } } else if (uri.getScheme().equalsIgnoreCase("file")) { File file = new File(uri); if (!file.isDirectory()) inputStream = new FileInputStream(uri.getPath()); else inputStream = RSSDirectoryBuilder.build(file); } else if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) { try { HttpGet method = new HttpGet(uri.toString()); if (resultHeaders != null) for (Entry<String, String> resultHeader : resultHeaders.entrySet()) method.setHeader(new BasicHeader(resultHeader.getKey(), resultHeader.getValue())); if (userAgent != null) method.setHeader(CoreProtocolPNames.USER_AGENT, userAgent); SizeRestrictedHttpResponse response = httpClient.execute(method, new SizeRestrictedResponseHandler(maximumContentLength, uri)); try { if (response != null) { inputStream = new ByteArrayInputStream(response.getResponse()); contentType = response.getContentType() != null ? response.getContentType().getValue() : null; } else return null; } catch (RuntimeException e) { method.abort(); throw e; } } catch (IllegalArgumentException e) { logger.error("Invalid URL " + uri.toString() + " - not returning content", e); return null; } } else { logger.error("Unknown protocol " + uri.getScheme() + ". Skipping feed."); return null; } // Guess the character encoding using ROME's reader, then buffer it so we can discard the input stream (and close the connection) InputStream readerInputStream = new BufferedInputStream(inputStream); MediaType mediaType = autoDetectParser.getDetector().detect(readerInputStream, new Metadata()); try { Reader reader = null; if (mediaType.getType().equals("application")) { if (mediaType.getSubtype().equals("x-gzip")) { GZIPInputStream gzipInputStream = new GZIPInputStream(readerInputStream); if (encodingOverride != null) reader = readerToBuffer(new StringBuffer(), new InputStreamReader(gzipInputStream, encodingOverride), false); else reader = readerToBuffer(new StringBuffer(), contentType != null ? new XmlHtmlReader(gzipInputStream, contentType, true) : new XmlReader(gzipInputStream, true), false); gzipInputStream.close(); } else if (mediaType.getSubtype().equals("zip")) { ZipFile zipFile = null; // ZipInputStream can't do read-aheads, so we have to use a temporary on-disk file instead File temporaryFile = File.createTempFile("profiler-", ".zip"); try { FileOutputStream zipOutputStream = new FileOutputStream(temporaryFile); IOUtils.copy(readerInputStream, zipOutputStream); readerInputStream.close(); zipOutputStream.flush(); zipOutputStream.close(); // Create a new entry and process it zipFile = new ZipFile(temporaryFile); Enumeration<? extends ZipEntry> zipEnumeration = zipFile.entries(); ZipEntry zipEntry = zipEnumeration.nextElement(); if (zipEntry == null || zipEntry.isDirectory() || zipEnumeration.hasMoreElements()) { logger.error( "ZIP files are currently expected to contain one and only one entry, which is to be a file"); return null; } // We currently only perform prolog stripping for ZIP files InputStream zipInputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry)); if (encodingOverride != null) reader = readerToBuffer(new StringBuffer(), new InputStreamReader( new BufferedInputStream(zipInputStream), encodingOverride), true); else result = readerToBuffer(new StringBuffer(), contentType != null ? new XmlHtmlReader(new BufferedInputStream(zipInputStream), contentType, true) : new XmlReader(new BufferedInputStream(zipInputStream), true), true); } catch (Exception e) { logger.error("An error occurred during ZIP file processing", e); return null; } finally { if (zipFile != null) zipFile.close(); if (!temporaryFile.delete()) logger.error("Unable to delete temporary file"); } } } if (result == null) { if (encodingOverride != null) result = readerToBuffer(new StringBuffer(), reader != null ? reader : new InputStreamReader(readerInputStream, encodingOverride), false); else result = readerToBuffer(new StringBuffer(), reader != null ? reader : contentType != null ? new XmlHtmlReader(readerInputStream, contentType, true) : new XmlReader(readerInputStream, true), false); } } catch (Exception e) { logger.error("An error occurred during stream processing", e); return null; } finally { inputStream.close(); } } catch (IOException e) { logger.error("Could not retrieve the given feed: " + e.getMessage(), e); return null; } return result; }
From source file:fr.gouv.finances.cp.xemelios.importers.batch.BatchRealImporter.java
private ImportContent files(final String extension, final String titreEtat) { ImportContent ic = new ImportContent(); Vector<File> ret = new Vector<File>(); ret.addAll(files);/*from w w w .j a v a 2 s . c o m*/ // on regarde si l'un des fichiers a importer est un zip for (int i = 0; i < ret.size(); i++) { if (ret.get(i).getName().toLowerCase().endsWith(".zip")) { if (ret.get(i).exists()) { ZipFile zf = null; try { zf = new ZipFile(ret.get(i)); for (Enumeration<? extends ZipEntry> enumer = zf.entries(); enumer.hasMoreElements();) { ZipEntry ze = enumer.nextElement(); if (!ze.isDirectory()) { String fileName = ze.getName(); String entryName = fileName.toLowerCase(); fileName = fileName.replace(File.pathSeparatorChar, '_') .replace(File.separatorChar, '_').replace(':', '|').replace('\'', '_') .replace('/', '_'); logger.debug(entryName); if (PJRef.isPJ(ze)) { PJRef pj = new PJRef(ze); File tmpFile = pj.writeTmpFile(FileUtils.getTempDir(), zf); ic.pjs.add(pj); filesToDrop.add(tmpFile); } else if ((entryName.endsWith(extension.toLowerCase()) || entryName.endsWith(".xml")) && !fileName.startsWith("_")) { // on decompresse le fichier dans le // repertoire temporaire, comme ca il sera // supprime en quittant InputStream is = zf.getInputStream(ze); BufferedInputStream bis = new BufferedInputStream(is); File output = new File(FileUtils.getTempDir(), fileName); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(output)); byte[] buffer = new byte[1024]; int read = bis.read(buffer); while (read > 0) { bos.write(buffer, 0, read); read = bis.read(buffer); } bos.flush(); bos.close(); bis.close(); ic.filesToImport.add(output); filesToDrop.add(output); } } } zf.close(); } catch (ZipException zEx) { System.out.println( "Le fichier " + ret.get(i).getName() + " n'est pas une archive ZIP valide."); } catch (IOException ioEx) { ioEx.printStackTrace(); } finally { if (zf != null) { try { zf.close(); } catch (Throwable t) { } } } } } else if (ret.get(i).getName().toLowerCase().endsWith(".gz")) { try { String fileName = ret.get(i).getName(); fileName = fileName.substring(0, fileName.length() - 3); File output = new File(FileUtils.getTempDir(), fileName); GZIPInputStream gis = new GZIPInputStream(new FileInputStream(ret.get(i))); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output)); byte[] buffer = new byte[1024]; int read = gis.read(buffer); while (read > 0) { bos.write(buffer, 0, read); read = gis.read(buffer); } bos.flush(); bos.close(); gis.close(); ic.filesToImport.add(output); filesToDrop.add(output); } catch (IOException ioEx) { // nothing to do } } else { ic.filesToImport.add(ret.get(i)); // dans ce cas l, on ne le supprime pas } } return ic; }