List of usage examples for java.util.zip ZipEntry ZipEntry
public ZipEntry(ZipEntry e)
From source file:com.validation.manager.core.tool.Tool.java
public static File createZipFile(List<File> files, String zipName) throws FileNotFoundException, IOException { if (!zipName.endsWith(".zip")) { zipName += ".zip"; }//from ww w. j a v a 2s .c om File f = new File(zipName); if (f.getParentFile() != null) { f.getParentFile().mkdirs(); } try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f))) { files.forEach(file -> { try { ZipEntry ze = new ZipEntry(file.getName()); out.putNextEntry(ze); byte[] data = FileUtils.readFileToByteArray(file); out.write(data, 0, data.length); out.closeEntry(); } catch (IOException ex) { Exceptions.printStackTrace(ex); } }); } return f; }
From source file:com.esofthead.mycollab.vaadin.resources.StreamDownloadResourceSupportExtDrive.java
private void addFolderToZip(String path, Resource res, ZipOutputStream zip) throws Exception { List<Resource> lstResource; if (ResourceUtils.getType(res) == ResourceType.MyCollab) { lstResource = resourceService.getResources(res.getPath()); } else {//from w ww .j a v a 2 s .co m ExternalResourceService service = ResourceUtils.getExternalResourceService(ResourceUtils.getType(res)); lstResource = service.getResources(ResourceUtils.getExternalDrive(res), res.getPath()); } if (res instanceof Folder && lstResource.size() == 0) { // emptyFolder zip.putNextEntry(new ZipEntry(path + "/" + res.getName() + "/")); } else { if (res instanceof Folder) { zip.putNextEntry(new ZipEntry(path + "/" + res.getName() + "/")); } for (Resource curRes : lstResource) { if (curRes instanceof Folder) { addFolderToZip(path + "/" + res.getName(), curRes, zip); } else { addFileToZip(path + "/" + res.getName(), (Content) curRes, zip); } } } }
From source file:fr.smile.alfresco.module.panier.scripts.SmilePanierExportZipWebScript.java
/** * Adds the entry./* www. j a v a 2s. c o m*/ * * @param content the content * @param zipOutputStream the zip output stream * @param path the path */ private void addEntry(FileInfo content, ZipOutputStream zipOutputStream, String path) { try { DictionaryService dictionaryService = services.getDictionaryService(); ContentService contentService = services.getContentService(); FileFolderService fileFolderService = services.getFileFolderService(); String calculatePath = path; QName typeContent = content.getType(); String inContentName = content.getName(); NodeRef inContentNodeRef = content.getNodeRef(); logger.debug("Add entrry: " + inContentName); if (dictionaryService.isSubClass(typeContent, ContentModel.TYPE_CONTENT)) { logger.debug("Entry: " + inContentName + " is a content"); calculatePath = calculatePath + inContentName; logger.debug("calculatePath : " + calculatePath); ZipEntry e = new ZipEntry(calculatePath); zipOutputStream.putNextEntry(e); ContentReader inFileReader = contentService.getReader(inContentNodeRef, ContentModel.PROP_CONTENT); if (inFileReader != null) { InputStream in = inFileReader.getContentInputStream(); final int initSize = 1024; byte buffer[] = new byte[initSize]; while (true) { int readBytes = in.read(buffer, 0, buffer.length); if (readBytes <= 0) { break; } zipOutputStream.write(buffer, 0, readBytes); } in.close(); zipOutputStream.closeEntry(); } else { logger.warn("Error during read content of file " + inContentName); } } else if (dictionaryService.isSubClass(typeContent, ContentModel.TYPE_FOLDER)) { logger.debug("Entry: " + inContentName + " is a content"); calculatePath = calculatePath + inContentName + "/"; logger.debug("calculatePath : " + calculatePath); List<FileInfo> files = fileFolderService.list(inContentNodeRef); if (files.size() == 0) { ZipEntry e = new ZipEntry(calculatePath); zipOutputStream.putNextEntry(e); } else { for (FileInfo file : files) { addEntry(file, zipOutputStream, calculatePath); } } } } catch (Exception e) { throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Erreur exportation Zip : " + e.getMessage(), e); } }
From source file:au.org.ala.layers.grid.GridClassBuilder.java
public static HashMap<Integer, GridClass> buildFromGrid(String filePath) throws IOException { File wktDir = new File(filePath); wktDir.mkdirs();/*from www. j a v a 2 s . c o m*/ int[] wktMap = null; //track values for the SLD ArrayList<Integer> maxValues = new ArrayList<Integer>(); ArrayList<String> labels = new ArrayList<String>(); HashMap<Integer, GridClass> classes = new HashMap<Integer, GridClass>(); Properties p = new Properties(); p.load(new FileReader(filePath + ".txt")); boolean mergeProperties = false; Map<String, Set<Integer>> groupedKeys = new HashMap<String, Set<Integer>>(); Map<Integer, Integer> translateKeys = new HashMap<Integer, Integer>(); Map<String, Integer> translateValues = new HashMap<String, Integer>(); ArrayList<Integer> keys = new ArrayList<Integer>(); for (String key : p.stringPropertyNames()) { try { int k = Integer.parseInt(key); keys.add(k); //grouping of property file keys by value String value = p.getProperty(key); Set<Integer> klist = groupedKeys.get(value); if (klist == null) klist = new HashSet<Integer>(); else mergeProperties = true; klist.add(k); groupedKeys.put(value, klist); if (!translateValues.containsKey(value)) translateValues.put(value, translateValues.size() + 1); translateKeys.put(k, translateValues.get(value)); } catch (NumberFormatException e) { logger.info("Excluding shape key '" + key + "'"); } catch (Exception e) { logger.error(e.getMessage(), e); } } java.util.Collections.sort(keys); Grid g = new Grid(filePath); boolean generateWkt = false; //((long) g.nrows) * ((long) g.ncols) < (long) Integer.MAX_VALUE; if (mergeProperties) { g.replaceValues(translateKeys); if (!new File(filePath + ".txt.old").exists()) FileUtils.moveFile(new File(filePath + ".txt"), new File(filePath + ".txt.old")); StringBuilder sb = new StringBuilder(); for (String value : translateValues.keySet()) { sb.append(translateValues.get(value)).append("=").append(value).append('\n'); } FileUtils.writeStringToFile(new File(filePath + ".txt"), sb.toString()); return buildFromGrid(filePath); } if (generateWkt) { for (String name : groupedKeys.keySet()) { try { Set<Integer> klist = groupedKeys.get(name); String key = klist.iterator().next().toString(); int k = Integer.parseInt(key); GridClass gc = new GridClass(); gc.setName(name); gc.setId(k); if (klist.size() == 1) klist = null; logger.info("getting wkt for " + filePath + " > " + key); Map wktIndexed = Envelope.getGridSingleLayerEnvelopeAsWktIndexed( filePath + "," + key + "," + key, klist, wktMap); //write class wkt File zipFile = new File(filePath + File.separator + key + ".wkt.zip"); ZipOutputStream zos = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); zos.putNextEntry(new ZipEntry(key + ".wkt")); zos.write(((String) wktIndexed.get("wkt")).getBytes()); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream( new FileOutputStream(filePath + File.separator + key + ".wkt")); bos.write(((String) wktIndexed.get("wkt")).getBytes()); bos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (bos != null) { try { bos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("wkt written to file"); gc.setArea_km(SpatialUtil.calculateArea((String) wktIndexed.get("wkt")) / 1000.0 / 1000.0); //store map wktMap = (int[]) wktIndexed.get("map"); //write wkt index FileWriter fw = null; try { fw = new FileWriter(filePath + File.separator + key + ".wkt.index"); fw.append((String) wktIndexed.get("index")); fw.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (fw != null) { try { fw.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //write wkt index a binary, include extents (minx, miny, maxx, maxy) and area (sq km) int minPolygonNumber = 0; int maxPolygonNumber = 0; RandomAccessFile raf = null; try { raf = new RandomAccessFile(filePath + File.separator + key + ".wkt.index.dat", "rw"); String[] index = ((String) wktIndexed.get("index")).split("\n"); for (int i = 0; i < index.length; i++) { if (index[i].length() > 1) { String[] cells = index[i].split(","); int polygonNumber = Integer.parseInt(cells[0]); raf.writeInt(polygonNumber); //polygon number int polygonStart = Integer.parseInt(cells[1]); raf.writeInt(polygonStart); //character offset if (i == 0) { minPolygonNumber = polygonNumber; } else if (i == index.length - 1) { maxPolygonNumber = polygonNumber; } } } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (raf != null) { try { raf.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //for SLD maxValues.add(gc.getMaxShapeIdx()); labels.add(name.replace("\"", "'")); gc.setMinShapeIdx(minPolygonNumber); gc.setMaxShapeIdx(maxPolygonNumber); logger.info("getting multipolygon for " + filePath + " > " + key); MultiPolygon mp = Envelope.getGridEnvelopeAsMultiPolygon(filePath + "," + key + "," + key); gc.setBbox(mp.getEnvelope().toText().replace(" (", "(").replace(", ", ",")); classes.put(k, gc); try { //write class kml zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".kml.zip")); zos.putNextEntry(new ZipEntry(key + ".kml")); Encoder encoder = new Encoder(new KMLConfiguration()); encoder.setIndenting(true); encoder.encode(mp, KML.Geometry, zos); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("kml written to file"); final SimpleFeatureType TYPE = DataUtilities.createType("class", "the_geom:MultiPolygon,id:Integer,name:String"); FeatureJSON fjson = new FeatureJSON(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); SimpleFeature sf = featureBuilder.buildFeature(null); //write class geojson zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".geojson.zip")); zos.putNextEntry(new ZipEntry(key + ".geojson")); featureBuilder.add(mp); featureBuilder.add(k); featureBuilder.add(name); fjson.writeFeature(sf, zos); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("geojson written to file"); //write class shape file File newFile = new File(filePath + File.separator + key + ".shp"); ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("url", newFile.toURI().toURL()); params.put("create spatial index", Boolean.FALSE); ShapefileDataStore newDataStore = null; try { newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); newDataStore.createSchema(TYPE); newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); Transaction transaction = new DefaultTransaction("create"); String typeName = newDataStore.getTypeNames()[0]; SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName); SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; featureStore.setTransaction(transaction); List<SimpleFeature> features = new ArrayList<SimpleFeature>(); DefaultFeatureCollection collection = new DefaultFeatureCollection(); collection.addAll(features); featureStore.setTransaction(transaction); features.add(sf); featureStore.addFeatures(collection); transaction.commit(); transaction.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (newDataStore != null) { try { newDataStore.dispose(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".shp.zip")); //add .dbf .shp .shx .prj String[] exts = { ".dbf", ".shp", ".shx", ".prj" }; for (String ext : exts) { zos.putNextEntry(new ZipEntry(key + ext)); FileInputStream fis = null; try { fis = new FileInputStream(filePath + File.separator + key + ext); byte[] buffer = new byte[1024]; int size; while ((size = fis.read(buffer)) > 0) { zos.write(buffer, 0, size); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //remove unzipped files new File(filePath + File.separator + key + ext).delete(); } zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("shape file written to zip"); } catch (Exception e) { logger.error(e.getMessage(), e); } } catch (Exception e) { logger.error(e.getMessage(), e); } } //write polygon mapping g.writeGrid(filePath + File.separator + "polygons", wktMap, g.xmin, g.ymin, g.xmax, g.ymax, g.xres, g.yres, g.nrows, g.ncols); //copy the header file to get it exactly the same, but change the data type copyHeaderAsInt(filePath + ".grd", filePath + File.separator + "polygons.grd"); } else { //build classes without generating polygons Map<Float, float[]> info = new HashMap<Float, float[]>(); for (int j = 0; j < keys.size(); j++) { info.put(keys.get(j).floatValue(), new float[] { 0, Float.NaN, Float.NaN, Float.NaN, Float.NaN }); } g.getClassInfo(info); for (int j = 0; j < keys.size(); j++) { int k = keys.get(j); String key = String.valueOf(k); String name = p.getProperty(key); GridClass gc = new GridClass(); gc.setName(name); gc.setId(k); //for SLD maxValues.add(Integer.valueOf(key)); labels.add(name.replace("\"", "'")); gc.setMinShapeIdx(Integer.valueOf(key)); gc.setMaxShapeIdx(Integer.valueOf(key)); float[] stats = info.get(keys.get(j).floatValue()); //only include if area > 0 if (stats[0] > 0) { gc.setBbox("POLYGON((" + stats[1] + " " + stats[2] + "," + stats[1] + " " + stats[4] + "," + stats[3] + " " + stats[4] + "," + stats[3] + " " + stats[2] + "," + stats[1] + " " + stats[2] + "))"); gc.setArea_km((double) stats[0]); classes.put(k, gc); } } } //write sld exportSLD(filePath + File.separator + "polygons.sld", new File(filePath + ".txt").getName(), maxValues, labels); writeProjectionFile(filePath + File.separator + "polygons.prj"); //write .classes.json ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File(filePath + ".classes.json"), classes); return classes; }
From source file:game.com.HandleDownloadFolderServlet.java
public static void addDirToZipArchive(ZipOutputStream zos, File fileToZip, String parrentDirectoryName) throws Exception { if (fileToZip == null || !fileToZip.exists()) { return;//from ww w .ja v a2s. c o m } String zipEntryName = fileToZip.getName(); if (parrentDirectoryName != null && !parrentDirectoryName.isEmpty()) { zipEntryName = parrentDirectoryName + "/" + fileToZip.getName(); } if (fileToZip.isDirectory()) { System.out.println("+" + zipEntryName); for (File file : fileToZip.listFiles()) { addDirToZipArchive(zos, file, zipEntryName); } } else { System.out.println(" " + zipEntryName); byte[] buffer = new byte[1024]; FileInputStream fis = new FileInputStream(fileToZip); zos.putNextEntry(new ZipEntry(zipEntryName)); int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); fis.close(); } }
From source file:com.ecofactor.qa.automation.platform.util.FileUtil.java
/** * Adds the file to zip./*from w w w . j a v a2 s . c om*/ * @param path the path * @param srcFile the src file * @param zip the zip */ private static void addFileToZip(final String path, final String srcFile, final ZipOutputStream zip) { try { final File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip); } else { final byte[] buf = new byte[1024]; int len; final FileInputStream inputStream = new FileInputStream(srcFile); zip.putNextEntry( new ZipEntry(new StringBuilder(path).append(SLASH).append(folder.getName()).toString())); do { len = inputStream.read(buf); zip.write(buf, 0, len); } while (len > 0); inputStream.close(); } } catch (IOException e) { LOGGER.error("Error in add flies to zip", e); } }
From source file:com.insightml.utils.io.IoUtils.java
public static void zip2(final List<Pair<InputStream, String>> files, final File target) { final byte[] buffer = new byte[1024]; try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(target))) { for (final Pair<InputStream, String> file : files) { final ZipEntry ze = new ZipEntry(file.getSecond()); zos.putNextEntry(ze);/*from ww w. j a va2 s . com*/ int len; while ((len = file.getFirst().read(buffer)) > 0) { zos.write(buffer, 0, len); } file.getFirst().close(); zos.closeEntry(); } } catch (final IOException e) { throw new IllegalStateException(e); } }
From source file:net.morphbank.mbsvc3.webservices.Uploader.java
private String createZipFile() { String fileName = folderPath + "xml" + getNextReqFileNumber(folderPath) + ".zip"; String list = ""; try {// ww w. java 2 s .co m FileOutputStream fout = new FileOutputStream(fileName); ZipOutputStream zout = new ZipOutputStream(fout); for (int i = 0; i < listOfXmlFiles.size(); i++) { String file = listOfXmlFiles.get(i); if (file.endsWith(".xml")) { list += file; FileInputStream fin = new FileInputStream(listOfXmlFiles.get(i)); ZipEntry ze = new ZipEntry(listOfXmlFiles.get(i).replaceAll(folderPath, "")); zout.putNextEntry(ze); for (int c = fin.read(); c != -1; c = fin.read()) { zout.write(c); } fin.close(); } } zout.close(); fout.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fileName.replaceAll(folderPath, ""); }
From source file:de.uni_koeln.spinfo.maalr.services.editor.server.EditorServiceImpl.java
public void export(Set<String> fields, EditorQuery query, File dest) throws NoDatabaseAvailableException, IOException { query.setCurrent(0);// w w w . j a v a2s.c o m ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(dest)); zout.putNextEntry(new ZipEntry("exported.tsv")); OutputStream out = new BufferedOutputStream(zout); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); for (String field : fields) { writer.write(field); writer.write("\t"); } writer.write("\n"); while (true) { LexEntryList result = Database.getInstance().queryForLexEntries(query.getUserOrIp(), query.getRole(), query.getVerification(), query.getVerifier(), query.getStartTime(), query.getEndTime(), query.getState(), query.getPageSize(), query.getCurrent(), query.getSortColumn(), query.isSortAscending()); if (result == null || result.getEntries() == null || result.getEntries().size() == 0) break; for (LexEntry lexEntry : result.entries()) { addUserInfos(lexEntry); LemmaVersion version = lexEntry.getCurrent(); write(writer, version, fields); writer.write("\n"); } query.setCurrent(query.getCurrent() + query.getPageSize()); } writer.flush(); zout.closeEntry(); writer.close(); }