List of usage examples for java.util.zip ZipOutputStream write
public synchronized void write(byte[] b, int off, int len) throws IOException
From source file:io.openvidu.server.recording.service.SingleStreamRecordingService.java
private void generateZipFileAndCleanFolder(String folder, String fileName) { FileOutputStream fos = null;//from w ww .ja v a 2s. c om ZipOutputStream zipOut = null; final File[] files = new File(folder).listFiles(); try { fos = new FileOutputStream(folder + fileName); zipOut = new ZipOutputStream(fos); for (int i = 0; i < files.length; i++) { String fileExtension = FilenameUtils.getExtension(files[i].getName()); if (files[i].isFile() && (fileExtension.equals("json") || fileExtension.equals("webm"))) { // Zip video files and json sync metadata file FileInputStream fis = new FileInputStream(files[i]); ZipEntry zipEntry = new ZipEntry(files[i].getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } fis.close(); } if (!files[i].getName().startsWith(RecordingManager.RECORDING_ENTITY_FILE)) { // Clean inspected file if it is not files[i].delete(); } } } catch (IOException e) { log.error("Error generating ZIP file {}. Error: {}", folder + fileName, e.getMessage()); } finally { try { zipOut.close(); fos.close(); this.updateFilePermissions(folder); } catch (IOException e) { log.error("Error closing FileOutputStream or ZipOutputStream. Error: {}", e.getMessage()); e.printStackTrace(); } } }
From source file:edu.stanford.epad.epadws.handlers.dicom.DownloadUtil.java
public static boolean ZipAndStreamFiles(OutputStream out, List<String> fileNames, String dirPath) { File dir_file = new File(dirPath); int dir_l = dir_file.getAbsolutePath().length(); ZipOutputStream zipout = new ZipOutputStream(out); zipout.setLevel(1);//from www . j a v a 2 s . com for (int i = 0; i < fileNames.size(); i++) { File f = (File) new File(dirPath + fileNames.get(i)); if (f.canRead()) { log.debug("Adding file: " + f.getAbsolutePath()); try { zipout.putNextEntry(new ZipEntry(f.getAbsolutePath().substring(dir_l + 1))); } catch (Exception e) { log.warning("Error adding to zip file", e); return false; } BufferedInputStream fr; try { fr = new BufferedInputStream(new FileInputStream(f)); byte buffer[] = new byte[0xffff]; int b; while ((b = fr.read(buffer)) != -1) zipout.write(buffer, 0, b); fr.close(); zipout.closeEntry(); } catch (Exception e) { log.warning("Error closing zip file", e); return false; } } } try { zipout.finish(); out.flush(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
From source file:org.messic.server.api.APISong.java
@Transactional public void getSongsZip(User user, List<Long> desiredSongs, OutputStream os) throws IOException { ZipOutputStream zos = new ZipOutputStream(os); // level - the compression level (0-9) zos.setLevel(9);/*from w ww .j ava 2s.co m*/ HashMap<String, String> songs = new HashMap<String, String>(); for (Long songSid : desiredSongs) { MDOSong song = daoSong.get(user.getLogin(), songSid); if (song != null) { // add file // extract the relative name for entry purpose String entryName = song.getLocation(); if (songs.get(entryName) == null) { // not repeated songs.put(entryName, "ok"); ZipEntry ze = new ZipEntry(entryName); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(song.calculateAbsolutePath(daoSettings.getSettings())); int len; byte buffer[] = new byte[1024]; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); } } } zos.close(); }
From source file:org.egov.ptis.actions.reports.SearchNoticesAction.java
/** * @param inputStream//from w w w. ja v a 2s.c om * @param noticeNo * @param out * @return zip output stream file */ private ZipOutputStream addFilesToZip(final InputStream inputStream, final String noticeNo, final ZipOutputStream out) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Entered into addFilesToZip method"); final byte[] buffer = new byte[1024]; try { out.setLevel(Deflater.DEFAULT_COMPRESSION); out.putNextEntry(new ZipEntry(noticeNo.replaceAll("/", "_"))); int len; while ((len = inputStream.read(buffer)) > 0) out.write(buffer, 0, len); inputStream.close(); } catch (final IllegalArgumentException iae) { LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, iae); throw new ValidationException(Arrays.asList(new ValidationError(ERROR1, iae.getMessage()))); } catch (final FileNotFoundException fnfe) { LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, fnfe); throw new ValidationException(Arrays.asList(new ValidationError(ERROR1, fnfe.getMessage()))); } catch (final IOException ioe) { LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, ioe); throw new ValidationException(Arrays.asList(new ValidationError(ERROR1, ioe.getMessage()))); } if (LOGGER.isDebugEnabled()) LOGGER.debug("Exit from addFilesToZip method"); return out; }
From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java
private void copyToZip(byte[] buffer, ZipOutputStream zout, File[] files, int i, FileInputStream fin) throws IOException { zout.putNextEntry(new ZipEntry(files[i].getName())); int length;/*from w w w. ja v a 2 s. c o m*/ while ((length = fin.read(buffer)) > 0) { zout.write(buffer, 0, length); } }
From source file:controllers.admin.AuditableController.java
/** * Creates an archive of all the audit logs files and set it into the * personal space of the current user.// w ww.j a v a 2 s .c om */ public Promise<Result> exportAuditLogs() { return Promise.promise(new Function0<Result>() { @Override public Result apply() throws Throwable { try { final String currentUserId = getUserSessionManagerPlugin().getUserSessionId(ctx()); final String errorMessage = Msg.get("admin.auditable.export.notification.error.message"); final String successTitle = Msg.get("admin.auditable.export.notification.success.title"); final String successMessage = Msg.get("admin.auditable.export.notification.success.message"); final String notFoundMessage = Msg.get("admin.auditable.export.notification.not_found.message"); final String errorTitle = Msg.get("admin.auditable.export.notification.error.title"); // Audit log export requested if (log.isDebugEnabled()) { log.debug("Audit log export : Audit log export requested by " + currentUserId); } // Execute asynchronously getSysAdminUtils().scheduleOnce(false, "AUDITABLE", Duration.create(0, TimeUnit.MILLISECONDS), new Runnable() { @Override public void run() { // Find the files to be archived String logFilesPathAsString = getConfiguration() .getString("maf.audit.log.location"); File logFilesPath = new File(logFilesPathAsString); File logDirectory = logFilesPath.getParentFile(); if (!logDirectory.exists()) { log.error("Log directory " + logDirectory.getAbsolutePath() + " is not found, please check the configuration"); return; } final String logFilePrefix = (logFilesPath.getName().indexOf('.') != -1 ? logFilesPath.getName().substring(0, logFilesPath.getName().indexOf('.')) : logFilesPath.getName()); if (log.isDebugEnabled()) { log.debug("Audit log export : Selecting files to archive"); } File[] filesToArchive = logDirectory.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(logFilePrefix); } }); if (filesToArchive.length != 0) { if (log.isDebugEnabled()) { log.debug("Audit log export : zipping the " + filesToArchive.length + " archive files"); } // Write to the user personal space final String fileName = String.format( "auditExport_%1$td_%1$tm_%1$ty_%1$tH-%1$tM-%1$tS.zip", new Date()); ZipOutputStream out = null; try { OutputStream personalOut = getPersonalStoragePlugin() .createNewFile(currentUserId, fileName); out = new ZipOutputStream(personalOut); for (File fileToArchive : filesToArchive) { ZipEntry e = new ZipEntry(fileToArchive.getName()); out.putNextEntry(e); byte[] data = FileUtils.readFileToByteArray(fileToArchive); out.write(data, 0, data.length); out.closeEntry(); } getNotificationManagerPlugin().sendNotification(currentUserId, NotificationCategory.getByCode(Code.AUDIT), successTitle, successMessage, controllers.my.routes.MyPersonalStorage.index().url()); } catch (Exception e) { log.error("Fail to export the audit archives", e); getNotificationManagerPlugin().sendNotification(currentUserId, NotificationCategory.getByCode(Code.ISSUE), errorTitle, errorMessage, controllers.admin.routes.AuditableController .listAuditable().url()); } finally { IOUtils.closeQuietly(out); } } else { log.error("No audit archive found in the folder"); getNotificationManagerPlugin().sendNotification(currentUserId, NotificationCategory.getByCode(Code.ISSUE), errorTitle, notFoundMessage, controllers.admin.routes.AuditableController.listAuditable().url()); } } }); return ok(Json.newObject()); } catch (Exception e) { return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(), getMessagesPlugin()); } } }); }
From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java
/** * Creates a zip archive of the currently serialized files in * getCurrentDirectory(), placing the archive in getArchiveDirectory(). * * @throws RuntimeException if clazz cannot be serialized. This exception * has an informative message and wraps the * originally thrown exception as root cause. * @see #getCurrentDirectory()/* w w w . jav a 2s . co m*/ * @see #getArchiveDirectory() */ public void archiveCurrentDirectory() throws RuntimeException { System.out.println("Making zip archive of files in " + getCurrentDirectory() + ", putting it in " + getArchiveDirectory() + "."); File current = new File(getCurrentDirectory()); if (!current.exists() || !current.isDirectory()) { throw new IllegalArgumentException("There is no " + current.getAbsolutePath() + " directory. " + "\nThis is where the serialized classes should be. " + "Please run serializeCurrentDirectory() first."); } File archive = new File(getArchiveDirectory()); if (archive.exists() && !archive.isDirectory()) { throw new IllegalArgumentException( "Output directory " + archive.getAbsolutePath() + " is not a directory."); } if (!archive.exists()) { boolean success = archive.mkdirs(); } String[] filenames = current.list(); // Create a buffer for reading the files byte[] buf = new byte[1024]; try { String version = Version.currentRepositoryVersion().toString(); // Create the ZIP file String outFilename = "serializedclasses-" + version + ".zip"; File _file = new File(getArchiveDirectory(), outFilename); FileOutputStream fileOut = new FileOutputStream(_file); ZipOutputStream out = new ZipOutputStream(fileOut); // Compress the files for (String filename : filenames) { File file = new File(current, filename); FileInputStream in = new FileInputStream(file); // Add ZIP entry to output stream. ZipEntry entry = new ZipEntry(filename); entry.setSize(file.length()); entry.setTime(file.lastModified()); out.putNextEntry(entry); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Complete the entry out.closeEntry(); in.close(); } // Complete the ZIP file out.close(); System.out.println("Finished writing zip file " + outFilename + "."); } catch (IOException e) { throw new RuntimeException("There was an I/O error associated with " + "the process of zipping up files in " + getCurrentDirectory() + ".", e); } }
From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java
/** * Creates a zip archive of the currently serialized files in * getCurrentDirectory(), placing the archive in getArchiveDirectory(). * * @throws RuntimeException if clazz cannot be serialized. This exception * has an informative message and wraps the * originally thrown exception as root cause. * @see #getCurrentDirectory()/*w w w .j a va2 s . c om*/ * @see #getArchiveDirectory() */ public void archiveCurrentDirectory() throws RuntimeException { System.out.println("Making zip archive of files in " + getCurrentDirectory() + ", putting it in " + getArchiveDirectory() + "."); File current = new File(getCurrentDirectory()); if (!current.exists() || !current.isDirectory()) { throw new IllegalArgumentException("There is no " + current.getAbsolutePath() + " directory. " + "\nThis is where the serialized classes should be. " + "Please run serializeCurrentDirectory() first."); } File archive = new File(getArchiveDirectory()); if (archive.exists() && !archive.isDirectory()) { throw new IllegalArgumentException( "Output directory " + archive.getAbsolutePath() + " is not a directory."); } if (!archive.exists()) { archive.mkdirs(); } String[] filenames = current.list(); // Create a buffer for reading the files byte[] buf = new byte[1024]; try { String version = Version.currentRepositoryVersion().toString(); // Create the ZIP file String outFilename = "serializedclasses-" + version + ".zip"; File _file = new File(getArchiveDirectory(), outFilename); FileOutputStream fileOut = new FileOutputStream(_file); ZipOutputStream out = new ZipOutputStream(fileOut); // Compress the files for (String filename : filenames) { File file = new File(current, filename); FileInputStream in = new FileInputStream(file); // Add ZIP entry to output stream. ZipEntry entry = new ZipEntry(filename); entry.setSize(file.length()); entry.setTime(file.lastModified()); out.putNextEntry(entry); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Complete the entry out.closeEntry(); in.close(); } // Complete the ZIP file out.close(); System.out.println("Finished writing zip file " + outFilename + "."); } catch (IOException e) { throw new RuntimeException("There was an I/O error associated with " + "the process of zipping up files in " + getCurrentDirectory() + ".", e); } }
From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java
public String exportZippedResultsForUser(String deviceId) throws FileNotFoundException { String resultsDir = deviceId + File.separator; String zipFilename = deviceId + ".zip"; new File(resultsDir).mkdir(); saveResultsToFilesForDeviceId(deviceId, resultsDir); ZipOutputStream zipOutputStream = null; try {//from w w w. j a va 2 s .c o m zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFilename)); File zipDir = new File(resultsDir); String[] dirList = zipDir.list(); byte[] readBuffer = new byte[4096]; int bytesIn = 0; for (int i = 0; i < dirList.length; i++) { FileInputStream fis = null; try { File f = new File(zipDir, dirList[i]); fis = new FileInputStream(f); ZipEntry anEntry = new ZipEntry(f.getPath()); zipOutputStream.putNextEntry(anEntry); while ((bytesIn = fis.read(readBuffer)) != -1) { zipOutputStream.write(readBuffer, 0, bytesIn); } } catch (IOException ex) { ex.printStackTrace(); } finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } finally { if (zipOutputStream != null) { try { zipOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } removeDir(resultsDir); return zipFilename; }
From source file:org.messic.server.api.APIPlayLists.java
@Transactional public void getPlaylistZip(User user, Long playlistSid, OutputStream os) throws IOException, SidNotFoundMessicException { MDOPlaylist mdoplaylist = daoPlaylist.get(user.getLogin(), playlistSid); if (mdoplaylist == null) { throw new SidNotFoundMessicException(); }/*w w w . j a v a 2 s. c o m*/ List<MDOSong> desiredSongs = mdoplaylist.getSongs(); ZipOutputStream zos = new ZipOutputStream(os); // level - the compression level (0-9) zos.setLevel(9); HashMap<String, String> songs = new HashMap<String, String>(); M3U m3u = new M3U(); m3u.setExtensionM3U(true); List<Resource> resources = m3u.getResources(); for (MDOSong song : desiredSongs) { if (song != null) { // add file // extract the relative name for entry purpose String entryName = song.getLocation(); if (songs.get(entryName) == null) { Resource r = new Resource(); r.setLocation(song.getLocation()); r.setName(song.getName()); resources.add(r); songs.put(entryName, "ok"); // song not repeated ZipEntry ze = new ZipEntry(entryName); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(song.calculateAbsolutePath(daoSettings.getSettings())); int len; byte buffer[] = new byte[1024]; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); } } } // the last is the playlist m3u ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { m3u.writeTo(baos, "UTF8"); // song not repeated ZipEntry ze = new ZipEntry(mdoplaylist.getName() + ".m3u"); zos.putNextEntry(ze); byte[] bytes = baos.toByteArray(); zos.write(bytes, 0, bytes.length); zos.closeEntry(); } catch (Exception e) { e.printStackTrace(); } zos.close(); }