List of usage examples for java.util.zip ZipInputStream ZipInputStream
public ZipInputStream(InputStream in)
From source file:com.codelanx.codelanxlib.util.Reflections.java
/** * Checks whether or not there is a plugin on the server with the name of * the passed {@code name} paramater. This method achieves this by scanning * the plugins folder and reading the {@code plugin.yml} files of any * respective jarfiles in the directory. * //www . ja va2 s. com * @since 0.1.0 * @version 0.1.0 * * @param name The name of the plugin as specified in the {@code plugin.yml} * @return The {@link File} for the plugin jarfile, or {@code null} if not * found */ public static File findPluginJarfile(String name) { File plugins = new File("plugins"); Exceptions.illegalState(plugins.isDirectory(), "'plugins' isn't a directory! (wat)"); for (File f : plugins.listFiles((File pathname) -> { return pathname.getPath().endsWith(".jar"); })) { try (InputStream is = new FileInputStream(f); ZipInputStream zi = new ZipInputStream(is)) { ZipEntry ent = null; while ((ent = zi.getNextEntry()) != null) { if (ent.getName().equalsIgnoreCase("plugin.yml")) { break; } } if (ent == null) { continue; //no plugin.yml found } ZipFile z = new ZipFile(f); try (InputStream fis = z.getInputStream(ent); InputStreamReader fisr = new InputStreamReader(fis); BufferedReader scan = new BufferedReader(fisr)) { String in; while ((in = scan.readLine()) != null) { if (in.startsWith("name: ")) { if (in.substring(6).equalsIgnoreCase(name)) { return f; } } } } } catch (IOException ex) { Debugger.error(ex, "Error reading plugin jarfiles"); } } return null; }
From source file:com.wheelermarine.publicAccessSites.Updater.java
@Override protected Integer doInBackground(URL... urls) { try {/*from w w w. j a va2 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").endsWith(".zip")) { 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); } }); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(dataURL.toString()); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (entity == null) throw new IOException("Error downloading update."); Map<Integer, Location> locations = null; // Download the ZIP archive. Log.v(TAG, "Downloading: " + dataURL.getFile()); InputStream in = entity.getContent(); 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); } } 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:com.facebook.buck.java.JarDirectoryStepTest.java
@Test public void jarsShouldContainDirectoryEntries() throws IOException { Path zipup = folder.newFolder("dir-zip"); Path subdir = zipup.resolve("dir/subdir"); Files.createDirectories(subdir); Files.write(subdir.resolve("a.txt"), "cake".getBytes()); JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"), ImmutableSet.of(zipup), /* main class */ null, /* manifest file */ null); ExecutionContext context = TestExecutionContext.newInstance(); int returnCode = step.execute(context); assertEquals(0, returnCode);/*from w w w . java2 s. co m*/ Path zip = zipup.resolve("output.jar"); assertTrue(Files.exists(zip)); // Iterate over each of the entries, expecting to see the directory names as entries. Set<String> expected = Sets.newHashSet("dir/", "dir/subdir/"); try (ZipInputStream is = new ZipInputStream(Files.newInputStream(zip))) { for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) { expected.remove(entry.getName()); } } assertTrue("Didn't see entries for: " + expected, expected.isEmpty()); }
From source file:de.micromata.genome.gdbfs.FileSystemUtils.java
/** * Copy from zip.//from w ww . j ava2 s. c o m * * @param zipIn the zip in * @param target the target */ public static void copyFromZip(InputStream zipIn, FsObject target) { ZipInputStream zin = new ZipInputStream(zipIn); try { while (true) { ZipEntry ze = zin.getNextEntry(); if (ze == null) { break; } copyFromZip(ze, zin, target); zin.closeEntry(); } } catch (IOException ex) { throw new RuntimeIOException(ex); } }
From source file:com.jlgranda.fede.ejb.mail.reader.FacturaElectronicaMailReader.java
/** * Obtiene una lista de objetos <tt>FacturaReader</tt> desde el mensaje de correo, si existe * * @param mime4jMessage// w w w . j a v a2 s . c o m * @return lista de instancias instancia <tt>FacturaReader</tt> si existe la factura, null * en caso contrario */ private List<FacturaReader> handleMessage(org.apache.james.mime4j.dom.Message mime4jMessage) throws IOException, Exception { List<FacturaReader> result = new ArrayList<>(); ByteArrayOutputStream os = null; String filename = null; Factura factura = null; EmailHelper emailHelper = new EmailHelper(); if (mime4jMessage.isMultipart()) { org.apache.james.mime4j.dom.Multipart mime4jMultipart = (org.apache.james.mime4j.dom.Multipart) mime4jMessage .getBody(); emailHelper.parseBodyParts(mime4jMultipart); //Obtener la factura en los adjuntos if (emailHelper.getAttachments().isEmpty()) { //If it's single part message, just get text body String text = emailHelper.getHtmlBody().toString(); emailHelper.getTxtBody().append(text); if (mime4jMessage.getSubject().contains("Ghost")) { String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"", "\" target=\"_blank\">Descarga formato XML</a>"); if (url != null) { result.add(FacturaElectronicaURLReader.getFacturaElectronica(url)); } } } else { for (Entity entity : emailHelper.getAttachments()) { filename = EmailHelper.getFilename(entity); //if (entity.getBody() instanceof BinaryBody) { if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType()) || "application/xml".equalsIgnoreCase(entity.getMimeType()) || "text/xml".equalsIgnoreCase(entity.getMimeType()) || "text/plain".equalsIgnoreCase(entity.getMimeType())) && (filename != null && filename.endsWith(".xml"))) { //attachFiles += part.getFileName() + ", "; os = EmailHelper.writeBody(entity.getBody()); factura = FacturaUtil.read(os.toString()); if (factura != null) { result.add(new FacturaReader(factura, os.toString(), entity.getFilename(), mime4jMessage.getFrom().get(0).getAddress())); } } else if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType()) || "aplication/xml".equalsIgnoreCase(entity.getMimeType()) || "text/xml".equalsIgnoreCase(entity.getMimeType())) && (filename != null && filename.endsWith(".zip"))) { //http://www.java2s.com/Tutorial/Java/0180__File/UnzipusingtheZipInputStream.htm os = EmailHelper.writeBody(entity.getBody()); ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(os.toByteArray())); try { ZipEntry entry = null; String tmp = null; ByteArrayOutputStream fout = null; while ((entry = zis.getNextEntry()) != null) { if (entry.getName().endsWith(".xml")) { //logger.debug("Unzipping {}", entry.getFilename()); fout = new ByteArrayOutputStream(); for (int c = zis.read(); c != -1; c = zis.read()) { fout.write(c); } tmp = new String(fout.toByteArray(), Charset.defaultCharset()); factura = FacturaUtil.read(tmp); if (factura != null) { result.add(new FacturaReader(factura, tmp, entity.getFilename())); } fout.close(); } zis.closeEntry(); } zis.close(); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(zis); } } else if ("message/rfc822".equalsIgnoreCase(entity.getMimeType())) { if (entity.getBody() instanceof org.apache.james.mime4j.message.MessageImpl) { result.addAll( handleMessage((org.apache.james.mime4j.message.MessageImpl) entity.getBody())); } } } } } else { //If it's single part message, just get text body String text = emailHelper.getTxtPart(mime4jMessage); emailHelper.getTxtBody().append(text); if (mime4jMessage.getSubject().contains("Ghost")) { String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"", "\" target=\"_blank\">Descarga formato XML</a>"); if (url != null) { result.add(FacturaElectronicaURLReader.getFacturaElectronica(url)); } } } return result; }
From source file:com.ephesoft.dcma.gwt.customworkflow.server.ImportPluginUploadServlet.java
/** * @param tempZipFile/*w w w . j a va 2 s . c om*/ * @param exportSerailizationFolderPath * @param printWriter * @return * @throws FileNotFoundException * @throws IOException */ private String processZipFileEntries(File tempZipFile, String exportSerailizationFolderPath, PrintWriter printWriter) throws FileNotFoundException, IOException { String errorMessageString; ZipInputStream zipInputStream; List<ZipEntry> zipEntries; tempOutputUnZipDir = exportSerailizationFolderPath + File.separator + zipFileName; File tempOutputUnZipDirFile = new File(tempOutputUnZipDir); try { FileUtils.copyFile(tempZipFile, tempOutputUnZipDirFile); // FileUtils.unzip(tempZipFile, tempOutputUnZipDir); } catch (Exception e) { LOG.error("Unable to copy the file." + e, e); printWriter.write("Unable to copy the file.Please try again."); tempZipFile.delete(); } zipInputStream = new ZipInputStream(new FileInputStream(tempOutputUnZipDir)); // new ZipInputStream(new FileInputStream(tempOutputUnZipDir)).getNextEntry(); zipEntries = new ArrayList<ZipEntry>(); ZipEntry nextEntry = zipInputStream.getNextEntry(); while (nextEntry != null) { zipEntries.add(nextEntry); nextEntry = zipInputStream.getNextEntry(); } errorMessageString = processZipFileContents(zipEntries); return errorMessageString; }
From source file:gov.nih.nci.caarray.application.project.FileUploadUtils.java
/** * Unpack the given file, which must be a ZIP file, and add its files individually to the given project and save * them in the data store. If any file within the ZIP file has the same name as a file already belonging to the * project, it will not be added to the project. If any file within one of the ZIP files is itself a ZIP file, it * will be added to the project, and will not recursively unpacked. The ZIP file must not contain directories. If it * does, an InvalidFileException will be thrown. * @param project the project to which the unpacked files should be added. * @param fileName the name of the file being unpacked. * @param inputStream the InputStream object which points to the File data * * @return a result object with information about number of files actually added to the project and conflicting * files// w w w.j a v a 2 s.co m * @throws InvalidFileException if any file within the ZIP file is within a subdirectory, or if there is an error * adding any file to the project. */ private void unpackFile(Project project, String fileName, InputStream inputStream) throws InvalidFileException { ZipInputStream zipStream = null; try { zipStream = new ZipInputStream(inputStream); ZipEntry entry = zipStream.getNextEntry(); final Set<String> existingFileNames = new HashSet<String>(project.getFileNames()); while (entry != null) { String entryName = entry.getName(); checkForDirectory(entry); if (!checkAlreadyAdded(existingFileNames, entryName)) { addEntryToProject(project, zipStream, entryName); existingFileNames.add(entryName); } entry = zipStream.getNextEntry(); } } catch (final IOException e) { throw new InvalidFileException(fileName, UNPACKING_ERROR_KEY, result, UNPACKING_ERROR_MESSAGE, e); } catch (final InvalidFileException e) { throw new InvalidFileException(fileName, UNPACKING_ERROR_KEY, result, UNPACKING_ERROR_MESSAGE, e); } finally { IOUtils.closeQuietly(zipStream); IOUtils.closeQuietly(inputStream); } }
From source file:dpfmanager.shell.modules.report.core.ReportGenerator.java
/** * Read the file of the path./*from ww w .j a v a 2 s . c o m*/ * * @param pathStr the file path to read. * @return the content of the file in path */ public String readFile(String pathStr) { String text = ""; String name = pathStr.substring(pathStr.lastIndexOf("/") + 1, pathStr.length()); Path path = Paths.get(pathStr); try { if (Files.exists(path)) { // Look in current dir BufferedReader br = new BufferedReader(new FileReader(pathStr)); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } text = sb.toString(); br.close(); } else { // Look in JAR CodeSource src = ReportGenerator.class.getProtectionDomain().getCodeSource(); if (src != null) { URL jar = src.getLocation(); ZipInputStream zip; zip = new ZipInputStream(jar.openStream()); ZipEntry zipFile; boolean found = false; while ((zipFile = zip.getNextEntry()) != null && !found) { if (zipFile.getName().endsWith(name)) { BufferedReader br = new BufferedReader(new InputStreamReader(zip)); String line = br.readLine(); while (line != null) { text += line + System.lineSeparator(); line = br.readLine(); } found = true; } zip.closeEntry(); } } } } catch (FileNotFoundException e) { context.send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.ERROR, "Template for html not found in dir.")); } catch (IOException e) { context.send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.ERROR, "Error reading " + pathStr)); } return text; }
From source file:cn.edu.sdust.silence.itransfer.filemanage.FileManager.java
/** * //w ww. j ava2 s . c o m * @param zip_file * @param directory */ public void extractZipFiles(String zip_file, String directory) { byte[] data = new byte[BUFFER]; String name, path, zipDir; ZipEntry entry; ZipInputStream zipstream; if (!(directory.charAt(directory.length() - 1) == '/')) directory += "/"; if (zip_file.contains("/")) { path = zip_file; name = path.substring(path.lastIndexOf("/") + 1, path.length() - 4); zipDir = directory + name + "/"; } else { path = directory + zip_file; name = path.substring(path.lastIndexOf("/") + 1, path.length() - 4); zipDir = directory + name + "/"; } new File(zipDir).mkdir(); try { zipstream = new ZipInputStream(new FileInputStream(path)); while ((entry = zipstream.getNextEntry()) != null) { String buildDir = zipDir; String[] dirs = entry.getName().split("/"); if (dirs != null && dirs.length > 0) { for (int i = 0; i < dirs.length - 1; i++) { buildDir += dirs[i] + "/"; new File(buildDir).mkdir(); } } int read = 0; FileOutputStream out = new FileOutputStream(zipDir + entry.getName()); while ((read = zipstream.read(data, 0, BUFFER)) != -1) out.write(data, 0, read); zipstream.closeEntry(); out.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:msearch.io.MSFilmlisteLesen.java
private boolean filmlisteJsonEinlesen(File vonDatei, ListeFilme listeFilme) { boolean ret = false; BZip2CompressorInputStream bZip2CompressorInputStream; JsonFactory jsonF = new JsonFactory(); JsonParser jp = null;/*from w w w . ja va2 s . c om*/ JsonToken jsonToken; String sender = "", thema = ""; try { // ########################################################## // und jetzt die Liste einlesen, URL kann es jetzt schon nicht mehr sein! if (!vonDatei.exists()) { MSLog.fehlerMeldung(702030698, MSLog.FEHLER_ART_PROG, "MSearchIoXmlFilmlisteLesen.filmlisteLesen", "Datei existiert nicht: " + vonDatei.getName()); return false; } if (vonDatei.getName().endsWith(MSConst.FORMAT_XZ)) { XZInputStream xZInputStream = new XZInputStream(new FileInputStream(vonDatei)); jp = jsonF.createParser(new InputStreamReader(xZInputStream, MSConst.KODIERUNG_UTF)); } else if (vonDatei.getName().endsWith(MSConst.FORMAT_BZ2)) { bZip2CompressorInputStream = new BZip2CompressorInputStream(new FileInputStream(vonDatei)); jp = jsonF.createParser(new InputStreamReader(bZip2CompressorInputStream, MSConst.KODIERUNG_UTF)); } else if (vonDatei.getName().endsWith(MSConst.FORMAT_ZIP)) { ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(vonDatei)); zipInputStream.getNextEntry(); jp = jsonF.createParser(new InputStreamReader(zipInputStream, MSConst.KODIERUNG_UTF)); } else { jp = jsonF.createParser(vonDatei); // geht so am schnellsten } if (jp.nextToken() != JsonToken.START_OBJECT) { throw new IOException("Expected data to start with an Object"); } while ((jsonToken = jp.nextToken()) != null) { if (jsonToken == JsonToken.END_OBJECT) { break; } if (jp.isExpectedStartArrayToken()) { for (int k = 0; k < ListeFilme.MAX_ELEM; ++k) { listeFilme.metaDaten[k] = jp.nextTextValue(); } break; } } while ((jsonToken = jp.nextToken()) != null) { if (jsonToken == JsonToken.END_OBJECT) { break; } if (jp.isExpectedStartArrayToken()) { // sind nur die Feldbeschreibungen, brauch mer nicht jp.nextToken(); break; } } while ((jsonToken = jp.nextToken()) != null) { if (jsonToken == JsonToken.END_OBJECT) { break; } if (jp.isExpectedStartArrayToken()) { DatenFilm datenFilm = new DatenFilm(); for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) { datenFilm.arr[DatenFilm.COLUMN_NAMES_JSON[i]] = jp.nextTextValue(); /// fr die Entwicklungszeit if (datenFilm.arr[DatenFilm.COLUMN_NAMES_JSON[i]] == null) { datenFilm.arr[DatenFilm.COLUMN_NAMES_JSON[i]] = ""; } } if (datenFilm.arr[DatenFilm.FILM_SENDER_NR].equals("")) { datenFilm.arr[DatenFilm.FILM_SENDER_NR] = sender; } else { sender = datenFilm.arr[DatenFilm.FILM_SENDER_NR]; } if (datenFilm.arr[DatenFilm.FILM_THEMA_NR].equals("")) { datenFilm.arr[DatenFilm.FILM_THEMA_NR] = thema; } else { thema = datenFilm.arr[DatenFilm.FILM_THEMA_NR]; } listeFilme.importFilmliste(datenFilm); } } jp.close(); ret = true; } catch (Exception ex) { MSLog.fehlerMeldung(468956200, MSLog.FEHLER_ART_PROG, "MSearchIoXmlFilmlisteLesen.filmlisteLesen", ex, "von: " + vonDatei.getName()); } return ret; }