List of usage examples for java.util.zip ZipInputStream closeEntry
public void closeEntry() throws IOException
From source file:de.mpg.escidoc.pubman.multipleimport.processor.ZfNProcessor.java
private void initialize() { this.init = true; try {//from ww w. j av a 2s .c o m InputStream in = new FileInputStream(getSourceFile()); ArrayList<String> itemList = new ArrayList<String>(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); String item = null; final int bufLength = 1024; char[] buffer = new char[bufLength]; int readReturn; int count = 0; ZipEntry zipentry; ZipInputStream zipinputstream = new ZipInputStream(in); while ((zipentry = zipinputstream.getNextEntry()) != null) { count++; StringWriter sw = new StringWriter(); Reader reader = new BufferedReader(new InputStreamReader(zipinputstream, "UTF-8")); while ((readReturn = reader.read(buffer)) != -1) { sw.write(buffer, 0, readReturn); } item = new String(sw.toString()); itemList.add(item); this.fileNames.add(zipentry.getName()); reader.close(); zipinputstream.closeEntry(); } this.logger.debug("Zip file contains " + count + "elements"); zipinputstream.close(); this.counter = 0; this.originalData = byteArrayOutputStream.toByteArray(); this.items = itemList.toArray(new String[] {}); this.length = this.items.length; } catch (Exception e) { this.logger.error("Could not read zip File: " + e.getMessage()); throw new RuntimeException("Error reading input stream", e); } }
From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java
public boolean writeConfiguration(String homeDir, byte[] configurationContents) { File root = new File(homeDir); if (!root.isDirectory() || !root.canWrite()) { return false; }/*w ww.j a va 2 s .c o m*/ boolean written = true; try { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(configurationContents)); ZipEntry next = null; while ((next = input.getNextEntry()) != null) { File newFile = new File(root, next.getName()); FileUtils.forceMkdir(newFile.getParentFile()); FileOutputStream file = new FileOutputStream(newFile); IOUtils.copy(input, file); file.close(); input.closeEntry(); } input.close(); } catch (IOException e) { log.error("Unable to write configuration files to " + root, e); written = false; } return written; }
From source file:com.wakatime.eclipse.plugin.Dependencies.java
private void unzip(String zipFile, File outputDir) throws IOException { if (!outputDir.exists()) outputDir.mkdirs();//w w w. j av a2 s.c om 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()) { // WakaTime.log("Creating directory: "+newFile.getParentFile().getAbsolutePath()); newFile.mkdirs(); } else { // WakaTime.log("Extracting File: "+newFile.getAbsolutePath()); 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(); }
From source file:com.joliciel.csvLearner.CSVEventListReader.java
/** * Scan a feature directory and all of its sub-directories, and add the * contents of the feature files to the event map. * /*from www . j av a2s. c o m*/ * @param featureDir * @throws IOException */ void scanFeatureDir(File featureDir, boolean grouped) throws IOException { LOG.debug("Scanning feature directory " + featureDir.getPath()); File[] files = featureDir.listFiles(); if (files == null) { LOG.debug("Not a directory!"); return; } for (File file : files) { if (file.isDirectory()) { // recursively scan this feature sub-directory this.scanFeatureDir(file, grouped); } else { String fileName = file.getName(); LOG.debug("Scanning file " + fileName); Map<String, GenericEvent> currentEventMap = eventMap; if (eventFileMap != null) { currentEventMap = new TreeMap<String, GenericEvent>(); // copy the results to the event map for (GenericEvent event : eventMap.values()) { GenericEvent eventClone = new GenericEvent(event.getIdentifier()); eventClone.setTest(event.isTest()); eventClone.setOutcome(event.getOutcome()); currentEventMap.put(event.getIdentifier(), eventClone); } eventFileMap.put(fileName, currentEventMap); } InputStream inputStream = null; try { if (fileName.endsWith(".dsc_limits.csv") || fileName.endsWith(".nrm_limits.csv")) { LOG.trace("Ignoring limits file: " + fileName); } else if (fileName.endsWith(".csv")) { inputStream = new FileInputStream(file); this.scanCSVFile(inputStream, true, grouped, fileName, currentEventMap); } else if (fileName.endsWith(".zip")) { inputStream = new FileInputStream(file); ZipInputStream zis = new ZipInputStream(inputStream); ZipEntry zipEntry; while ((zipEntry = zis.getNextEntry()) != null) { LOG.debug("Scanning zip entry " + zipEntry.getName()); this.scanCSVFile(zis, false, grouped, fileName, currentEventMap); zis.closeEntry(); } zis.close(); } else { throw new RuntimeException("Bad file extension in feature directory: " + file.getName()); } } finally { if (inputStream != null) inputStream.close(); } } // file or directory? } // next file }
From source file:io.fabric8.tooling.archetype.generator.ArchetypeHelper.java
/** * Searches ZIP archive and returns properties found in "META-INF/maven/archetype-metadata.xml" entry * * @return//from w ww .ja v a 2 s . com * @throws IOException */ public Map<String, String> parseProperties() throws IOException { Map<String, String> replaceProperties = new HashMap<String, String>(); ZipInputStream zip = null; try { zip = new ZipInputStream(archetypeIn); boolean ok = true; while (ok) { ZipEntry entry = zip.getNextEntry(); if (entry == null) { ok = false; } else { if (!entry.isDirectory()) { String fullName = entry.getName(); if (fullName != null && fullName.equals("META-INF/maven/archetype-metadata.xml")) { parseReplaceProperties(zip, replaceProperties); } } zip.closeEntry(); } } } catch (Exception e) { throw new IOException(e.getMessage(), e); } finally { if (zip != null) { zip.close(); } } return replaceProperties; }
From source file:de.tudarmstadt.ukp.clarin.webanno.brat.dao.DaoUtilsTest.java
@SuppressWarnings("resource") @Test//from ww w.j a va 2s . c o m public void testZipFolder() { File toBeZippedFiles = new File("src/test/resources"); File zipedFiles = new File("target/" + toBeZippedFiles.getName() + ".zip"); try { ZipUtils.zipFolder(toBeZippedFiles, zipedFiles); } catch (Exception e) { LOG.info("Zipping fails" + ExceptionUtils.getRootCauseMessage(e)); } FileInputStream fs; try { fs = new FileInputStream(zipedFiles); ZipInputStream zis = new ZipInputStream(fs); ZipEntry zE; while ((zE = zis.getNextEntry()) != null) { for (File toBeZippedFile : toBeZippedFiles.listFiles()) { if ((FilenameUtils.getBaseName(toBeZippedFile.getName())) .equals(FilenameUtils.getBaseName(zE.getName()))) { // Extract the zip file, save it to temp and compare ZipFile zipFile = new ZipFile(zipedFiles); ZipEntry zipEntry = zipFile.getEntry(zE.getName()); InputStream is = zipFile.getInputStream(zipEntry); File temp = File.createTempFile("temp", ".txt"); OutputStream out = new FileOutputStream(temp); IOUtils.copy(is, out); FileUtils.contentEquals(toBeZippedFile, temp); } } zis.closeEntry(); } } catch (FileNotFoundException e) { LOG.info("zipped file not found " + ExceptionUtils.getRootCauseMessage(e)); } catch (IOException e) { LOG.info("Unable to get file " + ExceptionUtils.getRootCauseMessage(e)); } }
From source file:edu.isi.wings.portal.classes.StorageHandler.java
public static String unzipFile(File f, String todirname, String toDirectory) { File todir = new File(toDirectory); if (!todir.exists()) todir.mkdirs();/*from w ww. j a v a 2s.co m*/ try { // Check if the zip file contains only one directory ZipFile zfile = new ZipFile(f); String topDir = null; boolean isOneDir = true; for (Enumeration<? extends ZipEntry> e = zfile.entries(); e.hasMoreElements();) { ZipEntry ze = e.nextElement(); String name = ze.getName().replaceAll("/.+$", ""); name = name.replaceAll("/$", ""); // OSX Zips carry an extra __MACOSX directory. Ignore it if (name.equals("__MACOSX")) continue; if (topDir == null) topDir = name; else if (!topDir.equals(name)) { isOneDir = false; break; } } zfile.close(); // Delete existing directory (if any) FileUtils.deleteDirectory(new File(toDirectory + File.separator + todirname)); // Unzip file(s) into toDirectory/todirname ZipInputStream zis = new ZipInputStream(new FileInputStream(f)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String fileName = ze.getName(); // OSX Zips carry an extra __MACOSX directory. Ignore it if (fileName.startsWith("__MACOSX")) { ze = zis.getNextEntry(); continue; } // Get relative file path translated to 'todirname' if (isOneDir) fileName = fileName.replaceFirst(topDir, todirname); else fileName = todirname + File.separator + fileName; // Create directories File newFile = new File(toDirectory + File.separator + fileName); if (ze.isDirectory()) newFile.mkdirs(); else newFile.getParentFile().mkdirs(); try { // Copy file FileOutputStream fos = new FileOutputStream(newFile); IOUtils.copy(zis, fos); fos.close(); String mime = new Tika().detect(newFile); if (mime.equals("application/x-sh") || mime.startsWith("text/")) FileUtils.writeLines(newFile, FileUtils.readLines(newFile)); // Set all files as executable for now newFile.setExecutable(true); } catch (FileNotFoundException fe) { // Silently ignore //fe.printStackTrace(); } ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); return toDirectory + File.separator + todirname; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.protocoderrunner.utils.FileIO.java
static public void extractZip(String zipFile, String location) throws IOException { int size;//from w ww . j a va2 s. c o m int BUFFER_SIZE = 1024; byte[] buffer = new byte[BUFFER_SIZE]; try { if (!location.endsWith("/")) { location += "/"; } File f = new File(location); if (!f.isDirectory()) { f.mkdirs(); } ZipInputStream zin = new ZipInputStream( new BufferedInputStream(new FileInputStream(zipFile), BUFFER_SIZE)); try { ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) { String path = location + ze.getName(); File unzipFile = new File(path); if (ze.isDirectory()) { if (!unzipFile.isDirectory()) { unzipFile.mkdirs(); } } else { // check for and create parent directories if they don't exist File parentDir = unzipFile.getParentFile(); if (null != parentDir) { if (!parentDir.isDirectory()) { parentDir.mkdirs(); } } // unzip the file FileOutputStream out = new FileOutputStream(unzipFile, false); BufferedOutputStream fout = new BufferedOutputStream(out, BUFFER_SIZE); try { while ((size = zin.read(buffer, 0, BUFFER_SIZE)) != -1) { fout.write(buffer, 0, size); } zin.closeEntry(); } finally { fout.flush(); fout.close(); } } } } finally { zin.close(); } } catch (Exception e) { Log.e(TAG, "Unzip exception", e); } }
From source file:com.adobe.communities.ugc.migration.importer.MessagesImportServlet.java
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { final ResourceResolver resolver = request.getResourceResolver(); UGCImportHelper.checkUserPrivileges(resolver, rrf); // first check to see if the caller provided an explicit selector for our MessagingOperationsService final RequestParameter serviceSelector = request.getRequestParameter("serviceSelector"); // if no serviceSelector parameter was provided, we'll try going with whatever we get through the Reference if (null != serviceSelector && !serviceSelector.getString().equals("")) { // make sure the messagingServiceTracker was created by the activate method if (null == messagingServiceTracker) { throw new ServletException("Cannot use messagingServiceTracker"); }// ww w.j a v a 2 s .co m // search for the MessagingOperationsService corresponding to the provided selector messagingService = messagingServiceTracker.getService(serviceSelector.getString()); if (null == messagingService) { throw new ServletException( "MessagingOperationsService for selector " + serviceSelector.getString() + "was not found"); } } // finally get the uploaded file final RequestParameter[] fileRequestParameters = request.getRequestParameters("file"); if (fileRequestParameters != null && fileRequestParameters.length > 0 && !fileRequestParameters[0].isFormField()) { final Map<String, Object> messageModifiers = new HashMap<String, Object>(); if (fileRequestParameters[0].getFileName().endsWith(".json")) { // if upload is a single json file... final InputStream inputStream = fileRequestParameters[0].getInputStream(); final JsonParser jsonParser = new JsonFactory().createParser(inputStream); jsonParser.nextToken(); // get the first token importMessages(request, jsonParser, messageModifiers); } else if (fileRequestParameters[0].getFileName().endsWith(".zip")) { ZipInputStream zipInputStream; try { zipInputStream = new ZipInputStream(fileRequestParameters[0].getInputStream()); } catch (IOException e) { throw new ServletException("Could not open zip archive"); } ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { final JsonParser jsonParser = new JsonFactory().createParser(zipInputStream); jsonParser.nextToken(); // get the first token importMessages(request, jsonParser, messageModifiers); zipInputStream.closeEntry(); zipEntry = zipInputStream.getNextEntry(); } zipInputStream.close(); } else { throw new ServletException("Unrecognized file input type"); } if (!messageModifiers.isEmpty()) { try { Thread.sleep(3000); //wait 3 seconds to allow the messages to be indexed by solr for search } catch (final InterruptedException e) { // do nothing. } updateMessageDetails(request, messageModifiers); } } else { throw new ServletException("No file provided for UGC data"); } }
From source file:org.nuxeo.ecm.platform.io.impl.IOManagerImpl.java
void importDocumentsAndResources(DocumentsImporter docsImporter, InputStream in, String repo) throws IOException { ZipInputStream zip = new ZipInputStream(in); // first entry will be documents ZipEntry zentry = zip.getNextEntry(); String docZipFilename = DOCUMENTS_ADAPTER_NAME + ".zip"; if (zentry == null || !docZipFilename.equals(zentry.getName())) { zip.close();/*from w ww. j a va 2s . c o m*/ throw new NuxeoException("Invalid archive"); } // fill in a new stream File temp = Framework.createTempFile("nuxeo-import-adapters-", ".zip"); FileOutputStream outDocs = new FileOutputStream(temp); try { FileUtils.copy(zip, outDocs); } finally { outDocs.close(); } zip.closeEntry(); InputStream tempIn = new FileInputStream(temp.getPath()); DocumentTranslationMap map = docsImporter.importDocs(tempIn); tempIn.close(); temp.delete(); while ((zentry = zip.getNextEntry()) != null) { String entryName = zentry.getName(); if (entryName.endsWith(".xml")) { String ioAdapterName = entryName.substring(0, entryName.length() - 4); IOResourceAdapter adapter = getAdapter(ioAdapterName); if (adapter == null) { log.warn("Adapter " + ioAdapterName + " not available. Unable to import associated resources."); continue; } IOResources resources = adapter.loadResourcesFromXML(zip); IOResources newResources = adapter.translateResources(repo, resources, map); log.info("store resources with adapter " + ioAdapterName); adapter.storeResources(newResources); } else { log.warn("skip entry: " + entryName); } try { // we might have an undesired stream close in the client zip.closeEntry(); } catch (IOException e) { log.error("Please check code handling entry " + entryName, e); } } zip.close(); }