List of usage examples for java.util.zip ZipInputStream ZipInputStream
public ZipInputStream(InputStream in, Charset charset)
From source file:eu.freme.eservices.epublishing.EPublishingService.java
/** * Creates an EPUB3 file from the input stream. * @param metadata Some extra meta data * @param in The input. It is supposed to be a zip file. The caller of this method is responsible for closing the stream! * @return The EPUB. It is the binary contents of a zipped EPUB-3 file. * @throws InvalidZipException//from w ww. j av a 2s .co m * @throws EPubCreationException * @throws IOException * @throws MissingMetadataException */ public byte[] createEPUB(Metadata metadata, InputStream in) throws InvalidZipException, EPubCreationException, IOException, MissingMetadataException { // initialize the class that parses the input, and passes data to the EPUB creator File unzippedPath = new File(tempFolderPath, "freme_epublishing_" + System.currentTimeMillis()); FileUtils.forceDeleteOnExit(unzippedPath); try (ZipInputStream zin = new ZipInputStream(in, StandardCharsets.UTF_8)) { Unzipper.unzip(zin, unzippedPath); EPubCreator creator = new EPubCreatorImpl(metadata, unzippedPath); // write the EPUB "file", in this case to bytes try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { creator.onEnd(bos); return bos.toByteArray(); } } catch (IOException ex) { Logger.getLogger(EPublishingService.class.getName()).log(Level.SEVERE, null, ex); throw new InvalidZipException( "Something went wrong with the provided Zip file. Make sure you are providing a valid Zip file."); } finally { FileUtils.deleteDirectory(unzippedPath); } }
From source file:eu.freme.eservices.publishing.EPublishingService.java
/** * Creates an EPUB3 file from the input stream. * @param metadata Some extra meta mockup-endpoint-data * @param in The input. It is supposed to be a zip file. The caller of this method is responsible for closing the stream! * @return The EPUB. It is the binary contents of a zipped EPUB-3 file. * @throws InvalidZipException/*from www . j a v a 2 s. co m*/ * @throws EPubCreationException * @throws IOException * @throws MissingMetadataException */ public byte[] createEPUB(Metadata metadata, InputStream in) throws InvalidZipException, EPubCreationException, IOException, MissingMetadataException { // initialize the class that parses the input, and passes mockup-endpoint-data to the EPUB creator File unzippedPath = new File(tempFolderPath, "freme_epublishing_" + System.currentTimeMillis()); FileUtils.forceDeleteOnExit(unzippedPath); try (ZipInputStream zin = new ZipInputStream(in, StandardCharsets.UTF_8)) { Unzipper.unzip(zin, unzippedPath); EPubCreator creator = new EPubCreatorImpl(metadata, unzippedPath); // write the EPUB "file", in this case to bytes try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { creator.onEnd(bos); return bos.toByteArray(); } } catch (IOException ex) { Logger.getLogger(EPublishingService.class.getName()).log(Level.SEVERE, null, ex); throw new InvalidZipException( "Something went wrong with the provided Zip file. Make sure you are providing a valid Zip file."); } finally { FileUtils.deleteDirectory(unzippedPath); } }
From source file:io.gromit.geolite2.geonames.CountryFinder.java
/** * Read countries.//w w w. jav a2 s .c o m * * @param countriesLocationUrl the countries location url * @return the country finder */ private CountryFinder readCountries(String countriesLocationUrl) { ZipInputStream zipis = null; try { zipis = new ZipInputStream(new URL(countriesLocationUrl).openStream(), Charset.forName("UTF-8")); ZipEntry zipEntry = zipis.getNextEntry(); logger.info("reading " + zipEntry.getName()); if (crc == zipEntry.getCrc()) { logger.info("skipp, same CRC"); return this; } CsvParserSettings settings = new CsvParserSettings(); settings.setSkipEmptyLines(true); settings.trimValues(true); CsvFormat format = new CsvFormat(); format.setDelimiter('\t'); format.setLineSeparator("\n"); format.setCharToEscapeQuoteEscaping('\0'); format.setQuote('\0'); settings.setFormat(format); CsvParser parser = new CsvParser(settings); List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8")); for (String[] entry : lines) { Country country = new Country(); country.setIso(entry[0]); country.setIso3(entry[1]); country.setName(entry[2]); country.setCapital(entry[3]); country.setContinent(entry[4]); country.setCurrencyCode(entry[5]); country.setCurrencyName(entry[6]); country.setPhone(entry[7]); country.setLanguage(StringUtils.substringBefore(entry[8], ",")); country.setGeonameId(NumberUtils.toInt(entry[9])); geonameMap.put(country.getGeonameId(), country); isoMap.put(country.getIso(), country); } } catch (Exception e) { throw new RuntimeException(e); } finally { try { zipis.close(); } catch (Exception e) { } ; } logger.info("loaded " + geonameMap.size() + " countries"); return this; }
From source file:org.kawakicchi.bookshelf.interfaces.book.BookController.java
@RequestMapping(value = { "/store" }, method = RequestMethod.POST) public String store(@ModelAttribute StoreForm form, final Model model) { setting(model);//from w w w.j a v a 2 s. co m if (BookshelfUtil.isBlank(form.getTitle()) || form.getFile().isEmpty()) { model.addAttribute("form", form); final List<SeriesEntity> seriesList = viewerService.getSeriesList(); model.addAttribute("seriesList", seriesList); return "/book/store"; } File tmpDir = new File("tmp"); tmpDir.mkdirs(); List<ContentEntity> files = new ArrayList<ContentEntity>(); byte[] buf = new byte[1024]; try (ZipInputStream zipStream = new ZipInputStream(form.getFile().getInputStream(), Charset.forName("MS932"))) { for (ZipEntry entry = zipStream.getNextEntry(); entry != null; entry = zipStream.getNextEntry()) { if (entry.isDirectory()) continue; String id = BookshelfUtil.generateUUID(); File tmpFile = Paths.get(tmpDir.getAbsolutePath(), id).toFile(); OutputStream oStream = new FileOutputStream(tmpFile); int size = -1; while (0 <= (size = zipStream.read(buf, 0, 1024))) { oStream.write(buf, 0, size); } oStream.close(); Metadata metadata = ImageMetadataReader.readMetadata(tmpFile); for (Directory directory : metadata.getDirectories()) { for (Tag tag : directory.getTags()) { System.out.format("[%s] - %s = %s", directory.getName(), tag.getTagName(), tag.getDescription()); } if (directory.hasErrors()) { for (String error : directory.getErrors()) { System.err.format("ERROR: %s", error); } } } BufferedImage img = ImageIO.read(tmpFile); System.out.println(String.format("%d / %d", img.getWidth(), img.getHeight())); String[] ss = entry.getName().split("/"); files.add(new ContentEntity(ss[ss.length - 1], tmpFile, img.getWidth(), img.getHeight())); } } catch (ImageProcessingException ex) { } catch (IOException ex) { } bookshelfService.createBook(form.getTitle(), form.getSeries(), files); return "/book/store"; }
From source file:io.sledge.core.impl.installer.SledgePackageConfigurer.java
private void createNewZipfileWithReplacedPlaceholders(InputStream packageStream, Path configurationPackagePath, Properties envProps) throws IOException { // For reading the original configuration package ZipInputStream configPackageZipStream = new ZipInputStream(new BufferedInputStream(packageStream), Charset.forName("UTF-8")); // For outputting the configured (placeholders replaced) version of the package as zip file File outZipFile = configurationPackagePath.toFile(); ZipOutputStream outConfiguredZipStream = new ZipOutputStream(new FileOutputStream(outZipFile)); ZipEntry zipEntry;//w w w .j av a 2s. com while ((zipEntry = configPackageZipStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) { configPackageZipStream.closeEntry(); continue; } else { ByteArrayOutputStream output = new ByteArrayOutputStream(); int length; byte[] buffer = new byte[2048]; while ((length = configPackageZipStream.read(buffer, 0, buffer.length)) >= 0) { output.write(buffer, 0, length); } InputStream zipEntryInputStream = new BufferedInputStream( new ByteArrayInputStream(output.toByteArray())); if (zipEntry.getName().endsWith("instance.properties")) { ByteArrayOutputStream envPropsOut = new ByteArrayOutputStream(); envProps.store(envPropsOut, "Environment configurations"); zipEntryInputStream = new BufferedInputStream( new ByteArrayInputStream(envPropsOut.toByteArray())); } else if (isTextFile(zipEntry.getName(), zipEntryInputStream)) { String configuredContent = StrSubstitutor.replace(output, envProps); zipEntryInputStream = new BufferedInputStream( new ByteArrayInputStream(configuredContent.getBytes())); } // Add to output zip file addToZipFile(zipEntry.getName(), zipEntryInputStream, outConfiguredZipStream); zipEntryInputStream.close(); configPackageZipStream.closeEntry(); } } outConfiguredZipStream.close(); configPackageZipStream.close(); }
From source file:io.gromit.geolite2.geonames.CityFinder.java
/** * Read cities./*from ww w . j a v a 2 s . c om*/ * * @param citiesLocationUrl the cities location url * @return the city finder */ private CityFinder readCities(String citiesLocationUrl) { ZipInputStream zipis = null; CsvParserSettings settings = new CsvParserSettings(); settings.setSkipEmptyLines(true); settings.trimValues(true); CsvFormat format = new CsvFormat(); format.setDelimiter('\t'); format.setLineSeparator("\n"); format.setComment('\0'); format.setCharToEscapeQuoteEscaping('\0'); format.setQuote('\0'); settings.setFormat(format); CsvParser parser = new CsvParser(settings); try { zipis = new ZipInputStream(new URL(citiesLocationUrl).openStream(), Charset.forName("UTF-8")); ZipEntry zipEntry = zipis.getNextEntry(); logger.info("reading " + zipEntry.getName()); if (crc == zipEntry.getCrc()) { logger.info("skipp, same CRC"); return this; } RTree<City, Geometry> rtreeRead = RTree.create(); List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8")); for (String[] entry : lines) { City city = new City(); city.setGeonameId(Integer.decode(entry[0])); city.setName(entry[1]); try { try { city.setLatitude(Double.valueOf(entry[2])); city.setLongitude(Double.valueOf(entry[3])); rtreeRead = rtreeRead.add(city, Geometries.pointGeographic(city.getLongitude(), city.getLatitude())); } catch (NumberFormatException | NullPointerException e) { } city.setCountryIsoCode(entry[4]); city.setSubdivisionOne(entry[5]); city.setSubdivisionTwo(entry[6]); city.setTimeZone(entry[7]); } catch (ArrayIndexOutOfBoundsException e) { } geonameMap.put(city.getGeonameId(), city); } this.rtree = rtreeRead; logger.info("loaded " + geonameMap.size() + " cities"); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { try { zipis.close(); } catch (Exception e) { } ; } return this; }
From source file:herddb.upgrade.ZIPUtils.java
public static List<File> unZip(InputStream fs, File outDir) throws IOException { try (ZipInputStream zipStream = new ZipInputStream(fs, StandardCharsets.UTF_8);) { ZipEntry entry = zipStream.getNextEntry(); List<File> listFiles = new ArrayList<>(); while (entry != null) { if (entry.isDirectory()) { entry = zipStream.getNextEntry(); continue; }// ww w.j a va2 s. co m String normalized = normalizeFilenameForFileSystem(entry.getName()); File outFile = new File(outDir, normalized); File parentDir = outFile.getParentFile(); if (parentDir != null && !parentDir.isDirectory()) { Files.createDirectories(parentDir.toPath()); } listFiles.add(outFile); try (FileOutputStream out = new FileOutputStream(outFile); SimpleBufferedOutputStream oo = new SimpleBufferedOutputStream(out)) { IOUtils.copyLarge(zipStream, oo); } entry = zipStream.getNextEntry(); } return listFiles; } catch (IllegalArgumentException ex) { throw new IOException(ex); } }
From source file:io.gromit.geolite2.geonames.SubdivisionFinder.java
/** * Read countries.// w w w . ja v a 2 s .c o m * * @param subdivisionOneLocationUrl the subdivision one location url * @return the time zone finder */ public SubdivisionFinder readLevelOne(String subdivisionOneLocationUrl) { ZipInputStream zipis = null; try { zipis = new ZipInputStream(new URL(subdivisionOneLocationUrl).openStream(), Charset.forName("UTF-8")); ZipEntry zipEntry = zipis.getNextEntry(); logger.info("reading " + zipEntry.getName()); if (crc1 == zipEntry.getCrc()) { logger.info("skipp, same CRC"); return this; } CsvParserSettings settings = new CsvParserSettings(); settings.setSkipEmptyLines(true); settings.trimValues(true); CsvFormat format = new CsvFormat(); format.setDelimiter('\t'); format.setLineSeparator("\n"); format.setCharToEscapeQuoteEscaping('\0'); format.setQuote('\0'); settings.setFormat(format); CsvParser parser = new CsvParser(settings); List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8")); for (String[] entry : lines) { Subdivision subdivision = new Subdivision(); subdivision.setId(entry[0]); subdivision.setName(entry[1]); subdivision.setGeonameId(NumberUtils.toInt(entry[2])); idOneMap.put(subdivision.getId(), subdivision); geonameIdMap.put(subdivision.getGeonameId(), subdivision); } logger.info("loaded " + lines.size() + " subdivisions level 1"); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { try { zipis.close(); } catch (Exception e) { } ; } return this; }
From source file:io.sledge.core.impl.extractor.SledgeApplicationPackageExtractor.java
@Override public DeploymentConfiguration getDeploymentConfiguration(InputStream appPackageInputStream) { DeploymentConfiguration deploymentConfig = null; ZipInputStream zipStream = new ZipInputStream(new BufferedInputStream(appPackageInputStream), Charset.forName("UTF-8")); try {// w w w . j a v a 2 s.c om byte[] buffer = new byte[2048]; ZipEntry zipEntry = null; while ((zipEntry = zipStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) { zipStream.closeEntry(); continue; } if (zipEntry.getName().startsWith(SLEDGEFILE_XML)) { ByteArrayOutputStream output = new ByteArrayOutputStream(); int length; while ((length = zipStream.read(buffer, 0, buffer.length)) >= 0) { output.write(buffer, 0, length); } DeploymentConfigurationReader deploymentConfigReader = new DeploymentConfigurationReaderXml(); deploymentConfig = deploymentConfigReader .parseDeploymentConfiguration(new ByteArrayInputStream(output.toByteArray())); zipStream.closeEntry(); // Stop here, the file is read break; } } } catch (IOException e) { log.error(e.getMessage(), e); } finally { try { zipStream.close(); appPackageInputStream.reset(); } catch (IOException e) { log.error(e.getMessage(), e); } } return deploymentConfig; }
From source file:com.gnadenheimer.mg3.controller.admin.AdminConfigController.java
@FXML private void cmdUpdateSET(ActionEvent event) { Task taskUpdateSET = new Task<Void>() { @Override//from w ww . j a va 2 s .c om public Void call() { try { EntityManager entityManager = Utils.getInstance().getEntityManagerFactory() .createEntityManager(); entityManager.getTransaction().begin(); String temp = ""; Integer count = 0; entityManager.createQuery("delete from TblContribuyentes t").executeUpdate(); for (Integer i = 0; i <= 9; i++) { URL url = new URL( "http://www.set.gov.py/rest/contents/download/collaboration/sites/PARAGUAY-SET/documents/informes-periodicos/ruc/ruc" + String.valueOf(i) + ".zip"); ZipInputStream zipStream = new ZipInputStream(url.openStream(), StandardCharsets.UTF_8); zipStream.getNextEntry(); Scanner sc = new Scanner(zipStream, "UTF-8"); while (sc.hasNextLine()) { String[] ruc = sc.nextLine().split("\\|"); temp = ruc[0] + " - " + ruc[1] + " - " + ruc[2]; if (ruc[0].length() > 0 && ruc[1].length() > 0 && ruc[2].length() == 1) { TblContribuyentes c = new TblContribuyentes(); c.setRucSinDv(ruc[0]); c.setRazonSocial(StringEscapeUtils.escapeSql(ruc[1])); c.setDv(ruc[2]); entityManager.persist(c); updateMessage("Descargando listado de RUC con terminacion " + String.valueOf(i) + " - Cantidad de contribuyentes procesada: " + String.format("%,d", count) + " de aprox. 850.000."); count++; } else { updateMessage(temp); } } entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); } updateMessage("Lista de RUC actualizada..."); return null; } catch (Exception ex) { App.showException(this.getClass().getName(), ex.getMessage(), ex); } return null; } }; lblUpdateSET.textProperty().bind(taskUpdateSET.messageProperty()); new Thread(taskUpdateSET).start(); }