List of usage examples for java.util.zip ZipFile getInputStream
public InputStream getInputStream(ZipEntry entry) throws IOException
From source file:com.seajas.search.contender.service.modifier.FeedModifierService.java
/** * Retrieve the content of a result feed URL. * /* w w w. j a va 2 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);/*w ww. j a v a 2 s. c om*/ // 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; }
From source file:com.meltmedia.cadmium.core.util.WarUtils.java
/** * <p>This method updates a template war with the following settings.</p> * @param templateWar The name of the template war to pull from the classpath. * @param war The path of an external war to update (optional). * @param newWarNames The name to give the new war. (note: only the first element of this list is used.) * @param repoUri The uri to a github repo to pull content from. * @param branch The branch of the github repo to pull content from. * @param configRepoUri The uri to a github repo to pull config from. * @param configBranch The branch of the github repo to pull config from. * @param domain The domain to bind a vHost to. * @param context The context root that this war will deploy to. * @param secure A flag to set if this war needs to have its contents password protected. * @throws Exception// ww w.j av a 2 s .c om */ public static void updateWar(String templateWar, String war, List<String> newWarNames, String repoUri, String branch, String configRepoUri, String configBranch, String domain, String context, boolean secure, Logger log) throws Exception { ZipFile inZip = null; ZipOutputStream outZip = null; InputStream in = null; OutputStream out = null; try { if (war != null) { if (war.equals(newWarNames.get(0))) { File tmpZip = File.createTempFile(war, null); tmpZip.delete(); tmpZip.deleteOnExit(); new File(war).renameTo(tmpZip); war = tmpZip.getAbsolutePath(); } inZip = new ZipFile(war); } else { File tmpZip = File.createTempFile("cadmium-war", "war"); tmpZip.delete(); tmpZip.deleteOnExit(); in = WarUtils.class.getClassLoader().getResourceAsStream(templateWar); out = new FileOutputStream(tmpZip); FileSystemManager.streamCopy(in, out); inZip = new ZipFile(tmpZip); } outZip = new ZipOutputStream(new FileOutputStream(newWarNames.get(0))); ZipEntry cadmiumPropertiesEntry = null; cadmiumPropertiesEntry = inZip.getEntry("WEB-INF/cadmium.properties"); Properties cadmiumProps = updateProperties(inZip, cadmiumPropertiesEntry, repoUri, branch, configRepoUri, configBranch); ZipEntry jbossWeb = null; jbossWeb = inZip.getEntry("WEB-INF/jboss-web.xml"); Enumeration<? extends ZipEntry> entries = inZip.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); if (e.getName().equals(cadmiumPropertiesEntry.getName())) { storeProperties(outZip, cadmiumPropertiesEntry, cadmiumProps, newWarNames); } else if (((domain != null && domain.length() > 0) || (context != null && context.length() > 0)) && e.getName().equals(jbossWeb.getName())) { updateDomain(inZip, outZip, jbossWeb, domain, context); } else if (secure && e.getName().equals("WEB-INF/web.xml")) { addSecurity(inZip, outZip, e); } else { outZip.putNextEntry(e); if (!e.isDirectory()) { FileSystemManager.streamCopy(inZip.getInputStream(e), outZip, true); } outZip.closeEntry(); } } } finally { if (FileSystemManager.exists("tmp_cadmium-war.war")) { new File("tmp_cadmium-war.war").delete(); } try { if (inZip != null) { inZip.close(); } } catch (Exception e) { if (log != null) { log.error("Failed to close " + war); } } try { if (outZip != null) { outZip.close(); } } catch (Exception e) { if (log != null) { log.error("Failed to close " + newWarNames.get(0)); } } try { if (out != null) { out.close(); } } catch (Exception e) { } try { if (in != null) { in.close(); } } catch (Exception e) { } } }
From source file:org.broad.igv.feature.genome.GenomeManager.java
/** * Gets a list of all the locally cached genome archive files that * IGV knows about.// ww w .j a v a2 s. c o m * * @return LinkedHashSet<GenomeListItem> * @throws IOException * @see GenomeListItem */ private List<GenomeListItem> getCachedGenomeArchiveList() throws IOException { if (cachedGenomeArchiveList == null) { cachedGenomeArchiveList = new LinkedList<GenomeListItem>(); if (!DirectoryManager.getGenomeCacheDirectory().exists()) { return cachedGenomeArchiveList; } File[] files = DirectoryManager.getGenomeCacheDirectory().listFiles(); for (File file : files) { if (file.isDirectory()) { continue; } if (!file.getName().toLowerCase().endsWith(Globals.GENOME_FILE_EXTENSION)) { continue; } ZipFile zipFile = null; FileInputStream fis = null; ZipInputStream zipInputStream = null; try { zipFile = new ZipFile(file); fis = new FileInputStream(file); zipInputStream = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry zipEntry = zipFile.getEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME); if (zipEntry == null) { continue; // Should never happen } InputStream inputStream = zipFile.getInputStream(zipEntry); Properties properties = new Properties(); properties.load(inputStream); int version = 0; if (properties.containsKey(Globals.GENOME_ARCHIVE_VERSION_KEY)) { try { version = Integer.parseInt(properties.getProperty(Globals.GENOME_ARCHIVE_VERSION_KEY)); } catch (Exception e) { log.error("Error parsing genome version: " + version, e); } } GenomeListItem item = new GenomeListItem( properties.getProperty(Globals.GENOME_ARCHIVE_NAME_KEY), file.getAbsolutePath(), properties.getProperty(Globals.GENOME_ARCHIVE_ID_KEY)); cachedGenomeArchiveList.add(item); } catch (ZipException ex) { log.error("\nZip error unzipping cached genome.", ex); try { file.delete(); zipInputStream.close(); } catch (Exception e) { //ignore exception when trying to delete file } } catch (IOException ex) { log.warn("\nIO error unzipping cached genome.", ex); try { file.delete(); } catch (Exception e) { //ignore exception when trying to delete file } } finally { try { if (zipInputStream != null) { zipInputStream.close(); } if (zipFile != null) { zipFile.close(); } if (fis != null) { fis.close(); } } catch (IOException ex) { log.warn("Error closing genome zip stream!", ex); } } } } return cachedGenomeArchiveList; }
From source file:com.flexive.core.storage.GenericDivisionImporter.java
/** * Import briefcases// w w w . java 2s . com * * @param con an open and valid connection to store imported data * @param zip zip file containing the data * @param exportInfo information about the exported data * @throws Exception on errors */ public void importFlatStorages(Connection con, ZipFile zip, FxDivisionExportInfo exportInfo) throws Exception { if (!canImportFlatStorages(exportInfo)) { importFlatStoragesHierarchical(con, zip); return; } ZipEntry ze = getZipEntry(zip, FILE_FLATSTORAGE_META); Statement stmt = con.createStatement(); try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(zip.getInputStream(ze)); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.evaluate("/flatstorageMeta/storageMeta", document, XPathConstants.NODESET); Node currNode; List<String> storages = new ArrayList<String>(5); for (int i = 0; i < nodes.getLength(); i++) { currNode = nodes.item(i); int cbigInt = Integer.parseInt(currNode.getAttributes().getNamedItem("bigInt").getNodeValue()); int cdouble = Integer.parseInt(currNode.getAttributes().getNamedItem("double").getNodeValue()); int cselect = Integer.parseInt(currNode.getAttributes().getNamedItem("select").getNodeValue()); int cstring = Integer.parseInt(currNode.getAttributes().getNamedItem("string").getNodeValue()); int ctext = Integer.parseInt(currNode.getAttributes().getNamedItem("text").getNodeValue()); String tableName = null; String description = null; if (currNode.hasChildNodes()) { for (int j = 0; j < currNode.getChildNodes().getLength(); j++) if (currNode.getChildNodes().item(j).getNodeName().equals("name")) { tableName = currNode.getChildNodes().item(j).getTextContent(); } else if (currNode.getChildNodes().item(j).getNodeName().equals("description")) { description = currNode.getChildNodes().item(j).getTextContent(); } } if (tableName != null) { if (description == null) description = "FlatStorage " + tableName; final FxFlatStorage flatStorage = FxFlatStorageManager.getInstance(); for (FxFlatStorageInfo fi : flatStorage.getFlatStorageInfos()) { if (fi.getName().equals(tableName)) { flatStorage.removeFlatStorage(tableName); break; } } // TODO - flat storage type detection flatStorage.createFlatStorage(con, tableName, FxFlatStorageInfo.Type.TypeNormal, description, cstring, ctext, cbigInt, cdouble, cselect); storages.add(tableName); } } importTable(stmt, zip, ze, "flatstorageMeta/mapping", DatabaseConst.TBL_STRUCT_FLATSTORE_MAPPING); ZipEntry zeData = getZipEntry(zip, FILE_DATA_FLAT); for (String storage : storages) importTable(stmt, zip, zeData, "flatstorages/storage[@name='" + storage + "']/data", storage); } finally { Database.closeObjects(GenericDivisionImporter.class, stmt); } }
From source file:com.flexive.core.storage.GenericDivisionImporter.java
/** * Import sequencer settings/* ww w . ja v a2 s. co m*/ * * @param con an open and valid connection to store imported data * @param zip zip file containing the data * @throws Exception on errors */ public void importSequencers(Connection con, ZipFile zip) throws Exception { ZipEntry ze = getZipEntry(zip, FILE_SEQUENCERS); Statement stmt = con.createStatement(); try { SequencerStorage seq = StorageManager.getSequencerStorage(); for (CustomSequencer cust : seq.getCustomSequencers()) seq.removeSequencer(cust.getName()); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(zip.getInputStream(ze)); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.evaluate("/sequencers/syssequence", document, XPathConstants.NODESET); Node currNode; String seqName; long value; for (int i = 0; i < nodes.getLength(); i++) { currNode = nodes.item(i); if (currNode.hasChildNodes()) { seqName = null; value = -1L; for (int j = 0; j < currNode.getChildNodes().getLength(); j++) if (currNode.getChildNodes().item(j).getNodeName().equals("name")) { seqName = currNode.getChildNodes().item(j).getTextContent(); } else if (currNode.getChildNodes().item(j).getNodeName().equals("value")) { value = Long.parseLong(currNode.getChildNodes().item(j).getTextContent()); } if (value != -1L && seqName != null) { try { if (value <= 0) value = 1; //make sure we have a valid value FxSystemSequencer sseq = FxSystemSequencer.valueOf(seqName); //check if this is really a system sequencer seq.setSequencerId(sseq.getSequencerName(), value); LOG.info("Set sequencer [" + seqName + "] to [" + value + "]"); } catch (IllegalArgumentException e) { LOG.error("Could not find system sequencer named [" + seqName + "]!"); } } } } nodes = (NodeList) xPath.evaluate("/sequencers/usrsequence", document, XPathConstants.NODESET); boolean rollOver = false; for (int i = 0; i < nodes.getLength(); i++) { currNode = nodes.item(i); if (currNode.hasChildNodes()) { seqName = null; value = -1L; for (int j = 0; j < currNode.getChildNodes().getLength(); j++) if (currNode.getChildNodes().item(j).getNodeName().equals("name")) { seqName = currNode.getChildNodes().item(j).getTextContent(); } else if (currNode.getChildNodes().item(j).getNodeName().equals("value")) { value = Long.parseLong(currNode.getChildNodes().item(j).getTextContent()); } else if (currNode.getChildNodes().item(j).getNodeName().equals("rollover")) { rollOver = "1".equals(currNode.getChildNodes().item(j).getTextContent()); } if (value != -1L && seqName != null) { seq.createSequencer(seqName, rollOver, value); LOG.info("Created sequencer [" + seqName + "] with start value [" + value + "], rollover: " + rollOver); } } } } finally { Database.closeObjects(GenericDivisionImporter.class, stmt); } }
From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java
@SuppressWarnings("rawtypes") @Override/*from w w w .java2s.c om*/ public String uploadMappings(MultipartFile mapping) { String msg = ""; String tempFolderName = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER + File.separator; String mappingFolderName = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_MAPPINGS_FOLDER + File.separator; String mappingName = mapping.getOriginalFilename(); if (mappingName.endsWith(".zip")) { boolean allFailed = true; File tempMappings = new File(tempFolderName + mappingName); (new File(tempFolderName)).mkdirs(); try { mapping.transferTo(tempMappings); try { ZipFile zipfile = new ZipFile(tempMappings); for (Enumeration e = zipfile.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); if (entry.isDirectory()) { System.out.println("Incorrect file (Can't be a folder instead): " + entry.getName() + " has been ignored"); } else if (entry.getName().endsWith(DHISCONNECTOR_MAPPING_FILE_SUFFIX)) { File outputFile = new File(mappingFolderName, entry.getName()); if (outputFile.exists()) { System.out.println( "File: " + outputFile.getName() + " already exists and has been ignored"); } else { BufferedInputStream inputStream = new BufferedInputStream( zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream( new FileOutputStream(outputFile)); try { System.out.println("Extracting: " + entry); IOUtils.copy(inputStream, outputStream); allFailed = false; } finally { outputStream.close(); inputStream.close(); } } } else { System.out.println("Incorrect file: " + entry.getName() + " has been ignored"); } } if (!allFailed) { msg = Context.getMessageSourceService() .getMessage("dhisconnector.uploadMapping.groupSuccess"); } else { msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.allFailed"); } FileUtils.deleteDirectory(new File(tempFolderName)); } catch (Exception e) { System.out.println("Error while extracting file:" + mapping.getName() + " ; " + e); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if (mappingName.endsWith(DHISCONNECTOR_MAPPING_FILE_SUFFIX)) { try { File uploadedMapping = new File(mappingFolderName + mappingName); if (uploadedMapping.exists()) { msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.exists"); } else { mapping.transferTo(uploadedMapping); msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.singleSuccess"); } } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.wrongType"); } return msg; }
From source file:nl.strohalm.cyclos.themes.ThemeHandlerImpl.java
@Override protected void doSelect(final String fileName) { ZipFile zipFile = null; final LocalSettings settings = settingsService.getLocalSettings(); final String charset = settings.getCharset(); try {/*from w ww . j a v a 2s. c om*/ final File file = realFile(fileName); if (!file.exists()) { throw new ThemeNotFoundException(fileName); } zipFile = new ZipFile(file); // Ensure the properties entry exists properties(zipFile); // Find all currently used images by style final Map<String, Collection<String>> imagesByFile = new HashMap<String, Collection<String>>(); final File imageDir = webImageHelper.imagePath(Image.Nature.STYLE); final File[] cssFiles = imageDir.listFiles(STYLE_FILTER); for (final File css : cssFiles) { final String contents = FileUtils.readFileToString(css, charset); final List<String> urls = CSSHelper.resolveURLs(contents); imagesByFile.put(css.getName(), urls); } // Read the files final Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); // We will not handle directories if (entry.isDirectory()) { continue; } final String name = entry.getName(); final String entryFileName = new File(name).getName(); if (name.startsWith("images/")) { final ImageType type = ImageType.getByFileName(entryFileName); // Save the image final Image image = imageService.save(Image.Nature.STYLE, type, entryFileName, zipFile.getInputStream(entry)); // Update the physical image webImageHelper.update(image); } else if (name.startsWith("styles/")) { // Save the style sheet CustomizedFile customizedFile = new CustomizedFile(); customizedFile.setName(entryFileName); customizedFile.setType(CustomizedFile.Type.STYLE); final String contents = IOUtils.toString(zipFile.getInputStream(entry), charset); customizedFile.setContents(contents); final File originalFile = customizationHelper.originalFileOf(Type.STYLE, entryFileName); if (originalFile.exists()) { customizedFile.setOriginalContents(FileUtils.readFileToString(originalFile, charset)); } customizedFile = customizedFileService.saveForTheme(customizedFile); // Update the physical file final File physicalFile = customizationHelper.customizedFileOf(CustomizedFile.Type.STYLE, entryFileName); customizationHelper.updateFile(physicalFile, customizedFile); // Remove images that are no longer used final List<String> newImages = CSSHelper.resolveURLs(contents); final Collection<String> oldImages = imagesByFile.get(entryFileName); if (CollectionUtils.isNotEmpty(oldImages)) { for (final String imageName : oldImages) { if (!newImages.contains(imageName)) { // No longer used. Remove it imageService.removeStyleImage(imageName); // Remove the physical file final File imageFile = new File(imageDir, imageName); customizationHelper.deleteFile(imageFile); } } } } } } catch (final ThemeException e) { throw e; } catch (final Exception e) { throw new ThemeException(e); } finally { try { zipFile.close(); } catch (final Exception e) { // Ignore } } }
From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileUtilities.java
public void decompressZip(File inputZipPath, File zipPath) { int BUFFER = 2048; List<File> zipFiles = new ArrayList<File>(); try {/*from w w w . j a v a 2 s.co m*/ zipPath.mkdir(); } catch (SecurityException e) { jlog.fatal("Security exception when creating " + zipPath.getName()); } ZipFile zipFile = null; boolean isZip = true; // Open Zip file for reading (should be in temppath) try { zipFile = new ZipFile(inputZipPath, ZipFile.OPEN_READ); } catch (IOException e) { jlog.fatal("IO exception in " + inputZipPath.getName()); } // Create an enumeration of the entries in the zip file Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); if (isZip) { // Process each entry while (zipFileEntries.hasMoreElements()) { // Get a zip file entry ZipEntry entry = zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = null; // destFile should be pointing to temppath\%date%\ try { destFile = new File(zipPath.getAbsolutePath(), currentEntry); destFile = new File(zipPath.getAbsolutePath(), destFile.getName()); } catch (NullPointerException e) { jlog.fatal("File not found" + destFile.getName()); } // If the entry is a .zip add it to the list so that it can be extracted if (currentEntry.endsWith(".zip")) { zipFiles.add(destFile); } try { // Extract file if not a directory if (!entry.isDirectory()) { // Stream the zip entry BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; FileOutputStream fos = null; // Write the current file to disk try { fos = new FileOutputStream(destFile); } catch (FileNotFoundException e) { jlog.fatal("File not found " + destFile.getName()); } catch (SecurityException e) { jlog.fatal("Access denied to " + destFile.getName()); } BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); dest.close(); is.close(); } } catch (IOException ioe) { jlog.fatal("IO exception in " + zipFile.getName()); } } try { zipFile.close(); } catch (IOException e) { jlog.fatal("IO exception when closing " + zipFile.getName()); } } // Recursively decompress the list of zip files for (File f : zipFiles) { decompressZip(f, zipPath); } return; }