List of usage examples for java.util.zip ZipEntry ZipEntry
public ZipEntry(ZipEntry e)
From source file:net.minecraftforge.fml.common.asm.transformers.MarkerTransformer.java
private static void processJar(File inFile, File outFile, MarkerTransformer[] transformers) throws IOException { ZipInputStream inJar = null;/* www . ja v a2 s .c o m*/ ZipOutputStream outJar = null; try { try { inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile))); } catch (FileNotFoundException e) { throw new FileNotFoundException("Could not open input file: " + e.getMessage()); } try { outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); } catch (FileNotFoundException e) { throw new FileNotFoundException("Could not open output file: " + e.getMessage()); } ZipEntry entry; while ((entry = inJar.getNextEntry()) != null) { if (entry.isDirectory()) { outJar.putNextEntry(entry); continue; } byte[] data = new byte[4096]; ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream(); int len; do { len = inJar.read(data); if (len > 0) { entryBuffer.write(data, 0, len); } } while (len != -1); byte[] entryData = entryBuffer.toByteArray(); String entryName = entry.getName(); if (entryName.endsWith(".class") && !entryName.startsWith(".")) { ClassNode cls = new ClassNode(); ClassReader rdr = new ClassReader(entryData); rdr.accept(cls, 0); String name = cls.name.replace('/', '.').replace('\\', '.'); for (MarkerTransformer trans : transformers) { entryData = trans.transform(name, name, entryData); } } ZipEntry newEntry = new ZipEntry(entryName); outJar.putNextEntry(newEntry); outJar.write(entryData); } } finally { IOUtils.closeQuietly(outJar); IOUtils.closeQuietly(inJar); } }
From source file:com.datasalt.pangool.solr.TupleSolrOutputFormat.java
private static void createZip(File dir, File out) throws IOException { HashSet<File> files = new HashSet<File>(); // take only conf/ and lib/ for (String allowedDirectory : SolrRecordWriter.getAllowedConfigDirectories()) { File configDir = new File(dir, allowedDirectory); boolean configDirExists; /** If the directory does not exist, and is required, bail out */ if (!(configDirExists = configDir.exists()) && SolrRecordWriter.isRequiredConfigDirectory(allowedDirectory)) { throw new IOException(String.format("required configuration directory %s is not present in %s", allowedDirectory, dir)); }/* w w w . j a va 2 s .c o m*/ if (!configDirExists) { continue; } listFiles(configDir, files); // Store the files in the existing, allowed // directory configDir, in the list of files // to store in the zip file } out.delete(); int subst = dir.toString().length(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(out)); byte[] buf = new byte[1024]; for (File f : files) { ZipEntry ze = new ZipEntry(f.toString().substring(subst)); zos.putNextEntry(ze); InputStream is = new FileInputStream(f); int cnt; while ((cnt = is.read(buf)) >= 0) { zos.write(buf, 0, cnt); } is.close(); zos.flush(); zos.closeEntry(); } zos.close(); }
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// w ww . jav a 2 s .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: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? }/*ww w . j a v a2 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 {/*from www .j a va2s .c om*/ // 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:de.thorstenberger.examServer.webapp.action.PDFBulkExport.java
/** * @param tasklet//from w w w. ja v a 2 s . c om * @param userId * @param zos * @return * @throws IOException */ private boolean addGeneratedPDFS(final Tasklet tasklet, final String userId, final ZipOutputStream zos) throws IOException { final ExamServerManager esm = (ExamServerManager) getBean("examServerManager"); boolean wroteAtLeastOneFile = false; // find all existing pdfs for this user and this taskId for (final File pdfFile : new File(esm.getHomeDir(), userId).listFiles(getPdfFileFilter(tasklet, userId))) { log.info(String.format("adding existing pdf '%s'", pdfFile.getName())); wroteAtLeastOneFile = true; // add pdf to zip final ZipEntry ze = new ZipEntry(pdfFile.getName()); zos.putNextEntry(ze); final InputStream is = new FileInputStream(pdfFile); IOUtils.copy(is, zos); is.close(); } return wroteAtLeastOneFile; }
From source file:com.webautomation.ScreenCaptureHtmlUnitDriver.java
public static byte[] createZip(Map<String, byte[]> files) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zipfile = new ZipOutputStream(bos); Iterator<String> i = files.keySet().iterator(); String fileName = null;/*www .j ava 2s . c o m*/ ZipEntry zipentry = null; while (i.hasNext()) { fileName = i.next(); zipentry = new ZipEntry(fileName); zipfile.putNextEntry(zipentry); zipfile.write(files.get(fileName)); } zipfile.close(); return bos.toByteArray(); }
From source file:io.sledge.core.impl.installer.SledgePackageConfigurer.java
private void addToZipFile(String zipEntryName, InputStream inStream, ZipOutputStream zipStream) throws IOException { log.debug("Adding zip entry: " + zipEntryName); ZipEntry entry = new ZipEntry(zipEntryName); zipStream.putNextEntry(entry);// w w w . ja v a 2 s . c o m byte[] readBuffer = new byte[2048]; int amountRead; int written = 0; while ((amountRead = inStream.read(readBuffer)) > 0) { zipStream.write(readBuffer, 0, amountRead); written += amountRead; } zipStream.closeEntry(); log.debug("Written " + written + " bytes for: " + zipEntryName); }
From source file:com.adobe.communities.ugc.migration.legacyExport.GenericExportServlet.java
protected void exportContent(Resource rootNode, final String rootPath) throws IOException, ServletException { final String relPath = rootNode.getPath() .substring(rootNode.getPath().indexOf(rootPath) + rootPath.length()); String entryName = relPath.isEmpty() ? "root.json" : relPath + ".json"; responseWriter = new OutputStreamWriter(zip); final JSONWriter writer = new JSONWriter(responseWriter); writer.setTidy(true);/*from ww w . j av a 2s . co m*/ if (rootNode.isResourceType(Comment.RESOURCE_TYPE)) { // if we're traversing a tree and come to a comment, we need to be looking at the comment system's // resource instead of the resource for the comment itself as we continue our dive. Comment comment = rootNode.adaptTo(Comment.class); if (null != comment) { CommentSystem commentSystem = comment.getCommentSystem(); entries.put(commentSystem.getResource().getPath(), true); return; } } try { if (rootNode.isResourceType("social/qna/components/qnaforum")) { final Forum forum = rootNode.adaptTo(Forum.class); if (forum == null) { // avoid throwing a null pointer exception for (final Resource resource : rootNode.getChildren()) { exportContent(resource, rootPath); } return; } final Iterator<Post> posts = forum.getTopics(); if (posts.hasNext()) { zip.putNextEntry(new ZipEntry(entryName)); final JSONWriter forumObject = writer.object(); forumObject.key(ContentTypeDefinitions.LABEL_CONTENT_TYPE); forumObject.value(ContentTypeDefinitions.LABEL_QNA_FORUM); forumObject.key(ContentTypeDefinitions.LABEL_CONTENT); forumObject.object(); while (posts.hasNext()) { final Post post = posts.next(); forumObject.key(post.getId()); final JSONWriter postObject = forumObject.object(); UGCExportHelper.extractTopic(postObject, post, rootNode.getResourceResolver(), "social/qna/components/hbs/topic", "social/qna/components/hbs/post", responseWriter); forumObject.endObject(); } forumObject.endObject(); writer.endObject(); responseWriter.flush(); zip.closeEntry(); } } else if (rootNode.isResourceType(Forum.RESOURCE_TYPE) || rootNode.isResourceType("social/forum/components/hbs/forum")) { final Forum forum = rootNode.adaptTo(Forum.class); if (forum == null) { // avoid throwing a null pointer exception for (final Resource resource : rootNode.getChildren()) { exportContent(resource, rootPath); } return; } final Iterator<Post> posts = forum.getTopics(); if (posts.hasNext()) { zip.putNextEntry(new ZipEntry(entryName)); final JSONWriter forumObject = writer.object(); forumObject.key(ContentTypeDefinitions.LABEL_CONTENT_TYPE); forumObject.value(ContentTypeDefinitions.LABEL_FORUM); forumObject.key(ContentTypeDefinitions.LABEL_CONTENT); forumObject.object(); while (posts.hasNext()) { final Post post = posts.next(); forumObject.key(post.getId()); final JSONWriter postObject = forumObject.object(); UGCExportHelper.extractTopic(postObject, post, rootNode.getResourceResolver(), "social/forum/components/hbs/topic", "social/forum/components/hbs/post", responseWriter); forumObject.endObject(); } forumObject.endObject(); writer.endObject(); responseWriter.flush(); zip.closeEntry(); } } else if (rootNode.isResourceType(CommentSystem.RESOURCE_TYPE)) { if (rootNode.getName().equals("entrycomments")) { return; // these are special cases of comments that will be handled by journal instead } final CommentSystem commentSystem = rootNode.adaptTo(CommentSystem.class); if (commentSystem == null) { // avoid throwing a null pointer exception for (final Resource resource : rootNode.getChildren()) { exportContent(resource, rootPath); } return; } // we only export after all other nodes have been searched and exported as needed entries.put(commentSystem.getResource().getPath(), true); } else if (rootNode.isResourceType(CalendarConstants.RT_CALENDAR_COMPONENT) || rootNode.isResourceType(CalendarConstants.MIX_CALENDAR) || rootNode.getResourceType().endsWith("calendar")) { CqCalendar calendar = rootNode.adaptTo(CqCalendar.class); if (calendar == null) { // avoid throwing a null pointer exception if this node isn't actually a // calendar for (final Resource resource : rootNode.getChildren()) { exportContent(resource, rootPath); } return; } final Iterator<Event> events = calendar.getEvents(); if (!events.hasNext()) { return; } zip.putNextEntry(new ZipEntry(entryName)); final JSONWriter calendarNode = writer.object(); calendarNode.key(ContentTypeDefinitions.LABEL_CONTENT_TYPE); calendarNode.value(ContentTypeDefinitions.LABEL_CALENDAR); calendarNode.key(ContentTypeDefinitions.LABEL_CONTENT); JSONWriter eventObjects = calendarNode.array(); while (events.hasNext()) { final Event event = events.next(); ValueMap eventProperties = event.getProperties(); // we renamed "start" and "end" going from version 5.6.1 to 6.1 Map<String, String> propertyNames = new HashMap<String, String>(); propertyNames.put("start", "calendar_event_start_dt"); propertyNames.put("end", "calendar_event_end_dt"); propertyNames.put("jcr:title", "subject"); propertyNames.put("jcr:created", "added"); propertyNames.put("jcr:primaryType", null); UGCExportHelper.extractProperties(eventObjects.object(), eventProperties, propertyNames, "social/calendar/components/hbs/event"); eventObjects.endObject(); } calendarNode.endArray(); writer.endObject(); responseWriter.flush(); zip.closeEntry(); } else if (rootNode.isResourceType("social/tally/components/poll")) { // No constant defined in 5.6.1 return; // we know what it is, but there's no antecedent to put it into for 6.1 } else if (rootNode.isResourceType("social/tally/components/voting")) { // No constant defined in 5.6.1 zip.putNextEntry(new ZipEntry(entryName)); final JSONWriter tallyNode = writer.object(); tallyNode.key(ContentTypeDefinitions.LABEL_CONTENT_TYPE); tallyNode.value(ContentTypeDefinitions.LABEL_TALLY); tallyNode.key(ContentTypeDefinitions.LABEL_CONTENT); final JSONWriter responseArray = tallyNode.array(); UGCExportHelper.extractTally(responseArray, rootNode, "Voting"); tallyNode.endArray(); writer.endObject(); responseWriter.flush(); zip.closeEntry(); } else if (rootNode.isResourceType("social/tally/components/rating")) { // No constant defined in 5.6.1 zip.putNextEntry(new ZipEntry(entryName)); final JSONWriter tallyNode = writer.object(); tallyNode.key(ContentTypeDefinitions.LABEL_CONTENT_TYPE); tallyNode.value(ContentTypeDefinitions.LABEL_TALLY); tallyNode.key(ContentTypeDefinitions.LABEL_CONTENT); final JSONWriter responseArray = tallyNode.array(); UGCExportHelper.extractTally(responseArray, rootNode, "Rating"); tallyNode.endArray(); writer.endObject(); responseWriter.flush(); zip.closeEntry(); } else if (rootNode.isResourceType("social/journal/components/entrylist")) { final Journal journal = rootNode.adaptTo(Journal.class); if (journal == null) { // avoid throwing a null pointer exception for (final Resource resource : rootNode.getChildren()) { exportContent(resource, rootPath); } return; } zip.putNextEntry(new ZipEntry(entryName)); final JSONWriter journalNode = writer.object(); journalNode.key(ContentTypeDefinitions.LABEL_CONTENT_TYPE); journalNode.value(ContentTypeDefinitions.LABEL_JOURNAL); journalNode.key(ContentTypeDefinitions.LABEL_CONTENT); JSONWriter entryObjects = journalNode.object(); final List<JournalEntry> entries = journal.getEntries(); for (final JournalEntry entry : entries) { entryObjects.key(entry.getId()); UGCExportHelper.extractJournalEntry(entryObjects.object(), entry, responseWriter); entryObjects.endObject(); final Iterator<Comment> comments = entry.getComments(); if (comments.hasNext()) { final Comment comment = comments.next(); final CommentSystem commentSystem = comment.getCommentSystem(); entriesToSkip.put(commentSystem.getResource().getPath(), true); } } journalNode.endObject(); writer.endObject(); responseWriter.flush(); zip.closeEntry(); } else { for (final Resource resource : rootNode.getChildren()) { exportContent(resource, rootPath); } } } catch (final JSONException e) { throw new ServletException(e); } }
From source file:edu.umd.cs.submit.CommandLineSubmit.java
/** * @param p/*w w w . 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; }