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.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor.java

protected String getSymbolicName(File file) {
    Manifest mf = JarUtils.getManifest(file);
    if (mf != null) {
        Attributes attrs = mf.getMainAttributes();
        String id = attrs.getValue("Bundle-SymbolicName");
        if (id != null) {
            int p = id.indexOf(';');
            if (p > -1) { // remove properties part if any
                id = id.substring(0, p);
            }/*from   ww  w. j av  a 2s .  c  o  m*/
            return id;
        }
    }
    return null;
}

From source file:org.moe.cli.ParameterParserTest.java

@Test
public void linkLibrary() throws Exception {

    File project = tmpDir.newFolder();
    File outputJar = new File(project, "TestLib.jar");

    // prepare file with ldFlags
    String flags = "-lTestLibrary";
    File ldFlags = new File(project, "ldflags");
    ldFlags.createNewFile();//from   ww  w .j av a 2s  . c om
    PrintWriter write = new PrintWriter(ldFlags);
    write.print(flags);
    write.close();

    ClassLoader cl = this.getClass().getClassLoader();
    URL library = cl.getResource("natives/simulator/libTestLibrary.a");
    URL deviceLibrary = cl.getResource("natives/device/libTestLibrary.a");
    URL headersURL = cl.getResource("natives/Headers/TestFramework.h");

    File headers = new File(headersURL.getPath());
    URL bundle = cl.getResource("moe_logo.png");
    CommandLine argc = parseArgs(new String[] { "--library",
            String.format("%s:%s", library.getPath(), deviceLibrary.getPath()), "--headers",
            headers.getParentFile().getPath(), "--package-name", "org", "--output-file-path",
            outputJar.getPath(), "--ld-flags", ldFlags.getPath(), "--bundle", bundle.getPath() });

    IExecutor executor = ExecutorManager.getExecutorByParams(argc);
    assertNotNull(executor);
    assertTrue(executor instanceof ThirdPartyLibraryLinkExecutor);

    // generate binding & prepare output jar
    executor.execute();

    // check output jar file existence
    assertTrue(outputJar.exists());

    JarFile jarFile = new JarFile(outputJar);
    Manifest manifest = jarFile.getManifest();

    Attributes attributes = manifest.getMainAttributes();
    String manifestLDFlags = attributes.getValue("MOE_CUSTOM_LINKER_FLAGS");
    Set<String> realLDFlags = new HashSet<String>(Arrays.asList(flags.split(";")));
    realLDFlags.add("-ObjC");
    assertEquals(realLDFlags, new HashSet<String>(Arrays.asList(manifestLDFlags.split(";"))));

    String manifestSimFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_simulator");
    assertEquals("./lib/iphonesimulator/libTestLibrary.a", manifestSimFramework);

    String manifestDevFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_device");
    assertEquals("./lib/iphoneos/libTestLibrary.a", manifestDevFramework);

    String manifestBundle = attributes.getValue("MOE_BUNDLE_FILE_RESOURCES");
    assertEquals("./bundle/moe_logo.png;", manifestBundle);

    assertNotNull(jarFile.getEntry("bundle/moe_logo.png"));
    assertNotNull(jarFile.getEntry("lib/iphonesimulator/libTestLibrary.a"));
    assertNotNull(jarFile.getEntry("lib/iphoneos/libTestLibrary.a"));

    jarFile.close();

}

From source file:org.kepler.kar.karxml.KarXmlGenerator.java

/**
 * Read in all attributes for the entry and append them to the xml.
 * //from  w w w  . j a  v a 2 s .  com
 * @param entry
 */
private void appendXmlForEntryAttributes(KAREntry entry) {

    karxml.append(tab + tab + "<karEntryAttributes>" + nl);

    // the name of a KAREntry is not found in it's attributes
    // must get it directly
    String entryName = entry.getName();
    karxml.append(tab + tab + tab + "<Name>" + nl);
    karxml.append(tab + tab + tab + tab + entryName + nl);
    karxml.append(tab + tab + tab + "</Name>" + nl);

    Attributes atts = entry.getAttributes();

    for (Object att : atts.keySet()) {
        // System.out.println( att.toString() );
        if (att instanceof Name) {

            Name attrName = (Name) att;
            String value = atts.getValue(attrName);

            karxml.append(tab + tab + tab + "<" + attrName + ">" + nl);
            karxml.append(tab + tab + tab + tab + value + nl);
            karxml.append(tab + tab + tab + "</" + attrName + ">" + nl);

        }
    }

    karxml.append(tab + tab + "</karEntryAttributes>" + nl);

}

From source file:at.gv.egovernment.moa.id.configuration.config.ConfigurationProvider.java

private String parseVersionFromManifest() {

    try {//from ww w .  j a  v  a2  s .  co m
        Class clazz = ConfigurationProvider.class;
        String className = clazz.getSimpleName() + ".class";
        String classPath = clazz.getResource(className).toString();

        if (classPath.startsWith("jar")) {
            log.info("MOA-ID-Configuration Version can NOT parsed from Manifest. Set blank Version");
            return Constants.DEFAULT_VERSION;

        }

        String manifestPath = classPath.substring(0,
                classPath.lastIndexOf("WEB-INF/classes/") + "WEB-INF/classes/".length())
                + "../../META-INF/MANIFEST.MF";

        Manifest manifest = new Manifest(new URL(manifestPath).openStream());
        ;

        Attributes attributes = manifest.getMainAttributes();
        String version = attributes.getValue("version");

        if (MiscUtil.isNotEmpty(version))
            return version;

        else {
            log.info("MOA-ID-Configuration Version not found in Manifest. Set blank Version");
            return Constants.DEFAULT_VERSION;

        }

    } catch (Throwable e) {
        log.info("MOA-ID Version can NOT parsed from Manifest. Set blank Version");

        return Constants.DEFAULT_VERSION;
    }

}

From source file:org.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor.java

protected void processManifest(FragmentDescriptor fd, String fileName, Manifest mf) {
    Attributes attrs = mf.getMainAttributes();
    String id = attrs.getValue("Bundle-SymbolicName");
    if (id != null) {
        int p = id.indexOf(';');
        if (p > -1) { // remove properties part if any
            id = id.substring(0, p);/*from w w  w.java2  s  .  com*/
        }
        jar2Id.put(fileName, id);
        fd.name = id;
        if (fd.requires != null && !fd.requires.isEmpty()) {
            throw new RuntimeException(
                    "In compatibility mode you must not use <require> tags for OSGi bundles - use Require-Bundle manifest header instead. Bundle: "
                            + fileName);
        }
        // needed to control start-up order (which differs from
        // Require-Bundle)
        String requires = attrs.getValue("Nuxeo-Require");
        if (requires == null) { // if not specific requirement is met use
                                // Require-Bundle
            requires = attrs.getValue("Require-Bundle");
        }
        if (requires != null) {
            String[] ids = StringUtils.split(requires, ',', true);
            fd.requires = new ArrayList<String>(ids.length);
            for (int i = 0; i < ids.length; i++) {
                String rid = ids[i];
                p = rid.indexOf(';');
                if (p > -1) { // remove properties part if any
                    ids[i] = rid.substring(0, p);
                }
                fd.requires.add(ids[i]);
            }
        }

        String requiredBy = attrs.getValue("Nuxeo-RequiredBy");
        if (requiredBy != null) {
            String[] ids = StringUtils.split(requiredBy, ',', true);
            for (int i = 0; i < ids.length; i++) {
                String rid = ids[i];
                p = rid.indexOf(';');
                if (p > -1) { // remove properties part if any
                    ids[i] = rid.substring(0, p);
                }
            }
            fd.requiredBy = ids;
        }

    } else {
        jar2Id.put(fileName, fd.name);
    }
}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

/**
 * From the constructor of {@link JarInputStream}:
 * <p>/*from   ww w . ja  v  a2s .com*/
 * This implementation assumes the META-INF/MANIFEST.MF entry
 * should be either the first or the second entry (when preceded
 * by the dir META-INF/). It skips the META-INF/ and then
 * "consumes" the MANIFEST.MF to initialize the Manifest object.
 * <p>
 * A simple implementation of {@link JarDirectoryStep} would iterate over all entries to be
 * included, adding them to the output jar, while merging manifest files, writing the merged
 * manifest as the last item in the jar. That will generate jars the {@code JarInputStream} won't
 * be able to find the manifest for.
 */
@Test
public void manifestShouldBeSecondEntryInJar() throws IOException {
    Path manifestPath = Paths.get(JarFile.MANIFEST_NAME);

    // Create a directory with a manifest in it and more than two files.
    Path dir = folder.newFolder();
    Manifest dirManifest = new Manifest();
    Attributes attrs = new Attributes();
    attrs.putValue("From-Dir", "cheese");
    dirManifest.getEntries().put("Section", attrs);

    Files.createDirectories(dir.resolve(manifestPath).getParent());
    try (OutputStream out = Files.newOutputStream(dir.resolve(manifestPath))) {
        dirManifest.write(out);
    }
    Files.write(dir.resolve("A.txt"), "hello world".getBytes(UTF_8));
    Files.write(dir.resolve("B.txt"), "hello world".getBytes(UTF_8));
    Files.write(dir.resolve("aa.txt"), "hello world".getBytes(UTF_8));
    Files.write(dir.resolve("bb.txt"), "hello world".getBytes(UTF_8));

    // Create a jar with a manifest and more than two other files.
    Path inputJar = folder.newFile("example.jar");
    try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(inputJar))) {
        byte[] data = "hello world".getBytes(UTF_8);
        ZipEntry entry = new ZipEntry("C.txt");
        zos.putNextEntry(entry);
        zos.write(data, 0, data.length);
        zos.closeEntry();

        entry = new ZipEntry("cc.txt");
        zos.putNextEntry(entry);
        zos.write(data, 0, data.length);
        zos.closeEntry();

        entry = new ZipEntry("META-INF/");
        zos.putNextEntry(entry);
        zos.closeEntry();

        // Note: at end of the stream. Technically invalid.
        entry = new ZipEntry(JarFile.MANIFEST_NAME);
        zos.putNextEntry(entry);
        Manifest zipManifest = new Manifest();
        attrs = new Attributes();
        attrs.putValue("From-Zip", "peas");
        zipManifest.getEntries().put("Section", attrs);
        zipManifest.write(zos);
        zos.closeEntry();
    }

    // Merge and check that the manifest includes everything
    Path output = folder.newFile("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new FakeProjectFilesystem(folder.getRoot()), output,
            ImmutableSortedSet.of(dir, inputJar), null, null);
    int exitCode = step.execute(TestExecutionContext.newInstance()).getExitCode();

    assertEquals(0, exitCode);

    Manifest manifest;
    try (InputStream is = Files.newInputStream(output); JarInputStream jis = new JarInputStream(is)) {
        manifest = jis.getManifest();
    }

    assertNotNull(manifest);
    Attributes readAttributes = manifest.getAttributes("Section");
    assertEquals(2, readAttributes.size());
    assertEquals("cheese", readAttributes.getValue("From-Dir"));
    assertEquals("peas", readAttributes.getValue("From-Zip"));
}

From source file:org.talend.core.ui.metadata.celleditor.ModuleListDialog.java

private void addListeners() {
    innerBtn.addSelectionListener(new SelectionAdapter() {

        @Override/*from   ww w .j av a2 s .c om*/
        public void widgetSelected(SelectionEvent e) {
            checkField(true);
        }

    });
    extBtn.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            checkField(false);
        }

    });
    jarsViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            if (jarsViewer.getList().getSelection().length <= 0) {
                getOKButton().setEnabled(false);
            } else {
                getOKButton().setEnabled(true);
            }
            selecteModuleArray = jarsViewer.getList().getSelection();
        }
    });
    selectField.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            if (selectField.getText().trim().length() <= 0) {
                getOKButton().setEnabled(false);
            } else {
                String version = "0.0.1-SNAPSHOT";

                try {

                    Manifest manifest = new JarFile(selectField.getText()).getManifest();
                    Attributes mainAttribs = manifest.getMainAttributes();

                    if (StringUtils.isNotBlank(mainAttribs.getValue("Bundle-Version"))) {
                        version = mainAttribs.getValue("Bundle-Version");
                    } else if (StringUtils.isNotBlank(mainAttribs.getValue("Implementation-Version"))) {
                        version = mainAttribs.getValue("Implementation-Version");
                    }
                } catch (Exception eee) {

                }

                if (versionLabel != null) {
                    versionLabel.setText(version);
                }

                getOKButton().setEnabled(true);
            }
        }
    });

    addBtn.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            FileDialog dialog = new FileDialog(getShell());
            dialog.setFilterExtensions(new String[] { "*.jar", "*.zip", "*.*", "*" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
            String userDir = System.getProperty("user.dir"); //$NON-NLS-1$
            String pathSeparator = System.getProperty("file.separator"); //$NON-NLS-1$
            dialog.setFilterPath(userDir + pathSeparator + "lib" + pathSeparator + "java"); //$NON-NLS-1$ //$NON-NLS-2$
            String path = dialog.open();
            if (path == null) {
                return;
            }
            if (!jarsList.contains(path)) {
                jarsList.add(path);
                jarsViewer.setInput(jarsList);
            } else {
                MessageDialog.openWarning(getShell(), Messages.getString("ModuleListCellEditor.warningTitle"), //$NON-NLS-1$
                        Messages.getString("ModuleListCellEditor.warningMessage")); //$NON-NLS-1$
            }
            if (jarsList.size() > 0) {
                getOKButton().setEnabled(true);
            } else {
                getOKButton().setEnabled(false);
            }
        }

    });

    delBtn.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            for (Object o : ((StructuredSelection) jarsViewer.getSelection()).toList()) {
                jarsList.remove(o);
            }
            jarsViewer.setInput(jarsList);

            if (jarsList.size() > 0) {
                getOKButton().setEnabled(true);
            } else {
                getOKButton().setEnabled(false);
            }
        }
    });
}

From source file:com.github.lindenb.jvarkit.util.command.Command.java

private void loadManifest() {
    try {/*from ww w. ja  va2 s  . c  o m*/
        Enumeration<URL> resources = getClass().getClassLoader().getResources("META-INF/MANIFEST.MF");//not '/META-INF'
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            InputStream in = url.openStream();
            if (in == null) {
                continue;
            }

            Manifest m = new Manifest(in);
            in.close();
            in = null;
            java.util.jar.Attributes attrs = m.getMainAttributes();
            if (attrs == null) {
                continue;
            }
            String s = attrs.getValue("Git-Hash");
            if (s != null && !s.isEmpty() && !s.contains("$")) //ant failed
            {
                this.gitHash = s;
            }

            s = attrs.getValue("Compile-Date");
            if (s != null && !s.isEmpty()) //ant failed
            {
                this.compileDate = s;
            }
        }
    } catch (Exception err) {

    }

}

From source file:org.eclipse.ecr.testlib.NXRuntimeTestCase.java

protected String readSymbolicName(BundleFile bf) {
    Manifest manifest = bf.getManifest();
    if (manifest == null) {
        return null;
    }//from   w  w w . ja v  a  2  s .  c  o m
    Attributes attrs = manifest.getMainAttributes();
    String name = attrs.getValue("Bundle-SymbolicName");
    if (name == null) {
        return null;
    }
    String[] sp = name.split(";", 2);
    return sp[0];
}

From source file:org.echocat.nodoodle.classloading.FileClassLoader.java

private boolean isSealed(String name, Manifest man) {
    final String path = name.replace('.', '/').concat("/");
    Attributes attr = man.getAttributes(path);
    String sealed = null;/*from www  .ja v  a  2s.c  o m*/
    if (attr != null) {
        sealed = attr.getValue(Name.SEALED);
    }
    if (sealed == null) {
        if ((attr = man.getMainAttributes()) != null) {
            sealed = attr.getValue(Name.SEALED);
        }
    }
    return "true".equalsIgnoreCase(sealed);
}