List of usage examples for java.util.zip ZipOutputStream DEFLATED
int DEFLATED
To view the source code for java.util.zip ZipOutputStream DEFLATED.
Click Source Link
From source file:fr.smile.alfresco.module.panier.scripts.SmilePanierExportZipWebScript.java
@Override public void execute(WebScriptRequest request, WebScriptResponse res) throws IOException { String userName = AuthenticationUtil.getFullyAuthenticatedUser(); PersonService personService = services.getPersonService(); NodeRef userNodeRef = personService.getPerson(userName); MimetypeService mimetypeService = services.getMimetypeService(); FileFolderService fileFolderService = services.getFileFolderService(); Charset archiveEncoding = Charset.forName("ISO-8859-1"); String encoding = request.getParameter("encoding"); if (StringUtils.isNotEmpty(encoding)) { archiveEncoding = Charset.forName(encoding); }// w w w . ja v a 2 s . co m ZipOutputStream fileZip = new ZipOutputStream(res.getOutputStream(), archiveEncoding); String folderName = "mon_panier"; try { String zipFileExtension = "." + mimetypeService.getExtension(MimetypeMap.MIMETYPE_ZIP); res.setContentType(MimetypeMap.MIMETYPE_ZIP); res.setHeader("Content-Transfer-Encoding", "binary"); res.addHeader("Content-Disposition", "attachment;filename=\"" + normalizeZipFileName(folderName) + zipFileExtension + "\""); res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); res.setHeader("Pragma", "public"); res.setHeader("Expires", "0"); fileZip.setMethod(ZipOutputStream.DEFLATED); fileZip.setLevel(Deflater.BEST_COMPRESSION); String archiveRootPath = folderName + "/"; List<NodeRef> list = smilePanierService.getSelection(userNodeRef); List<FileInfo> filesInfos = new ArrayList<FileInfo>(); for (int i = 0; i < list.size(); i++) { FileInfo fileInfo = fileFolderService.getFileInfo(list.get(i)); filesInfos.add(fileInfo); } for (FileInfo file : filesInfos) { addEntry(file, fileZip, archiveRootPath); } fileZip.closeEntry(); } catch (Exception e) { throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Erreur exportation Zip", e); } finally { fileZip.close(); } }
From source file:JarUtil.java
/** * Adds the given file to the specified JAR file. * // w w w . j av a 2 s. com * @param file * the file that should be added * @param jarFile * The JAR to which the file should be added * @param parentDir * the parent directory of the file, this is used to calculate * the path witin the JAR file. When null is given, the file will * be added into the root of the JAR. * @param compress * True when the jar file should be compressed * @throws FileNotFoundException * when the jarFile does not exist * @throws IOException * when a file could not be written or the jar-file could not * read. */ public static void addToJar(File file, File jarFile, File parentDir, boolean compress) throws FileNotFoundException, IOException { File tmpJarFile = File.createTempFile("tmp", ".jar", jarFile.getParentFile()); JarOutputStream out = new JarOutputStream(new FileOutputStream(tmpJarFile)); if (compress) { out.setLevel(ZipOutputStream.DEFLATED); } else { out.setLevel(ZipOutputStream.STORED); } // copy contents of old jar to new jar: JarFile inputFile = new JarFile(jarFile); JarInputStream in = new JarInputStream(new FileInputStream(jarFile)); CRC32 crc = new CRC32(); byte[] buffer = new byte[512 * 1024]; JarEntry entry = (JarEntry) in.getNextEntry(); while (entry != null) { InputStream entryIn = inputFile.getInputStream(entry); add(entry, entryIn, out, crc, buffer); entryIn.close(); entry = (JarEntry) in.getNextEntry(); } in.close(); inputFile.close(); int sourceDirLength; if (parentDir == null) { sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1; } else { sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1 - parentDir.getAbsolutePath().length(); } addFile(file, out, crc, sourceDirLength, buffer); out.close(); // remove old jar file and rename temp file to old one: if (jarFile.delete()) { if (!tmpJarFile.renameTo(jarFile)) { throw new IOException( "Unable to rename temporary JAR file to [" + jarFile.getAbsolutePath() + "]."); } } else { throw new IOException("Unable to delete old JAR file [" + jarFile.getAbsolutePath() + "]."); } }
From source file:org.apache.felix.webconsole.internal.misc.ConfigurationRender.java
/** * @see org.apache.felix.webconsole.AbstractWebConsolePlugin#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from ww w .j a v a2 s . c o m protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getPathInfo().endsWith(".txt")) { response.setContentType("text/plain; charset=utf-8"); ConfigurationWriter pw = new PlainTextConfigurationWriter(response.getWriter()); printConfigurationStatus(pw, ConfigurationPrinter.MODE_TXT); pw.flush(); } else if (request.getPathInfo().endsWith(".zip")) { String type = getServletContext().getMimeType(request.getPathInfo()); if (type == null) { type = "application/x-zip"; } response.setContentType(type); ZipOutputStream zip = new ZipOutputStream(response.getOutputStream()); zip.setLevel(Deflater.BEST_SPEED); zip.setMethod(ZipOutputStream.DEFLATED); final ConfigurationWriter pw = new ZipConfigurationWriter(zip); printConfigurationStatus(pw, ConfigurationPrinter.MODE_ZIP); pw.flush(); addAttachments(pw, ConfigurationPrinter.MODE_ZIP); zip.finish(); } else if (request.getPathInfo().endsWith(".nfo")) { WebConsoleUtil.setNoCache(response); response.setContentType("text/html; charset=utf-8"); String name = request.getPathInfo(); name = name.substring(name.lastIndexOf('/') + 1); name = name.substring(0, name.length() - 4); name = WebConsoleUtil.urlDecode(name); ConfigurationWriter pw = new HtmlConfigurationWriter(response.getWriter()); pw.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); pw.println(" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); pw.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); pw.println("<head><title>dummy</title></head><body><div>"); Collection printers = getConfigurationPrinters(); for (Iterator i = printers.iterator(); i.hasNext();) { final PrinterDesc desc = (PrinterDesc) i.next(); if (desc.label.equals(name)) { printConfigurationPrinter(pw, desc, ConfigurationPrinter.MODE_WEB); pw.println("</div></body></html>"); return; } } response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid configuration printer: " + name); } else { super.doGet(request, response); } }
From source file:org.nuxeo.ecm.platform.io.impl.IOManagerImpl.java
void exportDocumentsAndResources(OutputStream out, String repo, DocumentsExporter docsExporter, Collection<String> ioAdapters) throws IOException { List<String> doneAdapters = new ArrayList<>(); ZipOutputStream zip = new ZipOutputStream(out); zip.setMethod(ZipOutputStream.DEFLATED); zip.setLevel(9);/*from w ww.j av a 2 s . c om*/ ByteArrayOutputStream docsZip = new ByteArrayOutputStream(); DocumentTranslationMap map = docsExporter.exportDocs(docsZip); ZipEntry docsEntry = new ZipEntry(DOCUMENTS_ADAPTER_NAME + ".zip"); zip.putNextEntry(docsEntry); zip.write(docsZip.toByteArray()); zip.closeEntry(); docsZip.close(); doneAdapters.add(DOCUMENTS_ADAPTER_NAME); Collection<DocumentRef> allSources = map.getDocRefMap().keySet(); if (ioAdapters != null && !ioAdapters.isEmpty()) { for (String adapterName : ioAdapters) { String filename = adapterName + ".xml"; IOResourceAdapter adapter = getAdapter(adapterName); if (adapter == null) { log.warn("Adapter " + adapterName + " not found"); continue; } if (doneAdapters.contains(adapterName)) { log.warn("Export for adapter " + adapterName + " already done"); continue; } IOResources resources = adapter.extractResources(repo, allSources); resources = adapter.translateResources(repo, resources, map); ByteArrayOutputStream adapterOut = new ByteArrayOutputStream(); adapter.getResourcesAsXML(adapterOut, resources); ZipEntry adapterEntry = new ZipEntry(filename); zip.putNextEntry(adapterEntry); zip.write(adapterOut.toByteArray()); zip.closeEntry(); doneAdapters.add(adapterName); adapterOut.close(); } } try { zip.close(); } catch (ZipException e) { // empty zip file, do nothing } }
From source file:org.waterforpeople.mapping.dataexport.KMLApplet.java
private void processFile(String fileName, ArrayList<String> countryList) throws Exception { System.out.println("Calling GenerateDocument"); VelocityContext context = new VelocityContext(); File f = new File(fileName); if (!f.exists()) { f.createNewFile();/*from w w w. ja v a 2 s.c om*/ } ZipOutputStream zipOut = null; try { zipOut = new ZipOutputStream(new FileOutputStream(fileName)); zipOut.setLevel(ZipOutputStream.DEFLATED); ZipEntry entry = new ZipEntry("ap.kml"); zipOut.putNextEntry(entry); zipOut.write(mergeContext(context, "template/DocumentHead.vm").getBytes("UTF-8")); for (String countryCode : countryList) { int i = 0; String cursor = null; PlacemarkDtoResponse pdr = BulkDataServiceClient.fetchPlacemarks(countryCode, serverBase, cursor); if (pdr != null) { cursor = pdr.getCursor(); List<PlacemarkDto> placemarkDtoList = pdr.getDtoList(); SwingUtilities.invokeLater(new StatusUpdater("Staring to processes " + countryCode)); writePlacemark(placemarkDtoList, zipOut); SwingUtilities.invokeLater(new StatusUpdater("Processing complete for " + countryCode)); while (cursor != null) { pdr = BulkDataServiceClient.fetchPlacemarks(countryCode, serverBase, cursor); if (pdr != null) { if (pdr.getCursor() != null) cursor = pdr.getCursor(); else cursor = null; placemarkDtoList = pdr.getDtoList(); System.out.println("Starting to process: " + countryCode); writePlacemark(placemarkDtoList, zipOut); System.out.println("Fetching next set of records for: " + countryCode + " : " + i++); } else { break; } } } } zipOut.write(mergeContext(context, "template/DocumentFooter.vm").getBytes("UTF-8")); zipOut.closeEntry(); zipOut.close(); } catch (Exception ex) { System.out.println(ex + " " + ex.getMessage() + " "); ex.printStackTrace(System.out); } }
From source file:controller.GaleriaController.java
@br.com.caelum.vraptor.Path("galeria/zipGaleria/{galeriaId}") public Download zipGaleria(long galeriaId) { validator.ensure(sessao.getIdsPermitidosDeGalerias().contains(galeriaId), new SimpleMessage("galeria", "Acesso negado")); Galeria galeria = new Galeria(); galeria.setId(galeriaId);/*www .j a v a 2s . c o m*/ List<Imagem> imagens = imagemDao.listByGaleria(galeria); validator.addIf(imagens == null || imagens.isEmpty(), new SimpleMessage("galeria", "Galeria vazia")); validator.onErrorRedirectTo(UsuarioController.class).viewGaleria(galeriaId); List<Path> paths = new ArrayList<>(); for (Imagem imagem : imagens) { String realPath = servletContext.getRealPath("/"); java.nio.file.Path imagemPath = new File(realPath + "/" + UPLOAD_DIR + "/" + imagem.getFileName()) .toPath(); paths.add(imagemPath); } byte buffer[] = new byte[2048]; try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos)) { zos.setMethod(ZipOutputStream.DEFLATED); zos.setLevel(5); for (Path path : paths) { try (FileInputStream fis = new FileInputStream(path.toFile()); BufferedInputStream bis = new BufferedInputStream(fis)) { String pathFileName = path.getFileName().toString(); zos.putNextEntry(new ZipEntry(pathFileName)); int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { zos.write(buffer, 0, bytesRead); } zos.closeEntry(); zos.flush(); } catch (IOException e) { result.include("mensagem", "Erro no download do zip"); result.forwardTo(UsuarioController.class).viewGaleria(galeriaId); return null; } } zos.finish(); byte[] zip = baos.toByteArray(); Download download = new ByteArrayDownload(zip, "application/zip", sessao.getUsuario().getNome() + ".zip"); return download; //zipDownload = new ZipDownload(sessao.getUsuario().getNome() + ".zip", paths); //return zipDownloadBuilder.build(); } catch (IOException e) { result.include("mensagem", "Erro no download do zip"); result.forwardTo(UsuarioController.class).viewGaleria(galeriaId); return null; } }
From source file:org.eclipse.mylyn.internal.context.core.InteractionContextExternalizer.java
/** * For testing/*w w w. ja va2 s.co m*/ */ public void writeContext(IInteractionContext context, ZipOutputStream outputStream, IInteractionContextWriter writer) throws IOException { String handleIdentifier = context.getHandleIdentifier(); String encoded = URLEncoder.encode(handleIdentifier, InteractionContextManager.CONTEXT_FILENAME_ENCODING); ZipEntry zipEntry = new ZipEntry(encoded + InteractionContextManager.CONTEXT_FILE_EXTENSION_OLD); outputStream.putNextEntry(zipEntry); outputStream.setMethod(ZipOutputStream.DEFLATED); writer.setOutputStream(outputStream); writer.writeContextToStream(context); outputStream.flush(); outputStream.closeEntry(); addAdditionalInformation(context, outputStream); }
From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java
protected void doUpload() { DbAdapter dba = new DbAdapter(this); dba.open();/*from w w w.j a v a 2 s. c om*/ Cursor allLogs = dba.fetchAll(); StringBuilder sb = new StringBuilder(); allLogs.moveToFirst(); sb.append("DateTime"); sb.append(","); sb.append("Process"); sb.append(","); sb.append("Type"); sb.append(","); sb.append("Component"); sb.append(","); sb.append("ActionString"); sb.append(","); sb.append("Category"); sb.append("\n"); while (!allLogs.isAfterLast()) { sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_TIME))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_PROCESSTAG))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_1))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_2))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_3))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_4))); sb.append("\n"); allLogs.moveToNext(); } dba.close(); File appDir = getDir("toUpload", MODE_PRIVATE); UUID uuid; uuid = MainScreen.getOrCreateUUID(this); long time = System.currentTimeMillis(); String basename = uuid.toString() + "_AT_" + time; String filename = basename + ".zip.enc"; File file = new File(appDir, filename); FileOutputStream out = null; ZipOutputStream outzip = null; CipherOutputStream outcipher = null; Cipher datac = null; File keyfile = new File(appDir, basename + ".key.enc"); //Log.i("sb length", Integer.toString(sb.length())); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String email = prefs.getString(MainScreen.EMAIL_KEY, ""); String emailFilename = "email.txt"; String csvFilename = "mouflon_log_" + time + ".csv"; try { SecretKey aeskey = generateAESKey(); //Log.i("secret key", bytearrToString(aeskey.getEncoded())); encryptAndWriteAESKey(aeskey, keyfile); datac = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC"); byte[] ivbytes = genIV(); IvParameterSpec iv = new IvParameterSpec(ivbytes); datac.init(Cipher.ENCRYPT_MODE, aeskey, iv); out = new FileOutputStream(file); out.write(ivbytes); //Log.i("iv bytes", bytearrToString(ivbytes)); outcipher = new CipherOutputStream(out, datac); outzip = new ZipOutputStream(outcipher); outzip.setMethod(ZipOutputStream.DEFLATED); //write the first file (e-mail address) String androidVersion = android.os.Build.VERSION.RELEASE; String deviceName = android.os.Build.MODEL; ZipEntry infoEntry = new ZipEntry("info.txt"); outzip.putNextEntry(infoEntry); outzip.write((androidVersion + "\n" + deviceName).getBytes()); outzip.closeEntry(); ZipEntry emailEntry = new ZipEntry(emailFilename); outzip.putNextEntry(emailEntry); outzip.write(email.getBytes()); outzip.closeEntry(); ZipEntry csvEntry = new ZipEntry(csvFilename); outzip.putNextEntry(csvEntry); outzip.write(sb.toString().getBytes()); outzip.closeEntry(); } catch (Exception e) { e.printStackTrace(); } finally { try { outzip.close(); outcipher.close(); out.close(); } catch (IOException e) { //ignore } catch (NullPointerException ne) { //ignore } } //here we actually upload the files String containerFilename = basename + "_container.zip"; File containerFile = new File(appDir, containerFilename); zipUp(containerFile, new File[] { file, keyfile }); boolean success = uploadFile(containerFile); containerFile.delete(); file.delete(); keyfile.delete(); if (success && prefs.getBoolean(MainScreen.DELETE_KEY, true)) { DbAdapter dba2 = new DbAdapter(this); dba2.open(); dba2.clearDB(); dba2.close(); } if (!success && prefs.getBoolean(MainScreen.UPLOAD_KEY, false)) { Editor e = prefs.edit(); e.putInt(MainScreen.DAY_KEY, 6); //reset it to run tomorrow if it fails e.commit(); } String s = success ? "Upload complete. Thanks!" : "Upload Failed"; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(UploadFile.this) .setSmallIcon(R.drawable.ic_launcher_bw).setContentTitle("Mouflon Recorder").setContentText(s) .setAutoCancel(true).setOngoing(false); if (mManual) { //only show a notification if we manually upload the file. Intent toLaunch = new Intent(UploadFile.this, MainScreen.class); //The notification has to go somewhere. PendingIntent pi = PendingIntent.getActivity(UploadFile.this, 0, toLaunch, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pi); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(1, mBuilder.build()); } stopSelf(); }
From source file:com.l2jfree.sql.L2DataSource.java
protected static final boolean writeBackup(String databaseName, InputStream in) throws IOException { FileUtils.forceMkdir(new File("backup/database")); final Date time = new Date(); final L2TextBuilder tb = new L2TextBuilder(); tb.append("backup/database/DatabaseBackup_"); tb.append(new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date())); tb.append("_uptime-").append(L2Config.getShortUptime()); tb.append(".zip"); final File backupFile = new File(tb.moveToString()); int written = 0; ZipOutputStream out = null;/*from w ww .j a v a2 s .c o m*/ try { out = new ZipOutputStream(new FileOutputStream(backupFile)); out.setMethod(ZipOutputStream.DEFLATED); out.setLevel(Deflater.BEST_COMPRESSION); out.setComment("L2jFree Schema Backup Utility\r\n\r\nBackup date: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS z").format(new Date())); out.putNextEntry(new ZipEntry(databaseName + ".sql")); byte[] buf = new byte[4096]; for (int read; (read = in.read(buf)) != -1;) { out.write(buf, 0, read); written += read; } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } if (written == 0) { backupFile.delete(); return false; } _log.info("DatabaseBackupManager: Database `" + databaseName + "` backed up successfully in " + (System.currentTimeMillis() - time.getTime()) / 1000 + " s."); return true; }
From source file:org.opensha.commons.util.FileUtils.java
/** * This function creates a Zip file called "allFiles.zip" for all the * files that exist in filesPath./*from www . j av a2 s . c o m*/ * @param filesPath String Folder with absolute path in zip file will be created. * This function searches for all the files in the folder "filesPath" and adds * those to a single zip file "allFiles.zip". */ public static void createZipFile(String filesPath) { int BUFFER = 8192; String zipFileName = "allFiles.zip"; if (!filesPath.endsWith(SystemUtils.FILE_SEPARATOR)) filesPath = filesPath + SystemUtils.FILE_SEPARATOR; try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filesPath + zipFileName); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); out.setMethod(ZipOutputStream.DEFLATED); byte data[] = new byte[BUFFER]; // get a list of files from current directory File f = new File(filesPath); String files[] = f.list(); for (int i = 0; i < files.length; i++) { if (files[i].equals(zipFileName)) continue; System.out.println("Adding: " + files[i]); FileInputStream fi = new FileInputStream(filesPath + files[i]); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(files[i]); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } origin.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } }