List of usage examples for java.util.jar JarOutputStream close
public void close() throws IOException
From source file:JarEntryOutputStream.java
/** * Writes the entry to a the jar file. This is done by creating a * temporary jar file, copying the contents of the existing jar to the * temp jar, skipping the entry named by this.jarEntryName if it exists. * Then, if the stream was written to, then contents are written as a * new entry. Last, a callback is made to the EnhancedJarFile to * swap the temp jar in for the old jar. *//* w w w . j a v a2 s . com*/ private void writeToJar() throws IOException { File jarDir = new File(this.jar.getName()).getParentFile(); // create new jar File newJarFile = File.createTempFile("config", ".jar", jarDir); newJarFile.deleteOnExit(); JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile)); try { Enumeration entries = this.jar.entries(); // copy all current entries into the new jar while (entries.hasMoreElements()) { JarEntry nextEntry = (JarEntry) entries.nextElement(); // skip the entry named jarEntryName if (!this.jarEntryName.equals(nextEntry.getName())) { // the next 3 lines of code are a work around for // bug 4682202 in the java.sun.com bug parade, see: // http://developer.java.sun.com/developer/bugParade/bugs/4682202.html JarEntry entryCopy = new JarEntry(nextEntry); entryCopy.setCompressedSize(-1); jarOutputStream.putNextEntry(entryCopy); InputStream intputStream = this.jar.getInputStream(nextEntry); // write the data for (int data = intputStream.read(); data != -1; data = intputStream.read()) { jarOutputStream.write(data); } } } // write the new or modified entry to the jar if (size() > 0) { jarOutputStream.putNextEntry(new JarEntry(this.jarEntryName)); jarOutputStream.write(super.buf, 0, size()); jarOutputStream.closeEntry(); } } finally { // close close everything up try { if (jarOutputStream != null) { jarOutputStream.close(); } } catch (IOException ioe) { // eat it, just wanted to close stream } } // swap the jar this.jar.swapJars(newJarFile); }
From source file:com.simpligility.maven.plugins.android.phase09package.ApkMojo.java
private void extractDuplicateFiles(List<File> jarFiles, Collection<File> sourceFolders) throws IOException { getLog().debug("Extracting duplicates"); List<String> duplicates = new ArrayList<String>(); List<File> jarToModify = new ArrayList<File>(); for (String s : jars.keySet()) { List<File> l = jars.get(s); if (l.size() > 1) { getLog().warn("Duplicate file " + s + " : " + l); duplicates.add(s);/*from ww w . j a v a2s . co m*/ for (int i = 0; i < l.size(); i++) { if (!jarToModify.contains(l.get(i))) { jarToModify.add(l.get(i)); } } } } // Rebuild jars. Remove duplicates from ALL jars, then add them back into a duplicate-resources.jar File tmp = new File(targetDirectory.getAbsolutePath(), "unpacked-embedded-jars"); tmp.mkdirs(); File duplicatesJar = new File(tmp, "duplicate-resources.jar"); Set<String> duplicatesAdded = new HashSet<String>(); duplicatesJar.createNewFile(); final FileOutputStream fos = new FileOutputStream(duplicatesJar); final JarOutputStream zos = new JarOutputStream(fos); for (File file : jarToModify) { final int index = jarFiles.indexOf(file); if (index != -1) { final File newJar = removeDuplicatesFromJar(file, duplicates, duplicatesAdded, zos, index); getLog().debug("Removed duplicates from " + newJar); if (newJar != null) { jarFiles.set(index, newJar); } } else { removeDuplicatesFromFolder(file, file, duplicates, duplicatesAdded, zos); getLog().debug("Removed duplicates from " + file); } } //add transformed resources to duplicate-resources.jar if (transformers != null) { for (ResourceTransformer transformer : transformers) { if (transformer.hasTransformedResource()) { transformer.modifyOutputStream(zos); } } } zos.close(); fos.close(); if (!jarToModify.isEmpty() && duplicatesJar.length() > 0) { jarFiles.add(duplicatesJar); } }
From source file:org.infoglue.deliver.portal.deploy.Deploy.java
/** * Prepare a portlet according to Pluto (switch web.xml) * /*from w w w. j av a 2s . c om*/ * @param file .war to prepare * @param tmp the resulting updated .war * @param appName name of application (context name) * @return the portlet application definition (portlet.xml) * @throws IOException */ public static PortletApplicationDefinition prepareArchive(File file, File tmp, String appName) throws IOException { PortletApplicationDefinitionImpl portletApp = null; try { Mapping pdmXml = new Mapping(); try { URL url = Deploy.class.getResource("/" + PORTLET_MAPPING); pdmXml.loadMapping(url); } catch (Exception e) { throw new IOException("Failed to load mapping file " + PORTLET_MAPPING); } // Open the jar file. JarFile jar = new JarFile(file); // Extract and parse portlet.xml ZipEntry portletEntry = jar.getEntry(PORTLET_XML); if (portletEntry == null) { throw new IOException("Unable to find portlet.xml"); } InputStream pisDebug = jar.getInputStream(portletEntry); StringBuffer sb = new StringBuffer(); int i; while ((i = pisDebug.read()) > -1) { sb.append((char) i); } pisDebug.close(); InputSource xmlSource = new InputSource(new ByteArrayInputStream(sb.toString().getBytes("UTF-8"))); DOMParser parser = new DOMParser(); parser.parse(xmlSource); Document portletDocument = parser.getDocument(); //InputStream pis = jar.getInputStream(portletEntry); //Document portletDocument = XmlParser.parsePortletXml(pis); //pis.close(); InputStream pis = jar.getInputStream(portletEntry); ZipEntry webEntry = jar.getEntry(WEB_XML); InputStream wis = null; if (webEntry != null) { wis = jar.getInputStream(webEntry); /* webDocument = XmlParser.parseWebXml(wis); wis.close(); */ } Unmarshaller unmarshaller = new Unmarshaller(pdmXml); unmarshaller.setWhitespacePreserve(true); unmarshaller.setIgnoreExtraElements(true); unmarshaller.setIgnoreExtraAttributes(true); portletApp = (PortletApplicationDefinitionImpl) unmarshaller.unmarshal(portletDocument); // refill structure with necessary information Vector structure = new Vector(); structure.add(appName); structure.add(null); structure.add(null); portletApp.preBuild(structure); /* // now generate web part WebApplicationDefinitionImpl webApp = null; if (webDocument != null) { Unmarshaller unmarshallerWeb = new Unmarshaller(sdmXml); // modified by YCLI: START :: to ignore extra elements and // attributes unmarshallerWeb.setWhitespacePreserve(true); unmarshallerWeb.setIgnoreExtraElements(true); unmarshallerWeb.setIgnoreExtraAttributes(true); // modified by YCLI: END webApp = (WebApplicationDefinitionImpl) unmarshallerWeb.unmarshal(webDocument); } else { webApp = new WebApplicationDefinitionImpl(); DisplayNameImpl dispName = new DisplayNameImpl(); dispName.setDisplayName(appName); dispName.setLocale(Locale.ENGLISH); DisplayNameSetImpl dispSet = new DisplayNameSetImpl(); dispSet.add(dispName); webApp.setDisplayNames(dispSet); DescriptionImpl desc = new DescriptionImpl(); desc.setDescription("Automated generated Application Wrapper"); desc.setLocale(Locale.ENGLISH); DescriptionSetImpl descSet = new DescriptionSetImpl(); descSet.add(desc); webApp.setDescriptions(descSet); } org.apache.pluto.om.ControllerFactory controllerFactory = new org.apache.pluto.portalImpl.om.ControllerFactoryImpl(); ServletDefinitionListCtrl servletDefinitionSetCtrl = (ServletDefinitionListCtrl) controllerFactory .get(webApp.getServletDefinitionList()); Collection servletMappings = webApp.getServletMappings(); Iterator portlets = portletApp.getPortletDefinitionList().iterator(); while (portlets.hasNext()) { PortletDefinition portlet = (PortletDefinition) portlets.next(); // check if already exists ServletDefinition servlet = webApp.getServletDefinitionList() .get(portlet.getName()); if (servlet != null) { ServletDefinitionCtrl _servletCtrl = (ServletDefinitionCtrl) controllerFactory .get(servlet); _servletCtrl.setServletClass("org.apache.pluto.core.PortletServlet"); } else { servlet = servletDefinitionSetCtrl.add(portlet.getName(), "org.apache.pluto.core.PortletServlet"); } ServletDefinitionCtrl servletCtrl = (ServletDefinitionCtrl) controllerFactory .get(servlet); DisplayNameImpl dispName = new DisplayNameImpl(); dispName.setDisplayName(portlet.getName() + " Wrapper"); dispName.setLocale(Locale.ENGLISH); DisplayNameSetImpl dispSet = new DisplayNameSetImpl(); dispSet.add(dispName); servletCtrl.setDisplayNames(dispSet); DescriptionImpl desc = new DescriptionImpl(); desc.setDescription("Automated generated Portlet Wrapper"); desc.setLocale(Locale.ENGLISH); DescriptionSetImpl descSet = new DescriptionSetImpl(); descSet.add(desc); servletCtrl.setDescriptions(descSet); ParameterSet parameters = servlet.getInitParameterSet(); ParameterSetCtrl parameterSetCtrl = (ParameterSetCtrl) controllerFactory .get(parameters); Parameter parameter1 = parameters.get("portlet-class"); if (parameter1 == null) { parameterSetCtrl.add("portlet-class", portlet.getClassName()); } else { ParameterCtrl parameterCtrl = (ParameterCtrl) controllerFactory.get(parameter1); parameterCtrl.setValue(portlet.getClassName()); } Parameter parameter2 = parameters.get("portlet-guid"); if (parameter2 == null) { parameterSetCtrl.add("portlet-guid", portlet.getId().toString()); } else { ParameterCtrl parameterCtrl = (ParameterCtrl) controllerFactory.get(parameter2); parameterCtrl.setValue(portlet.getId().toString()); } boolean found = false; Iterator mappings = servletMappings.iterator(); while (mappings.hasNext()) { ServletMappingImpl servletMapping = (ServletMappingImpl) mappings.next(); if (servletMapping.getServletName().equals(portlet.getName())) { found = true; servletMapping.setUrlPattern("/" + portlet.getName().replace(' ', '_') + "/*"); } } if (!found) { ServletMappingImpl servletMapping = new ServletMappingImpl(); servletMapping.setServletName(portlet.getName()); servletMapping.setUrlPattern("/" + portlet.getName().replace(' ', '_') + "/*"); servletMappings.add(servletMapping); } SecurityRoleRefSet servletSecurityRoleRefs = ((ServletDefinitionImpl) servlet) .getInitSecurityRoleRefSet(); SecurityRoleRefSetCtrl servletSecurityRoleRefSetCtrl = (SecurityRoleRefSetCtrl) controllerFactory .get(servletSecurityRoleRefs); SecurityRoleSet webAppSecurityRoles = webApp.getSecurityRoles(); SecurityRoleRefSet portletSecurityRoleRefs = portlet.getInitSecurityRoleRefSet(); Iterator p = portletSecurityRoleRefs.iterator(); while (p.hasNext()) { SecurityRoleRef portletSecurityRoleRef = (SecurityRoleRef) p.next(); if (portletSecurityRoleRef.getRoleLink() == null && webAppSecurityRoles.get(portletSecurityRoleRef.getRoleName()) == null) { logger.info("Note: The web application has no security role defined which matches the role name \"" + portletSecurityRoleRef.getRoleName() + "\" of the security-role-ref element defined for the wrapper-servlet with the name '" + portlet.getName() + "'."); break; } SecurityRoleRef servletSecurityRoleRef = servletSecurityRoleRefs .get(portletSecurityRoleRef.getRoleName()); if (null != servletSecurityRoleRef) { logger.info("Note: Replaced already existing element of type <security-role-ref> with value \"" + portletSecurityRoleRef.getRoleName() + "\" for subelement of type <role-name> for the wrapper-servlet with the name '" + portlet.getName() + "'."); servletSecurityRoleRefSetCtrl.remove(servletSecurityRoleRef); } servletSecurityRoleRefSetCtrl.add(portletSecurityRoleRef); } } */ /* * TODO is this necessary? TagDefinitionImpl portletTagLib = new * TagDefinitionImpl(); Collection taglibs = * webApp.getCastorTagDefinitions(); taglibs.add(portletTagLib); */ // Duplicate jar-file with replaced web.xml FileOutputStream fos = new FileOutputStream(tmp); JarOutputStream tempJar = new JarOutputStream(fos); byte[] buffer = new byte[1024]; int bytesRead; for (Enumeration entries = jar.entries(); entries.hasMoreElements();) { JarEntry entry = (JarEntry) entries.nextElement(); JarEntry newEntry = new JarEntry(entry.getName()); tempJar.putNextEntry(newEntry); if (entry.getName().equals(WEB_XML)) { // Swap web.xml /* log.debug("Swapping web.xml"); OutputFormat of = new OutputFormat(); of.setIndenting(true); of.setIndent(4); // 2-space indention of.setLineWidth(16384); of.setDoctype(Constants.WEB_PORTLET_PUBLIC_ID, Constants.WEB_PORTLET_DTD); XMLSerializer serializer = new XMLSerializer(tempJar, of); Marshaller marshaller = new Marshaller(serializer.asDocumentHandler()); marshaller.setMapping(sdmXml); marshaller.marshal(webApp); */ PortletAppDescriptorService portletAppDescriptorService = new StreamPortletAppDescriptorServiceImpl( appName, pis, null); File tmpf = File.createTempFile("infoglue-web-xml", null); WebAppDescriptorService webAppDescriptorService = new StreamWebAppDescriptorServiceImpl(appName, wis, new FileOutputStream(tmpf)); org.apache.pluto.driver.deploy.Deploy d = new org.apache.pluto.driver.deploy.Deploy( webAppDescriptorService, portletAppDescriptorService); d.updateDescriptors(); FileInputStream fis = new FileInputStream(tmpf); while ((bytesRead = fis.read(buffer)) != -1) { tempJar.write(buffer, 0, bytesRead); } tmpf.delete(); } else { InputStream entryStream = jar.getInputStream(entry); if (entryStream != null) { while ((bytesRead = entryStream.read(buffer)) != -1) { tempJar.write(buffer, 0, bytesRead); } } } } tempJar.flush(); tempJar.close(); fos.flush(); fos.close(); /* * String strTo = dirDelim + "WEB-INF" + dirDelim + "tld" + dirDelim + * "portlet.tld"; String strFrom = "webapps" + dirDelim + strTo; * * copy(strFrom, webAppsDir + webModule + strTo); */ } catch (Exception e) { log.error("Failed to prepare archive", e); throw new IOException(e.getMessage()); } return portletApp; }
From source file:org.apache.pluto.util.assemble.ear.EarAssembler.java
public void assembleInternal(AssemblerConfig config) throws UtilityException, IOException { File source = config.getSource(); File dest = config.getDestination(); JarInputStream earIn = new JarInputStream(new FileInputStream(source)); JarOutputStream earOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(dest), BUFLEN)); try {//w w w . j ava 2s . co m JarEntry entry; // Iterate over entries in the EAR archive while ((entry = earIn.getNextJarEntry()) != null) { // If a war file is encountered, assemble it into a // ByteArrayOutputStream and write the assembled bytes // back to the EAR archive. if (entry.getName().toLowerCase().endsWith(".war")) { if (LOG.isDebugEnabled()) { LOG.debug("Assembling war file " + entry.getName()); } // keep a handle to the AssemblySink so we can write out // JarEntry metadata and the bytes later. AssemblySink warBytesOut = getAssemblySink(config, entry); JarOutputStream warOut = new JarOutputStream(warBytesOut); JarStreamingAssembly.assembleStream(new JarInputStream(earIn), warOut, config.getDispatchServletClass()); JarEntry warEntry = new JarEntry(entry); // Write out the assembled JarEntry metadata warEntry.setSize(warBytesOut.getByteCount()); warEntry.setCrc(warBytesOut.getCrc()); warEntry.setCompressedSize(-1); earOut.putNextEntry(warEntry); // Write out the assembled WAR file to the EAR warBytesOut.writeTo(earOut); earOut.flush(); earOut.closeEntry(); earIn.closeEntry(); } else { earOut.putNextEntry(entry); IOUtils.copy(earIn, earOut); earOut.flush(); earOut.closeEntry(); earIn.closeEntry(); } } } finally { earOut.close(); earIn.close(); } }
From source file:rita.widget.SourceCode.java
private void createCompileButton() { ImageIcon imgIcon = new ImageIcon(getClass().getResource("/images/sourcecode/bytecode.png")); this.compileButton = new JButton(imgIcon); this.compileButton.setToolTipText(Language.get("compileButton.tooltip")); final File basePathRobots = new File(Settings.getRobotsPath()); compileButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { // guardar el codigo fuente File sourcePath = saveSourceCode(); // COMPILA EN EL DIRECTORIO POR DEFAULT + LA RUTA DEL PACKAGE Collection<File> inFiles = createClassFiles(sourcePath); if (inFiles != null) { /* transformar el codigo fuente, que no tiene errores, para que los println aparezcan en una ventana. * La transformacin no deberia generar errores. *///from w ww. j ava 2 s .co m writeSourceFile(sourcePath, AgregadorDeConsola.getInstance().transformar(readSourceFile(sourcePath))); // volver a compilar, ahora con el codigo transformado inFiles = createClassFiles(sourcePath); if (inFiles != null) { createJarFile(inFiles); System.out.println("INSTALLPATH=" + Settings.getInstallPath()); System.out.println("SE ENVIA ROBOT:" + HelperEditor.currentRobotPackage + "." + HelperEditor.currentRobotName); // si quiere seleccionar enemigos if (Settings.getProperty("level.default").equals(Language.get("level.four"))) { try { DialogSelectEnemies.getInstance(); } catch (NoEnemiesException e2) { new MessageDialog(Language.get("robot.noEnemies"), MessageType.ERROR); } return; } else { callBatalla(null, null); } } else { System.out.println("Error en codigo transformado por AgregadorDeConsola"); } } } catch (Exception e1) { e1.printStackTrace(); } } /** Recibe un archivo conteniendo codigo fuente java, y crea el .class correspondiente * @param sourcePath El archivo .java * @return Un archivo conteniendo el path al .class generado, o null si no fue posible compilar porque hubo errores en el codigo fuente. */ private Collection<File> createClassFiles(File sourcePath) throws Exception, IOException { Collection<File> f = CompileString.compile(sourcePath, basePathRobots); if (CompileString.hasError()) { int cantErrores = 0; for (Diagnostic<?> diag : CompileString.diagnostics) { if (!diag.getKind().equals(Kind.WARNING)) { int line = (int) diag.getLineNumber(); int col = (int) diag.getColumnNumber(); if (line > 0 && col > 0) { highlightCode(line, col); cantErrores++; } } } if (cantErrores > 0) { new MessageDialog(Language.get("compile.error"), MessageType.ERROR); } return null; } else { return f; } } /* crea un jar con todas las clases del robot. el nombre del jar es el nombre del robot */ private void createJarFile(Collection<File> inFiles) throws FileNotFoundException, IOException { File jarFile = new File(basePathRobots, HelperEditor.currentRobotName + ".jar"); if (jarFile.exists()) { jarFile.delete(); } System.out.println("Path del JAR ==" + jarFile); jarFile.createNewFile(); FileOutputStream fos = new FileOutputStream(jarFile); BufferedOutputStream bo = new BufferedOutputStream(fos); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); JarOutputStream jarOutput = new JarOutputStream(fos, manifest); int basePathLength = basePathRobots.getAbsolutePath().length() + 1; // +1 para incluir al "/" final byte[] buf = new byte[1024]; int anz; try { // para todas las clases... for (File inFile : inFiles) { BufferedInputStream bi = new BufferedInputStream(new FileInputStream(inFile)); try { String relative = inFile.getAbsolutePath().substring(basePathLength); // copia y agrega el archivo .class al jar JarEntry je2 = new JarEntry(relative); jarOutput.putNextEntry(je2); while ((anz = bi.read(buf)) != -1) { jarOutput.write(buf, 0, anz); } jarOutput.closeEntry(); } finally { try { bi.close(); } catch (IOException ignored) { } } } } finally { try { jarOutput.close(); } catch (IOException ignored) { } try { fos.close(); } catch (IOException ignored) { } try { bo.close(); } catch (IOException ignored) { } } } }); compileButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { e.getComponent().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(MouseEvent e) { e.getComponent().setCursor(Cursor.getDefaultCursor()); } }); compileButton.setBounds(MIN_WIDTH, 0, MAX_WIDTH - MIN_WIDTH, BUTTON_HEIGHT); compileButton.setFont(smallButtonFont); compileButton.setAlignmentX(LEFT_ALIGNMENT); compileButton.setText(Language.get("compileButton.title")); }
From source file:org.dspace.installer_edm.InstallerCrosswalk.java
/** * Abre el jar para escribir el nuevo archivo class compilado, elresto de archivos los copia tal cual * * @throws IOException/*from w w w . j a va 2 s . c o m*/ */ protected void writeNewJar() throws IOException { // buffer para leer datos de los archivos final int BUFFER_SIZE = 1024; // directorio de trabajo File jarDir = new File(this.oaiApiJarJarFile.getName()).getParentFile(); // nombre del jar String name = oaiApiJarWorkFile.getName(); String extension = name.substring(name.lastIndexOf('.')); name = name.substring(0, name.lastIndexOf('.')); // archivo temporal del nuevo jar File newJarFile = File.createTempFile(name, extension, jarDir); newJarFile.deleteOnExit(); // flujo de escritura del nuevo jar JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile)); // recorrer todos los archivos del jar menos el crosswalk para replicarlos try { Enumeration<JarEntry> entries = oaiApiJarJarFile.entries(); while (entries.hasMoreElements()) { installerEDMDisplay.showProgress('.'); JarEntry entry = entries.nextElement(); if (!entry.getName().equals(edmCrossWalkClass)) { JarEntry entryOld = new JarEntry(entry); entryOld.setCompressedSize(-1); jarOutputStream.putNextEntry(entryOld); InputStream intputStream = oaiApiJarJarFile.getInputStream(entry); int count; byte data[] = new byte[BUFFER_SIZE]; while ((count = intputStream.read(data, 0, BUFFER_SIZE)) != -1) { jarOutputStream.write(data, 0, count); } intputStream.close(); } } installerEDMDisplay.showLn(); // aadir class compilado addClass2Jar(jarOutputStream); // cerrar jar original oaiApiJarJarFile.close(); // borrar jar original oaiApiJarWorkFile.delete(); // cambiar jar original por nuevo try { /*if (newJarFile.renameTo(oaiApiJarWorkFile) && oaiApiJarWorkFile.setExecutable(true, true)) { oaiApiJarWorkFile = new File(oaiApiJarName); } else { throw new IOException(); }*/ if (jarOutputStream != null) jarOutputStream.close(); FileUtils.moveFile(newJarFile, oaiApiJarWorkFile); oaiApiJarWorkFile.setExecutable(true, true); oaiApiJarWorkFile = new File(oaiApiJarName); } catch (Exception io) { io.printStackTrace(); throw new IOException(); } } finally { if (jarOutputStream != null) { jarOutputStream.close(); } } }
From source file:org.apache.sling.osgi.obr.Repository.java
File spoolModified(InputStream ins) throws IOException { JarInputStream jis = new JarInputStream(ins); // immediately handle the manifest JarOutputStream jos; Manifest manifest = jis.getManifest(); if (manifest == null) { throw new IOException("Missing Manifest !"); }// w ww .j av a 2 s . c om String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName"); if (symbolicName == null || symbolicName.length() == 0) { throw new IOException("Missing Symbolic Name in Manifest !"); } String version = manifest.getMainAttributes().getValue("Bundle-Version"); Version v = Version.parseVersion(version); if (v.getQualifier().indexOf("SNAPSHOT") >= 0) { String tStamp; synchronized (DATE_FORMAT) { tStamp = DATE_FORMAT.format(new Date()); } version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + "." + v.getQualifier().replaceAll("SNAPSHOT", tStamp); manifest.getMainAttributes().putValue("Bundle-Version", version); } File bundle = new File(this.repoLocation, symbolicName + "-" + v + ".jar"); OutputStream out = null; try { out = new FileOutputStream(bundle); jos = new JarOutputStream(out, manifest); jos.setMethod(JarOutputStream.DEFLATED); jos.setLevel(Deflater.BEST_COMPRESSION); JarEntry entryIn = jis.getNextJarEntry(); while (entryIn != null) { JarEntry entryOut = new JarEntry(entryIn.getName()); entryOut.setTime(entryIn.getTime()); entryOut.setComment(entryIn.getComment()); jos.putNextEntry(entryOut); if (!entryIn.isDirectory()) { spool(jis, jos); } jos.closeEntry(); jis.closeEntry(); entryIn = jis.getNextJarEntry(); } // close the JAR file now to force writing jos.close(); } finally { IOUtils.closeQuietly(out); } return bundle; }
From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java
private void compileJavaModule(File jarOutputFolder, File classesOutputFolder, String moduleName, String moduleVersion, File sourceFolder, File[] extraClassPath, String... sourceFileNames) throws IOException { JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); assertNotNull("Missing Java compiler, this test is probably being run with a JRE instead of a JDK!", javaCompiler);/*w w w . j a v a 2 s.c o m*/ StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null); Set<String> sourceDirectories = new HashSet<String>(); File[] javaSourceFiles = new File[sourceFileNames.length]; for (int i = 0; i < javaSourceFiles.length; i++) { javaSourceFiles[i] = new File(sourceFolder, sourceFileNames[i]); String sfn = sourceFileNames[i].replace(File.separatorChar, '/'); int p = sfn.lastIndexOf('/'); String sourceDir = sfn.substring(0, p); sourceDirectories.add(sourceDir); } Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaSourceFiles); StringBuilder cp = new StringBuilder(); for (int i = 0; i < extraClassPath.length; i++) { if (i > 0) cp.append(File.pathSeparator); cp.append(extraClassPath[i]); } CompilationTask task = javaCompiler.getTask(null, null, null, Arrays.asList("-d", classesOutputFolder.getPath(), "-cp", cp.toString(), "-sourcepath", sourceFolder.getPath()), null, compilationUnits); assertEquals(Boolean.TRUE, task.call()); File jarFolder = new File(jarOutputFolder, moduleName.replace('.', File.separatorChar) + File.separatorChar + moduleVersion); jarFolder.mkdirs(); File jarFile = new File(jarFolder, moduleName + "-" + moduleVersion + ".jar"); // now jar it up JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(jarFile)); for (String sourceFileName : sourceFileNames) { String classFileName = sourceFileName.substring(0, sourceFileName.length() - 5) + ".class"; ZipEntry entry = new ZipEntry(classFileName); outputStream.putNextEntry(entry); File classFile = new File(classesOutputFolder, classFileName); FileInputStream inputStream = new FileInputStream(classFile); Util.copy(inputStream, outputStream); inputStream.close(); outputStream.flush(); } outputStream.close(); for (String sourceDir : sourceDirectories) { File module = null; String sourceName = "module.properties"; File properties = new File(sourceFolder, sourceDir + File.separator + sourceName); if (properties.exists()) { module = properties; } else { sourceName = "module.xml"; properties = new File(sourceFolder, sourceDir + File.separator + sourceName); if (properties.exists()) { module = properties; } } if (module != null) { File moduleFile = new File(sourceFolder, sourceDir + File.separator + sourceName); FileInputStream inputStream = new FileInputStream(moduleFile); FileOutputStream moduleOutputStream = new FileOutputStream(new File(jarFolder, sourceName)); Util.copy(inputStream, moduleOutputStream); inputStream.close(); moduleOutputStream.flush(); moduleOutputStream.close(); } } }
From source file:com.netflix.nicobar.core.module.ScriptModuleUtils.java
/** * Convert a ScriptModule to its compiled equivalent ScriptArchive. * <p>/*w ww.j a v a 2 s. c o m*/ * A jar script archive is created containing compiled bytecode * from a script module, as well as resources and other metadata from * the source script archive. * <p> * This involves serializing the class bytes of all the loaded classes in * the script module, as well as copying over all entries in the original * script archive, minus any that have excluded extensions. The module spec * of the source script archive is transferred as is to the target bytecode * archive. * * @param module the input script module containing loaded classes * @param jarPath the path to a destination JarScriptArchive. * @param excludeExtensions a set of extensions with which * source script archive entries can be excluded. * * @throws Exception */ public static void toCompiledScriptArchive(ScriptModule module, Path jarPath, Set<String> excludeExtensions) throws Exception { ScriptArchive sourceArchive = module.getSourceArchive(); JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jarPath.toFile())); try { // First copy all resources (excluding those with excluded extensions) // from the source script archive, into the target script archive for (String archiveEntry : sourceArchive.getArchiveEntryNames()) { URL entryUrl = sourceArchive.getEntry(archiveEntry); boolean skip = false; for (String extension : excludeExtensions) { if (entryUrl.toString().endsWith(extension)) { skip = true; break; } } if (skip) continue; InputStream entryStream = entryUrl.openStream(); byte[] entryBytes = IOUtils.toByteArray(entryStream); entryStream.close(); jarStream.putNextEntry(new ZipEntry(archiveEntry)); jarStream.write(entryBytes); jarStream.closeEntry(); } // Now copy all compiled / loaded classes from the script module. Set<Class<?>> loadedClasses = module.getModuleClassLoader().getLoadedClasses(); Iterator<Class<?>> iterator = loadedClasses.iterator(); while (iterator.hasNext()) { Class<?> clazz = iterator.next(); String classPath = clazz.getName().replace(".", "/") + ".class"; URL resourceURL = module.getModuleClassLoader().getResource(classPath); if (resourceURL == null) { throw new Exception("Unable to find class resource for: " + clazz.getName()); } InputStream resourceStream = resourceURL.openStream(); jarStream.putNextEntry(new ZipEntry(classPath)); byte[] classBytes = IOUtils.toByteArray(resourceStream); resourceStream.close(); jarStream.write(classBytes); jarStream.closeEntry(); } // Copy the source moduleSpec, but tweak it to specify the bytecode compiler in the // compiler plugin IDs list. ScriptModuleSpec moduleSpec = sourceArchive.getModuleSpec(); ScriptModuleSpec.Builder newModuleSpecBuilder = new ScriptModuleSpec.Builder(moduleSpec.getModuleId()); newModuleSpecBuilder.addCompilerPluginIds(moduleSpec.getCompilerPluginIds()); newModuleSpecBuilder.addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID); newModuleSpecBuilder.addMetadata(moduleSpec.getMetadata()); newModuleSpecBuilder.addModuleDependencies(moduleSpec.getModuleDependencies()); // Serialize the modulespec with GSON and its default spec file name ScriptModuleSpecSerializer specSerializer = new GsonScriptModuleSpecSerializer(); String json = specSerializer.serialize(newModuleSpecBuilder.build()); jarStream.putNextEntry(new ZipEntry(specSerializer.getModuleSpecFileName())); jarStream.write(json.getBytes(Charsets.UTF_8)); jarStream.closeEntry(); } finally { if (jarStream != null) { jarStream.close(); } } }
From source file:org.wso2.carbon.integration.common.utils.FileManager.java
public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory) throws URISyntaxException, IOException { File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI()); File destinationFileDirectory = new File(destinationDirectory); JarOutputStream jarOutputStream = null; InputStream inputStream = null; try {/*from w ww . jav a2 s . c o m*/ JarFile jarFile = new JarFile(sourceFile); String fileName = jarFile.getName(); String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator)); File destinationFile = new File(destinationFileDirectory, fileNameLastPart); jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile)); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { try { JarEntry jarEntry = entries.nextElement(); inputStream = jarFile.getInputStream(jarEntry); //jarOutputStream.putNextEntry(jarEntry); //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName())); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) != -1) { jarOutputStream.write(buffer, 0, bytesRead); } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.warn("Fail to close jarOutStream"); } } if (jarOutputStream != null) { try { jarOutputStream.flush(); jarOutputStream.closeEntry(); } catch (IOException e) { log.warn("Error while closing jar out stream"); } } if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { log.warn("Error while closing jar file"); } } } } } finally { if (jarOutputStream != null) { try { jarOutputStream.close(); } catch (IOException e) { log.warn("Fail to close jarOutStream"); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.warn("Error while closing input stream"); } } } }