List of usage examples for java.util.zip ZipInputStream read
public int read(byte[] b, int off, int len) throws IOException
From source file:org.wso2.developerstudio.eclipse.test.automation.utils.server.CarbonServerManager.java
public void extractFile(String sourceFilePath, String extractedDir) throws IOException { FileOutputStream fileoutputstream = null; String fileDestination = extractedDir + File.separator; byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry;/*from w ww . j av a2 s .c o m*/ try { zipinputstream = new ZipInputStream(new FileInputStream(sourceFilePath)); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { // for each entry to be extracted String entryName = fileDestination + zipentry.getName(); entryName = entryName.replace('/', File.separatorChar); entryName = entryName.replace('\\', File.separatorChar); int n; File newFile = new File(entryName); boolean fileCreated = false; if (zipentry.isDirectory()) { if (!newFile.exists()) { fileCreated = newFile.mkdirs(); } zipentry = zipinputstream.getNextEntry(); continue; } else { File resourceFile = new File(entryName.substring(0, entryName.lastIndexOf(File.separator))); if (!resourceFile.exists()) { if (!resourceFile.mkdirs()) { break; } } } fileoutputstream = new FileOutputStream(entryName); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) { fileoutputstream.write(buf, 0, n); } fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); } catch (IOException e) { WorkbenchElementsValidator.log.error("Error on archive extraction ", e); throw new IOException("Error on archive extraction ", e); } finally { if (fileoutputstream != null) { fileoutputstream.close(); } if (zipinputstream != null) { zipinputstream.close(); } } }
From source file:com.twemyeez.picklr.InstallManager.java
public static void unzip() { // Firstly get the working directory String workingDirectory = Minecraft.getMinecraft().mcDataDir.getAbsolutePath(); // If it ends with a . then remove it if (workingDirectory.endsWith(".")) { workingDirectory = workingDirectory.substring(0, workingDirectory.length() - 1); }//ww w.jav a2s . co m // If it doesn't end with a / then add it if (!workingDirectory.endsWith("/") && !workingDirectory.endsWith("\\")) { workingDirectory = workingDirectory + "/"; } // Use a test file to see if libraries installed File file = new File(workingDirectory + "mods/mp3spi1.9.5.jar"); // If the libraries are installed, return if (file.exists()) { System.out.println("Checking " + file.getAbsolutePath()); System.out.println("Target file exists, so not downloading API"); return; } // Now try to download the libraries try { String location = "http://www.javazoom.net/mp3spi/sources/mp3spi1.9.5.zip"; // Define the URL URL url = new URL(location); // Get the ZipInputStream ZipInputStream zipInput = new ZipInputStream(new BufferedInputStream((url).openStream())); // Use a temporary ZipEntry as a buffer ZipEntry zipFile; // While there are more file entries while ((zipFile = zipInput.getNextEntry()) != null) { // Check if it is one of the file names that we want to copy Boolean required = false; if (zipFile.getName().indexOf("mp3spi1.9.5.jar") != -1) { required = true; } if (zipFile.getName().indexOf("jl1.0.1.jar") != -1) { required = true; } if (zipFile.getName().indexOf("tritonus_share.jar") != -1) { required = true; } if (zipFile.getName().indexOf("LICENSE.txt") != -1) { required = true; } // If it is, then we shall now copy it if (!zipFile.getName().replace("MpegAudioSPI1.9.5/", "").equals("") && required) { // Get the file location String tempFile = new File(zipFile.getName()).getName(); tempFile = tempFile.replace("LICENSE.txt", "MpegAudioLicence.txt"); // Initialise the target file File targetFile = (new File( workingDirectory + "mods/" + tempFile.replace("MpegAudioSPI1.9.5/", ""))); // Print a debug/alert message System.out.println("Picklr is extracting to " + workingDirectory + "mods/" + tempFile.replace("MpegAudioSPI1.9.5/", "")); // Make parent directories if required targetFile.getParentFile().mkdirs(); // If the file does not exist, create it if (!targetFile.exists()) { targetFile.createNewFile(); } // Create a buffered output stream to the destination BufferedOutputStream destinationOutput = new BufferedOutputStream( new FileOutputStream(targetFile, false), 2048); // Store the data read int bytesRead; // Data buffer byte dataBuffer[] = new byte[2048]; // While there is still data to write while ((bytesRead = zipInput.read(dataBuffer, 0, 2048)) != -1) { // Write it to the output stream destinationOutput.write(dataBuffer, 0, bytesRead); } // Flush the output destinationOutput.flush(); // Close the output stream destinationOutput.close(); } } // Close the zip input zipInput.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.exoplatform.services.jcr.ext.artifact.ArtifactManagingServiceImpl.java
public void importArtifacts(SessionProvider sp, InputStream in) throws RepositoryException, FileNotFoundException { LOG.info("Extract repository to temporary folder"); String path = System.getProperty("java.io.tmpdir") + File.separator + "maven2"; File temporaryFolder = new File(getUniqueFilename(path)); if (!temporaryFolder.mkdir()) { throw new FileNotFoundException("Cannot create temporary folder"); }/*from www . j a v a 2 s. c o m*/ ZipEntry entry; ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(in)); try { while ((entry = zipIn.getNextEntry()) != null) { if (!(entry.isDirectory() && new File(temporaryFolder + File.separator + entry.getName()).mkdir())) { int count; byte data[] = new byte[BUFFER]; File file = new File(temporaryFolder + File.separator + entry.getName()); FileUtils.touch(file); FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while ((count = zipIn.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } } } catch (IOException e) { LOG.error("Cannot get zip entry from stream", e); } finally { IOUtils.closeQuietly(zipIn); IOUtils.closeQuietly(in); } // main part - copy to JCR from temp folder // use uploading artifacts from local folder. importArtifacts(sp, temporaryFolder); try { FileUtils.deleteDirectory(temporaryFolder); } catch (IOException e) { LOG.error("Cannot remove temporary folder", e); } }
From source file:org.universAAL.itests.IntegrationTest.java
/** * Helper method for extracting zipped archive provided as input stream into * given directory.//from w w w. j av a 2s .co m * * @param is * @param destDirStr */ private void unzipInpuStream(final InputStream is, final String destDirStr) { try { File destDir = new File(destDirStr); final int BUFFER = 1024; BufferedOutputStream dest = null; ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { System.out.println("Extracting: " + entry); if (entry.getName().startsWith("META-INF")) { // META-INF (which includes MANIFEST) should not be // unpacked. It should be just ignored continue; } if (entry.isDirectory()) { File newDir = new File(destDir, entry.getName()); newDir.mkdirs(); } else { int count; byte[] data = new byte[BUFFER]; // write the files to the disk FileOutputStream fos = new FileOutputStream(new File(destDir, entry.getName())); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } } zis.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.wso2.carbon.pc.core.ProcessStore.java
public void processBPMN(String version, String type, StreamHostObject s) { InputStream barStream = s.getStream(); try {//from w w w. j ava 2 s . c om RegistryService registryService = ProcessCenterServerHolder.getInstance().getRegistryService(); if (registryService != null) { UserRegistry reg = registryService.getGovernanceSystemRegistry(); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); if (type.equals("bpmn_file")) { } else { // add each bpmn file as a new asset byte[] barContent = IOUtils.toByteArray(barStream); ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(barContent)); ZipEntry entry = null; while ((entry = zip.getNextEntry()) != null) { String entryName = entry.getName(); if (entryName.endsWith(".bpmn") || entryName.endsWith(".bpmn20.xml")) { // add bpmn xml as a separate resource StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[1024]; int read = 0; while ((read = zip.read(buffer, 0, 1024)) >= 0) { sb.append(new String(buffer, 0, read)); } String bpmnContent = sb.toString(); Resource bpmnResource = reg.newResource(); bpmnResource.setContent(bpmnContent); bpmnResource.setMediaType("text/xml"); String bpmnResourcePath = "bpmn_xml/" + entryName + "/" + version; reg.put(bpmnResourcePath, bpmnResource); // add bpmn asset String bpmnAssetName = entryName; String displayName = entryName; if (displayName.endsWith(".bpmn")) { displayName = displayName.substring(0, (entryName.length() - 5)); } String bpmnAssetPath = "bpmn/" + entryName + "/" + version; Document bpmnDoc = docBuilder.newDocument(); Element bpmnRoot = bpmnDoc.createElementNS(mns, "metadata"); bpmnDoc.appendChild(bpmnRoot); Element bpmnOverview = append(bpmnDoc, bpmnRoot, "overview", mns); appendText(bpmnDoc, bpmnOverview, "name", mns, displayName); appendText(bpmnDoc, bpmnOverview, "version", mns, version); appendText(bpmnDoc, bpmnOverview, "processpath", mns, ""); appendText(bpmnDoc, bpmnOverview, "description", mns, ""); Element bpmnAssetContentElement = append(bpmnDoc, bpmnRoot, "content", mns); appendText(bpmnDoc, bpmnAssetContentElement, "contentpath", mns, bpmnResourcePath); String bpmnAssetContent = xmlToString(bpmnDoc); Resource bpmnAsset = reg.newResource(); bpmnAsset.setContent(bpmnAssetContent); bpmnAsset.setMediaType("application/vnd.wso2-bpmn+xml"); reg.put(bpmnAssetPath, bpmnAsset); Resource storedBPMNAsset = reg.get(bpmnAssetPath); String bpmnAssetID = storedBPMNAsset.getUUID(); } } } } else { String msg = "Registry service is not available."; throw new ProcessCenterException(msg); } } catch (Exception e) { log.error("Failed to store bar archive: " + version, e); } }
From source file:org.stirrat.ecm.speedyarchiver.SpeedyArchiverServices.java
/** * Extract zip file into an archive folder. * /*from w w w . ja v a 2s . co m*/ * @param zipFilename * @param folder */ private void extractZipFile(String zipFilename, File folder) { try { File archiveFolderPath = createDestinationFolder(folder); if (archiveFolderPath == null) { throw new ServiceException("Unable to create destination folder: " + archiveFolderPath); } byte[] readBuffer = new byte[READ_BUFFER_SIZE]; ZipInputStream zipStream = null; ZipEntry zipFileEntry; zipStream = new ZipInputStream(new FileInputStream(zipFilename)); zipFileEntry = zipStream.getNextEntry(); while (zipFileEntry != null) { // convert to system folder separator char String entryName = zipFileEntry.getName().replaceAll("\\\\|/", Matcher.quoteReplacement(File.separator)); SystemUtils.trace(traceSection, "entryname " + entryName); File newFile = new File(entryName); String directory = newFile.getParent(); if (directory != null && !directory.equalsIgnoreCase("")) { SystemUtils.trace(traceSection, "creating a directory structure: " + directory); try { new File(archiveFolderPath + File.separator + directory).mkdirs(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } FileOutputStream outStream = new FileOutputStream(archiveFolderPath + File.separator + entryName); int n; while ((n = zipStream.read(readBuffer, 0, READ_BUFFER_SIZE)) > -1) { outStream.write(readBuffer, 0, n); } outStream.close(); zipStream.closeEntry(); zipFileEntry = zipStream.getNextEntry(); } zipStream.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.wso2.carbon.pc.core.ProcessStore.java
public void processBAR(String barName, String barVersion, String description, StreamHostObject s) { log.debug("Processing BPMN archive " + barName); InputStream barStream = s.getStream(); if (description == null) { description = ""; }/*from w w w . j a v a2s .co m*/ try { RegistryService registryService = ProcessCenterServerHolder.getInstance().getRegistryService(); if (registryService != null) { UserRegistry reg = registryService.getGovernanceSystemRegistry(); // add the bar asset // String barAssetContent = "<metadata xmlns='http://www.wso2.org/governance/metadata'>" + // "<overview><name>" + barName + "</name><version>" + barVersion + "</version><description>This is a test process2</description></overview></metadata>"; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements String mns = "http://www.wso2.org/governance/metadata"; Document doc = docBuilder.newDocument(); Element rootElement = doc.createElementNS(mns, "metadata"); doc.appendChild(rootElement); Element overviewElement = append(doc, rootElement, "overview", mns); appendText(doc, overviewElement, "name", mns, barName); appendText(doc, overviewElement, "version", mns, barVersion); appendText(doc, overviewElement, "description", mns, description); // add binary data of the bar asset as a separate resource Resource barResource = reg.newResource(); byte[] barContent = IOUtils.toByteArray(barStream); barResource.setContent(barContent); barResource.setMediaType("application/bar"); String barResourcePath = "bpmn_archives_binary/" + barName + "/" + barVersion; reg.put(barResourcePath, barResource); Element contentElement = append(doc, rootElement, "content", mns); appendText(doc, contentElement, "contentpath", mns, barResourcePath); // reg.addAssociation(barAssetPath, barResourcePath, "has_content"); // add each bpmn file as a new asset ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(barContent)); ZipEntry entry = null; while ((entry = zip.getNextEntry()) != null) { String entryName = entry.getName(); if (entryName.endsWith(".bpmn") || entryName.endsWith(".bpmn20.xml")) { // add bpmn xml as a separate resource StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[1024]; int read = 0; while ((read = zip.read(buffer, 0, 1024)) >= 0) { sb.append(new String(buffer, 0, read)); } String bpmnContent = sb.toString(); Resource bpmnResource = reg.newResource(); bpmnResource.setContent(bpmnContent); bpmnResource.setMediaType("text/xml"); String bpmnResourcePath = "bpmn_xml/" + barName + "." + entryName + "/" + barVersion; reg.put(bpmnResourcePath, bpmnResource); // add bpmn asset String bpmnAssetName = barName + "." + entryName; String displayName = entryName; if (displayName.endsWith(".bpmn")) { displayName = displayName.substring(0, (entryName.length() - 5)); } String bpmnAssetPath = "bpmn/" + barName + "." + entryName + "/" + barVersion; // String bpmnAssetContent = "<metadata xmlns='http://www.wso2.org/governance/metadata'>" + // "<overview><name>" + bpmnAssetName + "</name><version>" + barVersion + "</version>" + // "<description>This is a BPMN asset</description></overview></metadata>"; Document bpmnDoc = docBuilder.newDocument(); Element bpmnRoot = bpmnDoc.createElementNS(mns, "metadata"); bpmnDoc.appendChild(bpmnRoot); Element bpmnOverview = append(bpmnDoc, bpmnRoot, "overview", mns); // appendText(bpmnDoc, bpmnOverview, "name", mns, bpmnAssetName); appendText(bpmnDoc, bpmnOverview, "name", mns, displayName); appendText(bpmnDoc, bpmnOverview, "version", mns, barVersion); appendText(bpmnDoc, bpmnOverview, "package", mns, barName); appendText(bpmnDoc, bpmnOverview, "description", mns, ""); Element bpmnAssetContentElement = append(bpmnDoc, bpmnRoot, "content", mns); appendText(bpmnDoc, bpmnAssetContentElement, "contentpath", mns, bpmnResourcePath); String bpmnAssetContent = xmlToString(bpmnDoc); Resource bpmnAsset = reg.newResource(); bpmnAsset.setContent(bpmnAssetContent); bpmnAsset.setMediaType("application/vnd.wso2-bpmn+xml"); reg.put(bpmnAssetPath, bpmnAsset); Resource storedBPMNAsset = reg.get(bpmnAssetPath); String bpmnAssetID = storedBPMNAsset.getUUID(); Element bpmnElement = append(doc, rootElement, "bpmn", mns); appendText(doc, bpmnElement, "Name", mns, bpmnAssetName); appendText(doc, bpmnElement, "Path", mns, bpmnAssetPath); appendText(doc, bpmnElement, "Id", mns, bpmnAssetID); // reg.addAssociation(barAssetPath, bpmnAssetPath, "contains"); // reg.addAssociation(bpmnAssetPath, bpmnResourcePath, "has_content"); } } String barAssetContent = xmlToString(doc); Resource barAsset = reg.newResource(); barAsset.setContent(barAssetContent); barAsset.setMediaType("application/vnd.wso2-bar+xml"); String barAssetPath = "bar/admin/" + barName + "/" + barVersion; reg.put(barAssetPath, barAsset); } else { String msg = "Registry service is not available."; throw new ProcessCenterException(msg); } } catch (Exception e) { log.error("Failed to store bar archive: " + barName + " - " + barVersion, e); } }
From source file:org.sakaiproject.lessonbuildertool.cc.ZipLoader.java
private void unzip() throws FileNotFoundException, IOException { if (!unzipped) { BufferedOutputStream dest = null; InputStream fis = null;//from www . ja v a2s. c o m ZipInputStream zis = null; try { if (cc_inputStream != null) fis = cc_inputStream; else fis = new FileInputStream(cc); log.debug("unzip fis " + fis); zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { log.debug("zip name " + entry.getName()); //Fix the path to be correct for the system extracting it to String fileName = FilenameUtils.separatorsToSystem(entry.getName()); File target = new File(root, fileName); // not sure if you can put things like .. into a zip file, but be careful if (!target.getCanonicalPath().startsWith(rootPath)) throw new FileNotFoundException(target.getCanonicalPath()); if (entry.isDirectory()) { if (!target.mkdirs()) throw new IOException("Unable to make temporary directory"); } else { if (target.getParentFile().exists() == false) { target.getParentFile().mkdirs(); } int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); dest = null; log.debug("wrote file " + target); } } } catch (Exception x) { log.warn("exception " + x); } finally { if (zis != null) { try { zis.close(); } catch (Exception ignore) { } } if (fis != null) { try { fis.close(); } catch (Exception ignore) { } } if (dest != null) { try { dest.close(); } catch (Exception ignore) { } } } unzipped = true; } }
From source file:nl.knaw.dans.common.lang.file.UnzipUtil.java
private static List<File> extract(final ZipInputStream zipInputStream, String destPath, final int initialCapacityForFiles, final UnzipListener unzipListener, final long totSize) throws FileNotFoundException, IOException { if (unzipListener != null) unzipListener.onUnzipStarted(totSize); final File destPathFile = new File(destPath); if (!destPathFile.exists()) throw new FileNotFoundException(destPath); if (!destPathFile.isDirectory()) throw new IOException("Expected directory, got file."); if (!destPath.endsWith(File.separator)) destPath += File.separator; // now unzip/*from w ww .j a v a2s.co m*/ BufferedOutputStream out = null; ZipEntry entry; int count; final byte data[] = new byte[BUFFER_SIZE]; final ArrayList<File> files = new ArrayList<File>(initialCapacityForFiles); String entryname; String filename; String path; boolean cancel = false; final DefaultUnzipFilenameFilter filter = new DefaultUnzipFilenameFilter(); try { long bytesWritten = 0; while (((entry = zipInputStream.getNextEntry()) != null) && !cancel) { entryname = entry.getName(); final int fpos = entryname.lastIndexOf(File.separator); if (fpos >= 0) { path = entryname.substring(0, fpos); filename = entryname.substring(fpos + 1); } else { path = ""; filename = new String(entryname); } if (!filter.accept(destPathFile, filename)) { // file filtered out continue; } if (entry.isDirectory()) { if (!createPath(destPath, entryname, files, filter)) // directory filtered out continue; } else { if (!StringUtils.isBlank(path)) { if (!createPath(destPath, path, files, filter)) // path filtered out continue; } final String absFilename = destPath + entryname; final FileOutputStream fos = new FileOutputStream(absFilename); out = new BufferedOutputStream(fos, BUFFER_SIZE); try { // inner loop while ((count = zipInputStream.read(data, 0, BUFFER_SIZE)) != -1) { out.write(data, 0, count); bytesWritten += count; if (unzipListener != null) cancel = !unzipListener.onUnzipUpdate(bytesWritten, totSize); if (cancel) break; } out.flush(); } finally { out.close(); files.add(new File(absFilename)); } } } } finally { zipInputStream.close(); // rollback? if (cancel) { // first remove files for (final File file : files) { if (!file.isDirectory()) file.delete(); } // then folders for (final File file : files) { if (file.isDirectory()) file.delete(); } files.clear(); } } if (unzipListener != null) unzipListener.onUnzipComplete(files, cancel); return files; }
From source file:org.candlepin.sync.Importer.java
/** * Create a tar.gz archive of the exported directory. * * @param exportDir Directory where Candlepin data was exported. * @return File reference to the new archive tar.gz. */// w w w.j a v a 2 s.c om private File extractArchive(File tempDir, File exportFile) throws IOException, ImportExtractionException { log.debug("Extracting archive to: " + tempDir.getAbsolutePath()); byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; try { zipinputstream = new ZipInputStream(new FileInputStream(exportFile)); ZipEntry zipentry = zipinputstream.getNextEntry(); if (zipentry == null) { throw new ImportExtractionException( i18n.tr("The archive {0} is not " + "a properly compressed file or is empty", exportFile.getName())); } while (zipentry != null) { //for each entry to be extracted String entryName = zipentry.getName(); if (log.isDebugEnabled()) { log.debug("entryname " + entryName); } File newFile = new File(entryName); String directory = newFile.getParent(); if (directory != null) { new File(tempDir, directory).mkdirs(); } FileOutputStream fileoutputstream = null; try { fileoutputstream = new FileOutputStream(new File(tempDir, entryName)); int n; while ((n = zipinputstream.read(buf, 0, 1024)) > -1) { fileoutputstream.write(buf, 0, n); } } finally { if (fileoutputstream != null) { fileoutputstream.close(); } } zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } } finally { if (zipinputstream != null) { zipinputstream.close(); } } return new File(tempDir.getAbsolutePath(), "export"); }