List of usage examples for java.util.zip ZipInputStream read
public int read(byte b[]) throws IOException
b.length
bytes of data from this input stream into an array of bytes. From source file:controller.servlet.Upload.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w .j av a2 s . c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Subida de los ficheros al sistema. UploadedFile uF; UploadedFileDaoImpl uFD = new UploadedFileDaoImpl(); int numberOfCsvFiles = 0; int numberOfNotCsvFiles = 0; for (Part part : request.getParts()) { if (part.getName().equals("file")) { try (InputStream is = request.getPart(part.getName()).getInputStream()) { int i = is.available(); byte[] b = new byte[i]; if (b.length == 0) { break; } is.read(b); String fileName = obtenerNombreFichero(part); String extension = FilenameUtils.getExtension(fileName); String path = this.getServletContext().getRealPath(""); String ruta = path + File.separator + Path.UPLOADEDFILES_FOLDER + File.separator + fileName; File directorio = new File(path + File.separator + Path.UPLOADEDFILES_FOLDER); if (!directorio.exists()) { directorio.mkdirs(); } // Se sube el fichero en caso de ser zip o csv. if (extension.equals(Path.CSV_EXTENSION) || extension.equals(Path.ZIP_EXTENSION)) { try (FileOutputStream os = new FileOutputStream(ruta)) { os.write(b); } if (extension.equals(Path.CSV_EXTENSION)) { numberOfCsvFiles++; } } else { numberOfNotCsvFiles++; } // Extraccin de los ficheros incluidos en el zip. if (extension.equals(Path.ZIP_EXTENSION)) { ZipInputStream zis = new ZipInputStream( new FileInputStream(directorio + File.separator + fileName)); ZipEntry eachFile; while (null != (eachFile = zis.getNextEntry())) { File newFile = new File(directorio + File.separator + eachFile.getName()); // Se guardan los csv. if (FilenameUtils.getExtension(directorio + File.separator + eachFile.getName()) .equals(Path.CSV_EXTENSION)) { numberOfCsvFiles++; try (FileOutputStream fos = new FileOutputStream(newFile)) { int len; byte[] buffer = new byte[1024]; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } } zis.closeEntry(); // Insertar en BD uF = new UploadedFile(0, eachFile.getName(), new java.sql.Date(new Date().getTime()), false, null); uFD.createFile(uF); } else { numberOfNotCsvFiles++; } } File fileToDelete = new File( path + File.separator + Path.UPLOADEDFILES_FOLDER + File.separator + fileName); fileToDelete.delete(); } else { // Insertar en BD uF = new UploadedFile(0, fileName, new java.sql.Date(new Date().getTime()), false, null); uFD.createFile(uF); } } } } // Asignacin de valores. HttpSession session = request.getSession(true); session.setAttribute("numberOfCsvFiles", numberOfCsvFiles); session.setAttribute("numberOfNotCsvFiles", numberOfNotCsvFiles); if (numberOfCsvFiles == 0 && numberOfNotCsvFiles == 0) { session.setAttribute("error", true); } else { session.setAttribute("error", false); } processRequest(request, response); }
From source file:com.yahoo.storm.yarn.TestConfig.java
private void unzipFile(String filePath) { FileInputStream fis = null;//from w w w . ja v a 2 s .c o m ZipInputStream zipIs = null; ZipEntry zEntry = null; try { fis = new FileInputStream(filePath); zipIs = new ZipInputStream(new BufferedInputStream(fis)); while ((zEntry = zipIs.getNextEntry()) != null) { try { byte[] tmp = new byte[4 * 1024]; FileOutputStream fos = null; String opFilePath = "lib/" + zEntry.getName(); if (zEntry.isDirectory()) { LOG.debug("Create a folder " + opFilePath); if (zEntry.getName().indexOf(Path.SEPARATOR) == (zEntry.getName().length() - 1)) storm_home = opFilePath.substring(0, opFilePath.length() - 1); new File(opFilePath).mkdir(); } else { LOG.debug("Extracting file to " + opFilePath); fos = new FileOutputStream(opFilePath); int size = 0; while ((size = zipIs.read(tmp)) != -1) { fos.write(tmp, 0, size); } fos.flush(); fos.close(); } } catch (Exception ex) { ex.printStackTrace(); } } zipIs.close(); } catch (FileNotFoundException e) { LOG.warn(e.toString()); } catch (IOException e) { LOG.warn(e.toString()); } LOG.info("storm_home: " + storm_home); }
From source file:org.wso2.developerstudio.eclipse.utils.file.FileUtils.java
/** * Utility method to extract form a stream to a given directory * @param inputStream// w ww .j a va 2 s . co m * @param extractDir * @throws IOException */ public static void extractFromStream(InputStream inputStream, String extractDir) throws IOException { ZipInputStream zin = null; try { File unzipped = new File(extractDir); // Open the ZIP file zin = new ZipInputStream(inputStream); unzipped.mkdirs(); ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { String entryName = entry.getName(); File f = new File(extractDir + File.separator + entryName); if (entryName.endsWith("/") && !f.exists()) { // this is a // directory f.mkdirs(); continue; } // This is a file. Carry out File processing int lastIndexOfSlash = entryName.lastIndexOf("/"); String dirPath = ""; if (lastIndexOfSlash != -1) { dirPath = entryName.substring(0, lastIndexOfSlash); File dir = new File(extractDir + File.separator + dirPath); if (!dir.exists()) { dir.mkdirs(); } } if (!f.isDirectory()) { OutputStream out = new FileOutputStream(f); byte[] buf = new byte[40960]; // Transfer bytes from the ZIP file to the output file int len; while ((len = zin.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } } } catch (IOException e) { String msg = "Cannot unzip archive. It is probably corrupt"; System.err.println(msg); throw e; } finally { try { if (zin != null) { zin.close(); } } catch (IOException e) { throw e; } } }
From source file:com.thinkbiganalytics.feedmgr.service.ExportImportTemplateService.java
private ImportTemplate openZip(String fileName, InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; ZipInputStream zis = new ZipInputStream(inputStream); ZipEntry entry;//from www . j a v a2s .co m // while there are entries I process them ImportTemplate importTemplate = new ImportTemplate(fileName); while ((entry = zis.getNextEntry()) != null) { log.info("zip file entry: " + entry.getName()); // consume all the data from this entry ByteArrayOutputStream out = new ByteArrayOutputStream(); int len = 0; while ((len = zis.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); String outString = new String(out.toByteArray(), "UTF-8"); if (entry.getName().startsWith(NIFI_TEMPLATE_XML_FILE)) { importTemplate.setNifiTemplateXml(outString); } else if (entry.getName().startsWith(TEMPLATE_JSON_FILE)) { importTemplate.setTemplateJson(outString); } else if (entry.getName().startsWith(NIFI_CONNECTING_REUSABLE_TEMPLATE_XML_FILE)) { importTemplate.addNifiConnectingReusableTemplateXml(outString); } } zis.closeEntry(); zis.close(); if (!importTemplate.isValid()) { throw new UnsupportedOperationException( " The file you uploaded is not a valid archive. Please ensure the Zip file has been exported from the system and has 2 valid files named: " + NIFI_TEMPLATE_XML_FILE + ", and " + TEMPLATE_JSON_FILE); } importTemplate.setZipFile(true); return importTemplate; }
From source file:edu.monash.merc.system.remote.HttpHpaFileGetter.java
public boolean importHPAXML(String remoteFile, String localFile) { //use httpclient to get the remote file HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(remoteFile); ZipInputStream zis = null; FileOutputStream fos = null;//from w w w . j a v a2s .c o m try { HttpResponse response = httpClient.execute(httpGet); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { InputStream in = entity.getContent(); zis = new ZipInputStream(in); ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { String fileName = zipEntry.getName(); if (StringUtils.contains(fileName, HPA_FILE_NAME)) { System.out.println("======= found file."); File aFile = new File(localFile); fos = new FileOutputStream(aFile); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.flush(); break; } } } } else { throw new DMRemoteException("can't get the file from " + remoteFile); } } catch (Exception ex) { throw new DMRemoteException(ex); } finally { try { if (fos != null) { fos.close(); } if (zis != null) { zis.closeEntry(); zis.close(); } httpClient.getConnectionManager().shutdown(); } catch (Exception e) { //ignore whatever caught } } return true; }
From source file:fr.fastconnect.factory.tibco.bw.fcunit.PrepareTestMojo.java
private void removeFileInZipContaining(List<String> contentFilter, File zipFile) throws ZipException, IOException { ZipScanner zs = new ZipScanner(); zs.setSrc(zipFile);/*from w w w . ja v a2 s. c o m*/ String[] includes = { "**/*.process" }; zs.setIncludes(includes); //zs.setCaseSensitive(true); zs.init(); zs.scan(); File originalProjlib = zipFile; // to be overwritten File tmpProjlib = new File(zipFile.getAbsolutePath() + ".tmp"); // to read FileUtils.copyFile(originalProjlib, tmpProjlib); ZipFile listZipFile = new ZipFile(tmpProjlib); ZipInputStream readZipFile = new ZipInputStream(new FileInputStream(tmpProjlib)); ZipOutputStream writeZipFile = new ZipOutputStream(new FileOutputStream(originalProjlib)); ZipEntry zipEntry; boolean keep; while ((zipEntry = readZipFile.getNextEntry()) != null) { keep = true; for (String filter : contentFilter) { keep = keep && !containsString(filter, listZipFile.getInputStream(zipEntry)); } // if (!containsString("<pd:type>com.tibco.pe.core.OnStartupEventSource</pd:type>", listZipFile.getInputStream(zipEntry)) // && !containsString("<pd:type>com.tibco.plugin.jms.JMSTopicEventSource</pd:type>", listZipFile.getInputStream(zipEntry))) { if (keep) { writeZipFile.putNextEntry(zipEntry); int len = 0; byte[] buf = new byte[1024]; while ((len = readZipFile.read(buf)) >= 0) { writeZipFile.write(buf, 0, len); } writeZipFile.closeEntry(); //getLog().info("written"); } else { getLog().info("removed " + zipEntry.getName()); } } writeZipFile.close(); readZipFile.close(); listZipFile.close(); originalProjlib.setLastModified(originalProjlib.lastModified() - 100000); }
From source file:com.cisco.ca.cstg.pdi.services.ConfigurationServiceImpl.java
private void copyZipFile(File file, String path) throws FileNotFoundException, IOException { ZipInputStream zipIs = null; ZipEntry zEntry = null;//from w ww . j a v a2s .co m FileInputStream fis = null; try { fis = new FileInputStream(file); zipIs = new ZipInputStream(new BufferedInputStream(fis)); while ((zEntry = zipIs.getNextEntry()) != null) { byte[] tmp = new byte[4 * 1024]; File newFile = new File(zEntry.getName()); String directory = newFile.getParent(); if (directory == null) { try (FileOutputStream fos = new FileOutputStream(path + File.separator + zEntry.getName())) { int size = 0; while ((size = zipIs.read(tmp)) != -1) { fos.write(tmp, 0, size); fos.flush(); } } } } } catch (IOException e) { LOGGER.error("Error occured while trying to copy zip file.", e); throw e; } finally { if (zipIs != null) { zipIs.close(); } if (fis != null) { fis.close(); } file.delete(); } }
From source file:net.wastl.webmail.config.ExtConfigListener.java
/** * @param baseDir/*from w ww. j a va 2s. co m*/ * Parent directory of metaFile * @param metaFile * Properties file to be created. IT CAN NOT EXIST YET! * @throws IOException * if fail to create new XML Storage system */ protected void installXmlStorage(File baseDir, File metaFile) throws IOException { log.warn("Will attempt install a brand new data store"); final File dataDir = new File(baseDir, "data"); if (dataDir.exists()) throw new IOException("Target data path dir already exists: " + dataDir.getAbsolutePath()); if (!baseDir.isDirectory()) { final File parentDir = baseDir.getParentFile(); if (!parentDir.canWrite()) throw new IOException("Cannot create base RT directory '" + baseDir.getAbsolutePath() + "'"); if (!baseDir.mkdir()) throw new IOException("Failed to create base RT directory '" + baseDir.getAbsolutePath() + "'"); log.debug("Created base RT dir '" + baseDir.getAbsolutePath() + "'"); mkLockFile(); } if (!baseDir.canWrite()) throw new IOException( "Do not have privilegest to create meta file '" + metaFile.getAbsolutePath() + "'"); if (!dataDir.mkdir()) throw new IOException("Failed to create data directory '" + dataDir.getAbsolutePath() + "'"); log.debug("Created data dir '" + dataDir.getAbsolutePath() + "'"); // In my experience, you can't trust the return values of the // File.mkdir() method. But the file creations or extractions // wild fail below in that case, so that's no problem. // Could create a Properties object and save it, but why? final PrintWriter pw = new PrintWriter(new FileWriter(metaFile)); try { pw.println("webmail.data.path: ${rtconfig.dir}/data"); pw.println("webmail.mimetypes.filepath: " + "${rtconfig.dir}/mimetypes.txt"); pw.flush(); } finally { pw.close(); } final InputStream zipFileStream = getClass().getResourceAsStream("/data.zip"); if (zipFileStream == null) throw new IOException("Zip file 'data.zip' missing from web application"); final InputStream mimeInStream = getClass().getResourceAsStream("/mimetypes.txt"); if (mimeInStream == null) throw new IOException("Mime-types file 'mimetypes.txt' missing from web application"); ZipEntry entry; File newNode; FileOutputStream fileStream; long fileSize, bytesRead; int i; final byte[] buffer = new byte[10240]; final FileOutputStream mimeOutStream = new FileOutputStream(new File(baseDir, "mimetypes.txt")); try { while ((i = mimeInStream.read(buffer)) > 0) { mimeOutStream.write(buffer, 0, i); } mimeOutStream.flush(); } finally { mimeOutStream.close(); } log.debug("Extracted mime types file"); final ZipInputStream zipStream = new ZipInputStream(zipFileStream); try { while ((entry = zipStream.getNextEntry()) != null) { newNode = new File(dataDir, entry.getName()); if (entry.isDirectory()) { if (!newNode.mkdir()) throw new IOException( "Failed to extract dir '" + entry.getName() + "' from 'data.zip' file"); log.debug("Extracted dir '" + entry.getName() + "' to '" + newNode.getAbsolutePath() + "'"); zipStream.closeEntry(); continue; } fileSize = entry.getSize(); fileStream = new FileOutputStream(newNode); try { bytesRead = 0; while ((i = zipStream.read(buffer)) > 0) { fileStream.write(buffer, 0, i); bytesRead += i; } fileStream.flush(); } finally { fileStream.close(); } zipStream.closeEntry(); if (bytesRead != fileSize) throw new IOException("Expected " + fileSize + " bytes for '" + entry.getName() + ", but extracted " + bytesRead + " bytes to '" + newNode.getAbsolutePath() + "'"); log.debug("Extracted file '" + entry.getName() + "' to '" + newNode.getAbsolutePath() + "'"); } } finally { zipStream.close(); } }
From source file:org.moe.cli.manager.SourceCocoaPodsManager.java
private void extractXCodeProject() throws IOException { InputStream resStream = null; ZipInputStream zis = null; try {/*from w w w . j a v a 2 s .c o m*/ ClassLoader cl = this.getClass().getClassLoader(); resStream = cl.getResourceAsStream("template.xcodeproj.zip"); if (resStream != null) { zis = new ZipInputStream(resStream); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { File newDir = new File(JPod, entry.getName()); if (!newDir.exists()) { newDir.mkdirs(); } } else { File newDest = new File(JPod, entry.getName()); FileOutputStream output = null; try { output = new FileOutputStream(newDest); byte[] buffer = new byte[1024]; int len = 0; while ((len = zis.read(buffer)) > 0) { output.write(buffer, 0, len); } } finally { if (output != null) { output.close(); } } } } } else { throw new InvalidParameterException("Could not find Xcode project in resources"); } } finally { if (resStream != null) { resStream.close(); } if (zis != null) { zis.close(); } } }
From source file:org.sead.sda.LandingPage.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("tag") != null || request.getRequestURI().contains("/sda/list")) { String tag = ""; if (request.getParameter("tag") != null) { tag = request.getParameter("tag"); } else {/* ww w. j a va 2 s.com*/ tag = request.getRequestURI().split("/sda/list=")[1]; } // here we check whether the BagIt zip file for this RO exists in SDA SFTP sftp = new SFTP(); String bagName = getBagNameFromId(tag); if (sftp.doesFileExist(Constants.sdaPath + bagName + "/" + bagName + ".zip")) { System.out.println("Bag Exists in SDA..."); request.setAttribute("bagExists", "true"); } sftp.disConnectSessionAndChannel(); request.setAttribute("obTag", tag); request.setAttribute("landingPageUrl", Constants.landingPage); String keyList_cp = "@id|status|message|preferences"; String keyList_ore = "keyword|contact|creator|publication date|title|abstract|license|is version of|similarto|title|describes|@context|aggregates|has part|identifier|label|size"; // keyMapList = new HashMap<String, String>(); Shimcalls shim = new Shimcalls(); // Fix: accessing RO from c3pr here is wrong. we have to access the ore map in the // published package and read properties from that. JSONObject cp = shim.getResearchObject(tag); if (cp.isEmpty()) { RequestDispatcher dispatcher = request.getRequestDispatcher("/ro.jsp"); request.setAttribute("roExists", "false"); dispatcher.forward(request, response); return; } request.setAttribute("roExists", "true"); SeadMon.addLog(MonConstants.Components.LANDING_PAGE, tag, MonConstants.EventType.ACCESS); keyMap(cp, keyList_cp); shim.getObjectID(cp, "@id"); String oreUrl = shim.getID(); JSONObject oreFile = shim.getResearchObjectORE(oreUrl); keyMap(oreFile, keyList_ore); JSONObject describes = (JSONObject) oreFile.get(keyMapList.get("describes")); Map<String, List<String>> roProperties = new HashMap<String, List<String>>(); Map<String, String> downloadList = new HashMap<String, String>(); Map<String, String> linkedHashMap = new LinkedHashMap<String, String>(); Map<String, String> linkedHashMapTemp = new LinkedHashMap<String, String>(); Map<String, String> newDownloadList = new LinkedHashMap<String, String>(); // extract properties from ORE JSONArray status = (JSONArray) cp.get(keyMapList.get("Status".toLowerCase())); String doi = "No DOI Found"; // handle this as an exception String pubDate = null; for (Object st : status) { JSONObject jsonStatus = (JSONObject) st; String stage = (String) jsonStatus.get("stage"); if ("Success".equals(stage)) { doi = (String) jsonStatus.get("message"); pubDate = (String) jsonStatus.get("date"); } } roProperties.put("DOI", Arrays.asList(doi)); roProperties.put("Publication Date", Arrays.asList(pubDate)); roProperties.put("Full Metadata", Arrays.asList(Constants.landingPage + "/metadata/" + tag + "/oremap")); addROProperty("Creator", describes, roProperties); // addROProperty("Publication Date", describes, roProperties); addROProperty("Title", describes, roProperties); addROProperty("Abstract", describes, roProperties); addROProperty("Contact", describes, roProperties); addROProperty("Keyword", describes, roProperties); JSONObject preferences = (JSONObject) cp.get(keyMapList.get("Preferences".toLowerCase())); //addROProperty_License("License", preferences, cp, roProperties); addROProperty("License", preferences, roProperties); // check access rights if (isRORestricted(preferences)) { request.setAttribute("accessRestricted", "true"); List<String> rights = new ArrayList<String>(); rights.add("Restricted"); roProperties.put("Access Rights", rights); } //Map<String, String> properties = new HashMap<String, String>(); //String Label = properties.get("Label"); // extract Live Data Links from ORE String liveCopy = null; if (describes.get(keyMapList.get("Is Version Of".toLowerCase())) != null) { String versionOf = describes.get(keyMapList.get("Is Version Of".toLowerCase())).toString(); if (versionOf.startsWith("http")) { liveCopy = versionOf; } else if (describes.get(keyMapList.get("similarTo".toLowerCase())) != null) { String similar = describes.get(keyMapList.get("similarTo".toLowerCase())).toString(); similar = similar.substring(0, similar.indexOf("/resteasy") + 1); liveCopy = similar + "#collection?uri=" + versionOf; } } if (liveCopy != null) { List<String> liveCopyList = new ArrayList<String>(); if (shim.validUrl(liveCopy)) { liveCopyList.add(liveCopy); } else { liveCopyList.add("Not Available"); } roProperties.put("Live Data Links", liveCopyList); } // set properties as an attribute request.setAttribute("roProperties", roProperties); // String title = describes.get(keyMapList.get("Title".toLowerCase())).toString(); // extract file names from tar archive in SDA String requestURI = request.getRequestURI(); if (requestURI.contains("/sda/list")) { int c = 0; String[] requestURIsda = requestURI.split("/"); for (String item : requestURIsda) { if (item.equals("sda")) { c++; } } if (c % 2 != 0) { //extract RO hierarchy try { NewOREmap oreMap = new NewOREmap(oreFile, keyMapList); downloadList = oreMap.getHierarchy(); Set<String> nameList = downloadList.keySet(); for (String name : nameList) { String[] name_split = name.split("/"); String size = null; if (downloadList.get(name) != null) { int bytes = Integer.parseInt(downloadList.get(name)); int kb = bytes / 1024; int mb = kb / 1024; int gb = mb / 1024; if (bytes <= 1024) { size = bytes + " Bytes"; } else if (kb <= 1024) { size = kb + " KB"; } else if (mb <= 1024) { size = mb + " MB"; } else { size = gb + " GB"; } } String temp = null; if (name_split.length <= 2 && size != null) { temp = "<span style='padding-left:" + 30 * (name_split.length - 2) + "px'>" + name_split[name_split.length - 1] + "</span>"; linkedHashMap.put(name, temp); } else { temp = "<span style='padding-left:" + 30 * (name_split.length - 2) + "px'>" + "|__" + name_split[name_split.length - 1] + "</span>"; linkedHashMapTemp.put(name, temp); } newDownloadList.put(name, size); } for (String key : linkedHashMapTemp.keySet()) { linkedHashMap.put(key, linkedHashMapTemp.get(key)); } } catch (Exception e) { System.err.println("Landing Page OREmap error: inaccurate keys"); } } // set download list as an attribute // set linkedHashMap as an attribute } request.setAttribute("downloadList", newDownloadList); request.setAttribute("linkedHashMap", linkedHashMap); // forward the user to get_id UI RequestDispatcher dispatcher = request.getRequestDispatcher("/ro.jsp"); dispatcher.forward(request, response); } else if (!request.getRequestURI().contains("bootstrap")) { // collection title is the last part of the request URI String requestURI = request.getRequestURI(); String newURL = requestURI.substring(requestURI.lastIndexOf("sda/") + 4); String title = null; String filename = null; if (!newURL.contains("/")) { title = newURL; } else { title = newURL.split("/")[0]; filename = newURL.substring(newURL.indexOf("/") + 1); } title = URLDecoder.decode(title, "UTF-8"); newURL = URLDecoder.decode(newURL, "UTF-8"); // don't allow downloads for restricted ROs // Fix: use ORE from package Shimcalls shim = new Shimcalls(); JSONObject ro = shim.getResearchObject(title); String keyList_cp = "@id|status|message|preferences"; keyMapList = new HashMap<String, String>(); keyMap(ro, keyList_cp); if (isRORestricted((JSONObject) ro.get(keyMapList.get("Preferences".toLowerCase())))) { return; } SFTP sftp = new SFTP(); String bgName = getBagNameFromId(title); String target = Constants.sdaPath + bgName + "/" + bgName + ".zip"; if (!sftp.doesFileExist(target)) { target = Constants.sdaPath + title + "/" + title + ".tar"; } System.out.println("title " + title); System.out.println("filename " + filename); if (!title.equals("*")) { InputStream inStream = sftp.downloadFile(target); String mimeType = "application/octet-stream"; response.setContentType(mimeType); String headerKey = "Content-Disposition"; String headerValue = null; if (filename != null) { if (filename.contains("/")) { filename = filename.substring(filename.lastIndexOf("/") + 1); } headerValue = String.format("attachment; filename=\"%s\"", filename); } else { headerValue = String.format("attachment; filename=\"%s\"", target.substring(target.lastIndexOf("/") + 1)); } response.setHeader(headerKey, headerValue); OutputStream outStream = response.getOutputStream(); if (newURL.equals(title)) { //download tar file SeadMon.addLog(MonConstants.Components.LANDING_PAGE, title, MonConstants.EventType.DOWNLOAD); System.out.println("SDA download path: " + target); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } } else { //download individual files if (target.contains(".tar")) { System.out.println("SDA download path: " + Constants.sdaPath + newURL); TarArchiveInputStream myTarFile = new TarArchiveInputStream(inStream); TarArchiveEntry entry = null; String individualFiles; int offset; while ((entry = myTarFile.getNextTarEntry()) != null) { individualFiles = entry.getName(); if (individualFiles.equals(newURL)) { byte[] content = new byte[(int) entry.getSize()]; offset = 0; myTarFile.read(content, offset, content.length - offset); outStream.write(content); } } myTarFile.close(); } else { System.out.println("SDA download path: " + Constants.sdaPath + bgName + "/" + bgName + ".zip/" + bgName + "/" + newURL.substring(newURL.indexOf("/") + 1)); BufferedInputStream bin = new BufferedInputStream(inStream); ZipInputStream myZipFile = new ZipInputStream(bin); ZipEntry ze = null; while ((ze = myZipFile.getNextEntry()) != null) { if (ze.getName().equals(bgName + "/" + newURL.substring(newURL.indexOf("/") + 1))) { byte[] buffer = new byte[4096]; int len; while ((len = myZipFile.read(buffer)) != -1) { outStream.write(buffer, 0, len); } break; } } } } inStream.close(); outStream.close(); } sftp.disConnectSessionAndChannel(); } }