List of usage examples for java.util.zip ZipOutputStream close
public void close() throws IOException
From source file:com.photon.maven.plugins.android.phase09package.ApkMojo.java
private File removeDuplicatesFromJar(File in, List<String> duplicates) { File target = new File(project.getBasedir(), "target"); File tmp = new File(target, "unpacked-embedded-jars"); tmp.mkdirs();/* w w w . j ava 2s .co m*/ File out = new File(tmp, in.getName()); if (out.exists()) { return out; } try { out.createNewFile(); } catch (IOException e) { e.printStackTrace(); } // Create a new Jar file FileOutputStream fos = null; ZipOutputStream jos = null; try { fos = new FileOutputStream(out); jos = new ZipOutputStream(fos); } catch (FileNotFoundException e1) { getLog().error( "Cannot remove duplicates : the output file " + out.getAbsolutePath() + " does not found"); return null; } ZipFile inZip = null; try { inZip = new ZipFile(in); Enumeration<? extends ZipEntry> entries = inZip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); // If the entry is not a duplicate, copy. if (!duplicates.contains(entry.getName())) { // copy the entry header to jos jos.putNextEntry(entry); InputStream currIn = inZip.getInputStream(entry); copyStreamWithoutClosing(currIn, jos); currIn.close(); jos.closeEntry(); } } } catch (IOException e) { getLog().error("Cannot removing duplicates : " + e.getMessage()); return null; } try { if (inZip != null) { inZip.close(); } jos.close(); fos.close(); jos = null; fos = null; } catch (IOException e) { // ignore it. } getLog().info(in.getName() + " rewritten without duplicates : " + out.getAbsolutePath()); return out; }
From source file:com.joliciel.talismane.machineLearning.AbstractMachineLearningModel.java
@Override public final void persist(File modelFile) { try {// ww w .jav a 2s.c o m ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(modelFile, false)); Writer writer = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8")); zos.putNextEntry(new ZipEntry("algorithm.txt")); writer.write(this.getAlgorithm().name()); writer.flush(); zos.flush(); for (String descriptorKey : descriptors.keySet()) { zos.putNextEntry(new ZipEntry(descriptorKey + "_descriptors.txt")); List<String> descriptorList = descriptors.get(descriptorKey); for (String descriptor : descriptorList) { writer.write(descriptor + "\n"); writer.flush(); } zos.flush(); } zos.putNextEntry(new ZipEntry("attributes.txt")); for (String name : this.modelAttributes.keySet()) { String value = this.modelAttributes.get(name); writer.write(name + "\t" + value + "\n"); writer.flush(); } for (String name : this.dependencies.keySet()) { Object dependency = this.dependencies.get(name); zos.putNextEntry(new ZipEntry(name + "_dependency.obj")); ObjectOutputStream oos = new ObjectOutputStream(zos); try { oos.writeObject(dependency); } finally { oos.flush(); } zos.flush(); } this.persistOtherEntries(zos); if (this.externalResources != null) { zos.putNextEntry(new ZipEntry("externalResources.obj")); ObjectOutputStream oos = new ObjectOutputStream(zos); try { oos.writeObject(externalResources); } finally { oos.flush(); } zos.flush(); } this.writeDataToStream(zos); zos.putNextEntry(new ZipEntry("model.bin")); this.writeModelToStream(zos); zos.flush(); zos.close(); } catch (IOException ioe) { LogUtils.logError(LOG, ioe); throw new RuntimeException(ioe); } }
From source file:marytts.tools.voiceimport.VoicePackager.java
/** * Create zip file containing all of the voice files (including the config file, which should be in <b>files</b>). * /*from w w w .j av a2s. c om*/ * @param files * <property, File> Map, e.g. "WaveTimelineMaker.waveTimeline" → * File("VOICE_DIR/mary/timeline_waves.mry") * @return the zip File object * @throws Exception */ protected File createZipFile(HashMap<String, File> files) throws Exception { // TODO this should probably be optimized by using buffered Readers and Writer: byte[] buffer = new byte[4096]; // initialize zip file: String zipFileName = String.format("mary-%s-%s.zip", getVoiceName(), getMaryVersion()); logger.info("Creating voice package " + zipFileName); File zipFile = new File(getMaryBase() + "download" + File.separator + zipFileName); FileOutputStream outputStream = new FileOutputStream(zipFile); ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(zipFile)); // TODO this doesn't explicitly create each ancestor of the voicePath as a separate directory entry in the zip file, but // that doesn't seem necessary: String voicePath = "lib" + File.separator + "voices" + File.separator + getVoiceName() + File.separator; // iterate over files: for (String key : files.keySet()) { File file = files.get(key); // open data file for reading: FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (FileNotFoundException e) { if (key.equals(EXAMPLETEXTFILE) && getProp(EXAMPLETEXTFILE).length() == 0 && !getVoiceDomain().equalsIgnoreCase("limited")) { logger.debug("Example text file " + getProp(EXAMPLETEXTFILE) + " not found, ignoring."); continue; } else { logger.error("File " + file + " not found!"); throw e; } } // make new entry in zip file, with the appropriate target path: logger.debug("Deflating file " + file); if (key.equals("CONFIG")) { zipStream.putNextEntry(new ZipEntry("conf" + File.separator + file.getName())); } else { zipStream.putNextEntry(new ZipEntry(voicePath + file.getName())); } int len; // stream file contents into zip file: while ((len = inputStream.read(buffer)) > 0) { zipStream.write(buffer, 0, len); } // complete entry and close data file: zipStream.closeEntry(); inputStream.close(); } // close zip file: zipStream.close(); return zipFile; }
From source file:edu.ku.brc.specify.rstools.GoogleEarthExporter.java
/** * @param outputFile//w ww.j av a 2s . com * @param defaultIconFile */ protected void createKMZ(final File outputFile, final File defaultIconFile) throws IOException { // now we have the KML in outputFile // we need to create a KMZ (zip file containing doc.kml and other files) // create a buffer for reading the files byte[] buf = new byte[1024]; int len; // create the KMZ file File outputKMZ = File.createTempFile("sp6-export-", ".kmz"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputKMZ)); // add the doc.kml file to the ZIP FileInputStream in = new FileInputStream(outputFile); // add ZIP entry to output stream out.putNextEntry(new ZipEntry("doc.kml")); // copy the bytes while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // complete the entry out.closeEntry(); in.close(); // add a "files" directory to the KMZ file ZipEntry filesDir = new ZipEntry("files/"); out.putNextEntry(filesDir); out.closeEntry(); if (defaultIconFile != null) { File iconTmpFile = defaultIconFile; if (false) { // Shrink File ImageIcon icon = new ImageIcon(defaultIconFile.getAbsolutePath()); BufferedImage bimage = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); Graphics g = bimage.createGraphics(); g.drawImage(icon.getImage(), 0, 0, null); g.dispose(); BufferedImage scaledBI = GraphicsUtils.getScaledInstance(bimage, 16, 16, true); iconTmpFile = File.createTempFile("sp6-export-icon-scaled", ".png"); ImageIO.write(scaledBI, "PNG", iconTmpFile); } // add the specify32.png file (default icon file) to the ZIP (in the "files" directory) in = new FileInputStream(iconTmpFile); // add ZIP entry to output stream out.putNextEntry(new ZipEntry("files/specify32.png")); // copy the bytes while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // complete the entry out.closeEntry(); in.close(); } // complete the ZIP file out.close(); // now put the KMZ file where the KML output was FileUtils.copyFile(outputKMZ, outputFile); outputKMZ.delete(); }
From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java
protected void doUpload() { DbAdapter dba = new DbAdapter(this); dba.open();/* w w w. j a va 2 s. com*/ 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.streamsets.datacollector.bundles.SupportBundleManager.java
private void generateNewBundleInternal(List<BundleContentGenerator> generators, BundleType bundleType, ZipOutputStream zipStream) { try {//from ww w . j av a 2 s . c o m Properties runGenerators = new Properties(); Properties failedGenerators = new Properties(); // Let each individual content generator run to generate it's content for (BundleContentGenerator generator : generators) { BundleContentGeneratorDefinition definition = definitionMap .get(generator.getClass().getSimpleName()); BundleWriterImpl writer = new BundleWriterImpl(definition.getKlass().getName(), redactor, zipStream); try { LOG.debug("Generating content with {} generator", definition.getKlass().getName()); generator.generateContent(this, writer); runGenerators.put(definition.getKlass().getName(), String.valueOf(definition.getVersion())); } catch (Throwable t) { LOG.error("Generator {} failed", definition.getName(), t); failedGenerators.put(definition.getKlass().getName(), String.valueOf(definition.getVersion())); writer.ensureEndOfFile(); } } // generators.properties zipStream.putNextEntry(new ZipEntry("generators.properties")); runGenerators.store(zipStream, ""); zipStream.closeEntry(); // failed_generators.properties zipStream.putNextEntry(new ZipEntry("failed_generators.properties")); failedGenerators.store(zipStream, ""); zipStream.closeEntry(); if (!bundleType.isAnonymizeMetadata()) { // metadata.properties zipStream.putNextEntry(new ZipEntry("metadata.properties")); getMetadata(bundleType).store(zipStream, ""); zipStream.closeEntry(); } } catch (Exception e) { LOG.error("Failed to generate resource bundle", e); } finally { // And that's it try { zipStream.close(); } catch (IOException e) { LOG.error("Failed to finish generating the bundle", e); } } }
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;/* w ww.j a v a2 s .com*/ } // ...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.orange.mmp.midlet.MidletManager.java
/** * Builds a ZIP archive with the appropriate name * @param mobile// w w w.j a va 2s. c om * @param signMidlet * @param output * @return The ZIP filename * @throws IOException * @throws MMPException */ public String computeZip(Mobile mobile, Boolean signMidlet, OutputStream output) throws IOException, MMPException { //Compute Zip ZipOutputStream zipOS = new ZipOutputStream(output); try { //Get default service Service service = ServiceManager.getInstance().getDefaultService(); //Create fake ticket DeliveryTicket ticket = new DeliveryTicket(); ticket.setServiceId(service.getId()); //Get navigation widget (main scene) Widget appWidget = WidgetManager.getInstance().getWidget(ticket.getServiceId(), mobile.getBranchId()); if (appWidget == null) appWidget = WidgetManager.getInstance().getWidget(ticket.getServiceId()); if (appWidget == null) throw new IOException("application " + ticket.getServiceId() + " not found"); ByteArrayOutputStream tmpOS = null; //Add JAD zipOS.putNextEntry( new ZipEntry(appWidget.getName() + com.orange.mmp.midlet.Constants.JAD_FILE_EXTENSION)); tmpOS = getJad(ticket.getId(), mobile, signMidlet, service); tmpOS.writeTo(zipOS); zipOS.closeEntry(); //Add JAR zipOS.putNextEntry( new ZipEntry(appWidget.getName() + com.orange.mmp.midlet.Constants.JAR_FILE_EXTENSION)); tmpOS = getJar(service.getId(), mobile, signMidlet); tmpOS.writeTo(zipOS); zipOS.closeEntry(); zipOS.flush(); String[] tmpVersion = appWidget.getVersion().toString().split("\\."); if (tmpVersion.length > 2) { return appWidget.getName() + "_V" + tmpVersion[0] + "." + tmpVersion[1] + appWidget.getBranchId() + "." + tmpVersion[2]; } return appWidget.getName() + "_V" + appWidget.getVersion() + "_" + appWidget.getBranchId(); } finally { try { zipOS.close(); } catch (IOException ioe) { } } }
From source file:com.meltmedia.cadmium.core.util.WarUtils.java
/** * <p>This method updates a template war with the following settings.</p> * @param templateWar The name of the template war to pull from the classpath. * @param war The path of an external war to update (optional). * @param newWarNames The name to give the new war. (note: only the first element of this list is used.) * @param repoUri The uri to a github repo to pull content from. * @param branch The branch of the github repo to pull content from. * @param configRepoUri The uri to a github repo to pull config from. * @param configBranch The branch of the github repo to pull config from. * @param domain The domain to bind a vHost to. * @param context The context root that this war will deploy to. * @param secure A flag to set if this war needs to have its contents password protected. * @throws Exception// w w w .j a v a2 s . c o m */ public static void updateWar(String templateWar, String war, List<String> newWarNames, String repoUri, String branch, String configRepoUri, String configBranch, String domain, String context, boolean secure, Logger log) throws Exception { ZipFile inZip = null; ZipOutputStream outZip = null; InputStream in = null; OutputStream out = null; try { if (war != null) { if (war.equals(newWarNames.get(0))) { File tmpZip = File.createTempFile(war, null); tmpZip.delete(); tmpZip.deleteOnExit(); new File(war).renameTo(tmpZip); war = tmpZip.getAbsolutePath(); } inZip = new ZipFile(war); } else { File tmpZip = File.createTempFile("cadmium-war", "war"); tmpZip.delete(); tmpZip.deleteOnExit(); in = WarUtils.class.getClassLoader().getResourceAsStream(templateWar); out = new FileOutputStream(tmpZip); FileSystemManager.streamCopy(in, out); inZip = new ZipFile(tmpZip); } outZip = new ZipOutputStream(new FileOutputStream(newWarNames.get(0))); ZipEntry cadmiumPropertiesEntry = null; cadmiumPropertiesEntry = inZip.getEntry("WEB-INF/cadmium.properties"); Properties cadmiumProps = updateProperties(inZip, cadmiumPropertiesEntry, repoUri, branch, configRepoUri, configBranch); ZipEntry jbossWeb = null; jbossWeb = inZip.getEntry("WEB-INF/jboss-web.xml"); Enumeration<? extends ZipEntry> entries = inZip.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); if (e.getName().equals(cadmiumPropertiesEntry.getName())) { storeProperties(outZip, cadmiumPropertiesEntry, cadmiumProps, newWarNames); } else if (((domain != null && domain.length() > 0) || (context != null && context.length() > 0)) && e.getName().equals(jbossWeb.getName())) { updateDomain(inZip, outZip, jbossWeb, domain, context); } else if (secure && e.getName().equals("WEB-INF/web.xml")) { addSecurity(inZip, outZip, e); } else { outZip.putNextEntry(e); if (!e.isDirectory()) { FileSystemManager.streamCopy(inZip.getInputStream(e), outZip, true); } outZip.closeEntry(); } } } finally { if (FileSystemManager.exists("tmp_cadmium-war.war")) { new File("tmp_cadmium-war.war").delete(); } try { if (inZip != null) { inZip.close(); } } catch (Exception e) { if (log != null) { log.error("Failed to close " + war); } } try { if (outZip != null) { outZip.close(); } } catch (Exception e) { if (log != null) { log.error("Failed to close " + newWarNames.get(0)); } } try { if (out != null) { out.close(); } } catch (Exception e) { } try { if (in != null) { in.close(); } } catch (Exception e) { } } }