List of usage examples for java.util.zip ZipInputStream getNextEntry
public ZipEntry getNextEntry() throws IOException
From source file:com.redhat.plugin.eap6.EAP6DeploymentStructureMojo.java
private Document getDeploymentStructureFromArchive(File zipFile) throws Exception { getLog().debug("Read deployment-informations from archive <" + zipFile + ">"); ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry entry;/*w w w. j av a 2 s . c o m*/ Document doc = null; boolean done = false; while (!done && (entry = zis.getNextEntry()) != null) { String entryName = entry.getName().toLowerCase(); if (entryName.endsWith("meta-inf/" + JBOSS_SUBDEPLOYMENT) || entryName.endsWith("web-inf/" + JBOSS_SUBDEPLOYMENT)) { byte[] buf = IOUtils.toByteArray(zis); if (verbose) { getLog().debug(new String(buf, encoding)); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // doc=factory.newDocumentBuilder().parse(new ByteArrayInputStream(buf),encoding); doc = factory.newDocumentBuilder().parse( new org.xml.sax.InputSource(new java.io.StringReader(new String(buf, encoding).trim()))); done = true; } else { if (entry.getCompressedSize() >= 0) { if (verbose) { getLog().debug("Skipping entry <" + entryName + "> to next entry for bytes:" + entry.getCompressedSize()); } zis.skip(entry.getCompressedSize()); } } } zis.close(); return doc; }
From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4JRuntimesManager.java
private String buildPackagesList(File directory) { Set<String> packages = new HashSet<>(); final String SEPARATOR = ", "; StringBuilder builder = new StringBuilder(); if (directory != null && directory.isDirectory()) { for (File file : directory.listFiles(new JarFilter())) { ZipInputStream zipStream = null; try { zipStream = new ZipInputStream(new FileInputStream(file)); ZipEntry entry;//from ww w .j a v a 2 s .c o m while ((entry = zipStream.getNextEntry()) != null) { if (FilenameUtils.getExtension(entry.getName()).equals("class")) { packages.add(FilenameUtils.getPathNoEndSeparator(entry.getName()).replace('/', '.')); } } } catch (IOException e) { Logger.log(Logger.SEVERITY_ERROR, e); } finally { IOUtils.closeQuietly(zipStream); } } for (String pkg : packages) { builder.append(pkg); builder.append(SEPARATOR); } if (builder.length() >= SEPARATOR.length()) { builder.setLength(builder.length() - SEPARATOR.length()); } return builder.toString(); } else { return null; } }
From source file:com.mindquarry.desktop.workspace.SVNTestBase.java
/** * Extracts the zip file <code>zipName</code> into the folder * <code>destinationPath</code>. *///ww w .j a v a 2 s. c om private void extractZip(String zipName, String destinationPath) throws IOException { File dest = new File(destinationPath); // delete if test has failed and extracted dir is still present FileUtils.deleteDirectory(dest); dest.mkdirs(); byte[] buffer = new byte[1024]; ZipEntry zipEntry; ZipInputStream zipInputStream = new ZipInputStream( new FileInputStream("src/test/resources/com/mindquarry/desktop/workspace/" + zipName)); while (null != (zipEntry = zipInputStream.getNextEntry())) { File zippedFile = new File(destinationPath + zipEntry.getName()); if (zipEntry.isDirectory()) { zippedFile.mkdirs(); } else { // ensure the parent directory exists zippedFile.getParentFile().mkdirs(); OutputStream fileOutStream = new FileOutputStream(zippedFile); transferBytes(zipInputStream, fileOutStream, buffer); fileOutStream.close(); } } zipInputStream.close(); }
From source file:org.tonguetied.datatransfer.ExportServiceTest.java
public final void testCreateArchiveWithEmptyFiles() throws Exception { archiveTestDirectory = new File(USER_DIR, "testCreateArchiveWithEmptyFiles"); FileUtils.forceMkdir(archiveTestDirectory); FileUtils.touch(new File(archiveTestDirectory, "temp")); assertEquals(1, archiveTestDirectory.listFiles().length); assertTrue(archiveTestDirectory.isDirectory()); dataService.createArchive(archiveTestDirectory); assertEquals(2, archiveTestDirectory.listFiles().length); // examine zip file File[] files = archiveTestDirectory.listFiles(new FileExtensionFilter(".zip")); assertEquals(1, files.length);/*ww w .j a v a2s. co m*/ ZipInputStream zis = null; try { zis = new ZipInputStream(new FileInputStream(files[0])); ZipEntry zipEntry = zis.getNextEntry(); assertEquals("temp", zipEntry.getName()); zis.closeEntry(); } finally { IOUtils.closeQuietly(zis); } }
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 .ja va 2 s . c o 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:com.joliciel.jochre.search.JochreIndexBuilderImpl.java
private void updateDocumentInternal(File documentDir) { try {//ww w . ja v a2 s. c o m LOG.info("Updating index for " + documentDir.getName()); File zipFile = new File(documentDir, documentDir.getName() + ".zip"); if (!zipFile.exists()) { LOG.info("Nothing to index in " + documentDir.getName()); return; } long zipDate = zipFile.lastModified(); this.deleteDocumentInternal(documentDir); File[] offsetFiles = documentDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".obj"); } }); for (File offsetFile : offsetFiles) { offsetFile.delete(); } int i = 0; Map<String, String> fields = new TreeMap<String, String>(); File metaDataFile = new File(documentDir, "metadata.txt"); Scanner scanner = new Scanner( new BufferedReader(new InputStreamReader(new FileInputStream(metaDataFile), "UTF-8"))); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String key = line.substring(0, line.indexOf('\t')); String value = line.substring(line.indexOf('\t')); fields.put(key, value); } scanner.close(); JochreXmlDocument xmlDoc = this.searchService.newDocument(); JochreXmlReader reader = this.searchService.getJochreXmlReader(xmlDoc); ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze = null; while ((ze = zis.getNextEntry()) != null) { LOG.debug("Adding zipEntry " + i + ": " + ze.getName()); String baseName = ze.getName().substring(0, ze.getName().lastIndexOf('.')); UnclosableInputStream uis = new UnclosableInputStream(zis); reader.parseFile(uis, baseName); i++; } zis.close(); i = 0; StringBuilder sb = new StringBuilder(); coordinateStorage = searchService.getCoordinateStorage(); offsetLetterMap = new HashMap<Integer, JochreXmlLetter>(); int startPage = -1; int endPage = -1; int docCount = 0; int wordCount = 0; int cumulWordCount = 0; for (JochreXmlImage image : xmlDoc.getImages()) { if (startPage < 0) startPage = image.getPageIndex(); endPage = image.getPageIndex(); int remainingWords = xmlDoc.wordCount() - (cumulWordCount + wordCount); LOG.debug("Word count: " + wordCount + ", cumul word count: " + cumulWordCount + ", total xml words: " + xmlDoc.wordCount() + ", remaining words: " + remainingWords); if (wordsPerDoc > 0 && wordCount >= wordsPerDoc && remainingWords >= wordsPerDoc) { LOG.debug("Creating new index doc: " + docCount); JochreIndexDocument indexDoc = searchService.newJochreIndexDocument(documentDir, docCount, sb, coordinateStorage, startPage, endPage, fields); indexDoc.save(indexWriter); docCount++; sb = new StringBuilder(); coordinateStorage = searchService.getCoordinateStorage(); startPage = image.getPageIndex(); offsetLetterMap = new HashMap<Integer, JochreXmlLetter>(); cumulWordCount += wordCount; wordCount = 0; } LOG.debug("Processing page: " + image.getFileNameBase()); File imageFile = null; for (String imageExtension : imageExtensions) { imageFile = new File(documentDir, image.getFileNameBase() + "." + imageExtension); if (imageFile.exists()) break; imageFile = null; } if (imageFile == null) throw new RuntimeException("No image found in directory " + documentDir.getAbsolutePath() + ", baseName " + image.getFileNameBase()); coordinateStorage.addImage(sb.length(), imageFile.getName(), image.getPageIndex()); for (JochreXmlParagraph par : image.getParagraphs()) { coordinateStorage.addParagraph(sb.length(), new Rectangle(par.getLeft(), par.getTop(), par.getRight(), par.getBottom())); for (JochreXmlRow row : par.getRows()) { coordinateStorage.addRow(sb.length(), new Rectangle(row.getLeft(), row.getTop(), row.getRight(), row.getBottom())); int k = 0; for (JochreXmlWord word : row.getWords()) { wordCount++; for (JochreXmlLetter letter : word.getLetters()) { offsetLetterMap.put(sb.length(), letter); if (letter.getText().length() > 1) { for (int j = 1; j < letter.getText().length(); j++) { offsetLetterMap.put(sb.length() + j, letter); } } sb.append(letter.getText()); } k++; boolean finalDash = false; if (k == row.getWords().size() && word.getText().endsWith("-") && word.getText().length() > 1) finalDash = true; if (!finalDash) sb.append(" "); } } sb.append("\n"); } i++; } JochreIndexDocument indexDoc = searchService.newJochreIndexDocument(documentDir, docCount, sb, coordinateStorage, startPage, endPage, fields); indexDoc.save(indexWriter); File lastIndexDateFile = new File(documentDir, "indexDate.txt"); Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(lastIndexDateFile, false), "UTF8")); writer.write("" + zipDate); writer.flush(); writer.close(); } catch (IOException ioe) { LogUtils.logError(LOG, ioe); throw new RuntimeException(ioe); } }
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;/*www . j a v a2 s . 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:com.wheelermarine.android.publicAccesses.Updater.java
@Override protected Integer doInBackground(URL... urls) { try {/*from w ww.j av a 2 s . c om*/ final DatabaseHelper db = new DatabaseHelper(context); SQLiteDatabase database = db.getWritableDatabase(); if (database == null) throw new IllegalStateException("Unable to open database!"); database.beginTransaction(); try { // Clear out the old data. database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null); // Connect to the web server and locate the FTP download link. Log.v(TAG, "Finding update: " + urls[0]); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage("Locating update..."); progress.setIndeterminate(true); } }); Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get(); URL dataURL = null; for (Element element : doc.select("a")) { if (element.hasAttr("href") && element.attr("href").startsWith("ftp://ftp.dnr.state.mn.us")) { dataURL = new URL(element.attr("href")); } } // Make sure the download URL was fund. if (dataURL == null) throw new FileNotFoundException("Unable to locate data URL."); // Connect to the FTP server and download the update. Log.v(TAG, "Downloading update: " + dataURL); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage("Downloading update..."); progress.setIndeterminate(true); } }); FTPClient ftp = new FTPClient(); try { ftp.setConnectTimeout(timeout * 1000); ftp.setDefaultTimeout(timeout * 1000); ftp.connect(dataURL.getHost()); ftp.enterLocalPassiveMode(); // After connection attempt, you should check the reply code // to verify success. if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.disconnect(); throw new IOException("FTP server refused connection: " + ftp.getReplyString()); } // Login using the standard anonymous credentials. if (!ftp.login("anonymous", "anonymous")) { ftp.disconnect(); throw new IOException("FTP Error: " + ftp.getReplyString()); } Map<Integer, Location> locations = null; // Download the ZIP archive. Log.v(TAG, "Downloading: " + dataURL.getFile()); ftp.setFileType(FTP.BINARY_FILE_TYPE); InputStream in = ftp.retrieveFileStream(dataURL.getFile()); if (in == null) throw new FileNotFoundException(dataURL.getFile() + " was not found!"); try { ZipInputStream zin = new ZipInputStream(in); try { // Locate the .dbf entry in the ZIP archive. ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { if (entry.getName().endsWith(entryName)) { readDBaseFile(zin, database); } else if (entry.getName().endsWith(shapeEntryName)) { locations = readShapeFile(zin); } } } finally { try { zin.close(); } catch (Exception e) { // Ignore this error. } } } finally { in.close(); } if (locations != null) { final int recordCount = locations.size(); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setIndeterminate(false); progress.setMessage("Updating locations..."); progress.setMax(recordCount); } }); int progress = 0; for (int recordNumber : locations.keySet()) { PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber); Location loc = locations.get(recordNumber); access.setLatitude(loc.getLatitude()); access.setLongitude(loc.getLongitude()); db.updatePublicAccess(access); publishProgress(++progress); } } } finally { if (ftp.isConnected()) ftp.disconnect(); } database.setTransactionSuccessful(); return db.getPublicAccessesCount(); } finally { database.endTransaction(); } } catch (Exception e) { error = e; Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e); return -1; } }
From source file:io.fabric8.tooling.archetype.generator.ArchetypeHelper.java
/** * Main method which extracts given Maven Archetype in destination directory * * @return// w w w . j a va2 s.c o m */ public int execute() throws IOException { outputDir.mkdirs(); if (packageName == null || packageName.length() == 0) { packageName = groupId + "." + artifactId; } String packageDir = packageName.replace('.', '/'); info("Creating archetype using Maven groupId: " + groupId + ", artifactId: " + artifactId + ", version: " + version + " in directory: " + outputDir); Map<String, String> replaceProperties = new HashMap<String, String>(); ZipInputStream zip = null; try { zip = new ZipInputStream(archetypeIn); boolean ok = true; while (ok) { ZipEntry entry = zip.getNextEntry(); if (entry == null) { ok = false; } else { if (!entry.isDirectory()) { String fullName = entry.getName(); if (fullName != null && fullName.startsWith(zipEntryPrefix)) { String name = replaceFileProperties(fullName.substring(zipEntryPrefix.length()), replaceProperties); debug("Processing resource: " + name); int idx = name.lastIndexOf('/'); Matcher matcher = sourcePathRegexPattern.matcher(name); String dirName; if (packageName.length() > 0 && idx > 0 && matcher.matches()) { String prefix = matcher.group(1); dirName = prefix + packageDir + "/" + name.substring(prefix.length()); } else if (packageName.length() > 0 && name.startsWith(webInfResources)) { dirName = "src/main/webapp/WEB-INF/" + packageDir + "/resources" + name.substring(webInfResources.length()); } else { dirName = name; } // lets replace properties... File file = new File(outputDir, dirName); file.getParentFile().mkdirs(); FileOutputStream out = null; try { out = new FileOutputStream(file); boolean isBinary = false; for (String suffix : binarySuffixes) { if (name.endsWith(suffix)) { isBinary = true; break; } } if (isBinary) { // binary file? don't transform. copy(zip, out); } else { // text file... ByteArrayOutputStream bos = new ByteArrayOutputStream(); copy(zip, bos); String text = new String(bos.toByteArray(), "UTF-8"); out.write(transformContents(text, replaceProperties).getBytes()); } } finally { if (out != null) { out.close(); } } } else if (fullName != null && fullName.equals("META-INF/maven/archetype-metadata.xml")) { // we assume that this resource will be first in Archetype's ZIP // this way we can find out what are the required properties before we will actually use them parseReplaceProperties(zip, replaceProperties); replaceProperties.putAll(overrideProperties); } } zip.closeEntry(); } } } catch (Exception e) { throw new IOException(e.getMessage(), e); } finally { if (zip != null) { zip.close(); } } info("Using replace properties: " + replaceProperties); // now lets replace all the properties in the pom.xml if (!replaceProperties.isEmpty()) { File pom = new File(outputDir, "pom.xml"); FileReader reader = new FileReader(pom); String text = IOUtils.toString(reader); IOUtils.closeQuietly(reader); for (Map.Entry<String, String> e : replaceProperties.entrySet()) { text = replaceVariable(text, e.getKey(), e.getValue()); } FileWriter writer = new FileWriter(pom); IOUtils.write(text, writer); IOUtils.closeQuietly(writer); } // now lets create the default directories if (createDefaultDirectories) { File srcDir = new File(outputDir, "src"); File mainDir = new File(srcDir, "main"); File testDir = new File(srcDir, "test"); String srcDirName = "java"; // Who needs Scala in 2014? // if (new File(mainDir, "scala").exists() || new File(textDir, "scala").exists()) { // srcDirName = "scala"; // } for (File dir : new File[] { mainDir, testDir }) { for (String name : new String[] { srcDirName + "/" + packageDir, "resources" }) { new File(dir, name).mkdirs(); } } } return 0; }
From source file:com.pontecultural.flashcards.ReadSpreadsheet.java
public void run() { try {// w w w. jav a 2 s . c o m // This class is used to upload a zip file via // the web (ie,fileData). To test it, the file is // give to it directly via odsFile. One of // which must be defined. assertFalse(odsFile == null && fileData == null); XMLReader reader = null; final String ZIP_CONTENT = "content.xml"; // Open office files are zipped. // Walk through it and find "content.xml" ZipInputStream zin = null; try { if (fileData != null) { zin = new ZipInputStream(new BufferedInputStream(fileData.getInputStream())); } else { zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(odsFile))); } ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { if (entry.getName().equals(ZIP_CONTENT)) { break; } } SAXParserFactory spf = SAXParserFactory.newInstance(); //spf.setValidating(validate); SAXParser parser = spf.newSAXParser(); reader = parser.getXMLReader(); // reader.setErrorHandler(new MyErrorHandler()); reader.setContentHandler(this); // reader.parse(new InputSource(zf.getInputStream(entry))); reader.parse(new InputSource(zin)); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXParseException spe) { spe.printStackTrace(); } catch (SAXException se) { se.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (zin != null) zin.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } }