List of usage examples for java.util.zip ZipOutputStream closeEntry
public void closeEntry() throws IOException
From source file:org.auscope.portal.server.web.controllers.JobListController.java
/** * Sends the contents of one or more job files as a ZIP archive to the * client.//w w w . j a v a 2 s. co m * * @param request The servlet request including a jobId parameter and a * files parameter with the filenames separated by comma * @param response The servlet response receiving the data * * @return null on success or the joblist view with an error parameter on * failure. */ @RequestMapping("/downloadAsZip.do") public ModelAndView downloadAsZip(HttpServletRequest request, HttpServletResponse response) { String jobIdStr = request.getParameter("jobId"); String filesParam = request.getParameter("files"); GeodesyJob job = null; String errorString = null; if (jobIdStr != null) { try { int jobId = Integer.parseInt(jobIdStr); job = jobManager.getJobById(jobId); } catch (NumberFormatException e) { logger.error("Error parsing job ID!"); } } if (job != null && filesParam != null) { String[] fileNames = filesParam.split(","); logger.debug("Archiving " + fileNames.length + " file(s) of job " + jobIdStr); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=\"jobfiles.zip\""); try { boolean readOneOrMoreFiles = false; ZipOutputStream zout = new ZipOutputStream(response.getOutputStream()); for (String fileName : fileNames) { File f = new File(job.getOutputDir() + File.separator + fileName); if (!f.canRead()) { // if a file could not be read we go ahead and try the // next one. logger.error("File " + f.getPath() + " not readable!"); } else { byte[] buffer = new byte[16384]; int count = 0; zout.putNextEntry(new ZipEntry(fileName)); FileInputStream fin = new FileInputStream(f); while ((count = fin.read(buffer)) != -1) { zout.write(buffer, 0, count); } zout.closeEntry(); readOneOrMoreFiles = true; } } if (readOneOrMoreFiles) { zout.finish(); zout.flush(); zout.close(); return null; } else { zout.close(); errorString = new String("Could not access the files!"); logger.error(errorString); } } catch (IOException e) { errorString = new String("Could not create ZIP file: " + e.getMessage()); logger.error(errorString); } } // We only end up here in case of an error so return a suitable message if (errorString == null) { if (job == null) { errorString = new String("Invalid job specified!"); logger.error(errorString); } else if (filesParam == null) { errorString = new String("No filename(s) provided!"); logger.error(errorString); } else { // should never get here errorString = new String("Something went wrong."); logger.error(errorString); } } return new ModelAndView("joblist", "error", errorString); }
From source file:org.obiba.mica.file.service.FileSystemService.java
/** * Creates a zipped file of the path and it's subdirectories/files * * @param path//from w w w. ja va2 s. c o m * @param publishedFS * @return */ public String zipDirectory(String path, boolean publishedFS) { List<AttachmentState> attachmentStates = getAllowedStates(path, publishedFS); String zipName = Paths.get(path).getFileName().toString() + ".zip"; FileOutputStream fos = null; try { byte[] buffer = new byte[1024]; fos = tempFileService.getFileOutputStreamFromFile(zipName); ZipOutputStream zos = new ZipOutputStream(fos); for (AttachmentState state : attachmentStates) { if (FileUtils.isDirectory(state)) { zos.putNextEntry(new ZipEntry(relativizePaths(path, state.getFullPath()) + File.separator)); } else { zos.putNextEntry(new ZipEntry(relativizePaths(path, state.getFullPath()))); InputStream in = fileStoreService .getFile(publishedFS ? state.getPublishedAttachment().getFileReference() : state.getAttachment().getFileReference()); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); } zos.closeEntry(); } zos.finish(); } catch (IOException ioe) { Throwables.propagate(ioe); } finally { IOUtils.closeQuietly(fos); } return zipName; }
From source file:de.unioninvestment.portal.explorer.view.vfs.TableView.java
public void attach() { selectedDir = cb.getVfsUrl();/*from w w w .jav a2 s . c o m*/ try { final VFSFileExplorerPortlet app = instance; final User user = (User) app.getUser(); final FileSystemManager fFileSystemManager = fileSystemManager; final FileSystemOptions fOpts = opts; final Table table = new Table() { private static final long serialVersionUID = 1L; protected String formatPropertyValue(Object rowId, Object colId, Property property) { if (TABLE_PROP_FILE_NAME.equals(colId)) { if (property != null && property.getValue() != null) { return getDisplayPath(property.getValue().toString()); } } if (TABLE_PROP_FILE_DATE.equals(colId)) { if (property != null && property.getValue() != null) { SimpleDateFormat sdf = new SimpleDateFormat("dd.MMM yyyy HH:mm:ss"); return sdf.format((Date) property.getValue()); } } return super.formatPropertyValue(rowId, colId, property); } }; table.setSizeFull(); table.setMultiSelect(true); table.setSelectable(true); table.setImmediate(true); table.addContainerProperty(TABLE_PROP_FILE_NAME, String.class, null); table.addContainerProperty(TABLE_PROP_FILE_SIZE, Long.class, null); table.addContainerProperty(TABLE_PROP_FILE_DATE, Date.class, null); if (app != null) { app.getEventBus().addHandler(TableChangedEvent.class, new TableChangedEventHandler() { private static final long serialVersionUID = 1L; @Override public void onValueChanged(TableChangedEvent event) { try { selectedDir = event.getNewDirectory(); fillTableData(event.getNewDirectory(), table, fFileSystemManager, fOpts, null); } catch (IOException e) { e.printStackTrace(); } } }); } table.addListener(new Table.ValueChangeListener() { private static final long serialVersionUID = 1L; public void valueChange(ValueChangeEvent event) { Set<?> value = (Set<?>) event.getProperty().getValue(); if (null == value || value.size() == 0) { markedRows = null; } else { markedRows = value; } } }); fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); Button btDownload = new Button("Download File(s)"); btDownload.addListener(new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { if (markedRows == null || markedRows.size() == 0) getWindow().showNotification("No Files selected !", Window.Notification.TYPE_WARNING_MESSAGE); else { String[] files = new String[markedRows.size()]; int fileCount = 0; for (Object item : markedRows) { Item it = table.getItem(item); files[fileCount] = it.getItemProperty(TABLE_PROP_FILE_NAME).toString(); fileCount++; } File dlFile = null; if (fileCount == 1) { try { String fileName = files[0]; dlFile = getFileFromVFSObject(fFileSystemManager, fOpts, fileName); logger.log(Level.INFO, "vfs2portlet: download file " + fileName + " by " + user.getScreenName()); } catch (Exception e) { e.printStackTrace(); } } else { byte[] buf = new byte[1024]; try { dlFile = File.createTempFile("Files", ".zip"); ZipOutputStream out = new ZipOutputStream( new FileOutputStream(dlFile.getAbsolutePath())); for (int i = 0; i < files.length; i++) { String fileName = files[i]; logger.log(Level.INFO, "vfs2portlet: download file " + fileName + " by " + user.getScreenName()); File f = getFileFromVFSObject(fFileSystemManager, fOpts, fileName); FileInputStream in = new FileInputStream(f); out.putNextEntry(new ZipEntry(f.getName())); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); } catch (IOException e) { } } if (dlFile != null) { try { DownloadResource downloadResource = new DownloadResource(dlFile, getApplication()); getApplication().getMainWindow().open(downloadResource, "_new"); } catch (FileNotFoundException e) { getWindow().showNotification("File not found !", Window.Notification.TYPE_ERROR_MESSAGE); e.printStackTrace(); } } if (dlFile != null) { dlFile.delete(); } } } }); Button btDelete = new Button("Delete File(s)"); btDelete.addListener(new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { if (markedRows == null || markedRows.size() == 0) getWindow().showNotification("No Files selected !", Window.Notification.TYPE_WARNING_MESSAGE); else { for (Object item : markedRows) { Item it = table.getItem(item); String fileToDelete = it.getItemProperty(TABLE_PROP_FILE_NAME).toString(); logger.log(Level.INFO, "Delete File " + fileToDelete); try { FileObject delFile = fFileSystemManager.resolveFile(fileToDelete, fOpts); logger.log(Level.INFO, "vfs2portlet: delete file " + delFile.getName() + " by " + user.getScreenName()); boolean b = delFile.delete(); if (b) logger.log(Level.INFO, "delete ok"); else logger.log(Level.INFO, "delete failed"); } catch (FileSystemException e) { e.printStackTrace(); } } try { fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); } catch (IOException e) { e.printStackTrace(); } } } }); Button selAll = new Button("Select All", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(Button.ClickEvent event) { table.setValue(table.getItemIds()); } }); Button selNone = new Button("Select None", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(Button.ClickEvent event) { table.setValue(null); } }); final UploadReceiver receiver = new UploadReceiver(); upload = new Upload(null, receiver); upload.setImmediate(true); upload.setButtonCaption("File Upload"); upload.addListener((new Upload.SucceededListener() { private static final long serialVersionUID = 1L; public void uploadSucceeded(SucceededEvent event) { try { String fileName = receiver.getFileName(); ByteArrayOutputStream bos = receiver.getUploadedFile(); byte[] buf = bos.toByteArray(); ByteArrayInputStream bis = new ByteArrayInputStream(buf); String fileToAdd = selectedDir + "/" + fileName; logger.log(Level.INFO, "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName()); FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts); localFile.createFile(); OutputStream localOutputStream = localFile.getContent().getOutputStream(); IOUtils.copy(bis, localOutputStream); localOutputStream.flush(); fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); app.getMainWindow().showNotification("Upload " + fileName + " successful ! ", Notification.TYPE_TRAY_NOTIFICATION); } catch (Exception e) { e.printStackTrace(); } } })); upload.addListener(new Upload.FailedListener() { private static final long serialVersionUID = 1L; public void uploadFailed(FailedEvent event) { System.out.println("Upload failed ! "); } }); multiFileUpload = new MultiFileUpload() { private static final long serialVersionUID = 1L; protected void handleFile(File file, String fileName, String mimeType, long length) { try { byte[] buf = FileUtils.readFileToByteArray(file); ByteArrayInputStream bis = new ByteArrayInputStream(buf); String fileToAdd = selectedDir + "/" + fileName; logger.log(Level.INFO, "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName()); FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts); localFile.createFile(); OutputStream localOutputStream = localFile.getContent().getOutputStream(); IOUtils.copy(bis, localOutputStream); localOutputStream.flush(); fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); } catch (FileSystemException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } protected FileBuffer createReceiver() { FileBuffer receiver = super.createReceiver(); /* * Make receiver not to delete files after they have been * handled by #handleFile(). */ receiver.setDeleteFiles(false); return receiver; } }; multiFileUpload.setUploadButtonCaption("Upload File(s)"); HorizontalLayout filterGrp = new HorizontalLayout(); filterGrp.setSpacing(true); final TextField tfFilter = new TextField(); Button btFileFilter = new Button("Filter", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(Button.ClickEvent event) { String filterVal = (String) tfFilter.getValue(); try { if (filterVal == null || filterVal.length() == 0) { fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); } else { fillTableData(selectedDir, table, fFileSystemManager, fOpts, filterVal); } } catch (IOException e) { e.printStackTrace(); } } }); Button btResetFileFilter = new Button("Reset", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(Button.ClickEvent event) { try { tfFilter.setValue(""); fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); } catch (ReadOnlyException e) { e.printStackTrace(); } catch (ConversionException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); filterGrp.addComponent(tfFilter); filterGrp.addComponent(btFileFilter); filterGrp.addComponent(btResetFileFilter); addComponent(filterGrp); addComponent(table); HorizontalLayout btGrp = new HorizontalLayout(); btGrp.setSpacing(true); btGrp.addComponent(selAll); btGrp.setComponentAlignment(selAll, Alignment.MIDDLE_CENTER); btGrp.addComponent(selNone); btGrp.setComponentAlignment(selNone, Alignment.MIDDLE_CENTER); btGrp.addComponent(btDownload); btGrp.setComponentAlignment(btDownload, Alignment.MIDDLE_CENTER); List<Role> roles = null; boolean matchUserRole = false; try { if (user != null) { roles = user.getRoles(); } } catch (SystemException e) { e.printStackTrace(); } if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() == 0) { btGrp.addComponent(btDelete); btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER); } else if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() > 0) { matchUserRole = isUserInRole(roles, cb.getDeleteRoles()); if (matchUserRole) { btGrp.addComponent(btDelete); btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER); } } if (cb.isUploadEnabled() && cb.getUploadRoles().length() == 0) { btGrp.addComponent(upload); btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER); btGrp.addComponent(multiFileUpload); btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER); } else if (cb.isUploadEnabled() && cb.getUploadRoles().length() > 0) { matchUserRole = isUserInRole(roles, cb.getUploadRoles()); if (matchUserRole) { btGrp.addComponent(upload); btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER); btGrp.addComponent(multiFileUpload); btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER); } } addComponent(btGrp); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java
protected void exportMessages(ZipOutputStream zos, String path) throws WPBIOException { try {/* w ww . j ava 2 s . c om*/ List<WPBMessage> messages = dataStorage.getAllRecords(WPBMessage.class); Map<String, List<WPBMessage>> languageToMessages = new HashMap<String, List<WPBMessage>>(); for (WPBMessage message : messages) { String lcid = message.getLcid(); if (!languageToMessages.containsKey(lcid)) { languageToMessages.put(lcid, new ArrayList<WPBMessage>()); } languageToMessages.get(lcid).add(message); } Set<String> languages = languageToMessages.keySet(); for (String language : languages) { for (WPBMessage message : languageToMessages.get(language)) { String messageXmlPath = path + language + "/" + message.getExternalKey() + "/" + "metadata.xml"; Map<String, Object> map = new HashMap<String, Object>(); exporter.export(message, map); map.put("lcid", language); ZipEntry metadataZe = new ZipEntry(messageXmlPath); zos.putNextEntry(metadataZe); exportToXMLFormat(map, zos); zos.closeEntry(); } } } catch (IOException e) { log.log(Level.SEVERE, e.getMessage(), e); throw new WPBIOException("Cannot export messages to Zip", e); } }
From source file:org.bdval.BDVModel.java
/** * Save the model to a set the specified zip stream. The files will contain all the * information needed to apply the BDVal model to new samples. * * @param zipStream The stream to store the model to * @param options The options associated with this model * @param task The classification task used for this model * @param splitPlan The split plan used to generat this model * @param writeModelMode The mode saving the model * @throws IOException if there is a problem writing to the files *//*from www . java2 s . c o m*/ protected void save(final ZipOutputStream zipStream, final DAVOptions options, final ClassificationTask task, final SplitPlan splitPlan, final WriteModel writeModelMode) throws IOException { setZipStreamComment(zipStream); // Add ZIP entry for the model properties to output stream. saveProperties(zipStream, options, task, splitPlan, writeModelMode); // Add ZIP entries for the model training platform to output stream. savePlatform(zipStream, options); // Add ZIP entry for the model to output stream. zipStream.putNextEntry(new ZipEntry(FilenameUtils.getName(modelFilename))); // use an intermediate stream here since the model writer will close the stream final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); helper.model.write(byteArrayOutputStream); byteArrayOutputStream.writeTo(zipStream); zipStream.closeEntry(); if (options.scaleFeatures) { if (options.probesetScaleMeanMap.size() <= 0) { throw new IllegalArgumentException("mean map must be populated."); } if (options.probesetScaleRangeMap.size() <= 0) { throw new IllegalArgumentException("range map must be populated."); } } // Add ZIP entry for the scale mean map to output stream. saveMeansMap(zipStream, options); // Add ZIP entry for the scale range map to output stream. saveRangeMap(zipStream, options); }
From source file:org.esupportail.portlet.filemanager.services.ServersAccessService.java
private void addChildrensTozip(ZipOutputStream out, byte[] zippingBuffer, String dir, String folder, SharedUserPortletParameters userParameters) throws IOException { JsTreeFile tFile = get(dir, userParameters, false, false); if ("file".equals(tFile.getType())) { DownloadFile dFile = getFile(dir, userParameters); //GIP Recia : In some cases (ie, file has NTFS security permissions set), the dFile may be Null. //So we must check for null in order to prevent a general catastrophe if (dFile == null) { log.warn("Download file is null! " + dir); return; }/*from ww w. ja va 2s. c om*/ String fileName = unAccent(folder.concat(dFile.getBaseName())); //With java 7, encoding should be added to support special characters in the file names //http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244499 out.putNextEntry(new ZipEntry(fileName)); // MBD: this is a problem for large files, because IOUtils.toByteArray() copy all the file in memory //out.write(IOUtils.toByteArray(dFile.getInputStream())); int count; final InputStream dFileInputStream = dFile.getInputStream(); while ((count = dFileInputStream.read(zippingBuffer, 0, ZIP_BUFFER_SIZE)) != -1) { out.write(zippingBuffer, 0, count); } out.closeEntry(); } else { folder = unAccent(folder.concat(tFile.getTitle()).concat("/")); //Added for GIP Recia : This creates an empty file with the same name as the directory but it allows //for zipping empty directories out.putNextEntry(new ZipEntry(folder)); out.closeEntry(); List<JsTreeFile> childrens = this.getChildren(dir, userParameters); for (JsTreeFile child : childrens) { this.addChildrensTozip(out, zippingBuffer, child.getPath(), folder, userParameters); } } }
From source file:fr.smile.alfresco.module.panier.scripts.SmilePanierExportZipWebScript.java
/** * Adds the entry.//ww w . j av a2 s . com * * @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:com.orange.mmp.midlet.MidletManager.java
/** * Builds a ZIP archive with the appropriate name * @param mobile/*from w w w.j a va 2s .c o m*/ * @param signMidlet * @param output * @return The ZIP filename * @throws IOException * @throws MMPException */ public String computeZip(Mobile mobile, Boolean signMidlet, OutputStream output) throws IOException, MMPException { //Compute Zip ZipOutputStream zipOS = new ZipOutputStream(output); try { //Get default service Service service = ServiceManager.getInstance().getDefaultService(); //Create fake ticket DeliveryTicket ticket = new DeliveryTicket(); ticket.setServiceId(service.getId()); //Get navigation widget (main scene) Widget appWidget = WidgetManager.getInstance().getWidget(ticket.getServiceId(), mobile.getBranchId()); if (appWidget == null) appWidget = WidgetManager.getInstance().getWidget(ticket.getServiceId()); if (appWidget == null) throw new IOException("application " + ticket.getServiceId() + " not found"); ByteArrayOutputStream tmpOS = null; //Add JAD zipOS.putNextEntry( new ZipEntry(appWidget.getName() + com.orange.mmp.midlet.Constants.JAD_FILE_EXTENSION)); tmpOS = getJad(ticket.getId(), mobile, signMidlet, service); tmpOS.writeTo(zipOS); zipOS.closeEntry(); //Add JAR zipOS.putNextEntry( new ZipEntry(appWidget.getName() + com.orange.mmp.midlet.Constants.JAR_FILE_EXTENSION)); tmpOS = getJar(service.getId(), mobile, signMidlet); tmpOS.writeTo(zipOS); zipOS.closeEntry(); zipOS.flush(); String[] tmpVersion = appWidget.getVersion().toString().split("\\."); if (tmpVersion.length > 2) { return appWidget.getName() + "_V" + tmpVersion[0] + "." + tmpVersion[1] + appWidget.getBranchId() + "." + tmpVersion[2]; } return appWidget.getName() + "_V" + appWidget.getVersion() + "_" + appWidget.getBranchId(); } finally { try { zipOS.close(); } catch (IOException ioe) { } } }