List of usage examples for java.util.zip ZipOutputStream ZipOutputStream
public ZipOutputStream(OutputStream out)
From source file:at.alladin.rmbt.controlServer.QualityOfServiceExportResource.java
@Get public Representation request(final String entity) { //Before doing anything => check if a cached file already exists and is new enough String property = System.getProperty("java.io.tmpdir"); final File cachedFile = new File(property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML)); final File generatingFile = new File( property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML) + "_tmp"); if (cachedFile.exists()) { //check if file has been recently created OR a file is currently being created if (((cachedFile.lastModified() + cacheThresholdMs) > (new Date()).getTime()) || (generatingFile.exists() && (generatingFile.lastModified() + cacheThresholdMs) > (new Date()).getTime())) { //if so, return the cached file instead of a cost-intensive new one final OutputRepresentation result = new OutputRepresentation( zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_HTML) { @Override//from w ww . j a v a 2s. c om public void write(OutputStream out) throws IOException { InputStream is = new FileInputStream(cachedFile); IOUtils.copy(is, out); out.close(); } }; if (zip) { final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(FILENAME_ZIP); result.setDisposition(disposition); } return result; } } //final List<String> data = new ArrayList<String>(); final StringBuilder sb = new StringBuilder(); QoSTestObjectiveDao nnObjectiveDao = new QoSTestObjectiveDao(conn); QoSTestDescDao nnDescDao = new QoSTestDescDao(conn, null); try { Map<String, List<QoSTestObjective>> map = nnObjectiveDao.getAllToMap(); Iterator<String> keys = map.keySet().iterator(); sb.append("<h1>Contents:</h1>"); sb.append("<ol>"); sb.append("<li><a href=\"#table1\">qos_test_objective</a></li>"); sb.append("<li><a href=\"#table2\">qos_test_desc</a></li>"); sb.append("</ol><br>"); sb.append("<h1 id=\"table1\">Test objectives table (qos_test_objective)</h1>"); while (keys.hasNext()) { String testType = keys.next(); List<QoSTestObjective> list = map.get(testType); sb.append("<h2>Test group: " + testType.toUpperCase() + "</h2><ul>"); //data.add("<h2>Test group: " + testType.toUpperCase() + "</h2>"); for (QoSTestObjective item : list) { //data.add(item.toHtml()); sb.append("<li>"); sb.append(item.toHtml()); sb.append("</li>"); } sb.append("</ul>"); } Map<String, List<QoSTestDesc>> descMap = nnDescDao.getAllToMapIgnoreLang(); keys = descMap.keySet().iterator(); sb.append("<h1 id=\"table2\">Language table (qos_test_desc)</h1><ul>"); while (keys.hasNext()) { String descKey = keys.next(); List<QoSTestDesc> list = descMap.get(descKey); sb.append("<li><h4 id=\"" + descKey.replaceAll("[\\-\\+\\.\\^:,]", "_") + "\">KEY (column: desc_key): <i>" + descKey + "</i></h4><ul>"); //data.add("<h3>KEY: <i>" + descKey + "</i></h3><ul>"); for (QoSTestDesc item : list) { sb.append("<li><i>" + item.getLang() + "</i>: " + item.getValue() + "</li>"); //data.add("<li><i>" + item.getLang() + "</i>: " + item.getValue() + "</li>"); } sb.append("</ul></li>"); //data.add("</ul>"); } sb.append("</ul>"); } catch (final SQLException e) { e.printStackTrace(); return null; } final OutputRepresentation result = new OutputRepresentation( zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_HTML) { @Override public void write(OutputStream out) throws IOException { //cache in file => create temporary temporary file (to // handle errors while fulfilling a request) String property = System.getProperty("java.io.tmpdir"); final File cachedFile = new File( property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML) + "_tmp"); OutputStream outf = new FileOutputStream(cachedFile); if (zip) { final ZipOutputStream zos = new ZipOutputStream(outf); final ZipEntry zeLicense = new ZipEntry("LIZENZ.txt"); zos.putNextEntry(zeLicense); final InputStream licenseIS = getClass().getResourceAsStream("DATA_LICENSE.txt"); IOUtils.copy(licenseIS, zos); licenseIS.close(); final ZipEntry zeCsv = new ZipEntry(FILENAME_HTML); zos.putNextEntry(zeCsv); outf = zos; } try (OutputStreamWriter osw = new OutputStreamWriter(outf)) { osw.write(sb.toString()); osw.flush(); } if (zip) outf.close(); //if we reach this code, the data is now cached in a temporary tmp-file //so, rename the file for "production use2 //concurrency issues should be solved by the operating system File newCacheFile = new File(property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML)); Files.move(cachedFile.toPath(), newCacheFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); FileInputStream fis = new FileInputStream(newCacheFile); IOUtils.copy(fis, out); fis.close(); out.close(); } }; if (zip) { final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(FILENAME_ZIP); result.setDisposition(disposition); } return result; }
From source file:edu.umd.cs.submit.CommandLineSubmit.java
/** * @param p// www . j a v a2s.com * @param find * @param files * @param userProps * @return * @throws IOException * @throws FileNotFoundException */ public static MultipartPostMethod createFilePost(Properties p, FindAllFiles find, Collection<File> files, Properties userProps) throws IOException, FileNotFoundException { // ========================== assemble zip file in byte array // ============================== String loginName = userProps.getProperty("loginName"); String classAccount = userProps.getProperty("classAccount"); String from = classAccount; if (loginName != null && !loginName.equals(classAccount)) from += "/" + loginName; System.out.println(" submitted by " + from); System.out.println(); System.out.println("Submitting the following files"); ByteArrayOutputStream bytes = new ByteArrayOutputStream(4096); byte[] buf = new byte[4096]; ZipOutputStream zipfile = new ZipOutputStream(bytes); zipfile.setComment("zipfile for CommandLineTurnin, version " + VERSION); for (File resource : files) { if (resource.isDirectory()) continue; String relativePath = resource.getCanonicalPath().substring(find.rootPathLength + 1); System.out.println(relativePath); ZipEntry entry = new ZipEntry(relativePath); entry.setTime(resource.lastModified()); zipfile.putNextEntry(entry); InputStream in = new FileInputStream(resource); try { while (true) { int n = in.read(buf); if (n < 0) break; zipfile.write(buf, 0, n); } } finally { in.close(); } zipfile.closeEntry(); } // for each file zipfile.close(); MultipartPostMethod filePost = new MultipartPostMethod(p.getProperty("submitURL")); p.putAll(userProps); // add properties for (Map.Entry<?, ?> e : p.entrySet()) { String key = (String) e.getKey(); String value = (String) e.getValue(); if (!key.equals("submitURL")) filePost.addParameter(key, value); } filePost.addParameter("submitClientTool", "CommandLineTool"); filePost.addParameter("submitClientVersion", VERSION); byte[] allInput = bytes.toByteArray(); filePost.addPart(new FilePart("submittedFiles", new ByteArrayPartSource("submit.zip", allInput))); return filePost; }
From source file:eu.delving.services.controller.DataSetController.java
private void writeSipZip(String dataSetSpec, OutputStream outputStream, String accessKey) throws IOException, MappingNotFoundException, AccessKeyException, XMLStreamException, MetadataException, MappingException { MetaRepo.DataSet dataSet = metaRepo.getDataSet(dataSetSpec); if (dataSet == null) { throw new IOException("Data Set not found"); // IOException? }//from w ww . java 2 s.c o m ZipOutputStream zos = new ZipOutputStream(outputStream); zos.putNextEntry(new ZipEntry(FileStore.FACTS_FILE_NAME)); Facts facts = Facts.fromBytes(dataSet.getDetails().getFacts()); facts.setDownloadedSource(true); zos.write(Facts.toBytes(facts)); zos.closeEntry(); zos.putNextEntry(new ZipEntry(FileStore.SOURCE_FILE_NAME)); String sourceHash = writeSourceStream(dataSet, zos, accessKey); zos.closeEntry(); for (MetaRepo.Mapping mapping : dataSet.mappings().values()) { RecordMapping recordMapping = mapping.getRecordMapping(); zos.putNextEntry( new ZipEntry(String.format(FileStore.MAPPING_FILE_PATTERN, recordMapping.getPrefix()))); RecordMapping.write(recordMapping, zos); zos.closeEntry(); } zos.finish(); zos.close(); dataSet.setSourceHash(sourceHash, true); dataSet.save(); }
From source file:com.eviware.soapui.impl.wsdl.support.FileAttachment.java
public void setData(byte[] data) { try {// w w w . ja va 2s. c o m // write attachment-data to tempfile ByteArrayOutputStream tempData = new ByteArrayOutputStream(); ZipOutputStream out = new ZipOutputStream(tempData); out.putNextEntry(new ZipEntry(config.getName())); config.setSize(data.length); out.write(data); out.closeEntry(); out.finish(); out.close(); config.setData(tempData.toByteArray()); } catch (Exception e) { SoapUI.logError(e); } }
From source file:ZipImploder.java
/** * Implode target zip file from a source directory * //from ww w . ja v a2 s .co m * @param zipName * @param sourceDir * @param comment * @param method * @param level * @throws IOException */ public void processZip(String zipName, String sourceDir, String comment, int method, int level) throws IOException { String dest = setup(zipName, sourceDir); ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(dest))); configure(zos, comment, method, level); process(zos, new File(sourceDir)); }
From source file:io.fabric8.maven.generator.springboot.SpringBootGenerator.java
private void copyFilesToFatJar(List<File> libs, List<File> classes, File target) throws IOException { File tmpZip = File.createTempFile(target.getName(), null); tmpZip.delete();/*w ww . j a v a 2 s . c o m*/ // Using Apache commons rename, because renameTo has issues across file systems FileUtils.moveFile(target, tmpZip); byte[] buffer = new byte[8192]; ZipInputStream zin = new ZipInputStream(new FileInputStream(tmpZip)); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target)); for (ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry()) { if (matchesFatJarEntry(libs, ze.getName(), true) || matchesFatJarEntry(classes, ze.getName(), false)) { continue; } out.putNextEntry(ze); for (int read = zin.read(buffer); read > -1; read = zin.read(buffer)) { out.write(buffer, 0, read); } out.closeEntry(); } for (File lib : libs) { try (InputStream in = new FileInputStream(lib)) { out.putNextEntry(createZipEntry(lib, getFatJarFullPath(lib, true))); for (int read = in.read(buffer); read > -1; read = in.read(buffer)) { out.write(buffer, 0, read); } out.closeEntry(); } } for (File cls : classes) { try (InputStream in = new FileInputStream(cls)) { out.putNextEntry(createZipEntry(cls, getFatJarFullPath(cls, false))); for (int read = in.read(buffer); read > -1; read = in.read(buffer)) { out.write(buffer, 0, read); } out.closeEntry(); } } out.close(); tmpZip.delete(); }
From source file:ch.randelshofer.cubetwister.PreferencesTemplatesPanel.java
private void exportInternalTemplate(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportInternalTemplate if (exportFileChooser == null) { exportFileChooser = new JFileChooser(); exportFileChooser.setFileFilter(new ExtensionFileFilter("zip", "Zip Archive")); exportFileChooser.setSelectedFile( new File(userPrefs.get("cubetwister.exportedHTMLTemplate", "CubeTwister HTML-Template.zip"))); exportFileChooser.setApproveButtonText(labels.getString("filechooser.export")); }/*from ww w . j a va 2 s . c om*/ if (JFileChooser.APPROVE_OPTION == exportFileChooser.showSaveDialog(this)) { userPrefs.put("cubetwister.exportedHTMLTemplate", exportFileChooser.getSelectedFile().getPath()); final File target = exportFileChooser.getSelectedFile(); new BackgroundTask() { @Override public void construct() throws IOException { if (!target.getParentFile().exists()) { target.getParentFile().mkdirs(); } InputStream in = null; OutputStream out = null; try { in = getClass().getResourceAsStream("/htmltemplates.tar.bz"); out = new FileOutputStream(target); exportTarBZasZip(in, out); } finally { try { if (in != null) { in.close(); } } finally { if (out != null) { out.close(); } } } } private void exportTarBZasZip(InputStream in, OutputStream out) throws IOException { ZipOutputStream zout = new ZipOutputStream(out); TarInputStream tin = new TarInputStream(new BZip2CompressorInputStream(in)); for (TarArchiveEntry inEntry = tin.getNextEntry(); inEntry != null;) { ZipEntry outEntry = new ZipEntry(inEntry.getName()); zout.putNextEntry(outEntry); if (!inEntry.isDirectory()) { Files.copyStream(tin, zout); } zout.closeEntry(); } zout.finish(); } }.start(); } }
From source file:com.dbi.jmmerge.MapController.java
@RequestMapping(value = "maps/{server}", produces = "application/zip") public byte[] downloadMap(@PathVariable("server") String server, HttpServletResponse response) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bufstream = new BufferedOutputStream(baos); ZipOutputStream zip = new ZipOutputStream(bufstream); addDirectoryContents(null, new File(storageDir, server), zip); zip.finish();/* www . j ava2 s . com*/ zip.flush(); IOUtils.closeQuietly(zip); IOUtils.closeQuietly(bufstream); IOUtils.closeQuietly(baos); response.setStatus(HttpServletResponse.SC_OK); response.addHeader("Content-Disposition", "attachment; filename=\"" + server + ".zip\""); return baos.toByteArray(); }
From source file:com.jhash.oimadmin.Utils.java
public static void createJarFileFromContent(Map<String, byte[]> content, String[] fileSequence, String jarFileName) {// ww w . j a v a 2s .co m logger.trace("createJarFileFromContent({},{})", content, jarFileName); logger.trace("Trying to create a new jar file"); try (ZipOutputStream jarFileOutputStream = new ZipOutputStream(new FileOutputStream(jarFileName))) { jarFileOutputStream.setMethod(ZipOutputStream.STORED); for (String jarItem : fileSequence) { logger.trace("Processing item {}", jarItem); byte[] fileContent = content.get(jarItem); if (fileContent == null) throw new NullPointerException("Failed to locate content for file " + jarItem); JarEntry pluginXMLFileEntry = new JarEntry(jarItem); pluginXMLFileEntry.setTime(System.currentTimeMillis()); pluginXMLFileEntry.setSize(fileContent.length); pluginXMLFileEntry.setCompressedSize(fileContent.length); CRC32 crc = new CRC32(); crc.update(fileContent); pluginXMLFileEntry.setCrc(crc.getValue()); jarFileOutputStream.putNextEntry(pluginXMLFileEntry); jarFileOutputStream.write(fileContent); jarFileOutputStream.closeEntry(); } } catch (Exception exception) { throw new OIMAdminException("Failed to create the Jar file " + jarFileName, exception); } }
From source file:com.aurel.track.admin.customize.category.report.ReportAction.java
/** * Downloads the zip with the template and the other report files *///from ww w . jav a2 s.c o m public String download() { CategoryTokens categoryTokens = CategoryTokens.decodeNode(node); Integer objectID = categoryTokens.getObjectID(); File templateToDownload = ReportBL.getDirTemplate(objectID); servletResponse.reset(); servletResponse.setHeader("Content-Type", "application/zip"); servletResponse.setHeader("Cache-Control", "no-cache"); servletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + templateToDownload.getName() + ".zip" + "\""); ZipOutputStream zipOut; try { ServletOutputStream outs = servletResponse.getOutputStream(); zipOut = new ZipOutputStream(outs); ReportBL.zipFiles(templateToDownload, zipOut, templateToDownload.getAbsolutePath()); zipOut.close(); } catch (FileNotFoundException e) { LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException e) { LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return null; }