Example usage for java.util.jar Attributes getValue

List of usage examples for java.util.jar Attributes getValue

Introduction

In this page you can find the example usage for java.util.jar Attributes getValue.

Prototype

public String getValue(Name name) 

Source Link

Document

Returns the value of the specified Attributes.Name, or null if the attribute was not found.

Usage

From source file:org.openhab.tools.analysis.checkstyle.ServiceComponentManifestCheck.java

private void verifyManifest(FileText fileText) {
    File file = fileText.getFile();

    manifestPath = file.getPath();/*  w  w  w . j a  va  2s  .  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:org.jahia.loganalyzer.internal.JahiaLogAnalyzerImpl.java

@Override
public void retrieveBuildInformation() {
    try {/*from w  w  w. ja v  a2  s  .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.eclipse.virgo.kernel.artifact.bundle.BundleBridgeTests.java

@Test
public void testBuildDictionary() throws ArtifactGenerationException, IOException {
    File testFile = new File(System.getProperty("user.home")
            + "/virgo-build-cache/ivy-cache/repository/org.eclipse.virgo.mirrored/javax.servlet/3.0.0.v201112011016/javax.servlet-3.0.0.v201112011016.jar");

    ArtifactDescriptor inputArtefact = BUNDLE_BRIDGE.generateArtifactDescriptor(testFile);

    Dictionary<String, String> dictionary = BundleBridge.convertToDictionary(inputArtefact);

    JarFile testJar = new JarFile(testFile);
    Attributes attributes = testJar.getManifest().getMainAttributes();

    testJar.close();//ww w  . ja v a2s . c om

    assertEquals("Failed to match regenerated " + Constants.BUNDLE_SYMBOLICNAME,
            dictionary.get(Constants.BUNDLE_SYMBOLICNAME), attributes.getValue(Constants.BUNDLE_SYMBOLICNAME));
    assertEquals("Failed to match regenerated " + Constants.BUNDLE_VERSION,
            dictionary.get(Constants.BUNDLE_VERSION), attributes.getValue(Constants.BUNDLE_VERSION));
    assertEquals("Failed to match regenerated " + BUNDLE_MANIFEST_VERSION_HEADER_NAME,
            dictionary.get(BUNDLE_MANIFEST_VERSION_HEADER_NAME),
            attributes.getValue(BUNDLE_MANIFEST_VERSION_HEADER_NAME));
    assertEquals("Failed to match regenerated " + BUNDLE_NAME_HEADER_NAME,
            dictionary.get(BUNDLE_NAME_HEADER_NAME), attributes.getValue(BUNDLE_NAME_HEADER_NAME));

}

From source file:eu.chocolatejar.eclipse.plugin.cleaner.ArtifactParser.java

/**
 * Create an artifact for the jar based on jarsManifest
 * /*from w  w  w .ja  va2s.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:org.hyperic.hq.plugin.jboss.JBossDetector.java

public static String getVersion(File installPath, String jar) {
    File file = new File(installPath, "lib" + File.separator + jar);

    if (!file.exists()) {
        log.debug("[getVersion] file '" + file + "' not found");
        return null;
    }//from   w ww  .j  a  va 2 s  .  c o m

    Attributes attributes;
    try {
        JarFile jarFile = new JarFile(file);
        log.debug("[getVersion] jarFile='" + jarFile.getName() + "'");
        attributes = jarFile.getManifest().getMainAttributes();
        jarFile.close();
    } catch (IOException e) {
        log.debug(e, e);
        return null;
    }

    //e.g. Implementation-Version:
    //3.0.6 Date:200301260037
    //3.2.1 (build: CVSTag=JBoss_3_2_1 date=200306201521)
    //3.2.2 (build: CVSTag=JBoss_3_2_2 date=200310182216)
    //3.2.3 (build: CVSTag=JBoss_3_2_3 date=200311301445)
    //4.0.0DR2 (build: CVSTag=JBoss_4_0_0_DR2 date=200307030107)
    //5.0.1.GA (build: SVNTag=JBoss_5_0_1_GA date=200902231221)
    String version = attributes.getValue("Implementation-Version");
    log.debug("[getVersion] version='" + version + "'");

    if (version == null) {
        return null;
    }
    if (version.length() < 3) {
        return null;
    }

    if (!(Character.isDigit(version.charAt(0)) && (version.charAt(1) == '.')
            && Character.isDigit(version.charAt(2)))) {
        return null;
    }

    return version;
}

From source file:generate.MapGenerateAction.java

@Override
public String execute() {

    String file_path = "/home/chanakya/NetBeansProjects/Concepto/UploadedFiles";
    try {/*  w  w  w. j a  va2  s  .  c  o 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;
}

From source file:org.pentaho.reporting.libraries.base.versioning.VersionHelper.java

/**
 * Looks up a single value in the given attribute collection using the given key. If the key is not contained in the
 * attributes, this method returns the default value specified as parameter.
 *
 * @param attrs        the attributes where to lookup the key.
 * @param name         the name of the key to use for the lookup.
 * @param defaultValue the default value to return in case the attributes contain no such key.
 * @return the value from the attributes or the default values.
 *//*from   www.  j  a v a 2  s.  com*/
private String getValue(final Attributes attrs, final String name, final String defaultValue) {
    final String value = attrs.getValue(name);
    if (value == null) {
        return defaultValue;
    }
    return value.trim();
}

From source file:mobac.mapsources.loader.MapPackManager.java

public int getMapPackRevision(File mapPackFile) throws ZipException, IOException {
    ZipFile zip = new ZipFile(mapPackFile);
    try {//from   w  ww.  j av a 2s . co  m
        ZipEntry entry = zip.getEntry("META-INF/MANIFEST.MF");
        if (entry == null)
            throw new ZipException("Unable to find MANIFEST.MF");
        Manifest mf = new Manifest(zip.getInputStream(entry));
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackRevision").trim();
        return Utilities.parseSVNRevision(mpv);
    } catch (NumberFormatException e) {
        return -1;
    } finally {
        zip.close();
    }
}

From source file:org.hyperic.hq.plugin.tomcat.TomcatServerDetector.java

private boolean isCorrectVersion(String versionJar) {
    boolean correctVersion = false;
    try {/*from   w w  w  .  j  ava 2s .com*/
        JarFile jarFile = new JarFile(versionJar);
        log.debug("[isInstallTypeVersion] versionJar='" + jarFile.getName() + "'");
        Attributes attributes = jarFile.getManifest().getMainAttributes();
        jarFile.close();
        String tomcatVersion = attributes.getValue("Specification-Version");
        String expectedVersion = getTypeProperty("tomcatVersion");
        if (expectedVersion == null) {
            expectedVersion = getTypeInfo().getVersion();
        }
        log.debug("[isInstallTypeVersion] tomcatVersion='" + tomcatVersion + "' (" + expectedVersion + ")");
        correctVersion = tomcatVersion.equals(expectedVersion);
    } catch (IOException e) {
        log.debug("Error getting Tomcat version (" + e + ")", e);
    }
    return correctVersion;
}

From source file:be.iminds.aiolos.ui.DemoServlet.java

private void getRepositoryBundles(PrintWriter writer) {
    JSONArray components = new JSONArray();

    Repository[] repos = new Repository[] {};
    repos = repositoryTracker.getServices(repos);
    for (Repository repo : repos) {
        try {//from   w w w .  j a v  a  2s .c  o m
            CapabilityRequirementImpl requirement = new CapabilityRequirementImpl("osgi.identity", null);
            requirement.addDirective("filter", String.format("(%s=%s)", "osgi.identity", "*"));

            Map<Requirement, Collection<Capability>> result = repo
                    .findProviders(Collections.singleton(requirement));

            for (Capability c : result.values().iterator().next()) {
                String type = (String) c.getAttributes().get("type");
                if (type != null && type.equals("osgi.bundle")) {
                    String componentId = (String) c.getAttributes().get("osgi.identity");
                    String version = c.getAttributes().get("version").toString();
                    String name = null;
                    String description = null;
                    try {
                        RepositoryContent content = (RepositoryContent) c.getResource();
                        JarInputStream jar = new JarInputStream(content.getContent());
                        Manifest mf = jar.getManifest();
                        Attributes attr = mf.getMainAttributes();
                        name = attr.getValue("Bundle-Name");
                        description = attr.getValue("Bundle-Description");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    JSONObject component = new JSONObject();
                    component.put("componentId", componentId);
                    component.put("version", version);
                    component.put("name", name);
                    component.put("description", description);
                    components.add(component);
                }
            }
        } catch (Exception e) {
        }
    }

    writer.write(components.toJSONString());
}