List of usage examples for java.util.zip ZipInputStream getNextEntry
public ZipEntry getNextEntry() throws IOException
From source file:net.firejack.platform.service.content.broker.collection.ImportCollectionArchiveFileBroker.java
@Override protected ServiceResponse perform(ServiceRequest<NamedValues<InputStream>> request) throws Exception { InputStream inputStream = request.getData().get("inputStream"); try {// w w w .j a v a 2 s . c o m Long uploadFileTime = new Date().getTime(); String randomName = SecurityHelper.generateRandomSequence(16); String temporaryUploadFileName = randomName + "." + uploadFileTime; OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, temporaryUploadFileName, inputStream, helper.getTemp()); String contentXmlUploadedFile = null; String resourceZipUploadedFile = null; ZipInputStream zipFile = new ZipInputStream(OPFEngine.FileStoreService .download(OpenFlame.FILESTORE_BASE, temporaryUploadFileName, helper.getTemp())); try { ZipEntry entry; while ((entry = zipFile.getNextEntry()) != null) { if (PackageFileType.CONTENT_XML.getOfrFileName().equals(entry.getName())) { contentXmlUploadedFile = PackageFileType.CONTENT_XML.name() + randomName + "." + uploadFileTime; OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, contentXmlUploadedFile, zipFile, helper.getTemp()); } else if (PackageFileType.RESOURCE_ZIP.getOfrFileName().equals(entry.getName())) { resourceZipUploadedFile = PackageFileType.RESOURCE_ZIP.name() + randomName + "." + uploadFileTime; OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, resourceZipUploadedFile, zipFile, helper.getTemp()); } } } catch (IOException e) { throw new BusinessFunctionException(e.getMessage()); } finally { zipFile.close(); } InputStream contentXml = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE, contentXmlUploadedFile, helper.getTemp()); InputStream resourceZip = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE, resourceZipUploadedFile, helper.getTemp()); importContentProcessor.importContent(contentXml, resourceZip); IOUtils.closeQuietly(contentXml); IOUtils.closeQuietly(resourceZip); } catch (IOException e) { throw new BusinessFunctionException(e.getMessage()); } catch (JAXBException e) { throw new BusinessFunctionException(e.getMessage()); } return new ServiceResponse("Content Archive has uploaded successfully.", true); }
From source file:com.jadarstudios.rankcapes.forge.cape.CapePack.java
/** * Parses the Zip file in memory./*from w ww . j a v a2 s.co m*/ * * @param input the bytes of a valid zip file */ private void parsePack(byte[] input) { try { ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(input)); String metadata = ""; ZipEntry entry; while ((entry = zipInput.getNextEntry()) != null) { String name = entry.getName(); if (name.endsWith(".png")) { // remove file extension from the name. name = FilenameUtils.removeExtension(name); StaticCape cape = this.loadCape(name, zipInput); this.unprocessedCapes.put(name, cape); } else if (name.endsWith(".mcmeta")) { // parses the pack metadata. InputStreamReader streamReader = new InputStreamReader(zipInput); while (streamReader.ready()) { metadata += (char) streamReader.read(); } } } if (!Strings.isNullOrEmpty(metadata)) { this.parsePackMetadata(StringUtils.remove(metadata, (char) 65535)); } else { RankCapesForge.log.warn("Cape Pack metadata is missing!"); } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.eviware.soapui.impl.wsdl.support.FileAttachment.java
public InputStream getInputStream() throws IOException { BufferedInputStream inputStream = null; if (isCached()) { ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(config.getData())); zipInputStream.getNextEntry(); inputStream = new BufferedInputStream(zipInputStream); } else {/*from w w w . j a v a2 s . co m*/ String url = urlProperty.expand(); inputStream = new BufferedInputStream( url == null ? new ByteArrayInputStream(new byte[0]) : new FileInputStream(url)); } AttachmentEncoding encoding = getEncoding(); if (encoding == AttachmentEncoding.BASE64) { ByteArrayOutputStream data = Tools.readAll(inputStream, Tools.READ_ALL); return new ByteArrayInputStream(Base64.encodeBase64(data.toByteArray())); } else if (encoding == AttachmentEncoding.HEX) { ByteArrayOutputStream data = Tools.readAll(inputStream, Tools.READ_ALL); return new ByteArrayInputStream(new String(Hex.encodeHex(data.toByteArray())).getBytes()); } return inputStream; }
From source file:hoot.services.controllers.ogr.OgrAttributesResource.java
/** * This rest endpoint uploads multipart data from UI and then generates attribute output * Example: http://localhost:8080//hoot-services/ogr/info/upload?INPUT_TYPE=DIR * Output: {"jobId":"e43feae4-0644-47fd-a23c-6249e6e7f7fb"} * //from ww w . j a v a 2s . c om * After getting the jobId, one can track the progress through job status rest end point * Example: http://localhost:8080/hoot-services/job/status/e43feae4-0644-47fd-a23c-6249e6e7f7fb * Output: {"jobId":"e43feae4-0644-47fd-a23c-6249e6e7f7fb","statusDetail":null,"status":"complete"} * * Once status is "complete" * Result attribute can be obtained through * Example:http://localhost:8080/hoot-services/ogr/info/e43feae4-0644-47fd-a23c-6249e6e7f7fb * output: JSON of attributes * * @param inputType : [FILE | DIR] where FILE type should represents zip,shp or OMS and DIR represents FGDB * @param request * @return */ @POST @Path("/upload") @Produces(MediaType.TEXT_PLAIN) public Response processUpload(@QueryParam("INPUT_TYPE") final String inputType, @Context HttpServletRequest request) { JSONObject res = new JSONObject(); String jobId = UUID.randomUUID().toString(); try { log.debug("Starting file upload for ogr attribute Process"); Map<String, String> uploadedFiles = new HashMap<String, String>(); ; Map<String, String> uploadedFilesPaths = new HashMap<String, String>(); MultipartSerializer ser = new MultipartSerializer(); ser.serializeUpload(jobId, inputType, uploadedFiles, uploadedFilesPaths, request); List<String> filesList = new ArrayList<String>(); List<String> zipList = new ArrayList<String>(); Iterator it = uploadedFiles.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); String fName = pairs.getKey().toString(); String ext = pairs.getValue().toString(); String inputFileName = ""; inputFileName = uploadedFilesPaths.get(fName); JSONObject param = new JSONObject(); // If it is zip file then we crack open to see if it contains FGDB. // If so then we add the folder location and desired output name which is fgdb name in the zip if (ext.equalsIgnoreCase("ZIP")) { zipList.add(fName); String zipFilePath = homeFolder + "/upload/" + jobId + "/" + inputFileName; ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String zipName = ze.getName(); if (ze.isDirectory()) { if (zipName.toLowerCase().endsWith(".gdb/") || zipName.toLowerCase().endsWith(".gdb")) { String fgdbZipName = zipName; if (zipName.toLowerCase().endsWith(".gdb/")) { fgdbZipName = zipName.substring(0, zipName.length() - 1); } filesList.add("\"" + fName + "/" + fgdbZipName + "\""); } } else { if (zipName.toLowerCase().endsWith(".shp")) { filesList.add("\"" + fName + "/" + zipName + "\""); } } ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } else { filesList.add("\"" + inputFileName + "\""); } } String mergeFilesList = StringUtils.join(filesList.toArray(), ' '); String mergedZipList = StringUtils.join(zipList.toArray(), ';'); JSONArray params = new JSONArray(); JSONObject param = new JSONObject(); param.put("INPUT_FILES", mergeFilesList); params.add(param); param = new JSONObject(); param.put("INPUT_ZIPS", mergedZipList); params.add(param); String argStr = createPostBody(params); postJobRquest(jobId, argStr); } catch (Exception ex) { ResourceErrorHandler.handleError("Failed upload: " + ex.toString(), Status.INTERNAL_SERVER_ERROR, log); } res.put("jobId", jobId); return Response.ok(res.toJSONString(), MediaType.APPLICATION_JSON).build(); }
From source file:mitm.common.security.JCEPolicyManager.java
/** * Installs the jce policy into the current JRE (JRE is found using java.home system property). The input must * //from w ww. ja v a2 s .c o m * @param jcePolicy an input stream to the policy file in zip format as downloaded from SUN site. * @param copyScript path to the shell script that will copy the jar file to the correct location * @throws IOException */ public void installJCEPolicy(InputStream jcePolicy) throws IOException { /* * decodedPolicy should now contain a zip file with the policy files */ ZipInputStream zis = new ZipInputStream(jcePolicy); ZipEntry zipEntry; boolean exportFound = false; boolean localPolicyFound = false; while ((zipEntry = zis.getNextEntry()) != null) { String name = zipEntry.getName(); if (name == null) { continue; } if (name.endsWith("/" + US_EXPORT_POLICY_FILE)) { installJCEPolicy(zis, US_EXPORT_POLICY_FILE); exportFound = true; } if (name.endsWith("/" + LOCAL_POLICY_FILE)) { installJCEPolicy(zis, LOCAL_POLICY_FILE); localPolicyFound = true; } } if (!exportFound || !localPolicyFound) { throw new IOException("Not all policy files were found in the zip."); } }
From source file:com.liferay.sync.engine.document.library.handler.DownloadFilesHandler.java
@Override protected void doHandleResponse(HttpResponse httpResponse) throws Exception { long syncAccountId = getSyncAccountId(); final Session session = SessionManager.getSession(syncAccountId); Header header = httpResponse.getFirstHeader("Sync-JWT"); if (header != null) { session.addHeader("Sync-JWT", header.getValue()); }// ww w .j ava2 s. co m Map<String, DownloadFileHandler> handlers = (Map<String, DownloadFileHandler>) getParameterValue( "handlers"); InputStream inputStream = null; try { HttpEntity httpEntity = httpResponse.getEntity(); inputStream = new CountingInputStream(httpEntity.getContent()) { @Override protected synchronized void afterRead(int n) { session.incrementDownloadedBytes(n); super.afterRead(n); } }; inputStream = new RateLimitedInputStream(inputStream, syncAccountId); ZipInputStream zipInputStream = new ZipInputStream(inputStream); ZipEntry zipEntry = null; while ((zipEntry = zipInputStream.getNextEntry()) != null) { String zipEntryName = zipEntry.getName(); if (zipEntryName.equals("errors.json")) { JsonNode rootJsonNode = JSONUtil.readTree(new CloseShieldInputStream(zipInputStream)); Iterator<Map.Entry<String, JsonNode>> fields = rootJsonNode.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); Handler<Void> handler = handlers.remove(field.getKey()); JsonNode valueJsonNode = field.getValue(); JsonNode exceptionJsonNode = valueJsonNode.get("exception"); handler.handlePortalException(exceptionJsonNode.textValue()); } break; } DownloadFileHandler downloadFileHandler = handlers.get(zipEntryName); if (downloadFileHandler == null) { continue; } SyncFile syncFile = (SyncFile) downloadFileHandler.getParameterValue("syncFile"); if (downloadFileHandler.isUnsynced(syncFile)) { handlers.remove(zipEntryName); continue; } if (_logger.isTraceEnabled()) { _logger.trace("Handling response {} file path {}", DownloadFileHandler.class.getSimpleName(), syncFile.getFilePathName()); } try { downloadFileHandler.copyFile(syncFile, Paths.get(syncFile.getFilePathName()), new CloseShieldInputStream(zipInputStream), false); } catch (Exception e) { if (!isEventCancelled()) { _logger.error(e.getMessage(), e); downloadFileHandler.removeEvent(); FileEventUtil.downloadFile(getSyncAccountId(), syncFile, false); } } finally { handlers.remove(zipEntryName); downloadFileHandler.removeEvent(); } } } catch (Exception e) { if (!isEventCancelled()) { _logger.error(e.getMessage(), e); retryEvent(); } } finally { StreamUtil.cleanUp(inputStream); } }
From source file:com.yifanlu.PSXperiaTool.Extractor.CrashBandicootExtractor.java
private void extractZip(File zipFile, File output, FileFilter filter) throws IOException { Logger.info("Extracting ZIP file: %s to: %s", zipFile.getPath(), output.getPath()); if (!output.exists()) output.mkdirs();/* w w w . j av a 2s .co m*/ ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry entry; while ((entry = zip.getNextEntry()) != null) { File file = new File(output, entry.getName()); if (file.isDirectory()) continue; if (filter != null && !filter.accept(file)) continue; Logger.verbose("Unzipping %s", entry.getName()); FileUtils.touch(file); FileOutputStream out = new FileOutputStream(file.getPath()); int n; byte[] buffer = new byte[BLOCK_SIZE]; while ((n = zip.read(buffer)) != -1) { out.write(buffer, 0, n); } out.close(); zip.closeEntry(); Logger.verbose("Done extracting %s", entry.getName()); } zip.close(); Logger.debug("Done extracting ZIP."); }
From source file:be.fedict.eid.applet.service.signer.odf.ODFSignatureFacet.java
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { try {/*from w ww . j a va 2s .c o m*/ URL odfUrl = this.signatureService.getOpenDocumentURL(); InputStream odfInputStream = odfUrl.openStream(); ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream); ZipEntry zipEntry; DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); while (null != (zipEntry = odfZipInputStream.getNextEntry())) { if (ODFUtil.isToBeSigned(zipEntry)) { String name = zipEntry.getName(); /* * Whitespaces are illegal in URIs * * Note that OOo 3.0/3.1 seems to have a bug, seems like the * OOo signature verification doesn't convert it back to * whitespace, to be investigated */ String uri = name.replaceAll(" ", "%20"); Reference reference; if (name.endsWith(".xml") && !isEmpty(odfZipInputStream)) { /* apply transformation on non-empty XML files only */ List<Transform> transforms = new LinkedList<Transform>(); Transform transform = signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null); transforms.add(transform); reference = signatureFactory.newReference(uri, digestMethod, transforms, null, null); } else { reference = signatureFactory.newReference(uri, digestMethod); } references.add(reference); LOG.debug("entry: " + name); } } } catch (IOException e) { LOG.error("IO error: " + e.getMessage(), e); } catch (Exception e) { LOG.error("Error: " + e.getMessage(), e); } }
From source file:com.khubla.simpleioc.classlibrary.ClassLibrary.java
/** * find all the classes in a jar file/*w w w .ja v a 2 s.c om*/ */ private List<Class<?>> crackJar(String jarfile) throws Exception { try { /* * the ret */ final List<Class<?>> ret = new ArrayList<Class<?>>(); /* * the jar */ final FileInputStream fis = new FileInputStream(jarfile); final ZipInputStream zip_inputstream = new ZipInputStream(fis); ZipEntry current_zip_entry = null; while ((current_zip_entry = zip_inputstream.getNextEntry()) != null) { if (current_zip_entry.getName().endsWith(".class")) { if (current_zip_entry.getSize() > 0) { final ClassNode classNode = new ClassNode(); final ClassReader cr = new ClassReader(zip_inputstream); cr.accept(classNode, 0); if (annotated(classNode)) { ret.add(Class.forName(classNode.name.replaceAll("/", "."))); log.debug("Found " + classNode.name + " in " + jarfile); } } } } zip_inputstream.close(); fis.close(); return ret; } catch (final Throwable e) { throw new Exception("Exception in crackJar for jar '" + jarfile + "'", e); } }
From source file:io.gromit.geolite2.geonames.CountryFinder.java
/** * Read countries./*from w w w .ja v a 2s .co m*/ * * @param countriesLocationUrl the countries location url * @return the country finder */ private CountryFinder readCountries(String countriesLocationUrl) { ZipInputStream zipis = null; try { zipis = new ZipInputStream(new URL(countriesLocationUrl).openStream(), Charset.forName("UTF-8")); ZipEntry zipEntry = zipis.getNextEntry(); logger.info("reading " + zipEntry.getName()); if (crc == zipEntry.getCrc()) { logger.info("skipp, same CRC"); return this; } CsvParserSettings settings = new CsvParserSettings(); settings.setSkipEmptyLines(true); settings.trimValues(true); CsvFormat format = new CsvFormat(); format.setDelimiter('\t'); format.setLineSeparator("\n"); format.setCharToEscapeQuoteEscaping('\0'); format.setQuote('\0'); settings.setFormat(format); CsvParser parser = new CsvParser(settings); List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8")); for (String[] entry : lines) { Country country = new Country(); country.setIso(entry[0]); country.setIso3(entry[1]); country.setName(entry[2]); country.setCapital(entry[3]); country.setContinent(entry[4]); country.setCurrencyCode(entry[5]); country.setCurrencyName(entry[6]); country.setPhone(entry[7]); country.setLanguage(StringUtils.substringBefore(entry[8], ",")); country.setGeonameId(NumberUtils.toInt(entry[9])); geonameMap.put(country.getGeonameId(), country); isoMap.put(country.getIso(), country); } } catch (Exception e) { throw new RuntimeException(e); } finally { try { zipis.close(); } catch (Exception e) { } ; } logger.info("loaded " + geonameMap.size() + " countries"); return this; }