List of usage examples for java.util.zip ZipInputStream getNextEntry
public ZipEntry getNextEntry() throws IOException
From source file:com.polyvi.xface.extension.zip.XZipExt.java
/** * ??zip?//ww w . j a v a 2s .c om * * @param dstFileUri * * @param is * ?zip? * @return ?? * @throws IOException * @throws FileNotFoundException * @throws IllegalArgumentException */ private void unzipFileFromStream(Uri dstFileUri, InputStream is) throws IOException, FileNotFoundException, IllegalArgumentException { if (null == dstFileUri || null == is) { XLog.e(CLASS_NAME, "Method unzipFileFromStream: params is null"); throw new IllegalArgumentException(); } ZipInputStream zis = new ZipInputStream(is); ZipEntry entry = null; Uri unZipUri = null; while (null != (entry = zis.getNextEntry())) { File unZipFile = new File(dstFileUri.getPath() + File.separator + entry.getName()); unZipUri = Uri.fromFile(unZipFile); if (entry.isDirectory()) { if (!unZipFile.exists()) { unZipFile.mkdirs(); } } else { // ??? prepareForZipDir(unZipUri); OutputStream fos = mResourceApi.openOutputStream(unZipUri); int readLen = 0; byte buffer[] = new byte[XConstant.BUFFER_LEN]; while (-1 != (readLen = zis.read(buffer))) { fos.write(buffer, 0, readLen); } fos.close(); } } zis.close(); is.close(); }
From source file:org.syncope.core.rest.controller.ReportController.java
@PreAuthorize("hasRole('REPORT_READ')") @RequestMapping(method = RequestMethod.GET, value = "/execution/export/{executionId}") @Transactional(readOnly = true)//from ww w.j a va 2 s .c o m public void exportExecutionResult(final HttpServletResponse response, @PathVariable("executionId") final Long executionId, @RequestParam(value = "fmt", required = false) final ReportExecExportFormat fmt) throws NotFoundException { ReportExec reportExec = reportExecDAO.find(executionId); if (reportExec == null) { throw new NotFoundException("Report execution " + executionId); } if (!ReportExecStatus.SUCCESS.name().equals(reportExec.getStatus()) || reportExec.getExecResult() == null) { SyncopeClientCompositeErrorException sccee = new SyncopeClientCompositeErrorException( HttpStatus.BAD_REQUEST); SyncopeClientException sce = new SyncopeClientException(SyncopeClientExceptionType.InvalidReportExec); sce.addElement(reportExec.getExecResult() == null ? "No report data produced" : "Report did not run successfully"); sccee.addException(sce); throw sccee; } ReportExecExportFormat format = fmt == null ? ReportExecExportFormat.XML : fmt; LOG.debug("Exporting result of {} as {}", reportExec, format); response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); response.addHeader("Content-Disposition", "attachment; filename=" + reportExec.getReport().getName() + "." + format.name().toLowerCase()); // streaming SAX handler from a compressed byte array stream ByteArrayInputStream bais = new ByteArrayInputStream(reportExec.getExecResult()); ZipInputStream zis = new ZipInputStream(bais); try { // a single ZipEntry in the ZipInputStream (see ReportJob) zis.getNextEntry(); Pipeline<SAXPipelineComponent> pipeline = new NonCachingPipeline<SAXPipelineComponent>(); pipeline.addComponent(new XMLGenerator(zis)); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("status", reportExec.getStatus()); parameters.put("message", reportExec.getMessage()); parameters.put("startDate", reportExec.getStartDate()); parameters.put("endDate", reportExec.getEndDate()); switch (format) { case HTML: XSLTTransformer xsl2html = new XSLTTransformer(getClass().getResource("/report/report2html.xsl")); xsl2html.setParameters(parameters); pipeline.addComponent(xsl2html); pipeline.addComponent(XMLSerializer.createXHTMLSerializer()); break; case PDF: XSLTTransformer xsl2pdf = new XSLTTransformer(getClass().getResource("/report/report2fo.xsl")); xsl2pdf.setParameters(parameters); pipeline.addComponent(xsl2pdf); pipeline.addComponent(new FopSerializer(MimeConstants.MIME_PDF)); break; case RTF: XSLTTransformer xsl2rtf = new XSLTTransformer(getClass().getResource("/report/report2fo.xsl")); xsl2rtf.setParameters(parameters); pipeline.addComponent(xsl2rtf); pipeline.addComponent(new FopSerializer(MimeConstants.MIME_RTF)); break; case XML: default: pipeline.addComponent(XMLSerializer.createXMLSerializer()); } pipeline.setup(response.getOutputStream()); pipeline.execute(); LOG.debug("Result of {} successfully exported as {}", reportExec, format); } catch (Throwable t) { LOG.error("While exporting content", t); } finally { try { zis.close(); bais.close(); } catch (IOException e) { LOG.error("While closing stream for execution result", e); } } }
From source file:hoot.services.controllers.ingest.FileUploadResource.java
protected JSONObject _getZipContentType(final String zipFilePath, JSONArray contentTypes, String fName) throws Exception { JSONObject resultStat = new JSONObject(); String[] extList = { "gdb", "osm", "shp" }; int shpCnt = 0; int osmCnt = 0; int fgdbCnt = 0; ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String zipName = ze.getName(); // check to see if zipName ends with slash and remove if (zipName.endsWith("/")) { zipName = zipName.substring(0, zipName.length() - 1); }/*from w w w . ja v a2s .com*/ String[] fileNameParts = zipName.split("\\."); String ext = null; int partsLen = fileNameParts.length; if (partsLen > 1) { ext = fileNameParts[partsLen - 1]; } //See if there is extension and if none then throw error if (ext == null) { throw new Exception("Unknown file type."); } else { // for each type of extensions for (int i = 0; i < extList.length; i++) { if (ext.equalsIgnoreCase(extList[i])) { if (ze.isDirectory()) { if (ext.equals("gdb")) { JSONObject contentType = new JSONObject(); contentType.put("type", "FGDB_ZIP"); contentType.put("name", fName + "/" + zipName); contentTypes.add(contentType); fgdbCnt++; } else { throw new Exception("Unknown folder type. Only gdb folder type is supported."); } } else //file { if (ext.equals("shp")) { JSONObject contentType = new JSONObject(); contentType.put("type", "OGR_ZIP"); contentType.put("name", fName + "/" + zipName); contentTypes.add(contentType); shpCnt++; } else if (ext.equals("osm")) { JSONObject contentType = new JSONObject(); contentType.put("type", "OSM_ZIP"); contentType.put("name", fName + "/" + zipName); contentTypes.add(contentType); osmCnt++; } else { // We will not throw error here since shape file can contain mutiple types of support files. // We will let hoot-core decide if it can handle the zip. } } } // We do not allow mix of ogr and osm in zip if ((shpCnt + fgdbCnt) > 0 && osmCnt > 0) { throw new Exception("Zip should not contain both osm and ogr types."); } } } ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); resultStat.put("shpcnt", shpCnt); resultStat.put("fgdbcnt", fgdbCnt); resultStat.put("osmcnt", osmCnt); return resultStat; }
From source file:eionet.gdem.conversion.odf.ODFSpreadsheetAnalyzer.java
/** * Analyze the content file in a <code>File</code> which is a .zip file. * * @param inputStream/*from ww w . ja v a 2s . c o m*/ * a <code>File</code> that contains OpenDocument content-information information. */ public OpenDocumentSpreadsheet analyzeZip(InputStream inputStream) { OpenDocumentSpreadsheet spreadsheet = null; ZipInputStream zipStream = null; try { zipStream = new ZipInputStream(inputStream); while (zipStream.available() == 1) { // read possible contentEntry ZipEntry cententEntry = zipStream.getNextEntry(); if (cententEntry != null) { if ("content.xml".equals(cententEntry.getName())) { // if real contentEntry we use content to do real // analysis spreadsheet = analyzeSpreadsheet(zipStream); // analyze is made and we can break the loop break; } } } } catch (IOException ioe) { ioe.printStackTrace(); } finally { IOUtils.closeQuietly(zipStream); } return spreadsheet; }
From source file:edu.harvard.mcz.dwcaextractor.DwCaExtractor.java
/** * Setup conditions to run.//from www . j a v a 2 s . co m * * @param args command line arguments * @return true if setup was successful, false otherwise. */ protected boolean setup(String[] args) { boolean setupOK = false; CmdLineParser parser = new CmdLineParser(this); //parser.setUsageWidth(4096); try { parser.parseArgument(args); if (help) { parser.printUsage(System.out); System.exit(0); } if (archiveFilePath != null) { String filePath = archiveFilePath; logger.debug(filePath); File file = new File(filePath); if (!file.exists()) { // Error logger.error(filePath + " not found."); } if (!file.canRead()) { // error logger.error("Unable to read " + filePath); } if (file.isDirectory()) { // check if it is an unzipped dwc archive. dwcArchive = openArchive(file); } if (file.isFile()) { // unzip it File outputDirectory = new File(file.getName().replace(".", "_") + "_content"); if (!outputDirectory.exists()) { outputDirectory.mkdir(); try { byte[] buffer = new byte[1024]; ZipInputStream inzip = new ZipInputStream(new FileInputStream(file)); ZipEntry entry = inzip.getNextEntry(); while (entry != null) { String fileName = entry.getName(); File expandedFile = new File(outputDirectory.getPath() + File.separator + fileName); new File(expandedFile.getParent()).mkdirs(); FileOutputStream expandedfileOutputStream = new FileOutputStream(expandedFile); int len; while ((len = inzip.read(buffer)) > 0) { expandedfileOutputStream.write(buffer, 0, len); } expandedfileOutputStream.close(); entry = inzip.getNextEntry(); } inzip.closeEntry(); inzip.close(); logger.debug("Unzipped archive into " + outputDirectory.getPath()); } catch (FileNotFoundException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage(), e); } } // look into the unzipped directory dwcArchive = openArchive(outputDirectory); } if (dwcArchive != null) { if (checkArchive()) { // Check output csvPrinter = new CSVPrinter(new FileWriter(outputFilename, append), CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC)); // no exception thrown setupOK = true; } } else { System.out.println("Problem opening archive."); logger.error("Unable to unpack archive file."); } logger.debug(setupOK); } } catch (CmdLineException e) { logger.error(e.getMessage()); parser.printUsage(System.err); } catch (IOException e) { logger.error(e.getMessage()); System.out.println(e.getMessage()); parser.printUsage(System.err); } return setupOK; }
From source file:com.wheelermarine.publicAccessSites.Updater.java
@Override protected Integer doInBackground(URL... urls) { try {/*from w w w . jav a2 s .c o m*/ final DatabaseHelper db = new DatabaseHelper(context); SQLiteDatabase database = db.getWritableDatabase(); if (database == null) throw new IllegalStateException("Unable to open database!"); database.beginTransaction(); try { // Clear out the old data. database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null); // Connect to the web server and locate the FTP download link. Log.v(TAG, "Finding update: " + urls[0]); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage("Locating update..."); progress.setIndeterminate(true); } }); Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get(); URL dataURL = null; for (Element element : doc.select("a")) { if (element.hasAttr("href") && element.attr("href").endsWith(".zip")) { dataURL = new URL(element.attr("href")); } } // Make sure the download URL was fund. if (dataURL == null) throw new FileNotFoundException("Unable to locate data URL."); // Connect to the FTP server and download the update. Log.v(TAG, "Downloading update: " + dataURL); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage("Downloading update..."); progress.setIndeterminate(true); } }); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(dataURL.toString()); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (entity == null) throw new IOException("Error downloading update."); Map<Integer, Location> locations = null; // Download the ZIP archive. Log.v(TAG, "Downloading: " + dataURL.getFile()); InputStream in = entity.getContent(); if (in == null) throw new FileNotFoundException(dataURL.getFile() + " was not found!"); try { ZipInputStream zin = new ZipInputStream(in); try { // Locate the .dbf entry in the ZIP archive. ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { if (entry.getName().endsWith(entryName)) { readDBaseFile(zin, database); } else if (entry.getName().endsWith(shapeEntryName)) { locations = readShapeFile(zin); } } } finally { try { zin.close(); } catch (Exception e) { // Ignore this error. } } } finally { in.close(); } if (locations != null) { final int recordCount = locations.size(); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setIndeterminate(false); progress.setMessage("Updating locations..."); progress.setMax(recordCount); } }); int progress = 0; for (int recordNumber : locations.keySet()) { PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber); Location loc = locations.get(recordNumber); access.setLatitude(loc.getLatitude()); access.setLongitude(loc.getLongitude()); db.updatePublicAccess(access); publishProgress(++progress); } } database.setTransactionSuccessful(); return db.getPublicAccessesCount(); } finally { database.endTransaction(); } } catch (Exception e) { error = e; Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e); return -1; } }
From source file:com.jlgranda.fede.ejb.mail.reader.FacturaElectronicaMailReader.java
/** * Obtiene una lista de objetos <tt>FacturaReader</tt> desde el mensaje de correo, si existe * * @param mime4jMessage//from www.j a va 2 s . c o m * @return lista de instancias instancia <tt>FacturaReader</tt> si existe la factura, null * en caso contrario */ private List<FacturaReader> handleMessage(org.apache.james.mime4j.dom.Message mime4jMessage) throws IOException, Exception { List<FacturaReader> result = new ArrayList<>(); ByteArrayOutputStream os = null; String filename = null; Factura factura = null; EmailHelper emailHelper = new EmailHelper(); if (mime4jMessage.isMultipart()) { org.apache.james.mime4j.dom.Multipart mime4jMultipart = (org.apache.james.mime4j.dom.Multipart) mime4jMessage .getBody(); emailHelper.parseBodyParts(mime4jMultipart); //Obtener la factura en los adjuntos if (emailHelper.getAttachments().isEmpty()) { //If it's single part message, just get text body String text = emailHelper.getHtmlBody().toString(); emailHelper.getTxtBody().append(text); if (mime4jMessage.getSubject().contains("Ghost")) { String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"", "\" target=\"_blank\">Descarga formato XML</a>"); if (url != null) { result.add(FacturaElectronicaURLReader.getFacturaElectronica(url)); } } } else { for (Entity entity : emailHelper.getAttachments()) { filename = EmailHelper.getFilename(entity); //if (entity.getBody() instanceof BinaryBody) { if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType()) || "application/xml".equalsIgnoreCase(entity.getMimeType()) || "text/xml".equalsIgnoreCase(entity.getMimeType()) || "text/plain".equalsIgnoreCase(entity.getMimeType())) && (filename != null && filename.endsWith(".xml"))) { //attachFiles += part.getFileName() + ", "; os = EmailHelper.writeBody(entity.getBody()); factura = FacturaUtil.read(os.toString()); if (factura != null) { result.add(new FacturaReader(factura, os.toString(), entity.getFilename(), mime4jMessage.getFrom().get(0).getAddress())); } } else if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType()) || "aplication/xml".equalsIgnoreCase(entity.getMimeType()) || "text/xml".equalsIgnoreCase(entity.getMimeType())) && (filename != null && filename.endsWith(".zip"))) { //http://www.java2s.com/Tutorial/Java/0180__File/UnzipusingtheZipInputStream.htm os = EmailHelper.writeBody(entity.getBody()); ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(os.toByteArray())); try { ZipEntry entry = null; String tmp = null; ByteArrayOutputStream fout = null; while ((entry = zis.getNextEntry()) != null) { if (entry.getName().endsWith(".xml")) { //logger.debug("Unzipping {}", entry.getFilename()); fout = new ByteArrayOutputStream(); for (int c = zis.read(); c != -1; c = zis.read()) { fout.write(c); } tmp = new String(fout.toByteArray(), Charset.defaultCharset()); factura = FacturaUtil.read(tmp); if (factura != null) { result.add(new FacturaReader(factura, tmp, entity.getFilename())); } fout.close(); } zis.closeEntry(); } zis.close(); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(zis); } } else if ("message/rfc822".equalsIgnoreCase(entity.getMimeType())) { if (entity.getBody() instanceof org.apache.james.mime4j.message.MessageImpl) { result.addAll( handleMessage((org.apache.james.mime4j.message.MessageImpl) entity.getBody())); } } } } } else { //If it's single part message, just get text body String text = emailHelper.getTxtPart(mime4jMessage); emailHelper.getTxtBody().append(text); if (mime4jMessage.getSubject().contains("Ghost")) { String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"", "\" target=\"_blank\">Descarga formato XML</a>"); if (url != null) { result.add(FacturaElectronicaURLReader.getFacturaElectronica(url)); } } } return result; }
From source file:org.vietspider.server.handler.cms.metas.EditContentHandler.java
private byte[] loadZipEntry(File file, String fileName) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ZipInputStream zipInput = null; try {//from w w w.j av a2s . c o m zipInput = new ZipInputStream(new FileInputStream(file)); int read = -1; byte[] bytes = new byte[4 * 1024]; ZipEntry entry = null; while (true) { entry = zipInput.getNextEntry(); if (entry == null) break; if (entry.getName().equalsIgnoreCase(fileName)) { while ((read = zipInput.read(bytes, 0, bytes.length)) != -1) { outputStream.write(bytes, 0, read); } break; } } zipInput.close(); } finally { try { if (zipInput != null) zipInput.close(); } catch (Exception e) { } } return outputStream.toByteArray(); }
From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4jZippedInstaller.java
@Override public void performInstall(IProgressMonitor monitor, IPath dirPath) throws IOException { if (monitor == null) { monitor = new NullProgressMonitor(); }/*from ww w . j av a 2 s . co m*/ InputStream urlStream = null; try { URL url = getUrl(); URLConnection connection = url.openConnection(); connection.setConnectTimeout(TIMEOUT); connection.setReadTimeout(TIMEOUT); int length = connection.getContentLength(); monitor.beginTask(NLS.bind("Reading from {1}", getVersion(), getUrl().toString()), length >= 0 ? length : IProgressMonitor.UNKNOWN); urlStream = connection.getInputStream(); ZipInputStream zipStream = new ZipInputStream(urlStream); byte[] buffer = new byte[1024 * 8]; long start = System.currentTimeMillis(); int total = length; int totalRead = 0; ZipEntry entry; float kBps = -1; while ((entry = zipStream.getNextEntry()) != null) { if (monitor.isCanceled()) break; String fullFilename = entry.getName(); IPath fullFilenamePath = new Path(fullFilename); int secsRemaining = (int) ((total - totalRead) / 1024 / kBps); String textRemaining = secsToText(secsRemaining); monitor.subTask(NLS.bind("{0} remaining. Reading {1}", textRemaining.length() > 0 ? textRemaining : "unknown time", StringUtils .abbreviateMiddle(fullFilenamePath.removeFirstSegments(1).toString(), "...", 45))); int entrySize = (int) entry.getCompressedSize(); OutputStream output = null; try { int len = 0; int read = 0; String action = null; if (jarFiles.contains(fullFilename)) { action = "Copying"; String filename = FilenameUtils.getName(fullFilename); output = new FileOutputStream(dirPath.append(filename).toOSString()); } else { action = "Skipping"; output = new NullOutputStream(); } int secs = (int) ((System.currentTimeMillis() - start) / 1000); kBps = (float) totalRead / 1024 / secs; while ((len = zipStream.read(buffer)) > 0) { if (monitor.isCanceled()) break; read += len; monitor.subTask(NLS.bind("{0} remaining. {1} {2} at {3}KB/s ({4}KB / {5}KB)", new Object[] { String.format("%s", textRemaining.length() > 0 ? textRemaining : "unknown time"), action, StringUtils.abbreviateMiddle( fullFilenamePath.removeFirstSegments(1).toString(), "...", 45), String.format("%,.1f", kBps), String.format("%,.1f", (float) read / 1024), String.format("%,.1f", (float) entry.getSize() / 1024) })); output.write(buffer, 0, len); } totalRead += entrySize; monitor.worked(entrySize); } finally { IOUtils.closeQuietly(output); } } } finally { IOUtils.closeQuietly(urlStream); monitor.done(); } }
From source file:edu.mayo.pipes.iterators.Compressor.java
/** * Make a Zip file reader, and set it to read the first entry in the zip file.<br/> * All other entries in the zip file are ignored * * @param inStream Stream to read from * @throws IOException//from www . j av a 2 s . c o m */ public BufferedReader makeZipReader(InputStream inStream) throws IOException { ZipInputStream zipRead = new ZipInputStream(inStream); // ZipEntry zE = zipRead.getNextEntry (); zipRead.getNextEntry(); // Ignore result, we don't use // Now ready to read file, so create readers to do that InputStreamReader rStream = new InputStreamReader(zipRead); reader = new BufferedReader(rStream); comp = kZipCompression; return reader; }