List of usage examples for java.util.zip ZipInputStream read
public int read(byte[] b, int off, int len) throws IOException
From source file:com.marklogic.contentpump.CompressedAggXMLReader.java
@Override public boolean nextKeyValue() throws IOException, InterruptedException { if (zipIn == null || xmlSR == null) { hasNext = false;/*from w w w .java 2 s . co m*/ return false; } try { if (codec.equals(CompressionCodec.ZIP)) { ZipInputStream zis = (ZipInputStream) zipIn; if (xmlSR.hasNext()) { hasNext = nextRecordInAggregate(); if (hasNext) { return true; } } // xmlSR does not hasNext, // if there is next zipEntry, close xmlSR then create a new one ByteArrayOutputStream baos; while (true) { try { currZipEntry = ((ZipInputStream) zipIn).getNextEntry(); if (currZipEntry == null) { break; } if (currZipEntry.getSize() == 0) { continue; } subId = currZipEntry.getName(); long size = currZipEntry.getSize(); if (size == -1) { baos = new ByteArrayOutputStream(); } else { baos = new ByteArrayOutputStream((int) size); } int nb; while ((nb = zis.read(buf, 0, buf.length)) != -1) { baos.write(buf, 0, nb); } xmlSR.close(); start = 0; end = baos.size(); xmlSR = f.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()), encoding); nameSpaces.clear(); baos.close(); return nextRecordInAggregate(); } catch (IllegalArgumentException e) { LOG.warn("Skipped a zip entry in : " + file.toUri() + ", reason: " + e.getMessage()); } } // end of zip if (iterator != null && iterator.hasNext()) { //close previous zip and streams close(); initStreamReader(iterator.next()); return nextRecordInAggregate(); } //current split doesn't have more zip return false; } else if (codec.equals(CompressionCodec.GZIP)) { if (nextRecordInAggregate()) { return true; } // move to next gzip file in this split if (iterator != null && iterator.hasNext()) { // close previous zip and streams close(); initStreamReader(iterator.next()); return nextRecordInAggregate(); } return false; } } catch (XMLStreamException e) { LOG.error(e.getMessage(), e); } return true; }
From source file:InstallJars.java
/** Copy a zip entry. */ protected void copyEntry(String target, ZipInputStream zis, ZipEntry ze) throws IOException { String name = ze.getName();//w w w . j av a 2s. c o m boolean isDir = false; if (name.endsWith("/")) { name = name.substring(0, name.length() - 1); isDir = true; } String path = target + File.separator + name; path = path.replace('\\', '/'); String mod = ze.getSize() > 0 ? ("[" + ze.getCompressedSize() + ":" + ze.getSize() + "]") : ""; print("Expanding " + ze + mod + " to " + path); prepDirs(path, isDir); if (!isDir) { BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(path), BLOCK_SIZE * BLOCK_COUNT); try { byte[] buf = new byte[bufferSize]; for (int size = zis.read(buf, 0, buf.length), count = 0; size >= 0; size = zis.read(buf, 0, buf.length), count++) { // if (count % 4 == 0) print("."); os.write(buf, 0, size); } } finally { try { os.flush(); os.close(); } catch (IOException ioe) { } } } println(); }
From source file:org.latticesoft.util.common.FileUtil.java
public static void unzipFile(String src, String target) { try {/*from w ww . jav a 2 s .c om*/ BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(src); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry = null; StringBuffer sb = new StringBuffer(); byte data[] = new byte[SIZE]; while ((entry = zis.getNextEntry()) != null) { int count; sb.setLength(0); sb.append(target).append(File.separator).append(entry.getName()); if (log.isInfoEnabled()) { log.info("Unzipping to " + sb.toString()); } FileOutputStream fos = new FileOutputStream(sb.toString()); dest = new BufferedOutputStream(fos, SIZE); while ((count = zis.read(data, 0, SIZE)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } zis.close(); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } } }
From source file:org.artifactory.webapp.wicket.page.importexport.repos.ImportZipPanel.java
@Override public void onFileSaved(File file) { ZipInputStream zipinputstream = null; FileOutputStream fos = null;//from w w w. j a v a 2s . c o m File uploadedFile = null; File destFolder; try { uploadedFile = uploadForm.getUploadedFile(); zipinputstream = new ZipInputStream(new FileInputStream(uploadedFile)); ArtifactoryHome artifactoryHome = ContextHelper.get().getArtifactoryHome(); destFolder = new File(artifactoryHome.getTempUploadDir(), uploadedFile.getName() + "_extract"); FileUtils.deleteDirectory(destFolder); byte[] buf = new byte[DEFAULT_BUFF_SIZE]; ZipEntry zipentry; zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { //for each entry to be extracted String entryName = zipentry.getName(); File destFile = new File(destFolder, entryName); if (zipentry.isDirectory()) { if (!destFile.exists()) { if (!destFile.mkdirs()) { error("Cannot create directory " + destFolder); return; } } } else { fos = new FileOutputStream(destFile); int n; while ((n = zipinputstream.read(buf, 0, DEFAULT_BUFF_SIZE)) > -1) { fos.write(buf, 0, n); } fos.close(); } zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } //while setImportFromPath(destFolder); getImportForm().setVisible(true); } catch (Exception e) { String errorMessage = "Error during import of " + uploadedFile; String systemLogsPage = WicketUtils.absoluteMountPathForPage(SystemLogsPage.class); String logs = ". Please review the <a href=\"" + systemLogsPage + "\">log</a> for further information."; error(new UnescapedFeedbackMessage(errorMessage + logs)); log.error(errorMessage, e); onException(); } finally { IOUtils.closeQuietly(fos); IOUtils.closeQuietly(zipinputstream); FileUtils.deleteQuietly(uploadedFile); } }
From source file:org.intermine.web.search.ClassAttributes.java
private static void loadIndexFromDatabase(ObjectStore os, String path) { long time = System.currentTimeMillis(); LOG.info("Attempting to restore search index from database..."); if (os instanceof ObjectStoreInterMineImpl) { Database db = ((ObjectStoreInterMineImpl) os).getDatabase(); try {/* www . jav a2 s . com*/ InputStream is = MetadataManager.readLargeBinary(db, MetadataManager.SEARCH_INDEX); if (is != null) { GZIPInputStream gzipInput = new GZIPInputStream(is); ObjectInputStream objectInput = new ObjectInputStream(gzipInput); try { Object object = objectInput.readObject(); if (object instanceof LuceneIndexContainer) { index = (LuceneIndexContainer) object; LOG.info("Successfully restored search index information" + " from database in " + (System.currentTimeMillis() - time) + " ms"); LOG.info("Index: " + index); } else { LOG.warn("Object from DB has wrong class:" + object.getClass().getName()); } } finally { objectInput.close(); gzipInput.close(); } } else { LOG.warn("IS is null"); } if (index != null) { time = System.currentTimeMillis(); LOG.info("Attempting to restore search directory from database..."); is = MetadataManager.readLargeBinary(db, MetadataManager.SEARCH_INDEX_DIRECTORY); if (is != null) { if ("FSDirectory".equals(index.getDirectoryType())) { final int bufferSize = 2048; File directoryPath = new File(path + File.separator + LUCENE_INDEX_DIR); LOG.info("Directory path: " + directoryPath); // make sure we start with a new index if (directoryPath.exists()) { String[] files = directoryPath.list(); for (int i = 0; i < files.length; i++) { LOG.info("Deleting old file: " + files[i]); new File(directoryPath.getAbsolutePath() + File.separator + files[i]).delete(); } } else { directoryPath.mkdir(); } ZipInputStream zis = new ZipInputStream(is); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { LOG.info("Extracting: " + entry.getName() + " (" + entry.getSize() + " MB)"); FileOutputStream fos = new FileOutputStream( directoryPath.getAbsolutePath() + File.separator + entry.getName()); BufferedOutputStream bos = new BufferedOutputStream(fos, bufferSize); int count; byte[] data = new byte[bufferSize]; while ((count = zis.read(data, 0, bufferSize)) != -1) { bos.write(data, 0, count); } bos.flush(); bos.close(); } FSDirectory directory = FSDirectory.open(directoryPath); index.setDirectory(directory); LOG.info("Successfully restored FS directory from database in " + (System.currentTimeMillis() - time) + " ms"); time = System.currentTimeMillis(); } else if ("RAMDirectory".equals(index.getDirectoryType())) { GZIPInputStream gzipInput = new GZIPInputStream(is); ObjectInputStream objectInput = new ObjectInputStream(gzipInput); try { Object object = objectInput.readObject(); if (object instanceof FSDirectory) { RAMDirectory directory = (RAMDirectory) object; index.setDirectory(directory); time = System.currentTimeMillis() - time; LOG.info("Successfully restored RAM directory" + " from database in " + time + " ms"); } } finally { objectInput.close(); gzipInput.close(); } } else { LOG.warn("Unknown directory type specified: " + index.getDirectoryType()); } LOG.info("Directory: " + index.getDirectory()); } else { LOG.warn("index is null!"); } } } catch (ClassNotFoundException e) { LOG.error("Could not load search index", e); } catch (SQLException e) { LOG.error("Could not load search index", e); } catch (IOException e) { LOG.error("Could not load search index", e); } } else { LOG.error("ObjectStore is of wrong type!"); } }
From source file:org.saiku.service.importer.impl.LegacyImporterImpl.java
public void importLegacyReports(@NotNull IRepositoryManager repositoryManager, byte[] file) { ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(file)); //get the zipped file list entry ZipEntry ze = null;//ww w .j av a2s . c o m try { ze = zis.getNextEntry(); } catch (IOException e) { e.printStackTrace(); } String strUnzipped = ""; while (ze != null) { /* String fileName = ze.getName(); File newFile = new File(fileName); System.out.println("file unzip : "+ newFile.getAbsoluteFile()); byte[] bytes= new byte[2048]; try { zis.read(bytes, 0, 2048); } catch (IOException e) { e.printStackTrace(); } try { strUnzipped= new String( bytes, "UTF-8" ); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }*/ String fileName = ze.getName(); int size; byte[] buffer = new byte[2048]; FileOutputStream fos = null; try { fos = new FileOutputStream(fileName); } catch (FileNotFoundException e) { e.printStackTrace(); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { while ((size = zis.read(buffer, 0, buffer.length)) != -1) { bos.write(buffer, 0, size); } bos.flush(); bos.close(); strUnzipped = new String(bos.toByteArray(), "UTF-8"); } catch (IOException e) { e.printStackTrace(); } try { repositoryManager.saveInternalFile(strUnzipped, "/etc/legacyreports/" + fileName, "nt:saikufiles"); } catch (RepositoryException e) { e.printStackTrace(); } try { ze = zis.getNextEntry(); } catch (IOException e) { e.printStackTrace(); } } try { zis.closeEntry(); } catch (IOException e) { e.printStackTrace(); } try { zis.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.kchine.rpf.PoolUtils.java
public static void unzip(InputStream is, String destination, NameFilter nameFilter, int bufferSize, boolean showProgress, String taskName, int estimatedFilesNumber) { destination.replace('\\', '/'); if (!destination.endsWith("/")) destination = destination + "/"; final JTextArea area = showProgress ? new JTextArea() : null; final JProgressBar jpb = showProgress ? new JProgressBar(0, 100) : null; final JFrame f = showProgress ? new JFrame(taskName) : null; if (showProgress) { Runnable runnable = new Runnable() { public void run() { area.setFocusable(false); jpb.setIndeterminate(true); JPanel p = new JPanel(new BorderLayout()); p.add(jpb, BorderLayout.SOUTH); p.add(new JScrollPane(area), BorderLayout.CENTER); f.add(p);/*from w w w.j a v a 2 s . com*/ f.pack(); f.setSize(300, 90); f.setVisible(true); locateInScreenCenter(f); } }; if (SwingUtilities.isEventDispatchThread()) runnable.run(); else { SwingUtilities.invokeLater(runnable); } } try { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); int entriesNumber = 0; int currentPercentage = 0; int count; byte data[] = new byte[bufferSize]; ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (!entry.isDirectory() && (nameFilter == null || nameFilter.accept(entry.getName()))) { String entryName = entry.getName(); prepareFileDirectories(destination, entryName); String destFN = destination + File.separator + entry.getName(); FileOutputStream fos = new FileOutputStream(destFN); BufferedOutputStream dest = new BufferedOutputStream(fos, bufferSize); while ((count = zis.read(data, 0, bufferSize)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); if (showProgress) { ++entriesNumber; final int p = (int) (100 * entriesNumber / estimatedFilesNumber); if (p > currentPercentage) { currentPercentage = p; final JTextArea fa = area; final JProgressBar fjpb = jpb; SwingUtilities.invokeLater(new Runnable() { public void run() { fjpb.setIndeterminate(false); fjpb.setValue(p); fa.setText("\n" + p + "%" + " Done "); } }); SwingUtilities.invokeLater(new Runnable() { public void run() { fa.setCaretPosition(fa.getText().length()); fa.repaint(); fjpb.repaint(); } }); } } } } zis.close(); if (showProgress) { f.dispose(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:edu.ku.brc.specify.config.ResourceImportExportDlg.java
/** * @param zin/* www .j a v a 2 s. com*/ * @param entry * @return the contents of entry. * @throws IOException */ protected String readZipEntryToString(final ZipInputStream zin, final ZipEntry entry) throws IOException { StringBuilder result = new StringBuilder(); byte[] bytes = new byte[100]; int bytesRead = zin.read(bytes, 0, 100); while (bytesRead > 0) { result.append(new String(bytes, 0, bytesRead)); bytesRead = zin.read(bytes, 0, 100); } return result.toString(); }
From source file:org.sakaiproject.importer.impl.handlers.ResourcesHandler.java
protected void addAllResources(InputStream archive, String path, int notifyOption) { ZipInputStream zipStream = new ZipInputStream(archive); ZipEntry entry;/*from ww w. j av a 2s .c o m*/ String contentType; if (path.charAt(0) == '/') { path = path.substring(1); } if (!path.endsWith("/")) { path = path + "/"; } try { while ((entry = zipStream.getNextEntry()) != null) { Map resourceProps = new HashMap(); contentType = new MimetypesFileTypeMap().getContentType(entry.getName()); String title = entry.getName(); if (title.lastIndexOf("/") > 0) { title = title.substring(title.lastIndexOf("/") + 1); } resourceProps.put(ResourceProperties.PROP_DISPLAY_NAME, title); resourceProps.put(ResourceProperties.PROP_COPYRIGHT, COPYRIGHT); if (m_log.isDebugEnabled()) { m_log.debug("import ResourcesHandler about to add file entitled '" + title + "'"); } int count; ByteArrayOutputStream contents = new ByteArrayOutputStream(); byte[] data = new byte[BUFFER]; while ((count = zipStream.read(data, 0, BUFFER)) != -1) { contents.write(data, 0, count); } if (entry.isDirectory()) { addContentCollection(path + entry.getName(), resourceProps); addAllResources(new ByteArrayInputStream(contents.toByteArray()), path + entry.getName(), notifyOption); } else { addContentResource(path + entry.getName(), contentType, new ByteArrayInputStream(contents.toByteArray()), resourceProps, notifyOption); } } } catch (IOException e) { e.printStackTrace(); } }
From source file:gov.nasa.jpl.mudrod.main.MudrodEngine.java
private String decompressSVMWithSGDModel(String archiveName) throws IOException { URL scmArchive = getClass().getClassLoader().getResource(archiveName); if (scmArchive == null) { throw new IOException("Unable to locate " + archiveName + " as a classpath resource."); }//from w w w. j a va 2s .co m File tempDir = Files.createTempDirectory("mudrod").toFile(); assert tempDir.setWritable(true); File archiveFile = new File(tempDir, archiveName); FileUtils.copyURLToFile(scmArchive, archiveFile); // Decompress archive int BUFFER_SIZE = 512000; ZipInputStream zipIn = new ZipInputStream(new FileInputStream(archiveFile)); ZipEntry entry; while ((entry = zipIn.getNextEntry()) != null) { File f = new File(tempDir, entry.getName()); // If the entry is a directory, create the directory. if (entry.isDirectory() && !f.exists()) { boolean created = f.mkdirs(); if (!created) { LOG.error("Unable to create directory '{}', during extraction of archive contents.", f.getAbsolutePath()); } } else if (!entry.isDirectory()) { boolean created = f.getParentFile().mkdirs(); if (!created && !f.getParentFile().exists()) { LOG.error("Unable to create directory '{}', during extraction of archive contents.", f.getParentFile().getAbsolutePath()); } int count; byte data[] = new byte[BUFFER_SIZE]; FileOutputStream fos = new FileOutputStream(new File(tempDir, entry.getName()), false); try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) { while ((count = zipIn.read(data, 0, BUFFER_SIZE)) != -1) { dest.write(data, 0, count); } } } } return new File(tempDir, StringUtils.removeEnd(archiveName, ".zip")).toURI().toString(); }