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:plugin.notes.gui.NotesView.java
/** * Unzips one file from a zipinputstream * *@param zin Zip input stream *@param homeDir Directory to unzip the file to *@param entry Description of the Parameter *@exception IOException read or write error */// w w w. jav a 2 s . c o m private void unzip(ZipInputStream zin, String entry, File homeDir) throws IOException { // TODO: This function really should be in MiscUtils as a static File outFile = new File(homeDir.getPath() + File.separator + entry); File parentDir = outFile.getParentFile(); parentDir.mkdirs(); outFile.createNewFile(); FileOutputStream out = new FileOutputStream(outFile); byte[] b = new byte[512]; int len = 0; while ((len = zin.read(b)) != -1) { out.write(b, 0, len); } out.close(); }
From source file:fr.vdl.android.holocolors.HoloColorsDialog.java
private void unzipFile(File zipFile) throws Exception { File outputFolder = new File(resPathTextField.getText()); boolean overwriteAll = false; boolean overwriteNone = false; Object[] overwriteOptions = { "Overwrite this file", "Overwrite all", "Do not overwrite this file", "Do not overwrite any file" }; ZipInputStream zis = null; byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; try {//from www .jav a 2 s .co m zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String fileName = ze.getName().replaceFirst("res/", ""); File newFile = new File(outputFolder + File.separator + fileName); new File(newFile.getParent()).mkdirs(); boolean overwrite = overwriteAll || (!newFile.exists()); if (newFile.exists() && newFile.isFile() && !overwriteAll && !overwriteNone) { int option = JOptionPane.showOptionDialog(ahcPanel, newFile.getName() + " already exists, overwrite ?", "File exists", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon(getClass().getResource("/icons/H64.png")), overwriteOptions, overwriteOptions[0]); switch (option) { case 0: overwrite = true; break; case 1: overwrite = true; overwriteAll = true; break; case 2: overwrite = false; break; case 3: overwrite = false; overwriteNone = true; break; default: overwrite = false; } } if (overwrite && !fileName.endsWith(File.separator)) { FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } finally { if (zis != null) { try { zis.close(); } catch (IOException e) { } } } }
From source file:org.pentaho.di.trans.steps.zipfile.ZipFile.java
private void zipFile() throws KettleException { String localrealZipfilename = KettleVFS.getFilename(data.zipFile); boolean updateZip = false; byte[] buffer = null; OutputStream dest = null;/*from w ww . j a v a 2s .co m*/ BufferedOutputStream buff = null; ZipOutputStream out = null; InputStream in = null; ZipInputStream zin = null; ZipEntry entry = null; File tempFile = null; HashSet<String> fileSet = new HashSet<String>(); try { updateZip = (data.zipFile.exists() && meta.isOverwriteZipEntry()); if (updateZip) { // the Zipfile exists // and we weed to update entries // Let's create a temp file File fileZip = getFile(localrealZipfilename); tempFile = File.createTempFile(fileZip.getName(), null); // delete it, otherwise we cannot rename existing zip to it. tempFile.delete(); updateZip = fileZip.renameTo(tempFile); } // Prepare Zip File buffer = new byte[18024]; dest = KettleVFS.getOutputStream(localrealZipfilename, false); buff = new BufferedOutputStream(dest); out = new ZipOutputStream(buff); if (updateZip) { // User want to append files to existing Zip file // The idea is to rename the existing zip file to a temporary file // and then adds all entries in the existing zip along with the new files, // excluding the zip entries that have the same name as one of the new files. zin = new ZipInputStream(new FileInputStream(tempFile)); entry = zin.getNextEntry(); while (entry != null) { String name = entry.getName(); if (!fileSet.contains(name)) { // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(name)); // Transfer bytes from the ZIP file to the output file int len; while ((len = zin.read(buffer)) > 0) { out.write(buffer, 0, len); } fileSet.add(name); } entry = zin.getNextEntry(); } // Close the streams zin.close(); } // Set the method out.setMethod(ZipOutputStream.DEFLATED); out.setLevel(Deflater.BEST_COMPRESSION); // Associate a file input stream for the current file in = KettleVFS.getInputStream(data.sourceFile); // Add ZIP entry to output stream. // String relativeName = data.sourceFile.getName().getBaseName(); if (meta.isKeepSouceFolder()) { // Get full filename relativeName = KettleVFS.getFilename(data.sourceFile); if (data.baseFolder != null) { // Remove base folder data.baseFolder += Const.FILE_SEPARATOR; relativeName = relativeName.replace(data.baseFolder, ""); } } if (!fileSet.contains(relativeName)) { out.putNextEntry(new ZipEntry(relativeName)); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } } catch (Exception e) { throw new KettleException(BaseMessages.getString(PKG, "ZipFile.ErrorCreatingZip"), e); } finally { try { if (in != null) { // Close the current file input stream in.close(); } if (out != null) { // Close the ZipOutPutStream out.flush(); out.closeEntry(); out.close(); } if (buff != null) { buff.close(); } if (dest != null) { dest.close(); } // Delete Temp File if (tempFile != null) { tempFile.delete(); } fileSet = null; } catch (Exception e) { /* Ignore */ } } }
From source file:freenet.client.ArchiveManager.java
private void handleZIPArchive(ArchiveStoreContext ctx, FreenetURI key, InputStream data, String element, ArchiveExtractCallback callback, MutableBoolean gotElement, boolean throwAtExit, ClientContext context) throws ArchiveFailureException, ArchiveRestartException { if (logMINOR) Logger.minor(this, "Handling a ZIP Archive"); ZipInputStream zis = null; try {/*w w w .ja v a2s . co m*/ zis = new ZipInputStream(data); // MINOR: Assumes the first entry in the zip is a directory. ZipEntry entry; byte[] buf = new byte[32768]; HashSet<String> names = new HashSet<String>(); boolean gotMetadata = false; outerZIP: while (true) { entry = zis.getNextEntry(); if (entry == null) break; if (entry.isDirectory()) continue; String name = stripLeadingSlashes(entry.getName()); if (names.contains(name)) { Logger.error(this, "Duplicate key " + name + " in archive " + key); continue; } long size = entry.getSize(); if (name.equals(".metadata")) gotMetadata = true; if (size > maxArchivedFileSize && !name.equals(element)) { addErrorElement(ctx, key, name, "File too big: " + maxArchivedFileSize + " greater than current archived file size limit " + maxArchivedFileSize, true); } else { // Read the element long realLen = 0; Bucket output = tempBucketFactory.makeBucket(size); OutputStream out = output.getOutputStream(); try { int readBytes; while ((readBytes = zis.read(buf)) > 0) { out.write(buf, 0, readBytes); readBytes += realLen; if (readBytes > maxArchivedFileSize) { addErrorElement(ctx, key, name, "File too big: " + maxArchivedFileSize + " greater than current archived file size limit " + maxArchivedFileSize, true); out.close(); out = null; output.free(); continue outerZIP; } } } finally { if (out != null) out.close(); } if (size <= maxArchivedFileSize) { addStoreElement(ctx, key, name, output, gotElement, element, callback, context); names.add(name); trimStoredData(); } else { // We are here because they asked for this file. callback.gotBucket(output, context); gotElement.value = true; addErrorElement( ctx, key, name, "File too big: " + size + " greater than current archived file size limit " + maxArchivedFileSize, true); } } } // If no metadata, generate some if (!gotMetadata) { generateMetadata(ctx, key, names, gotElement, element, callback, context); trimStoredData(); } if (throwAtExit) throw new ArchiveRestartException("Archive changed on re-fetch"); if ((!gotElement.value) && element != null) callback.notInArchive(context); } catch (IOException e) { throw new ArchiveFailureException("Error reading archive: " + e.getMessage(), e); } finally { if (zis != null) { try { zis.close(); } catch (IOException e) { Logger.error(this, "Failed to close stream: " + e, e); } } } }
From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java
private boolean unpackZip(String path, String zipname) { InputStream is;//ww w . ja va2 s . c o m ZipInputStream zis; BufferedInputStream bis; try { String filename; is = new FileInputStream(path + zipname); bis = new BufferedInputStream(is); zis = new ZipInputStream(bis); ZipEntry ze; // byte[] buffer = new byte[1024]; // int count; long fileSize = 0; //Gesamtdownloadgre bestimmen // while ((ze = zis.getNextEntry()) != null) // { ze = zis.getNextEntry(); fileSize = ze.getSize() + fileSize; // } int fileSizeInKB = (int) (fileSize / 1024); Message msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UNZIP_STARTED, fileSizeInKB, 0, ""); activityHandler.sendMessage(msg); int bytesRead = 0, totalRead = 0; FileInputStream gis = new FileInputStream(path + zipname); BufferedInputStream fis = new BufferedInputStream(gis); ZipInputStream dis = new ZipInputStream(fis); while ((ze = dis.getNextEntry()) != null) { // zapis do souboru filename = ze.getName(); // Need to create directories if not exists, or // it will generate an Exception... if (ze.isDirectory()) { File fmd = new File(path + filename); fmd.mkdirs(); continue; } // // BufferedInputStream inStream = new BufferedInputStream(mFTPClient.retrieveFileStream(ftpPathName)); // File outFile = new File(fileName); FileOutputStream fileStream = new FileOutputStream(path + filename); byte[] data = new byte[KleFuEntry.DOWNLOAD_BUFFER_SIZE]; while (!isInterrupted() && (bytesRead = zis.read(data)) >= 0) { fileStream.write(data, 0, bytesRead); // update progress bar totalRead += bytesRead; int totalReadInKB = totalRead / 1024; msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UPDATE_PROGRESS_BAR, totalReadInKB, 0); activityHandler.sendMessage(msg); } // fileStream.close(); // inStream.close(); // FileOutputStream fout = new FileOutputStream(path + filename); // // while ((count = zis.read(buffer)) != -1) // { // fout.write(buffer, 0, count); // } // // fout.close(); // zis.closeEntry(); } zis.close(); dis.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
From source file:org.geoserver.wps.gs.download.DownloadProcessTest.java
/** * Private method for decoding a Shapefile * //from w w w .ja v a2 s .c om * @param input the input shp * @return the object a {@link SimpleFeatureCollection} object related to the shp file. * @throws Exception the exception */ private Object decodeShape(InputStream input) throws Exception { // create the temp directory and register it as a temporary resource File tempDir = IOUtils.createRandomDirectory(IOUtils.createTempDirectory("shpziptemp").getAbsolutePath(), "download-process", "download-services"); // unzip to the temporary directory ZipInputStream zis = null; File shapeFile = null; File zipFile = null; // extract shp-zip file try { zis = new ZipInputStream(input); ZipEntry entry = null; // Cycle on all the entries and copies the input shape in the target directory while ((entry = zis.getNextEntry()) != null) { String name = entry.getName(); File file = new File(tempDir, entry.getName()); if (entry.isDirectory()) { file.mkdir(); } else { if (file.getName().toLowerCase().endsWith(".shp")) { shapeFile = file; } else if (file.getName().toLowerCase().endsWith(".zip")) { zipFile = file; } int count; byte data[] = new byte[4096]; // write the files to the disk FileOutputStream fos = null; try { fos = new FileOutputStream(file); while ((count = zis.read(data)) != -1) { fos.write(data, 0, count); } fos.flush(); } finally { if (fos != null) { fos.close(); } } } zis.closeEntry(); } } finally { if (zis != null) { zis.close(); } } // Read the shapefile if (shapeFile == null) { if (zipFile != null) return decodeShape(new FileInputStream(zipFile)); else { FileUtils.deleteDirectory(tempDir); throw new IOException("Could not find any file with .shp extension in the zip file"); } } else { ShapefileDataStore store = new ShapefileDataStore(DataUtilities.fileToURL(shapeFile)); return store.getFeatureSource().getFeatures(); } }
From source file:org.sakaiproject.tool.assessment.contentpackaging.ImportService.java
public String unzipImportFile(String filename) { FileInputStream fileInputStream = null; FileOutputStream ofile = null; ZipInputStream zipStream = null; ZipEntry entry = null;/*w w w. j a v a 2s . c o m*/ ExternalContext external = FacesContext.getCurrentInstance().getExternalContext(); StringBuilder unzipLocation = new StringBuilder( (String) ((ServletContext) external.getContext()).getAttribute("FILEUPLOAD_REPOSITORY_PATH")); log.debug("****" + unzipLocation); unzipLocation.append("/jsf/upload_tmp/qti_imports/"); unzipLocation.append(AgentFacade.getAgentString()); unzipLocation.append("/unzip_files/"); unzipLocation.append(Long.toString(new java.util.Date().getTime())); try { fileInputStream = new FileInputStream(new File(filename)); byte[] data = new byte[fileInputStream.available()]; fileInputStream.read(data, 0, fileInputStream.available()); File dir = new File(unzipLocation.toString()); // directory where file would be saved if (!dir.exists()) { if (!dir.mkdirs()) { log.error("unable to mkdir " + dir.getPath()); } } Set dirsMade = new TreeSet(); zipStream = new ZipInputStream(new ByteArrayInputStream(data)); entry = (ZipEntry) zipStream.getNextEntry(); // Get the name of the imported zip file name. The value of "filename" has timestamp append to it. String tmpName = filename.substring(filename.lastIndexOf("/") + 1); qtiFilename = "exportAssessment.xml"; ArrayList xmlFilenames = new ArrayList(); while (entry != null) { String zipName = entry.getName(); int ix = zipName.lastIndexOf('/'); if (ix > 0) { String dirName = zipName.substring(0, ix); if (!dirsMade.contains(dirName)) { File d = new File(dir.getPath() + "/" + dirName); // If it already exists as a dir, don't do anything if (!(d.exists() && d.isDirectory())) { // Try to create the directory, warn if it fails if (!d.mkdirs()) { log.error("unable to mkdir " + dir.getPath() + "/" + dirName); } dirsMade.add(dirName); } } } File zipEntryFile = new File(dir.getPath() + "/" + entry.getName()); if (!zipEntryFile.isDirectory()) { ofile = new FileOutputStream(zipEntryFile); byte[] buffer = new byte[1024 * 10]; int bytesRead; while ((bytesRead = zipStream.read(buffer)) != -1) { ofile.write(buffer, 0, bytesRead); } } // Now try to get the QTI xml file name from the imsmanifest.xml if ("imsmanifest.xml".equals(entry.getName())) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(zipEntryFile); doc.getDocumentElement().normalize(); NodeList nodeLst = doc.getElementsByTagName("resource"); Node fstNode = nodeLst.item(0); NamedNodeMap namedNodeMap = fstNode.getAttributes(); qtiFilename = namedNodeMap.getNamedItem("href").getNodeValue(); } catch (Exception e) { log.error("error parsing imsmanifest.xml"); } } else if (entry.getName() != null && entry.getName().trim().endsWith(".xml")) { xmlFilenames.add(entry.getName().trim()); } zipStream.closeEntry(); entry = zipStream.getNextEntry(); } // If the QTI file doesn't exist in the zip, // we guess the name might be either exportAssessment.xml or the same as the zip file name if (!xmlFilenames.contains(qtiFilename.trim())) { if (xmlFilenames.contains("exportAssessment.xml")) { qtiFilename = "exportAssessment.xml"; } else { qtiFilename = tmpName.substring(0, tmpName.lastIndexOf("_")) + ".xml"; } } } catch (FileNotFoundException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); e.printStackTrace(); } finally { if (ofile != null) { try { ofile.close(); } catch (IOException e) { log.error(e.getMessage()); } } if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { log.error(e.getMessage()); } } if (zipStream != null) { try { zipStream.close(); } catch (IOException e) { log.error(e.getMessage()); } } } return unzipLocation.toString(); }
From source file:org.opendatakit.tables.tasks.InitializeTask.java
private void extractFromRawZip(int resourceId, boolean overwrite, ArrayList<String> result) { String message = null;/*from w w w . j a v a2 s . com*/ AssetFileDescriptor fd = null; try { fd = mContext.getResources().openRawResourceFd(resourceId); final long size = fd.getLength() / 2L; // apparently over-counts by 2x? InputStream rawInputStream = null; try { rawInputStream = fd.createInputStream(); ZipInputStream zipInputStream = null; ZipEntry entry = null; try { // count the number of files in the zip zipInputStream = new ZipInputStream(rawInputStream); int totalFiles = 0; while ((entry = zipInputStream.getNextEntry()) != null) { message = null; if (isCancelled()) { message = "cancelled"; result.add(entry.getName() + " " + message); break; } ++totalFiles; } zipInputStream.close(); // and re-open the stream, reading it this time... fd = mContext.getResources().openRawResourceFd(resourceId); rawInputStream = fd.createInputStream(); zipInputStream = new ZipInputStream(rawInputStream); long bytesProcessed = 0L; long lastBytesProcessedThousands = 0L; int nFiles = 0; while ((entry = zipInputStream.getNextEntry()) != null) { message = null; if (isCancelled()) { message = "cancelled"; result.add(entry.getName() + " " + message); break; } ++nFiles; File tempFile = new File(ODKFileUtils.getAppFolder(mAppName), entry.getName()); String formattedString = mContext.getString(R.string.expansion_unzipping_without_detail, entry.getName(), nFiles, totalFiles); String detail; if (entry.isDirectory()) { detail = mContext.getString(R.string.expansion_create_dir_detail); publishProgress(formattedString, detail); tempFile.mkdirs(); } else { int bufferSize = 8192; OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile, false), bufferSize); byte buffer[] = new byte[bufferSize]; int bread; while ((bread = zipInputStream.read(buffer)) != -1) { bytesProcessed += bread; long curThousands = (bytesProcessed / 1000L); if (curThousands != lastBytesProcessedThousands) { detail = mContext.getString(R.string.expansion_unzipping_detail, bytesProcessed, size); publishProgress(formattedString, detail); lastBytesProcessedThousands = curThousands; } out.write(buffer, 0, bread); } out.flush(); out.close(); detail = mContext.getString(R.string.expansion_unzipping_detail, bytesProcessed, size); publishProgress(formattedString, detail); } WebLogger.getLogger(mAppName).i(TAG, "Extracted ZipEntry: " + entry.getName()); message = mContext.getString(R.string.success); result.add(entry.getName() + " " + message); } ODKFileUtils.assertConfiguredTablesApp(mAppName, Tables.getInstance().getVersionCodeString()); String completionString = mContext.getString(R.string.expansion_unzipping_complete, totalFiles); publishProgress(completionString, null); } catch (IOException e) { WebLogger.getLogger(mAppName).printStackTrace(e); mPendingSuccess = false; if (e.getCause() != null) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } if (entry != null) { result.add(entry.getName() + " " + message); } else { result.add("Error accessing zipfile resource " + message); } } finally { if (zipInputStream != null) { try { zipInputStream.close(); rawInputStream = null; fd = null; } catch (IOException e) { WebLogger.getLogger(mAppName).printStackTrace(e); WebLogger.getLogger(mAppName).e(TAG, "Closing of ZipFile failed: " + e.toString()); } } if (rawInputStream != null) { try { rawInputStream.close(); fd = null; } catch (IOException e) { WebLogger.getLogger(mAppName).printStackTrace(e); WebLogger.getLogger(mAppName).e(TAG, "Closing of ZipFile failed: " + e.toString()); } } if (fd != null) { try { fd.close(); } catch (IOException e) { WebLogger.getLogger(mAppName).printStackTrace(e); WebLogger.getLogger(mAppName).e(TAG, "Closing of ZipFile failed: " + e.toString()); } } } } catch (Exception e) { WebLogger.getLogger(mAppName).printStackTrace(e); mPendingSuccess = false; if (e.getCause() != null) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } result.add("Error accessing zipfile resource " + message); } finally { if (rawInputStream != null) { try { rawInputStream.close(); } catch (IOException e) { WebLogger.getLogger(mAppName).printStackTrace(e); } } } } finally { if (fd != null) { try { fd.close(); } catch (IOException e) { WebLogger.getLogger(mAppName).printStackTrace(e); } } else { result.add("Error accessing zipfile resource."); } } }
From source file:org.wso2.carbon.registry.extensions.handlers.ZipWSDLMediaTypeHandler.java
public void put(RequestContext requestContext) throws RegistryException { if (!CommonUtil.isUpdateLockAvailable()) { return;//from w w w .j a va 2 s .c o m } CommonUtil.acquireUpdateLock(); // setting up session local path map for mounted setup. boolean pathMapSet = setSessionLocalPathMap(requestContext); try { Resource resource = requestContext.getResource(); String path = requestContext.getResourcePath().getPath(); try { // If the WSDL is already there, we don't need to re-run this handler unless the content is changed. // Re-running this handler causes issues with downstream handlers and other behaviour (ex:- lifecycles). // If you need to do a replace programatically, delete-then-replace. if (requestContext.getRegistry().resourceExists(path)) { // TODO: Add logic to compare content, and return only if the content didn't change. return; } } catch (Exception ignore) { } try { if (resource != null) { Object resourceContent = resource.getContent(); InputStream in = new ByteArrayInputStream((byte[]) resourceContent); Stack<File> fileList = new Stack<File>(); List<String> uriList = new LinkedList<String>(); List<UploadTask> tasks = new LinkedList<UploadTask>(); int threadPoolSize = this.threadPoolSize; File tempFile = File.createTempFile(tempFilePrefix, archiveExtension); File tempDir = new File(tempFile.getAbsolutePath().substring(0, tempFile.getAbsolutePath().length() - archiveExtension.length())); try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile)); try { byte[] contentChunk = new byte[1024]; int byteCount; while ((byteCount = in.read(contentChunk)) != -1) { out.write(contentChunk, 0, byteCount); } out.flush(); } finally { out.close(); } ZipEntry entry; makeDir(tempDir); ZipInputStream zs; List<String> wsdlUriList = new LinkedList<String>(); List<String> xsdUriList = new LinkedList<String>(); List<String> wadlUriList = new LinkedList<String>(); List<String> swaggerUriList = new LinkedList<String>(); zs = new ZipInputStream(new FileInputStream(tempFile)); try { entry = zs.getNextEntry(); while (entry != null) { String entryName = entry.getName(); FileOutputStream os; File file = new File(tempFile.getAbsolutePath().substring(0, tempFile.getAbsolutePath().length() - archiveExtension.length()) + File.separator + entryName); if (entry.isDirectory()) { if (!file.exists()) { makeDirs(file); fileList.push(file); } entry = zs.getNextEntry(); continue; } File parentFile = file.getParentFile(); if (!parentFile.exists()) { makeDirs(parentFile); } os = new FileOutputStream(file); try { fileList.push(file); byte[] contentChunk = new byte[1024]; int byteCount; while ((byteCount = zs.read(contentChunk)) != -1) { os.write(contentChunk, 0, byteCount); } } finally { os.close(); } zs.closeEntry(); entry = zs.getNextEntry(); if (entryName != null && entryName.toLowerCase().endsWith(wsdlExtension)) { String uri = tempFile.toURI().toString(); uri = uri.substring(0, uri.length() - archiveExtension.length()) + "/" + entryName; if (uri.startsWith("file:")) { uri = uri.substring(5); } while (uri.startsWith("/")) { uri = uri.substring(1); } uri = "file:///" + uri; if (uri.endsWith("/")) { uri = uri.substring(0, uri.length() - 1); } wsdlUriList.add(uri); } else if (entryName != null && entryName.toLowerCase().endsWith(xsdExtension)) { String uri = tempFile.toURI().toString(); uri = uri.substring(0, uri.length() - archiveExtension.length()) + "/" + entryName; if (uri.startsWith("file:")) { uri = uri.substring(5); } while (uri.startsWith("/")) { uri = uri.substring(1); } uri = "file:///" + uri; if (uri.endsWith("/")) { uri = uri.substring(0, uri.length() - 1); } xsdUriList.add(uri); } else if (entryName != null && entryName.toLowerCase().endsWith(wadlExtension)) { String uri = tempFile.toURI().toString(); uri = uri.substring(0, uri.length() - archiveExtension.length()) + "/" + entryName; if (uri.startsWith("file:")) { uri = uri.substring(5); } while (uri.startsWith("/")) { uri = uri.substring(1); } uri = "file:///" + uri; if (uri.endsWith("/")) { uri = uri.substring(0, uri.length() - 1); } wadlUriList.add(uri); } else if (entryName != null && entryName.toLowerCase().endsWith(swaggerExtension)) { String uri = tempFile.toURI().toString(); uri = uri.substring(0, uri.length() - archiveExtension.length()) + "/" + entryName; if (uri.startsWith("file:")) { uri = uri.substring(5); } while (uri.startsWith("/")) { uri = uri.substring(1); } uri = "file:///" + uri; if (uri.endsWith("/")) { uri = uri.substring(0, uri.length() - 1); } swaggerUriList.add(uri); } else if (entryName != null) { boolean isSkipFileExtension = false; for (String extension : skipFileExtensions) { if (entryName.toLowerCase().endsWith(extension.toLowerCase())) { isSkipFileExtension = true; break; } } if (!isSkipFileExtension) { String uri = tempFile.toURI().toString(); uri = uri.substring(0, uri.length() - archiveExtension.length()) + "/" + entryName; if (uri.startsWith("file:")) { uri = uri.substring(5); } while (uri.startsWith("/")) { uri = uri.substring(1); } uri = "file:///" + uri; if (uri.endsWith("/")) { uri = uri.substring(0, uri.length() - 1); } uriList.add(uri); } } } } finally { zs.close(); } Map<String, String> localPathMap = null; if (CurrentSession.getLocalPathMap() != null) { localPathMap = Collections.unmodifiableMap(CurrentSession.getLocalPathMap()); } if (wsdlUriList.isEmpty() && xsdUriList.isEmpty() && wadlUriList.isEmpty() && uriList.isEmpty() && swaggerUriList.isEmpty()) { throw new RegistryException("No Files found in the given archive"); } for (String uri : wsdlUriList) { tasks.add(new UploadWSDLTask(requestContext, uri, CurrentSession.getTenantId(), CurrentSession.getUserRegistry(), CurrentSession.getUserRealm(), CurrentSession.getUser(), CurrentSession.getCallerTenantId(), localPathMap)); } for (String uri : xsdUriList) { tasks.add(new UploadXSDTask(requestContext, uri, CurrentSession.getTenantId(), CurrentSession.getUserRegistry(), CurrentSession.getUserRealm(), CurrentSession.getUser(), CurrentSession.getCallerTenantId(), localPathMap)); } for (String uri : wadlUriList) { tasks.add(new UploadWadlTask(requestContext, uri, CurrentSession.getTenantId(), CurrentSession.getUserRegistry(), CurrentSession.getUserRealm(), CurrentSession.getUser(), CurrentSession.getCallerTenantId(), localPathMap)); } for (String uri : swaggerUriList) { tasks.add(new UploadSwaggerTask(requestContext, uri, CurrentSession.getTenantId(), CurrentSession.getUserRegistry(), CurrentSession.getUserRealm(), CurrentSession.getUser(), CurrentSession.getCallerTenantId(), localPathMap)); } String mediaType = resource.getProperty("registry.mediaType"); if (mediaType != null) { for (String uri : uriList) { tasks.add(new UploadFileTask(requestContext, uri, CurrentSession.getTenantId(), CurrentSession.getUserRegistry(), CurrentSession.getUserRealm(), CurrentSession.getUser(), CurrentSession.getCallerTenantId(), localPathMap, mediaType)); } uriList.clear(); } // calculate thread pool size for efficient use of resources in concurrent // update scenarios. int toAdd = wsdlUriList.size() + xsdUriList.size(); if (toAdd < threadPoolSize) { if (toAdd < (threadPoolSize / 8)) { threadPoolSize = 0; } else if (toAdd < (threadPoolSize / 2)) { threadPoolSize = (threadPoolSize / 8); } else { threadPoolSize = (threadPoolSize / 4); } } } finally { in.close(); resourceContent = null; resource.setContent(null); } uploadFiles(tasks, tempFile, fileList, tempDir, threadPoolSize, path, uriList, requestContext); } } catch (IOException e) { throw new RegistryException("Error occurred while unpacking Governance Archive", e); } if (Transaction.isRollbacked()) { throw new RegistryException( "A nested transaction was rollbacked and therefore " + "cannot proceed with this action."); } requestContext.setProcessingComplete(true); } finally { CommonUtil.releaseUpdateLock(); removeSessionLocalPathMap(pathMapSet); } }
From source file:me.piebridge.bible.Bible.java
private boolean unpackZip(File path) throws IOException { if (path == null || !path.isFile()) { return false; }//w w w . ja v a 2 s .co m File dirpath = getExternalFilesDirWrapper(); // bibledata-zh-cn-version.zip String filename = path.getAbsolutePath(); int sep = filename.lastIndexOf("-"); if (sep != -1) { filename = filename.substring(sep + 1, filename.length() - 4); } filename += ".sqlite3"; InputStream is = new FileInputStream(path); long fileSize = path.length(); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); try { ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { long zeSize = ze.getCompressedSize(); // zip is incomplete if (fileSize < zeSize) { break; } String zename = ze.getName(); if (zename == null || !zename.endsWith((".sqlite3"))) { continue; } sep = zename.lastIndexOf(File.separator); if (sep != -1) { zename = zename.substring(sep + 1); } File file; String version = zename.toLowerCase(Locale.US).replace(".sqlite3", ""); if (versionpaths.containsKey(version)) { file = new File(versionpaths.get(version)); } else { file = new File(dirpath, zename); } if (file.exists() && file.lastModified() > ze.getTime() && file.lastModified() > path.lastModified()) { continue; } Log.d(TAG, "unpacking " + file.getAbsoluteFile()); int length; File tmpfile = new File(dirpath, zename + ".tmp"); OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpfile)); byte[] buffer = new byte[8192]; int zero = 0; while ((length = zis.read(buffer)) != -1) { if (length == 0) { ++zero; if (zero > 3) { break; } } else { zero = 0; } os.write(buffer, 0, length); } os.close(); if (zero > 3) { return false; } else { tmpfile.renameTo(file); path.delete(); return true; } } } finally { is.close(); zis.close(); } return false; }