List of usage examples for java.util.zip ZipOutputStream setComment
public void setComment(String comment)
From source file:edu.umd.cs.eclipse.courseProjectManager.TurninProjectAction.java
public void run(IAction action) { // TODO Refactor: Should the places where we raise a dialog and return // could throw an exception instead? String timeOfSubmission = "t" + System.currentTimeMillis(); // Make sure we can get the workbench... IWorkbench workbench = PlatformUI.getWorkbench(); if (workbench == null) { Dialogs.errorDialog(null, "Warning: project submission failed", "Could not submit project", "Internal error: Can't get workbench", IStatus.ERROR); return;/*ww w .j a v a 2 s .c om*/ } // ...and the workbenchWindow IWorkbenchWindow wwin = workbench.getActiveWorkbenchWindow(); if (wwin == null) { Dialogs.errorDialog(null, "Error submitting project", "Could not submit project", "Internal error: Can't get workbench window", IStatus.ERROR); return; } // Shell to use as parent of dialogs. Shell parent = wwin.getShell(); // Sanity check. if (!(selection instanceof IStructuredSelection)) { Dialogs.errorDialog(parent, "Warning: Selection is Invalid", "Invalid turnin action: You have selected an object that is not a Project. Please select a Project and try again.", "Object selected is not a Project", IStatus.WARNING); return; } IStructuredSelection structured = (IStructuredSelection) selection; Object obj = structured.getFirstElement(); Debug.print("Selection object is a " + obj.getClass().getName() + " @" + System.identityHashCode(obj)); IProject project; if (obj instanceof IProject) { project = (IProject) obj; } else if (obj instanceof IProjectNature) { project = ((IProjectNature) obj).getProject(); } else { Dialogs.errorDialog(null, "Warning: Selection is Invalid", "Invalid turnin action: You have selected an object that is not a Project. Please select a Project and try again.", "Object selected is not a Project", IStatus.WARNING); return; } Debug.print("Got the IProject for the turnin action @" + System.identityHashCode(project)); // ================================= save dirty editors // ======================================== // save dirty editors try { if (!saveDirtyEditors(project, workbench)) { Dialogs.errorDialog(parent, "Submit not performed", "Projects cannot be submitted unless all open files are saved", "Unsaved files prevent submission", IStatus.WARNING); return; } } catch (CoreException e) { Dialogs.errorDialog(parent, "Submit not performed", "Could not turn on cvs management for all project files", e); return; } // ========================= Add all non-ignored files in the project // ========================= IResource[] files; try { Set<IResource> resourceSet = getProjectResources(project); ArrayList<IFile> addedFiles = new ArrayList<IFile>(); for (Iterator<IResource> iter = resourceSet.iterator(); iter.hasNext();) { IResource resource = iter.next(); if (resource instanceof IFile) { IFile file = (IFile) resource; if (!AutoCVSPlugin.isCVSIgnored(file) && !AutoCVSPlugin.isCVSManaged(file)) { addedFiles.add(file); } } } files = (IResource[]) addedFiles.toArray(new IResource[addedFiles.size()]); } catch (CoreException e) { Dialogs.errorDialog(parent, "Submit not performed", "Could not perform submit; unable to find non-ignored resources", e); return; // TODO what to do here? } // ================================= perform CVS commit // ======================================== // TODO Somehow move this into the previous try block // This forces add/commit operations when AutoSync was shut off // Would it just be easier to enable autoSync and then trigger // a resource changed delta, since this method appears to enable // autoSync anyway? // String cvsStatus = "Not performed"; try { cvsStatus = forceCommit(project, files); } catch (Exception e) { Dialogs.errorDialog(parent, "CVS commit not performed as part of submission due to unexpected exception", e.getClass().getName() + " " + e.getMessage(), e); } // ================================= perform CVS tag // ======================================== try { CVSOperations.tagProject(project, timeOfSubmission, CVSOperations.SYNC); } catch (Exception e) { AutoCVSPlugin.getPlugin().getEventLog() .logError("Error tagging submission; submission via the web unlikely to work", e); } // ================================= find properties // ======================================== // find the .submitProject file IResource submitProjectFile = project.findMember(AutoCVSPlugin.SUBMITPROJECT); if (submitProjectFile == null) { Dialogs.errorDialog(parent, "Warning: Project submission not enabled", "Submission is not enabled", "There is no " + AutoCVSPlugin.SUBMITPROJECT + " file for the project", IStatus.ERROR); return; } // Get the properties from the .submit file, and the .submitUser file, // if it exists // or can be fetched from the server Properties allSubmissionProps = null; try { allSubmissionProps = getAllProperties(timeOfSubmission, parent, project, submitProjectFile); } catch (IOException e) { String message = "IOException finding " + AutoCVSPlugin.SUBMITPROJECT + " and " + AutoCVSPlugin.SUBMITUSER + " files; " + cvsStatus; AutoCVSPlugin.getPlugin().getEventLog().logError(message, e); Dialogs.errorDialog(parent, "Submission failed", message, e.getMessage(), IStatus.ERROR); Debug.print("IOException: " + e); return; } catch (CoreException e) { String message = "IOException finding " + AutoCVSPlugin.SUBMITPROJECT + " and " + AutoCVSPlugin.SUBMITUSER + " files; " + cvsStatus; AutoCVSPlugin.getPlugin().getEventLog().logError(message, e); Dialogs.errorDialog(parent, "Submission failed", message, e.getMessage(), IStatus.ERROR); Debug.print("CoreException: " + e); return; } // // THE ACTUAL SUBMIT HAPPENS HERE // try { // ============================== find files to submit // ==================================== Collection<IFile> cvsFiles = findFilesForSubmission(project); // ========================== assemble zip file in byte array // ============================== ByteArrayOutputStream bytes = new ByteArrayOutputStream(4096); ZipOutputStream zipfile = new ZipOutputStream(bytes); zipfile.setComment("zipfile for submission created by CourseProjectManager version " + AutoCVSPlugin.getPlugin().getVersion()); try { byte[] buf = new byte[4096]; for (IFile file : cvsFiles) { if (!file.exists()) { Debug.print("Resource " + file.getName() + " being ignored because it doesn't exist"); continue; } ZipEntry entry = new ZipEntry(file.getProjectRelativePath().toString()); entry.setTime(file.getModificationStamp()); zipfile.putNextEntry(entry); // Copy file data to zip file InputStream in = file.getContents(); try { while (true) { int n = in.read(buf); if (n < 0) break; zipfile.write(buf, 0, n); } } finally { in.close(); } zipfile.closeEntry(); } } catch (IOException e1) { Dialogs.errorDialog(parent, "Warning: Project submission failed", "Unable to zip files for submission\n" + cvsStatus, e1); return; } finally { if (zipfile != null) zipfile.close(); } // ============================== Post to submit server // ==================================== String version = System.getProperties().getProperty("java.runtime.version"); boolean useEasyHttps = version.startsWith("1.3") || version.startsWith("1.2") || version.startsWith("1.4.0") || version.startsWith("1.4.1") || version.startsWith("1.4.2_0") && version.charAt(7) < '5'; if (useEasyHttps) { String submitURL = allSubmissionProps.getProperty("submitURL"); if (submitURL.startsWith("https")) submitURL = "easy" + submitURL; allSubmissionProps.setProperty("submitURL", submitURL); } // prepare multipart post method MultipartPostMethod filePost = new MultipartPostMethod(allSubmissionProps.getProperty("submitURL")); // add properties addAllPropertiesButSubmitURL(allSubmissionProps, filePost); // add filepart byte[] allInput = bytes.toByteArray(); filePost.addPart(new FilePart("submittedFiles", new ByteArrayPartSource("submit.zip", allInput))); // prepare httpclient HttpClient client = new HttpClient(); client.setConnectionTimeout(5000); int status = client.executeMethod(filePost); // Piggy-back uploading the launch events onto submitting. EclipseLaunchEventLog.postEventLogToServer(project); if (status == HttpStatus.SC_OK) { Dialogs.okDialog(parent, "Project submission successful", "Project " + allSubmissionProps.getProperty("projectNumber") + " was submitted successfully\n" + filePost.getResponseBodyAsString()); } else { Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submission failed", filePost.getStatusText() + "\n " + cvsStatus, IStatus.CANCEL); AutoCVSPlugin.getPlugin().getEventLog().logMessage(filePost.getResponseBodyAsString()); } } catch (CoreException e) { Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submissions via https failed\n" + cvsStatus, e); } catch (HttpConnection.ConnectionTimeoutException e) { Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submissions failed", "Connection timeout while trying to connect to submit server\n " + cvsStatus, IStatus.ERROR); } catch (IOException e) { Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submissions failed\n " + cvsStatus, e); } }
From source file:com.xpn.xwiki.export.html.HtmlPackager.java
/** * Apply export and create the ZIP package. * //from w w w . j a v a2 s . c o m * @param context the XWiki context used to render pages. * @throws IOException error when creating the package. * @throws XWikiException error when render the pages. */ public void export(XWikiContext context) throws IOException, XWikiException { context.getResponse().setContentType("application/zip"); context.getResponse().addHeader("Content-disposition", "attachment; filename=" + Util.encodeURI(this.name, context) + ".zip"); context.setFinished(true); ZipOutputStream zos = new ZipOutputStream(context.getResponse().getOutputStream()); File dir = context.getWiki().getTempDirectory(context); File tempdir = new File(dir, RandomStringUtils.randomAlphanumeric(8)); tempdir.mkdirs(); File attachmentDir = new File(tempdir, "attachment"); attachmentDir.mkdirs(); // Create custom URL factory ExportURLFactory urlf = new ExportURLFactory(); // Render pages to export renderDocuments(zos, tempdir, urlf, context); // Add required skins to ZIP file for (String skinName : urlf.getNeededSkins()) { addSkinToZip(skinName, zos, urlf.getExportedSkinFiles(), context); } // add "resources" folder File file = new File(context.getWiki().getEngineContext().getRealPath("/resources/")); addDirToZip(file, zos, "resources" + ZIPPATH_SEPARATOR, urlf.getExportedSkinFiles()); // Add attachments and generated skin files files to ZIP file addDirToZip(tempdir, zos, "", null); zos.setComment(this.description); // Finish ZIP file zos.finish(); zos.flush(); // Delete temporary directory deleteDirectory(tempdir); }
From source file:org.bdval.BDVModel.java
/** * Sets the comment for this model into zip stream. * * @param zipStream The stream to set the comment for *///from w w w .j a va 2 s . com protected void setZipStreamComment(final ZipOutputStream zipStream) { final String bdvalVersion = VersionUtils.getImplementationVersion(DiscoverAndValidate.class); final DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); zipStream.setComment(getClass().getName() + " generated with BDVal version " + bdvalVersion + " on " + dateFormat.format(new Date())); }
From source file:org.bdval.ConsensusBDVModel.java
/** * Save the juror models to a set of files. The files will contain all the information needed * to apply the BDVal model to new samples. * * @param zipStream The stream used to write the models 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 */// w ww. j ava2 s.co m private synchronized void saveJurorModels(final ZipOutputStream zipStream, final DAVOptions options, final ClassificationTask task, final SplitPlan splitPlan, final WriteModel writeModelMode) throws IOException { if (!jurorModelsAreLoaded) { throw new IllegalStateException("juror models must be loaded before save"); } // add the models directory entry for juror models (must end in "/") zipStream.putNextEntry(new ZipEntry(JUROR_MODEL_DIRECTORY + "/")); zipStream.closeEntry(); final String jurorModelDirectory = JUROR_MODEL_DIRECTORY + "/" + FilenameUtils.getBaseName(FilenameUtils.getPathNoEndSeparator(modelFilenamePrefix)) + "/"; zipStream.putNextEntry(new ZipEntry(jurorModelDirectory)); zipStream.closeEntry(); for (final BDVModel jurorModel : jurorModels) { // NOTE: for zip files, the directory MUST use "/" regardless of OS final String jurorModelFilename = jurorModelDirectory + FilenameUtils.getName(jurorModel.getModelFilenamePrefix()) + ".zip"; // Add ZIP entry for the model to output stream. zipStream.putNextEntry(new ZipEntry(jurorModelFilename)); // Create the ZIP file for the juror LOG.debug("Writing juror model as entry: " + jurorModelFilename); final ZipOutputStream jurorZipStream = new ZipOutputStream(zipStream); jurorZipStream.setComment("Juror model: " + jurorModel.getModelFilenamePrefix()); jurorModel.save(jurorZipStream, options, task, splitPlan, writeModelMode); jurorZipStream.finish(); // NOTE: we don't close the stream, that will close everything zipStream.closeEntry(); } }
From source file:org.candlepin.sync.Exporter.java
private File createZipArchiveWithDir(File tempDir, File exportDir, String exportFileName, String comment) throws FileNotFoundException, IOException { File archive = new File(tempDir, exportFileName); ZipOutputStream out = null; try {//from w ww.ja v a 2 s.com out = new ZipOutputStream(new FileOutputStream(archive)); out.setComment(comment); addFilesToArchive(out, exportDir.getParent().length() + 1, exportDir); } finally { if (out != null) { out.close(); } } return archive; }
From source file:org.candlepin.sync.Exporter.java
private File createSignedZipArchive(File tempDir, File toAdd, String exportFileName, byte[] signature, String comment) throws FileNotFoundException, IOException { File archive = new File(tempDir, exportFileName); ZipOutputStream out = null; try {// w w w. j av a 2s . c om out = new ZipOutputStream(new FileOutputStream(archive)); out.setComment(comment); addFileToArchive(out, toAdd.getParent().length() + 1, toAdd); addSignatureToArchive(out, signature); } finally { if (out != null) { out.close(); } } return archive; }
From source file:org.lockss.exporter.ZipExporter.java
void setZipComment(ZipOutputStream zip) { StringBuilder sb = new StringBuilder(); sb.append(au.getName());/*from ww w . j av a 2 s . c o m*/ sb.append(Constants.CRLF); sb.append("Exported from LOCKSS by "); sb.append(getHostName()); sb.append(" at "); sb.append(new Date()); sb.append(Constants.CRLF); try { zip.setComment(sb.toString()); } catch (RuntimeException e) { log.warning("Couldn't write zip comment", e); } }
From source file:org.tangram.components.CodeExporter.java
@LinkAction("/codes.zip") public TargetDescriptor codes(HttpServletRequest request, HttpServletResponse response) throws IOException { if (!request.getRequestURI().endsWith(".zip")) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } // if//from w w w . ja v a 2s. co m if (request.getAttribute(Constants.ATTRIBUTE_ADMIN_USER) == null) { throw new IOException("User may not execute action"); } // if long now = System.currentTimeMillis(); response.setContentType("application/x-zip-compressed"); CRC32 crc = new CRC32(); ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); zos.setComment("Tangram Repository Codes"); zos.setLevel(9); Collection<CodeResource> codes = codeResourceCache.getCodes(); for (CodeResource code : codes) { if (StringUtils.isNotBlank(code.getAnnotation())) { String mimeType = CodeHelper.getNormalizedMimeType(code.getMimeType()); String folder = CodeHelper.getFolder(mimeType); String extension = CodeHelper.getExtension(mimeType); if (mimeType.startsWith("text/")) { byte[] bytes = code.getCodeText().getBytes("UTF-8"); ZipEntry ze = new ZipEntry(folder + "/" + getFilename(code) + extension); ze.setTime(now); crc.reset(); crc.update(bytes); ze.setCrc(crc.getValue()); zos.putNextEntry(ze); zos.write(bytes); zos.closeEntry(); } // if } // if } // for zos.finish(); zos.close(); return TargetDescriptor.DONE; }
From source file:org.xdi.util.io.ResponseHelper.java
public static ZipOutputStream createZipStream(OutputStream output, String comment) { ZipOutputStream zos = new ZipOutputStream(output); zos.setComment("Shibboleth2 SP configuration files"); zos.setMethod(ZipOutputStream.DEFLATED); zos.setLevel(Deflater.DEFAULT_COMPRESSION); return zos;/*from w ww .jav a 2 s.com*/ }