List of usage examples for java.util.zip ZipInputStream close
public void close() throws IOException
From source file:com.espringtran.compressor4j.processor.GzipProcessor.java
/** * Read from compressed file/* w w w. jav a 2 s . c o m*/ * * @param srcPath * path of compressed file * @param fileCompressor * FileCompressor object * @throws Exception */ @Override public void read(String srcPath, FileCompressor fileCompressor) throws Exception { long t1 = System.currentTimeMillis(); byte[] data = FileUtil.convertFileToByte(srcPath); ByteArrayInputStream bais = new ByteArrayInputStream(data); GzipCompressorInputStream cis = new GzipCompressorInputStream(bais); ZipInputStream zis = new ZipInputStream(cis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { byte[] buffer = new byte[1024]; int readByte; ZipEntry entry = zis.getNextEntry(); while (entry != null) { long t2 = System.currentTimeMillis(); baos = new ByteArrayOutputStream(); readByte = zis.read(buffer); while (readByte != -1) { baos.write(buffer, 0, readByte); readByte = zis.read(buffer); } zis.closeEntry(); BinaryFile binaryFile = new BinaryFile(entry.getName(), baos.toByteArray()); fileCompressor.addBinaryFile(binaryFile); LogUtil.createAddFileLog(fileCompressor, binaryFile, t2, System.currentTimeMillis()); entry = zis.getNextEntry(); } } catch (Exception e) { FileCompressor.LOGGER.error("Error on get compressor file", e); } finally { baos.close(); zis.close(); cis.close(); bais.close(); } LogUtil.createReadLog(fileCompressor, srcPath, data.length, t1, System.currentTimeMillis()); }
From source file:edu.ucla.loni.server.Upload.java
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try {//from w w w. ja v a 2s . c o m @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req); // Go through the items and get the root and package String rootPath = ""; String packageName = ""; for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("root")) { rootPath = item.getString(); } else if (item.getFieldName().equals("packageName")) { packageName = item.getString(); } } } if (rootPath.equals("")) { res.getWriter().println("error :: Root directory has not been found."); return; } Directory root = Database.selectDirectory(rootPath); // Go through items and process urls and files for (FileItem item : items) { // Uploaded File if (item.isFormField() == false) { String filename = item.getName(); ; if (filename.equals("") == true) continue; try { InputStream in = item.getInputStream(); //determine if it is pipefile or zipfile //if it is pipefile => feed directly to writeFile function //otherwise, uncompresse it first and then one-by-one feed to writeFile if (filename.endsWith(".zip")) { ZipInputStream zip = new ZipInputStream(in); ZipEntry entry = zip.getNextEntry(); while (entry != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (baos != null) { byte[] arr = new byte[4096]; int index = 0; while ((index = zip.read(arr, 0, 4096)) != -1) { baos.write(arr, 0, index); } } InputStream is = new ByteArrayInputStream(baos.toByteArray()); writeFile(root, packageName, is); entry = zip.getNextEntry(); } zip.close(); } else { writeFile(root, packageName, in); } in.close(); } catch (Exception e) { res.getWriter().println("Failed to upload " + filename + ". " + e.getMessage()); } } // URLs if (item.isFormField() && item.getFieldName().equals("urls") && item.getString().equals("") == false) { String urlListAsStr = item.getString(); String[] urlList = urlListAsStr.split("\n"); for (String urlStr : urlList) { try { URL url = new URL(urlStr); URLConnection urlc = url.openConnection(); InputStream in = urlc.getInputStream(); writeFile(root, packageName, in); in.close(); } catch (Exception e) { res.getWriter().println("Failed to upload " + urlStr); return; } } } } } catch (Exception e) { res.getWriter().println("Error occurred while creating file. Error Message : " + e.getMessage()); } } }
From source file:InstallJars.java
public void installJar(URLConnection conn, String target, boolean doExpand, boolean doRun) throws IOException { if (doExpand) { println("Expanding JAR file " + target + " from " + conn.getURL().toExternalForm()); // *** may need to specialize for JAR format *** ZipInputStream zis = new ZipInputStream( new BufferedInputStream(conn.getInputStream(), BLOCK_SIZE * BLOCK_COUNT)); int count = 0; prepDirs(target, true);//from w w w. j a va 2 s . c o m try { while (zis.available() > 0) { ZipEntry ze = zis.getNextEntry(); copyEntry(target, zis, ze); count++; } } finally { try { zis.close(); } catch (IOException ioe) { } } println("Installed " + count + " files/directories"); } else { print("Installing JAR file " + target + " from " + conn.getURL().toExternalForm()); copyStream(conn, target); println(); if (doRun) { runTarget(target, true); } } }
From source file:com.adobe.communities.ugc.migration.importer.ImportFileUploadServlet.java
/** * The post operation accepts uploaded zip files, then explodes their contents and saves them into the jcr tree * @param request - the request// ww w . jav a 2 s.c o m * @param response - the response * @throws ServletException * @throws IOException */ protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { final ResourceResolver resolver = request.getResourceResolver(); UGCImportHelper.checkUserPrivileges(resolver, rrf); final Resource parentResource = resolver.getResource(UPLOAD_DIR); if (null == parentResource || parentResource instanceof NonExistingResource) { throw new ServletException("upload directory hasn't been created"); } // get the uploaded file final RequestParameter[] fileRequestParameters = request.getRequestParameters("file"); if (fileRequestParameters == null || fileRequestParameters.length <= 0 || fileRequestParameters[0].isFormField() || !fileRequestParameters[0].getFileName().endsWith(".zip")) { throw new ServletException("Unrecognized file input type"); } final String filename = fileRequestParameters[0].getFileName(); // create the folder name for the uploaded file contents final Random RNG = new Random(); final String randomString = String.valueOf(RNG.nextInt(Integer.MAX_VALUE)) + String.valueOf(RNG.nextInt(Integer.MAX_VALUE)); // record the folder name for sending back with the response final JSONWriter writer = new JSONWriter(response.getWriter()); writer.setTidy(true); final Calendar uploadDate = new GregorianCalendar(); try { writer.object(); writer.key("folderName"); writer.value(randomString); writer.key("filename"); writer.value(filename); writer.key("uploadDate"); writer.value(uploadDate.getTime().getTime()); // <-- not a typo writer.key("files"); writer.array(); } catch (JSONException e) { throw new ServletException("Unable to use JSONWriter", e); } // actually create the folder final Map<String, Object> folderProperties = new HashMap<String, Object>(); folderProperties.put(JcrConstants.JCR_PRIMARYTYPE, "sling:Folder"); folderProperties.put("uploadedFileName", filename); folderProperties.put("uploadDate", uploadDate); final Resource folder = resolver.create(parentResource, randomString, folderProperties); // prepare to read the uploaded zip file final InputStream uploadedFileInputStream; try { uploadedFileInputStream = fileRequestParameters[0].getInputStream(); } catch (IOException e) { throw new ServletException("Could not read zip archive"); } final ZipInputStream zipInputStream = new ZipInputStream(uploadedFileInputStream); try { saveExplodedFiles(resolver, folder, writer, zipInputStream, request.getParameter("basePath")); // close our JSONWriter writer.endArray(); writer.endObject(); } catch (final JSONException e) { throw new ServletException("Unable to close JSONWriter", e); } catch (final ServletException e) { resolver.delete(folder); // clean up after ourselves throw e; } finally { // close input streams zipInputStream.close(); uploadedFileInputStream.close(); } }
From source file:com.bibisco.manager.ProjectManager.java
public static void unZipIt(String pStrZipFile) { mLog.debug("Start unZipIt(String)"); try {//from ww w . j a v a 2 s .c o m // get temp directory path String lStrTempDirectory = ContextManager.getInstance().getTempDirectoryPath(); // get the zip file content ZipInputStream lZipInputStream = new ZipInputStream(new FileInputStream(pStrZipFile)); // get the zipped file list entry ZipEntry lZipEntry = lZipInputStream.getNextEntry(); while (lZipEntry != null) { String lStrFileName = lZipEntry.getName(); File lFileZipEntry = new File(lStrTempDirectory + File.separator + lStrFileName); // create all non exists folders new File(lFileZipEntry.getParent()).mkdirs(); FileOutputStream lFileOutputStream = new FileOutputStream(lFileZipEntry); byte[] buffer = new byte[1024]; int lIntLen; while ((lIntLen = lZipInputStream.read(buffer)) > 0) { lFileOutputStream.write(buffer, 0, lIntLen); } lFileOutputStream.close(); lZipEntry = lZipInputStream.getNextEntry(); } lZipInputStream.closeEntry(); lZipInputStream.close(); } catch (IOException e) { mLog.error(e); throw new BibiscoException(e, BibiscoException.IO_EXCEPTION); } mLog.debug("End unZipIt(String)"); }
From source file:nl.nn.adapterframework.webcontrol.api.SendJmsMessage.java
private void processZipFile(InputStream file, JmsSender qms, String replyTo) throws IOException { ZipInputStream archive = new ZipInputStream(file); for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) { String name = entry.getName(); int size = (int) entry.getSize(); if (size > 0) { byte[] b = new byte[size]; int rb = 0; int chunk = 0; while ((size - rb) > 0) { chunk = archive.read(b, rb, size - rb); if (chunk == -1) { break; }/* w w w. j av a 2s. co m*/ rb += chunk; } String currentMessage = XmlUtils.readXml(b, 0, rb, Misc.DEFAULT_INPUT_STREAM_ENCODING, false); // initiate MessageSender if ((replyTo != null) && (replyTo.length() > 0)) qms.setReplyToName(replyTo); processMessage(qms, name + "_" + Misc.createSimpleUUID(), currentMessage); } archive.closeEntry(); } archive.close(); }
From source file:org.foxbpm.web.service.impl.FlowManageServiceImpl.java
public void deployByZip(Map<String, Object> params) { ZipInputStream zipInputStream = null; try {//w w w . j a va2s. c om FileItem file = (FileItem) params.get("processFile"); if (null != file) { zipInputStream = new ZipInputStream(file.getInputStream()); String deploymentId = StringUtil.getString(params.get("deploymentId")); DeploymentBuilder deploymentBuilder = modelService.createDeployment(); deploymentBuilder.addZipInputStream(zipInputStream); // deploymentID? if (StringUtil.isNotEmpty(deploymentId)) { deploymentBuilder.updateDeploymentId(deploymentId); } deploymentBuilder.deploy(); } } catch (IOException e) { throw new FoxbpmWebException(e); } finally { if (null != zipInputStream) { try { zipInputStream.close(); } catch (IOException e) { throw new FoxbpmWebException(e); } } } }
From source file:dk.dma.msinm.web.rest.LocationRestService.java
/** * Parse the KML file of the uploaded .kmz or .kml file and returns a JSON list of locations * * @param request the servlet request/*from w w w . j a v a 2s. co m*/ * @return the corresponding list of locations */ @POST @javax.ws.rs.Path("/upload-kml") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("application/json;charset=UTF-8") public List<LocationVo> uploadKml(@Context HttpServletRequest request) throws FileUploadException, IOException { FileItemFactory factory = RepositoryService.newDiskFileItemFactory(servletContext); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { try { // .kml file if (item.getName().toLowerCase().endsWith(".kml")) { // Parse the KML and return the corresponding locations return parseKml(IOUtils.toString(item.getInputStream())); } // .kmz file else if (item.getName().toLowerCase().endsWith(".kmz")) { // Parse the .kmz file as a zip file ZipInputStream zis = new ZipInputStream(new BufferedInputStream(item.getInputStream())); ZipEntry entry; // Look for the first zip entry with a .kml extension while ((entry = zis.getNextEntry()) != null) { if (!entry.getName().toLowerCase().endsWith(".kml")) { continue; } log.info("Unzipping: " + entry.getName()); int size; byte[] buffer = new byte[2048]; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); while ((size = zis.read(buffer, 0, buffer.length)) != -1) { bytes.write(buffer, 0, size); } bytes.flush(); zis.close(); // Parse the KML and return the corresponding locations return parseKml(new String(bytes.toByteArray(), "UTF-8")); } } } catch (Exception ex) { log.error("Error extracting kmz", ex); } } } // Return an empty result return new ArrayList<>(); }
From source file:nl.nn.adapterframework.webcontrol.pipes.TestPipeLine.java
private String processZipFile(IPipeLineSession session, InputStream inputStream, String fileEncoding, IAdapter adapter, boolean writeSecLogMessage) throws IOException { String result = ""; String lastState = null;// ww w . j a v a2s . c o m ZipInputStream archive = new ZipInputStream(inputStream); for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) { String name = entry.getName(); int size = (int) entry.getSize(); if (size > 0) { byte[] b = new byte[size]; int rb = 0; int chunk = 0; while (((int) size - rb) > 0) { chunk = archive.read(b, rb, (int) size - rb); if (chunk == -1) { break; } rb += chunk; } String message = XmlUtils.readXml(b, 0, rb, fileEncoding, false); if (StringUtils.isNotEmpty(result)) { result += "\n"; } lastState = processMessage(adapter, message, writeSecLogMessage).getState(); result += name + ":" + lastState; } archive.closeEntry(); } archive.close(); session.put("state", lastState); session.put("result", result); return ""; }
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/* w w w .j av a2 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; }