List of usage examples for java.util.zip ZipInputStream getNextEntry
public ZipEntry getNextEntry() throws IOException
From source file:io.sledge.core.impl.installer.SledgePackageConfigurer.java
private void createNewZipfileWithReplacedPlaceholders(InputStream packageStream, Path configurationPackagePath, Properties envProps) throws IOException { // For reading the original configuration package ZipInputStream configPackageZipStream = new ZipInputStream(new BufferedInputStream(packageStream), Charset.forName("UTF-8")); // For outputting the configured (placeholders replaced) version of the package as zip file File outZipFile = configurationPackagePath.toFile(); ZipOutputStream outConfiguredZipStream = new ZipOutputStream(new FileOutputStream(outZipFile)); ZipEntry zipEntry;// w ww . j a va2 s . c om while ((zipEntry = configPackageZipStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) { configPackageZipStream.closeEntry(); continue; } else { ByteArrayOutputStream output = new ByteArrayOutputStream(); int length; byte[] buffer = new byte[2048]; while ((length = configPackageZipStream.read(buffer, 0, buffer.length)) >= 0) { output.write(buffer, 0, length); } InputStream zipEntryInputStream = new BufferedInputStream( new ByteArrayInputStream(output.toByteArray())); if (zipEntry.getName().endsWith("instance.properties")) { ByteArrayOutputStream envPropsOut = new ByteArrayOutputStream(); envProps.store(envPropsOut, "Environment configurations"); zipEntryInputStream = new BufferedInputStream( new ByteArrayInputStream(envPropsOut.toByteArray())); } else if (isTextFile(zipEntry.getName(), zipEntryInputStream)) { String configuredContent = StrSubstitutor.replace(output, envProps); zipEntryInputStream = new BufferedInputStream( new ByteArrayInputStream(configuredContent.getBytes())); } // Add to output zip file addToZipFile(zipEntry.getName(), zipEntryInputStream, outConfiguredZipStream); zipEntryInputStream.close(); configPackageZipStream.closeEntry(); } } outConfiguredZipStream.close(); configPackageZipStream.close(); }
From source file:com.permeance.utility.scriptinghelper.portlets.ScriptingHelperPortlet.java
public void execute(ActionRequest actionRequest, ActionResponse actionResponse) { try {/*w ww.ja va2 s . c o m*/ sCheckPermissions(actionRequest); String portletId = "_" + PortalUtil.getPortletId(actionRequest) + "_"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(100 * 1024 * 1024); PortletFileUpload upload = new PortletFileUpload(factory); FileItem fileUploaded = null; List<FileItem> items = upload.parseRequest(actionRequest); for (FileItem fi : items) { if (fi.isFormField()) { actionRequest.setAttribute(fi.getFieldName(), fi.getString()); if (fi.getFieldName().startsWith(portletId)) { actionRequest.setAttribute(fi.getFieldName().substring(portletId.length()), fi.getString()); } } else { fileUploaded = fi; } } String cmd = (String) actionRequest.getAttribute("cmd"); String language = (String) actionRequest.getAttribute("language"); String script = (String) actionRequest.getAttribute("script"); String editorheight = (String) actionRequest.getAttribute("editorheight"); String themesel = (String) actionRequest.getAttribute("themesel"); if (language == null) { language = getDefaultLanguage(); } if (script == null) { script = StringPool.BLANK; } actionResponse.setRenderParameter("language", language); actionResponse.setRenderParameter("script", script); actionResponse.setRenderParameter("editorheight", editorheight); actionResponse.setRenderParameter("themesel", themesel); if ("execute".equals(cmd)) { Map<String, Object> portletObjects = ScriptingHelperUtil.getPortletObjects(getPortletConfig(), getPortletContext(), actionRequest, actionResponse); UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream(); UnsyncPrintWriter unsyncPrintWriter = UnsyncPrintWriterPool.borrow(unsyncByteArrayOutputStream); portletObjects.put("out", unsyncPrintWriter); _log.info("Executing script"); ScriptingUtil.exec(null, portletObjects, language, script, StringPool.EMPTY_ARRAY); unsyncPrintWriter.flush(); actionResponse.setRenderParameter("script_output", unsyncByteArrayOutputStream.toString()); } else if ("save".equals(cmd)) { String newscriptname = (String) actionRequest.getAttribute("newscriptname"); if (newscriptname == null || newscriptname.trim().length() == 0) { actionResponse.setRenderParameter("script_trace", "No script name specified to save into!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Saving new script: " + newscriptname.trim()); PortletPreferences prefs = actionRequest.getPreferences(); prefs.setValue("savedscript." + newscriptname.trim(), script); prefs.setValue("lang." + newscriptname.trim(), language); prefs.store(); } else if ("saveinto".equals(cmd)) { String scriptname = (String) actionRequest.getAttribute("savedscript"); if (scriptname == null) { actionResponse.setRenderParameter("script_trace", "No script specified to save into!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Saving saved script: " + scriptname); PortletPreferences prefs = actionRequest.getPreferences(); prefs.setValue("savedscript." + scriptname, script); prefs.setValue("lang." + scriptname, language); prefs.store(); } else if ("loadfrom".equals(cmd)) { String scriptname = (String) actionRequest.getAttribute("savedscript"); if (scriptname == null) { actionResponse.setRenderParameter("script_trace", "No script specified to load from!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Loading saved script: " + scriptname); PortletPreferences prefs = actionRequest.getPreferences(); language = prefs.getValue("lang." + scriptname, getDefaultLanguage()); script = prefs.getValue("savedscript." + scriptname, StringPool.BLANK); actionResponse.setRenderParameter("language", language); actionResponse.setRenderParameter("script", script); } else if ("delete".equals(cmd)) { String scriptname = (String) actionRequest.getAttribute("savedscript"); if (scriptname == null) { actionResponse.setRenderParameter("script_trace", "No script specified to delete!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Deleting saved script: " + scriptname); PortletPreferences prefs = actionRequest.getPreferences(); prefs.reset("savedscript." + scriptname); prefs.reset("lang." + scriptname); prefs.store(); } else if ("import".equals(cmd)) { if (fileUploaded == null) { actionResponse.setRenderParameter("script_trace", "No file was uploaded for import!"); SessionErrors.add(actionRequest, "error"); return; } StringBuilder output = new StringBuilder(); InputStream instream = fileUploaded.getInputStream(); ZipInputStream zipstream = null; try { zipstream = new ZipInputStream(instream); ZipEntry entry = zipstream.getNextEntry(); while (entry != null) { String filename = entry.getName(); if (filename.contains("/")) { int qs = filename.lastIndexOf("/"); if (qs != -1) { filename = filename.substring(qs + 1); } } if (filename.contains("\\")) { int qs = filename.lastIndexOf("\\"); if (qs != -1) { filename = filename.substring(qs + 1); } } String ext = StringPool.BLANK; if (filename.length() > 0) { int qs = filename.lastIndexOf("."); if (qs > 0) { ext = filename.substring(qs + 1); filename = filename.substring(0, qs); } } String lang = resolveLanguage(ext); String imscript = getStreamAsString(zipstream, "utf-8", false); if (imscript != null && imscript.length() > 0) { _log.info("Importing script \"" + filename + "\" of type " + lang); output.append("Importing script \"" + filename + "\" of type " + lang + "\n"); PortletPreferences prefs = actionRequest.getPreferences(); prefs.setValue("savedscript." + filename, imscript); prefs.setValue("lang." + filename, lang); prefs.store(); } entry = zipstream.getNextEntry(); } actionResponse.setRenderParameter("script_output", output.toString()); } finally { try { if (zipstream != null) { zipstream.close(); } } catch (Exception e) { } try { if (instream != null) { instream.close(); } } catch (Exception e) { } } _log.info(fileUploaded.getName()); } SessionMessages.add(actionRequest, "success"); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.close(); actionResponse.setRenderParameter("script_trace", sw.toString()); _log.error(e); SessionErrors.add(actionRequest, e.toString()); } }
From source file:eu.europa.ec.markt.dss.validation102853.SignedDocumentValidator.java
/** * @param document/* ww w . j av a 2 s . c o m*/ * @return * @throws IOException */ private static SignedDocumentValidator getInstanceForAsics(DSSDocument document) throws IOException { ZipInputStream asics = new ZipInputStream(document.openStream()); try { String dataFileName = ""; ByteArrayOutputStream dataFile = null; ByteArrayOutputStream signatures = null; ZipEntry entry; boolean cadesSigned = false; boolean xadesSigned = false; while ((entry = asics.getNextEntry()) != null) { if (entry.getName().matches(PATTERN_SIGNATURES_P7S)) { if (xadesSigned) { throw new NotETSICompliantException(MSG.MORE_THAN_ONE_SIGNATURE); } signatures = new ByteArrayOutputStream(); IOUtils.copy(asics, signatures); signatures.close(); cadesSigned = true; } else if (entry.getName().matches(PATTERN_SIGNATURES_XML)) { if (cadesSigned) { throw new NotETSICompliantException(MSG.MORE_THAN_ONE_SIGNATURE); } signatures = new ByteArrayOutputStream(); IOUtils.copy(asics, signatures); signatures.close(); xadesSigned = true; } else if (entry.getName().equalsIgnoreCase(MIMETYPE)) { ByteArrayOutputStream mimetype = new ByteArrayOutputStream(); IOUtils.copy(asics, mimetype); mimetype.close(); // Mime type implementers MAY use // "application/vnd.etsi.asic-s+zip" to identify this format // or MAY // maintain the original mimetype of the signed data object. } else if (entry.getName().indexOf("/") == -1) { if (dataFile == null) { dataFile = new ByteArrayOutputStream(); IOUtils.copy(asics, dataFile); dataFile.close(); dataFileName = entry.getName(); } else { throw new ProfileException("ASiC-S profile support only one data file"); } } } if (xadesSigned) { ASiCXMLDocumentValidator xmlValidator = new ASiCXMLDocumentValidator( new InMemoryDocument(signatures.toByteArray()), dataFile.toByteArray(), dataFileName); return xmlValidator; } else if (cadesSigned) { CMSDocumentValidator pdfValidator = new CMSDocumentValidator( new InMemoryDocument(signatures.toByteArray())); pdfValidator.setExternalContent(new InMemoryDocument(dataFile.toByteArray())); return pdfValidator; } else { throw new RuntimeException("Is not xades nor cades signed"); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { try { asics.close(); } catch (IOException e) { } } }
From source file:com.github.maven_nar.AbstractDependencyMojo.java
public final NarInfo getNarInfo(final Artifact dependency) throws MojoExecutionException { // FIXME reported to maven developer list, isSnapshot changes behaviour // of getBaseVersion, called in pathOf. dependency.isSnapshot();// w w w. j a v a 2 s. co m if (dependency.getFile().isDirectory()) { getLog().debug("Dependency is not packaged: " + dependency.getFile()); return new NarInfo(dependency.getGroupId(), dependency.getArtifactId(), dependency.getBaseVersion(), getLog(), dependency.getFile()); } final File file = new File(getLocalRepository().getBasedir(), getLocalRepository().pathOf(dependency)); if (!file.exists()) { getLog().debug("Dependency nar file does not exist: " + file); return null; } ZipInputStream zipStream = null; try { zipStream = new ZipInputStream(new FileInputStream(file)); if (zipStream.getNextEntry() == null) { getLog().debug("Skipping unreadable artifact: " + file); return null; } } catch (IOException e) { throw new MojoExecutionException("Error while testing for zip file " + file, e); } finally { IOUtils.closeQuietly(zipStream); } JarFile jar = null; try { jar = new JarFile(file); final NarInfo info = new NarInfo(dependency.getGroupId(), dependency.getArtifactId(), dependency.getBaseVersion(), getLog()); if (!info.exists(jar)) { getLog().debug("Dependency nar file does not contain this artifact: " + file); return null; } info.read(jar); return info; } catch (final IOException e) { throw new MojoExecutionException("Error while reading " + file, e); } finally { IOUtils.closeQuietly(jar); } }
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 av a 2 s .com*/ 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:net.pms.configuration.DownloadPlugins.java
private void unzip(File f, String dir) { // Zip file with loads of goodies // Unzip it/*from w w w . ja va2s . c om*/ ZipInputStream zis; try { zis = new ZipInputStream(new FileInputStream(f)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { File dst = new File(dir + File.separator + entry.getName()); if (entry.isDirectory()) { dst.mkdirs(); continue; } int count; byte data[] = new byte[4096]; FileOutputStream fos = new FileOutputStream(dst); try (BufferedOutputStream dest = new BufferedOutputStream(fos, 4096)) { while ((count = zis.read(data, 0, 4096)) != -1) { dest.write(data, 0, count); } dest.flush(); } if (dst.getAbsolutePath().endsWith(".jar")) { jars.add(dst.toURI().toURL()); } } zis.close(); } catch (Exception e) { LOGGER.info("unzip error " + e); } f.delete(); }
From source file:com.coinblesk.client.backup.BackupRestoreDialogFragment.java
/** * Extracts all files from a zip to disk. * @param zip data (zip format)//from w w w.java 2 s . c om * @throws IOException */ private void extractZip(byte[] zip) throws IOException { ZipInputStream zis = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(zip); zis = new ZipInputStream(new BufferedInputStream(bais)); ZipEntry ze = null; // extract all entries Log.d(TAG, "Start extracting backup."); int i = 0; while ((ze = zis.getNextEntry()) != null) { if (!shouldIgnoreZipEntry(ze)) { extractFromZipAndSaveToFile(zis, ze); ++i; } else { Log.d(TAG, "Ignore entry: " + ze.getName()); } } Log.i(TAG, "Extracted " + i + " elements from backup."); } finally { if (zis != null) { try { zis.close(); } catch (IOException e) { Log.w(TAG, "Could not close zip input stream.", e); } } } }
From source file:org.tonguetied.datatransfer.ExportServiceTest.java
public final void testCreateArchiveWithFiles() throws Exception { archiveTestDirectory = new File(USER_DIR, "testCreateArchiveWithFiles"); FileUtils.forceMkdir(archiveTestDirectory); FileUtils.writeStringToFile(new File(archiveTestDirectory, "temp"), "test.value=value"); FileUtils.writeStringToFile(new File(archiveTestDirectory, "temp_en"), "test.value=valyoo"); assertEquals(2, archiveTestDirectory.listFiles().length); assertTrue(archiveTestDirectory.isDirectory()); dataService.createArchive(archiveTestDirectory); assertEquals(3, archiveTestDirectory.listFiles().length); // examine zip file File[] files = archiveTestDirectory.listFiles(new FileExtensionFilter(".zip")); assertEquals(1, files.length);//from www .j ava2 s . c o m ZipInputStream zis = null; final String[] fileNames = { "temp", "temp_en" }; try { zis = new ZipInputStream(new FileInputStream(files[0])); ZipEntry zipEntry = zis.getNextEntry(); Arrays.binarySearch(fileNames, zipEntry.getName()); zis.closeEntry(); zipEntry = zis.getNextEntry(); Arrays.binarySearch(fileNames, zipEntry.getName()); zis.closeEntry(); // confirm that there are no more files in the archive assertEquals(0, zis.available()); } finally { IOUtils.closeQuietly(zis); } }
From source file:me.hqm.plugindev.wget.WGCommand.java
/** * Download a URL (jar or zip) to a file * * @param url Valid URL/* www.j av a 2 s. c o m*/ * @return Success or failure */ private boolean download(URL url) { // The plugin folder path String path = plugin.getDataFolder().getParentFile().getPath(); // Wrap everything in a try/catch try { // Get the filename from the url String fileName = fileName(url); // Create a new input stream and output file InputStream in = url.openStream(); File outFile = new File(path + "/" + fileName); // If the file already exists, delete it if (outFile.exists()) { outFile.delete(); } // Create the output stream and download the file FileOutputStream out = new FileOutputStream(outFile); IOUtils.copy(in, out); // Close the streams in.close(); out.close(); // If downloaded file is a zip file... if (fileName.endsWith(".zip")) { // Declare a new input stream outside of a try/catch ZipInputStream zis = null; try { // Define the input stream zis = new ZipInputStream(new FileInputStream(outFile)); // Decalre a zip entry for the while loop ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { // Make a new file object for the entry File entryFile = new File(path, entry.getName()); // If it is a directory and doesn't already exist, create the new directory if (entry.isDirectory()) { if (!entryFile.exists()) { entryFile.mkdirs(); } } else { // Make sure all folders exist if (entryFile.getParentFile() != null && !entryFile.getParentFile().exists()) { entryFile.getParentFile().mkdirs(); } // Create file on disk if (!entryFile.exists() && !entryFile.createNewFile()) { // Access denied, let the console know throw new AccessDeniedException(entryFile.getPath()); } // Write data to file from zip. OutputStream os = null; try { os = new FileOutputStream(entryFile); IOUtils.copy(zis, os); } finally { // Silently close the output stream IOUtils.closeQuietly(os); } } } } finally { // Always close streams IOUtils.closeQuietly(zis); } // Delete the zip file outFile.delete(); } // Return success return true; } catch (NullPointerException | IOException oops) { getLogger().severe("---------- WGET BEGIN -----------"); getLogger().severe("An error occurred during a file download/extraction:"); oops.printStackTrace(); getLogger().severe("----------- WGET END ------------"); } // The download failed, report failure return false; }
From source file:com.aurel.track.exchange.track.importer.TrackImportAction.java
/** * Render the import page//from ww w . j a va2 s . c o m */ @Override /** * Save the zip file and import the data * @return */ public String execute() { LOGGER.info("Import started"); InputStream inputStream; try { inputStream = new FileInputStream(uploadFile); } catch (FileNotFoundException e) { LOGGER.error("Getting the input stream for the zip failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); JSONUtility.encodeJSON(servletResponse, JSONUtility.encodeJSONFailure(getText("admin.actions.importTp.err.failed"))); return null; } /** * delete the old temporary attachment directory if exists from previous imports */ String tempAttachmentDirectory = AttachBL.getAttachDirBase() + File.separator + AttachBL.tmpAttachments; AttachBL.deleteDirectory(new File(tempAttachmentDirectory)); /** * extract the zip to a temporary directory */ ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream)); final int BUFFER = 2048; File unzipTempDirectory = new File(tempAttachmentDirectory); if (!unzipTempDirectory.exists()) { unzipTempDirectory.mkdirs(); } BufferedOutputStream dest = null; ZipEntry zipEntry; try { while ((zipEntry = zipInputStream.getNextEntry()) != null) { File destFile = new File(unzipTempDirectory, zipEntry.getName()); // grab file's parent directory structure int count; byte data[] = new byte[BUFFER]; // write the files to the disk FileOutputStream fos = new FileOutputStream(destFile); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zipInputStream.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } zipInputStream.close(); } catch (Exception e) { LOGGER.error("Extracting the zip to the temporary directory failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); JSONUtility.encodeJSON(servletResponse, JSONUtility.encodeJSONFailure(getText("admin.actions.importTp.err.failed")), false); return null; } /** * get the data file (the only file from the zip which is not an attachment) */ File importDataFile = new File(tempAttachmentDirectory, ExchangeFieldNames.EXCHANGE_ZIP_ENTRY); if (!importDataFile.exists()) { LOGGER.error("The file " + ExchangeFieldNames.EXCHANGE_ZIP_ENTRY + " not found in the zip"); JSONUtility.encodeJSON(servletResponse, JSONUtility.encodeJSONFailure(getText("admin.actions.importTp.err.failed")), false); return null; } /** * field parser */ LOGGER.debug("Parsing the fields"); List<ISerializableLabelBean> customFieldsBeans = new ImporterFieldParser().parse(importDataFile); Map<Integer, Integer> fieldsMatcherMap = null; try { fieldsMatcherMap = TrackImportBL.getFieldMatchMap(customFieldsBeans); } catch (ImportExceptionList importExceptionList) { LOGGER.error("Getting the field match map failed "); JSONUtility.encodeJSON(servletResponse, ImportJSON.importErrorMessageListJSON( ErrorHandlerJSONAdapter.handleErrorList(importExceptionList.getErrorDataList(), locale), null, true)); return null; } /** * dropdown parser */ LOGGER.debug("Parsing the external dropdowns"); SortedMap<String, List<ISerializableLabelBean>> externalDropdowns = new ImporterDropdownParser() .parse(importDataFile, fieldsMatcherMap); /** * data parser */ LOGGER.debug("Parsing the items"); List<ExchangeWorkItem> externalReportBeansList = new ImporterDataParser().parse(importDataFile, fieldsMatcherMap); try { LOGGER.debug("Importing the items"); ImportCounts importCounts = TrackImportBL.importWorkItems(externalReportBeansList, externalDropdowns, fieldsMatcherMap, personID, locale); LOGGER.debug("Imported " + importCounts.getNoOfCreatedIssues() + " new issues " + " modified " + importCounts.getNoOfUpdatedIssues()); JSONUtility.encodeJSON(servletResponse, ImportJSON.importMessageJSON(true, getText("admin.actions.importTp.lbl.result", new String[] { Integer.valueOf(importCounts.getNoOfCreatedIssues()).toString(), Integer.valueOf(importCounts.getNoOfUpdatedIssues()).toString() }), true, locale), false); } catch (ImportExceptionList importExceptionList) { JSONUtility.encodeJSON(servletResponse, ImportJSON.importErrorMessageListJSON( ErrorHandlerJSONAdapter.handleErrorList(importExceptionList.getErrorDataList(), locale), null, true), false); return null; } catch (ImportException importException) { JSONUtility.encodeJSON(servletResponse, ImportJSON.importMessageJSON(false, getText(importException.getMessage()), true, locale), false); return null; } catch (Exception e) { JSONUtility.encodeJSON(servletResponse, ImportJSON.importMessageJSON(false, getText("admin.actions.importTp.err.failed"), true, locale), false); return null; } LOGGER.info("Import done"); return null; }