List of usage examples for java.util.jar Manifest getMainAttributes
public Attributes getMainAttributes()
From source file:org.apache.sqoop.integration.connectorloading.ClasspathTest.java
private Map<String, String> buildJar(String outputDir, Map<String, JarContents> sourceFileToJarMap) throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); List<File> sourceFiles = new ArrayList<>(); for (JarContents jarContents : sourceFileToJarMap.values()) { sourceFiles.addAll(jarContents.sourceFiles); }/*from w ww .jav a 2 s. com*/ fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(outputDir.toString()))); Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(sourceFiles); boolean compiled = compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call(); if (!compiled) { throw new RuntimeException("failed to compile"); } for (Map.Entry<String, JarContents> jarNameAndContents : sourceFileToJarMap.entrySet()) { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, "."); JarOutputStream target = new JarOutputStream( new FileOutputStream(outputDir.toString() + File.separator + jarNameAndContents.getKey()), manifest); List<String> classesForJar = new ArrayList<>(); for (File sourceFile : jarNameAndContents.getValue().getSourceFiles()) { //split the file on dot to get the filename from FILENAME.java String fileName = sourceFile.getName().split("\\.")[0]; classesForJar.add(fileName); } File dir = new File(outputDir); File[] directoryListing = dir.listFiles(); for (File compiledClass : directoryListing) { String classFileName = compiledClass.getName().split("\\$")[0].split("\\.")[0]; if (classesForJar.contains(classFileName)) { addFileToJar(compiledClass, target); } } for (File propertiesFile : jarNameAndContents.getValue().getProperitesFiles()) { addFileToJar(propertiesFile, target); } target.close(); } //delete non jar files File dir = new File(outputDir); File[] directoryListing = dir.listFiles(); for (File file : directoryListing) { String extension = file.getName().split("\\.")[1]; if (!extension.equals("jar")) { file.delete(); } } Map<String, String> jarMap = new HashMap<>(); jarMap.put(TEST_CONNECTOR_JAR_NAME, outputDir.toString() + File.separator + TEST_CONNECTOR_JAR_NAME); jarMap.put(TEST_DEPENDENCY_JAR_NAME, outputDir.toString() + File.separator + TEST_DEPENDENCY_JAR_NAME); return jarMap; }
From source file:org.lnicholls.galleon.app.AppDescriptor.java
public AppDescriptor(File jar) throws IOException, AppException { mJar = jar;//from w ww .jav a 2 s . c om JarFile zipFile = new JarFile(jar); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); String name = entry.getName(); if (name.toUpperCase().equals(JarFile.MANIFEST_NAME)) { InputStream in = null; try { in = zipFile.getInputStream(entry); Manifest manifest = new Manifest(in); Attributes attributes = manifest.getMainAttributes(); if (attributes.getValue("Main-Class") != null) { mClassName = (String) attributes.getValue("Main-Class"); if (attributes.getValue("HME-Arguments") != null) mArguments = (String) attributes.getValue("HME-Arguments"); if (attributes.getValue(TITLE) != null) mTitle = (String) attributes.getValue(TITLE); if (attributes.getValue(RELEASE_DATE) != null) mReleaseDate = (String) attributes.getValue(RELEASE_DATE); if (attributes.getValue(DESCRIPTION) != null) mDescription = (String) attributes.getValue(DESCRIPTION); if (attributes.getValue(DOCUMENTATION) != null) mDocumentation = (String) attributes.getValue(DOCUMENTATION); if (attributes.getValue(AUTHOR_NAME) != null) mAuthorName = (String) attributes.getValue(AUTHOR_NAME); if (attributes.getValue(AUTHOR_EMAIL) != null) mAuthorEmail = (String) attributes.getValue(AUTHOR_EMAIL); if (attributes.getValue(AUTHOR_HOMEPAGE) != null) mAuthorHomepage = (String) attributes.getValue(AUTHOR_HOMEPAGE); if (attributes.getValue(VERSION) != null) mVersion = (String) attributes.getValue(VERSION); if (attributes.getValue(CONFIGURATION) != null) mConfiguration = (String) attributes.getValue(CONFIGURATION); if (attributes.getValue(CONFIGURATION_PANEL) != null) mConfigurationPanel = (String) attributes.getValue(CONFIGURATION_PANEL); if (attributes.getValue(TAGS) != null) mTags = (String) attributes.getValue(TAGS); } if (mTitle == null) { mTitle = jar.getName().substring(0, jar.getName().indexOf('.')); } } catch (Exception ex) { Tools.logException(AppDescriptor.class, ex, "Cannot get descriptor: " + jar.getAbsolutePath()); } finally { if (in != null) { try { in.close(); in = null; } catch (Exception ex) { } } } break; } } zipFile.close(); }
From source file:org.springframework.cloud.deployer.thin.ThinJarAppWrapper.java
protected String getMainClass(Archive archive) { try {/*from w w w .j ava 2s.c o m*/ Manifest manifest = archive.getManifest(); String mainClass = null; if (manifest != null) { mainClass = manifest.getMainAttributes().getValue("Start-Class"); } if (mainClass == null) { throw new IllegalStateException("No 'Start-Class' manifest entry specified in " + this); } return mainClass; } catch (Exception e) { try { File root = new File(archive.getUrl().toURI()); if (archive instanceof ExplodedArchive) { return MainClassFinder.findSingleMainClass(root); } else { return MainClassFinder.findSingleMainClass(new JarFile(root), "/"); } } catch (Exception ex) { throw new IllegalStateException("Cannot find main class", e); } } }
From source file:com.impetus.kundera.classreading.ClasspathReader.java
/** * Scan class resource in the provided urls with the additional Class-Path * of each jar checking//from w w w . j av a 2 s . c o m * * @param classRelativePath * relative path to a class resource * @param urls * urls to be checked * @return list of class path included in the base package */ private URL[] findResourcesInUrls(String classRelativePath, URL[] urls) { List<URL> list = new ArrayList<URL>(); for (URL url : urls) { if (AllowedProtocol.isValidProtocol(url.getProtocol().toUpperCase()) && url.getPath().endsWith(".jar")) { try { JarFile jarFile = new JarFile(URLDecoder.decode(url.getFile(), Constants.CHARSET_UTF8)); // Checking the dependencies of this jar file Manifest manifest = jarFile.getManifest(); if (manifest != null) { String classPath = manifest.getMainAttributes().getValue("Class-Path"); // Scan all entries in the classpath if they are // specified in the jar if (!StringUtils.isEmpty(classPath)) { List<URL> subList = new ArrayList<URL>(); for (String cpEntry : classPath.split(" ")) { try { subList.add(new URL(cpEntry)); } catch (MalformedURLException e) { URL subResources = ClasspathReader.class.getClassLoader().getResource(cpEntry); if (subResources != null) { subList.add(subResources); } // logger.warn("Incorrect URL in the classpath of a jar file [" // + url.toString() // + "]: " + cpEntry); } } list.addAll(Arrays.asList(findResourcesInUrls(classRelativePath, subList.toArray(new URL[subList.size()])))); } } JarEntry present = jarFile.getJarEntry(classRelativePath + ".class"); if (present != null) { list.add(url); } } catch (IOException e) { logger.warn("Error during loading from context , Caused by:" + e.getMessage()); } } else if (url.getPath().endsWith("/")) { File file = new File(url.getPath() + classRelativePath + ".class"); if (file.exists()) { try { list.add(file.toURL()); } catch (MalformedURLException e) { throw new ResourceReadingException(e); } } } } return list.toArray(new URL[list.size()]); }
From source file:org.apache.sling.tooling.support.install.impl.InstallServlet.java
private void installBasedOnDirectory(HttpServletResponse resp, final File dir) throws FileNotFoundException, IOException { InstallationResult result = null;/*from www. ja v a 2 s . co m*/ if (dir.exists() && dir.isDirectory()) { logger.info("Checking dir {} for bundle install", dir); final File manifestFile = new File(dir, JarFile.MANIFEST_NAME); if (manifestFile.exists()) { FileInputStream fis = null; try { fis = new FileInputStream(manifestFile); final Manifest mf = new Manifest(fis); final String symbolicName = mf.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); if (symbolicName != null) { // search bundle Bundle found = getBundle(symbolicName); final File tempFile = File.createTempFile(dir.getName(), "bundle"); try { createJar(dir, tempFile, mf); final InputStream in = new FileInputStream(tempFile); try { String location = dir.getAbsolutePath(); installOrUpdateBundle(found, in, location); result = new InstallationResult(true, null); resp.setStatus(200); result.render(resp.getWriter()); return; } catch (final BundleException be) { logAndWriteError("Unable to install/update bundle from dir " + dir, be, resp); } } finally { tempFile.delete(); } } else { logAndWriteError("Manifest in " + dir + " does not have a symbolic name", resp); } } finally { IOUtils.closeQuietly(fis); } } else { result = new InstallationResult(false, "Dir " + dir + " does not have a manifest"); logAndWriteError("Dir " + dir + " does not have a manifest", resp); } } else { result = new InstallationResult(false, "Dir " + dir + " does not exist"); logAndWriteError("Dir " + dir + " does not exist", resp); } }
From source file:org.eclipse.emf.mwe.core.WorkflowEngine.java
/** * Tries to read the exact build version from the Manifest of the core.workflow plugin. Therefore the Manifest file * is located and the version is read from the attribute 'Bundle-Version'. * //from ww w . j a v a 2s .c o m * @return The build version string, format "4.1.1, Build 200609291913" */ private String getVersion() { try { URL url = new URL(MWEPlugin.INSTANCE.getBaseURL() + "META-INF/MANIFEST.MF"); final Manifest manifest = new Manifest(url.openStream()); // Original value : "4.1.1.200609291913" // Resulting value : "4.1.1, Build 200609291913" String version = manifest.getMainAttributes().getValue("Bundle-Version"); final int lastPoint = version.lastIndexOf('.'); return version.substring(0, lastPoint) + ", Build " + version.substring(lastPoint + 1); } catch (Exception e) { logger.warn("Couldn't compute version of mwe.core bundle.", e); return "unkown version"; } }
From source file:org.jahia.loganalyzer.internal.JahiaLogAnalyzerImpl.java
@Override public void retrieveBuildInformation() { try {//from w w w .j av a 2s. c o m URL urlToMavenPom = JahiaLogAnalyzerImpl.class.getClassLoader() .getResource("/META-INF/jahia-loganalyzer-marker.txt"); if (urlToMavenPom != null) { URLConnection urlConnection = urlToMavenPom.openConnection(); if (urlConnection instanceof JarURLConnection) { JarURLConnection conn = (JarURLConnection) urlConnection; JarFile jarFile = conn.getJarFile(); Manifest manifest = jarFile.getManifest(); Attributes attributes = manifest.getMainAttributes(); buildNumber = attributes.getValue("Implementation-Build"); version = attributes.getValue("Implementation-Version"); String buildTimestampValue = attributes.getValue("Implementation-Timestamp"); if (buildTimestampValue != null) { try { long buildTimestampTime = Long.parseLong(buildTimestampValue); buildTimestamp = new Date(buildTimestampTime); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } } } } } catch (IOException ioe) { log.error("Error while trying to retrieve build information", ioe); } catch (NumberFormatException nfe) { log.error("Error while trying to retrieve build information", nfe); } }
From source file:org.openhab.tools.analysis.checkstyle.ServiceComponentManifestCheck.java
private void verifyManifest(FileText fileText) { File file = fileText.getFile(); manifestPath = file.getPath();/*www. j a v a 2 s . co m*/ try { Manifest manifest = new Manifest(new FileInputStream(file)); Attributes attributes = manifest.getMainAttributes(); serviceComponentHeaderValue = attributes.getValue(SERVICE_COMPONENT_HEADER_NAME); if (serviceComponentHeaderValue != null) { serviceComponentHeaderLineNumber = findLineNumberSafe(fileText, SERVICE_COMPONENT_HEADER_NAME, 0, "Service component header line number not found."); List<String> serviceComponentsList = Arrays.asList(serviceComponentHeaderValue.trim().split(",")); for (String serviceComponent : serviceComponentsList) { // We assume that the defined service component refers to existing file File serviceComponentFile = new File(serviceComponent); String serviceComponentParentDirectoryName = serviceComponentFile.getParentFile().getName(); if (!serviceComponentParentDirectoryName.equals(OSGI_INF_DIRECTORY_NAME)) { // if the parent directory of the service is not // OSGI-INF logMessage(serviceComponentHeaderLineNumber, String.format("Incorrect directory for services - %s. " + "The best practice is services metadata files to be placed directly in OSGI-INF directory.", serviceComponentParentDirectoryName)); } String serviceComponentName = serviceComponentFile.getName(); // We will process either .xml or OSGi-INF/* service components if (serviceComponentName.endsWith(XML_EXTENSION) || serviceComponentName.endsWith(WILDCARD)) { manifestServiceComponents.add(serviceComponentName); } else { logMessage(serviceComponentHeaderLineNumber, String.format("The service %s is with invalid extension." + "Only XML metadata files for services description are expected in the OSGI-INF directory.", serviceComponentName)); } } } } catch (IOException e) { logger.error("Problem occurred while parsing the file " + file.getPath(), e); } }
From source file:eu.chocolatejar.eclipse.plugin.cleaner.ArtifactParser.java
/** * Create an artifact for the jar based on jarsManifest * //from www . ja va 2s . c o m * @param jar * the location of the bundle. It can be a folder or a file. * @param jarsManifest * manifest location can be within the folder or within the jar. * @return */ private Artifact parseFromManifest(File jar, File jarsManifest) { Manifest bundleManifest = readManifestfromJarOrDirectory(jarsManifest); if (bundleManifest == null) { logger.debug("Invalid manifest '{}'", jarsManifest); return null; } Attributes attributes = bundleManifest.getMainAttributes(); if (attributes == null) { logger.debug("Manifest '{}' doesn't contain attributes.", jarsManifest); return null; } String bundleSymbolicName = attributes.getValue(Constants.BUNDLE_SYMBOLICNAME); String bundleVersion = attributes.getValue(Constants.BUNDLE_VERSION); if (StringUtils.isBlank(bundleSymbolicName) || StringUtils.isBlank(bundleVersion)) { logger.warn("Manifest '{}' doesn't contain OSGI attributes.", jarsManifest); return null; } return new Artifact(jar, bundleSymbolicName, bundleVersion); }
From source file:generate.MapGenerateAction.java
@Override public String execute() { String file_path = "/home/chanakya/NetBeansProjects/Concepto/UploadedFiles"; try {/* ww w. j a v a 2s. co m*/ File fileToCreate = new File(file_path, concept_map.getUploadedFileFileName()); FileUtils.copyFile(concept_map.getUploadedFile(), fileToCreate); } catch (Throwable t) { System.out.println("E1: " + t.getMessage()); return ERROR; } try { List<String> temp_text = FileUtils.readLines(concept_map.getUploadedFile()); StringBuilder text = new StringBuilder(); for (String s : temp_text) { text.append(s); } concept_map.setInput_text(text.toString()); } catch (IOException e) { //e.printStackTrace(); System.out.println("E2: " + e.getMessage()); return ERROR; } String temp_filename = concept_map.getUploadedFileFileName().split("\\.(?=[^\\.]+$)")[0]; temp_filename = temp_filename.trim(); try { String temp = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar " + file_path + " " + temp_filename; System.out.println(temp); File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar"); JarFile jar = new JarFile(jarfile); Manifest manifest = jar.getManifest(); Attributes attrs = manifest.getMainAttributes(); String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS); System.out.println(mainClassName); URL url = new URL("file", null, jarfile.getAbsolutePath()); ClassLoader cl = new URLClassLoader(new URL[] { url }); Class mainClass = cl.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); String[] args = new String[2]; args[0] = file_path; args[1] = temp_filename; System.out.println(args[0]); System.out.println(args[1]); try { mainMethod.invoke(mainClass, new Object[] { args }); } catch (InvocationTargetException e) { System.out.println("This is the exception: " + e.getTargetException().toString()); } } catch (IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException | IOException e) { System.out.println("E3: " + e.getMessage()); return ERROR; } try { String temp2 = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar " + file_path + " " + temp_filename; System.out.println(temp2); File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar"); JarFile jar = new JarFile(jarfile); Manifest manifest = jar.getManifest(); Attributes attrs = manifest.getMainAttributes(); String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS); System.out.println(mainClassName); URL url = new URL("file", null, jarfile.getAbsolutePath()); ClassLoader cl = new URLClassLoader(new URL[] { url }); Class mainClass = cl.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); String[] args = new String[2]; args[0] = file_path; args[1] = temp_filename; mainMethod.invoke(mainClass, new Object[] { args }); } catch (InvocationTargetException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException | IOException e) { System.out.println("E4: " + e.getMessage()); return ERROR; } String cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/add_to_graph.py \"/home/chanakya/NetBeansProjects/Concepto/UploadedFiles/" + temp_filename + "_OllieOutput.txt\""; String[] finalCommand; finalCommand = new String[3]; finalCommand[0] = "/bin/sh"; finalCommand[1] = "-c"; finalCommand[2] = cmd; System.out.println("CMD: " + cmd); try { //ProcessBuilder builder = new ProcessBuilder(finalCommand); //builder.redirectErrorStream(true); //Process process = builder.start(); Process process = Runtime.getRuntime().exec(finalCommand); int exitVal = process.waitFor(); System.out.println("Process exitValue2: " + exitVal); } catch (Throwable t) { System.out.println("E5: " + t.getMessage()); return ERROR; } cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/json_correct.py"; finalCommand = new String[3]; finalCommand[0] = "/bin/sh"; finalCommand[1] = "-c"; finalCommand[2] = cmd; try { //Process process = Runtime.getRuntime().exec(finalCommand); ProcessBuilder builder = new ProcessBuilder(finalCommand); // builder.redirectErrorStream(true); Process process = builder.start(); int exitVal = process.waitFor(); System.out.println("Process exitValue3: " + exitVal); } catch (Throwable t) { System.out.println("E6: " + t.getMessage()); return ERROR; } try { List<String> temp_text_1 = FileUtils .readLines(FileUtils.getFile("/home/chanakya/NetBeansProjects/Concepto/web", "new_graph.json")); StringBuilder text_1 = new StringBuilder(); for (String s : temp_text_1) { text_1.append(s); } concept_map.setOutput_text(text_1.toString()); } catch (IOException e) { System.out.println("E7: " + e.getMessage()); return ERROR; } Random rand = new Random(); int unique_id = rand.nextInt(99999999); System.out.println("Going In DB"); try { MongoClient mongo = new MongoClient(); DB db = mongo.getDB("Major"); DBCollection collection = db.getCollection("ConceptMap"); BasicDBObject document = new BasicDBObject(); document.append("InputText", concept_map.getInput_text()); document.append("OutputText", concept_map.getOutput_text()); document.append("ChapterName", concept_map.getChapter_name()); document.append("ChapterNumber", concept_map.getChapter_number()); document.append("SectionName", concept_map.getSection_name()); document.append("SectionNumber", concept_map.getSection_number()); document.append("UniqueID", Integer.toString(unique_id)); collection.insert(document); //collection.save(document); } catch (MongoException e) { System.out.println("E8: " + e.getMessage()); return ERROR; } catch (UnknownHostException ex) { Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex); System.out.println("E9"); return ERROR; } System.out.println("Out DB"); return SUCCESS; }