List of usage examples for java.util.jar Manifest getMainAttributes
public Attributes getMainAttributes()
From source file:com.orange.mmp.dao.flf.ModuleDaoFlfImpl.java
public Module[] find(Module module) throws MMPDaoException { if (module == null) { throw new MMPDaoException("missing or bad data access object"); }/*from w ww .j a va2s .c o m*/ FilenameFilter jarFilter = new SuffixFileFilter(".jar"); File widgetsFiles[] = new File(this.path).listFiles(jarFilter); if (widgetsFiles == null) return new Module[0]; ArrayList<Module> list = new ArrayList<Module>(); JarFile jarFile = null; try { for (File found : widgetsFiles) { jarFile = new JarFile(found); Manifest manifest = jarFile.getManifest(); boolean match = (module.getId() == null && module.getLocation() == null && module.getVersion() == null && module.getName() == null && module.getCategory() == null); if (!match) { boolean goOnchecking = true; if (module.getLocation() != null && goOnchecking) { match = found.toURI().toString().equals(module.getLocation().toString()); goOnchecking = false; } if (module.getId() != null) { match = (manifest.getMainAttributes().getValue(MODULE_ID_HEADER) != null && manifest.getMainAttributes().getValue(MODULE_ID_HEADER).equals(module.getId())); goOnchecking = false; } if (module.getVersion() != null && goOnchecking) { match = (manifest.getMainAttributes().getValue(MODULE_VERSION_HEADER) != null && manifest .getMainAttributes().getValue(MODULE_VERSION_HEADER).equals(module.getVersion())); goOnchecking = match; } if (module.getName() != null && goOnchecking) { match = (manifest.getMainAttributes().getValue(MODULE_NAME_HEADER) != null && manifest .getMainAttributes().getValue(MODULE_NAME_HEADER).equals(module.getName())); goOnchecking = match; } if (module.getCategory() != null && goOnchecking) { match = (manifest.getMainAttributes().getValue(MODULE_CATEGORY_HEADER) != null && manifest .getMainAttributes().getValue(MODULE_CATEGORY_HEADER).equals(module.getCategory())); goOnchecking = match; } } if (match) { Module foundModule = new Module(); foundModule.setId(manifest.getMainAttributes().getValue(MODULE_ID_HEADER)); foundModule.setName(manifest.getMainAttributes().getValue(MODULE_NAME_HEADER)); foundModule .setVersion(new Version(manifest.getMainAttributes().getValue(MODULE_VERSION_HEADER))); foundModule.setCategory(manifest.getMainAttributes().getValue(MODULE_CATEGORY_HEADER)); foundModule.setLastModified(found.lastModified()); foundModule.setLocation(found.toURI()); list.add(foundModule); } jarFile.close(); } } catch (IOException ioe) { throw new MMPDaoException("failed to load module"); } finally { try { if (jarFile != null) jarFile.close(); } catch (IOException ioe) { //Nop just log } } Module[] modulesList = new Module[list.size()]; return list.toArray(modulesList); }
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 w w . ja v a2 s . c o 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.fusesource.mop.MOP.java
protected void setClassNameFromExecutableJar(List<File> dependencies) throws Exception, UsageException { // now lets figure out the className from the manifest // lets assume that the first file in the dependency list is usually the one we want to execute for (File file : dependencies) { JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attributes = manifest.getMainAttributes(); if (attributes != null) { //debug("file " + file + " has main attributes: " + new HashMap(attributes)); className = attributes.getValue(Attributes.Name.MAIN_CLASS); if (className != null && className.length() > 0) { className = className.trim(); if (className.length() > 0) { break; }/* www . j av a 2 s. c o m*/ } } else { LOG.debug("file " + file + " has no manifest main attributes: " + attributes); } } else { LOG.debug("file " + file + " has no manifest"); } } if (className == null) { throw new Exception("No Main-Class attribute could be found in the dependent jars!"); } }
From source file:org.eclipse.gemini.blueprint.test.AbstractOnTheFlyBundleCreatorTests.java
private void addImportPackage(Manifest manifest) { String[] rawImports = determineImports(); boolean trace = logger.isTraceEnabled(); if (trace)/*from ww w . ja v a2 s . c o m*/ logger.trace("Discovered raw imports " + ObjectUtils.nullSafeToString(rawImports)); Collection specialImportsOut = eliminateSpecialPackages(rawImports); Collection imports = eliminatePackagesAvailableInTheJar(specialImportsOut); if (trace) logger.trace("Filtered imports are " + imports); manifest.getMainAttributes().putValue(Constants.IMPORT_PACKAGE, StringUtils.collectionToCommaDelimitedString(imports)); }
From source file:org.codehaus.enunciate.modules.BasicAppModule.java
/** * Copies the classpath elements to WEB-INF. * * @throws java.io.IOException/* w ww . j a v a2s .co m*/ */ protected void doLibCopy() throws IOException { Enunciate enunciate = getEnunciate(); File buildDir = getBuildDir(); File webinf = new File(buildDir, "WEB-INF"); File webinfClasses = new File(webinf, "classes"); File webinfLib = new File(webinf, "lib"); //initialize the include filters. AntPatternMatcher pathMatcher = new AntPatternMatcher(); pathMatcher.setPathSeparator(File.separator); List<File> explicitIncludes = new ArrayList<File>(); List<String> includePatterns = new ArrayList<String>(); WebAppConfig webAppConfig = getWebAppConfig(); if (webAppConfig != null) { for (IncludeExcludeLibs el : webAppConfig.getIncludeLibs()) { if (el.getFile() != null) { //add explicit files to the include files list. explicitIncludes.add(el.getFile()); } String pattern = el.getPattern(); if (pattern != null) { //normalize the pattern to the platform. pattern = pattern.replace('/', File.separatorChar); if (pathMatcher.isPattern(pattern)) { //make sure that the includes pattern list only has patterns. includePatterns.add(pattern); } else { warn("Pattern '%s' is not a valid pattern, so it will not be applied.", pattern); } } } } if (includePatterns.isEmpty()) { //if no include patterns are specified, the implicit pattern is "**/*". String starPattern = "**" + File.separatorChar + "*"; debug("No include patterns have been specified. Using the implicit '%s' pattern.", starPattern); includePatterns.add(starPattern); } List<String> warLibs = new ArrayList<String>(); if (webAppConfig == null || webAppConfig.isIncludeClasspathLibs()) { debug("Using the Enunciate classpath as the initial list of libraries to be passed through the include/exclude filter."); //prime the list of libs to include in the war with what's on the enunciate classpath. warLibs.addAll(Arrays.asList(enunciate.getEnunciateRuntimeClasspath().split(File.pathSeparator))); } // Apply the "in filter" (i.e. the filter that specifies the files to be included). List<File> includedLibs = new ArrayList<File>(); for (String warLib : warLibs) { File libFile = new File(warLib); if (libFile.exists()) { for (String includePattern : includePatterns) { String absolutePath = libFile.getAbsolutePath(); if (absolutePath.startsWith(File.separator)) { //lob off the beginning "/" for Linux boxes. absolutePath = absolutePath.substring(1); } if (pathMatcher.match(includePattern, absolutePath)) { debug("Library '%s' passed the include filter. It matches pattern '%s'.", libFile.getAbsolutePath(), includePattern); includedLibs.add(libFile); break; } else if (enunciate.isDebug()) { debug("Library '%s' did NOT match include pattern '%s'.", includePattern); } } } } //Now, with what's left, apply the "exclude filter". boolean excludeDefaults = webAppConfig == null || webAppConfig.isExcludeDefaultLibs(); List<String> manifestClasspath = new ArrayList<String>(); Iterator<File> toBeIncludedIt = includedLibs.iterator(); while (toBeIncludedIt.hasNext()) { File toBeIncluded = toBeIncludedIt.next(); if (excludeDefaults && knownExclude(toBeIncluded)) { toBeIncludedIt.remove(); } else if (webAppConfig != null) { for (IncludeExcludeLibs excludeLibs : webAppConfig.getExcludeLibs()) { boolean exclude = false; if ((excludeLibs.getFile() != null) && (excludeLibs.getFile().equals(toBeIncluded))) { exclude = true; debug("%s was explicitly excluded.", toBeIncluded); } else { String pattern = excludeLibs.getPattern(); if (pattern != null) { pattern = pattern.replace('/', File.separatorChar); if (pathMatcher.isPattern(pattern)) { String absolutePath = toBeIncluded.getAbsolutePath(); if (absolutePath.startsWith(File.separator)) { //lob off the beginning "/" for Linux boxes. absolutePath = absolutePath.substring(1); } if (pathMatcher.match(pattern, absolutePath)) { exclude = true; debug("%s was excluded because it matches pattern '%s'", toBeIncluded, pattern); } } } } if (exclude) { toBeIncludedIt.remove(); if ((excludeLibs.isIncludeInManifest()) && (!toBeIncluded.isDirectory())) { //include it in the manifest anyway. manifestClasspath.add(toBeIncluded.getName()); debug("'%s' will be included in the manifest classpath.", toBeIncluded.getName()); } break; } } } } //now add the lib files that are explicitly included. includedLibs.addAll(explicitIncludes); //now we've got the final list, copy the libs. for (File includedLib : includedLibs) { if (includedLib.isDirectory()) { debug("Adding the contents of %s to WEB-INF/classes.", includedLib); enunciate.copyDir(includedLib, webinfClasses); } else { debug("Including %s in WEB-INF/lib.", includedLib); enunciate.copyFile(includedLib, includedLib.getParentFile(), webinfLib); } } // write the manifest file. Manifest manifest = webAppConfig == null ? WebAppConfig.getDefaultManifest() : webAppConfig.getManifest(); if ((manifestClasspath.size() > 0) && (manifest.getMainAttributes().getValue("Class-Path") == null)) { StringBuilder manifestClasspathValue = new StringBuilder(); Iterator<String> manifestClasspathIt = manifestClasspath.iterator(); while (manifestClasspathIt.hasNext()) { String entry = manifestClasspathIt.next(); manifestClasspathValue.append(entry); if (manifestClasspathIt.hasNext()) { manifestClasspathValue.append(" "); } } manifest.getMainAttributes().putValue("Class-Path", manifestClasspathValue.toString()); } File metaInf = new File(buildDir, "META-INF"); metaInf.mkdirs(); FileOutputStream manifestFileOut = new FileOutputStream(new File(metaInf, "MANIFEST.MF")); manifest.write(manifestFileOut); manifestFileOut.flush(); manifestFileOut.close(); }
From source file:org.rhq.core.clientapi.descriptor.PluginTransformer.java
private String getVersionFromPluginJarManifest(URL pluginJarUrl) throws IOException { JarInputStream jarInputStream = new JarInputStream(pluginJarUrl.openStream()); Manifest manifest = jarInputStream.getManifest(); if (manifest == null) { // BZ 682116 (ips, 03/25/11): The manifest file is not in the standard place as the 2nd entry of the JAR, // but we want to be flexible and support JARs that have a manifest file somewhere else, so scan the entire // JAR for one. JarEntry jarEntry;//from w w w . ja v a 2 s . co m while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { if (JarFile.MANIFEST_NAME.equalsIgnoreCase(jarEntry.getName())) { manifest = new Manifest(jarInputStream); break; } } } try { jarInputStream.close(); } catch (IOException e) { LOG.error("Failed to close plugin jar input stream for plugin jar [" + pluginJarUrl + "].", e); } if (manifest != null) { Attributes attributes = manifest.getMainAttributes(); return attributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION); } else { return null; } }
From source file:org.hyperic.hq.agent.server.AgentDaemon.java
private void loadAgentServerHandlerJars(File[] libJars) throws AgentConfigException { AgentServerHandler loadedHandler;//from ww w. j a v a 2 s . co m // Save the current context loader, and reset after we load plugin jars ClassLoader currentContext = Thread.currentThread().getContextClassLoader(); for (File libJar : libJars) { try { JarFile jarFile = new JarFile(libJar); Manifest manifest = jarFile.getManifest(); String mainClass = manifest.getMainAttributes().getValue("Main-Class"); if (mainClass != null) { String jarPath = libJar.getAbsolutePath(); loadedHandler = this.handlerLoader.loadServerHandler(jarPath); this.serverHandlers.add(loadedHandler); this.dispatcher.addServerHandler(loadedHandler); } jarFile.close(); } catch (Exception e) { throw new AgentConfigException("Failed to load " + "'" + libJar + "': " + e.getMessage()); } } // Restore the class loader Thread.currentThread().setContextClassLoader(currentContext); }
From source file:com.googlecode.mycontainer.maven.plugin.ExecMojo.java
/** * Create a jar with just a manifest containing a Main-Class entry for * SurefireBooter and a Class-Path entry for all classpath elements. Copied * from surefire (ForkConfiguration#createJar()) * //from w w w . j a v a 2s .c o m * @param classPath * List<String> of all classpath elements. * @return * @throws IOException */ private File createJar(List classPath, String mainClass) throws IOException { File file = File.createTempFile("maven-exec", ".jar"); file.deleteOnExit(); FileOutputStream fos = new FileOutputStream(file); JarOutputStream jos = new JarOutputStream(fos); jos.setLevel(JarOutputStream.STORED); JarEntry je = new JarEntry("META-INF/MANIFEST.MF"); jos.putNextEntry(je); Manifest man = new Manifest(); // we can't use StringUtils.join here since we need to add a '/' to // the end of directory entries - otherwise the jvm will ignore them. String cp = ""; for (Iterator it = classPath.iterator(); it.hasNext();) { String el = (String) it.next(); // NOTE: if File points to a directory, this entry MUST end in '/'. cp += UrlUtils.getURL(new File(el)).toExternalForm() + " "; } man.getMainAttributes().putValue("Manifest-Version", "1.0"); man.getMainAttributes().putValue("Class-Path", cp.trim()); man.getMainAttributes().putValue("Main-Class", mainClass); man.write(jos); jos.close(); return file; }
From source file:org.eclipse.birt.build.mavenrepogen.RepoGen.java
private FileInfo getFileInfo(final File file) throws IOException { if (file.isDirectory()) return null; if (!file.getAbsolutePath().toLowerCase().endsWith(".jar")) return null; System.out.println(file);/*from w w w .j a va 2s .c om*/ final Manifest manifest = getManifest(file); String artifactId; String version; if (manifest == null) { artifactId = file.getName(); final int indexOfDot = artifactId.lastIndexOf("."); if (indexOfDot >= 0) artifactId = artifactId.substring(0, indexOfDot); version = "1"; } else { final Attributes mainAttributes = manifest.getMainAttributes(); artifactId = mainAttributes.getValue("Bundle-SymbolicName"); if (artifactId != null) { final int indexofsemicolon = artifactId.indexOf(";"); if (indexofsemicolon >= 0) artifactId = artifactId.substring(0, indexofsemicolon); version = trimVersion(mainAttributes.getValue("Bundle-Version")); } else { artifactId = mainAttributes.getValue("Specification-Title"); if (artifactId != null) { version = mainAttributes.getValue("Specification-Version"); } else { artifactId = file.getName(); final int indexOfDot = artifactId.lastIndexOf("."); if (indexOfDot >= 0) artifactId = artifactId.substring(0, indexOfDot); version = "1"; } } } return new FileInfo(file, groupId, artifactId, version); }
From source file:jdbc.pool.CConnectionPoolManager.java
/** * Stores the version number array of the JDBCPool in the variable {@link #VERSION}. * /*from w ww. ja v a 2 s.c o m*/ * String[0] element is the product name. * String[1] element is the version number. * String[2] element is the date on which the JDBCPool was released. * */ private void getVersion() { String localFile = getClass().getProtectionDomain().getCodeSource().getLocation().toString(); localFile = localFile.concat("!/"); String tmpString = "jar:"; String localJarFileString = tmpString.concat(localFile); URL localJarFileURL; try { localJarFileURL = new URL(localJarFileString); JarURLConnection localJarFile = (JarURLConnection) localJarFileURL.openConnection(); Manifest mf = localJarFile.getManifest(); Attributes attributes = mf.getMainAttributes(); VERSION[0] = (String) attributes.getValue("Bundle-Name"); VERSION[1] = (String) attributes.getValue("Bundle-Version"); VERSION[2] = (String) attributes.getValue("Bundled-On"); } catch (MalformedURLException e) { //do nothing } catch (IOException e) { //do nothing } // URL url = getURL(); // if (url != null) // { // try { // String file = url.getFile(); // if (file.lastIndexOf(".jar") > -1) { // url = new URL(file.substring(0, file.lastIndexOf(".jar")+4)); // } else { // logger_.warn("Illegal Execution. Execution is not as distributed."); // return; // } // JarInputStream jis = null; // try { // jis = new JarInputStream(url.openStream()); // Manifest manifest = jis.getManifest(); // Attributes attributes = manifest.getMainAttributes(); // VERSION[0] = (String) attributes.getValue("Bundle-Name"); // VERSION[1] = (String) attributes.getValue("Bundle-Version"); // VERSION[2] = (String) attributes.getValue("Bundled-On"); // } finally { // if (jis != null) { // jis.close(); // } // } // } catch (Exception e) { // //Do nothing // } // return; // } else { // logger_.debug("Unable to find the class."); // logger_.warn("Illegal Execution. Execution is not as distributed."); // } // return; }