Example usage for java.util.jar Manifest getMainAttributes

List of usage examples for java.util.jar Manifest getMainAttributes

Introduction

In this page you can find the example usage for java.util.jar Manifest getMainAttributes.

Prototype

public Attributes getMainAttributes() 

Source Link

Document

Returns the main Attributes for the Manifest.

Usage

From source file:de.micromata.genome.jpa.impl.JpaWithExtLibrariesScanner.java

/**
 * A jar may have also declared more deps in manifest (like surefire).
 * /*from ww w.  j  ava  2  s.c  o m*/
 * @param url the url
 * @param collector the collector to use
 */
@SuppressWarnings("deprecation")
private void handleClassManifestClassPath(URL url, ScanResultCollector collector, Matcher<String> urlMatcher) {
    String urls = url.toString();
    URL urltoopen = fixUrlToOpen(url);
    urls = urltoopen.toString();
    if (urls.endsWith(".jar") == false) {
        return;
    }

    try (InputStream is = urltoopen.openStream()) {
        try (JarInputStream jarStream = new JarInputStream(is)) {
            Manifest manifest = jarStream.getManifest();
            if (manifest == null) {
                return;
            }
            Attributes attr = manifest.getMainAttributes();
            String val = attr.getValue("Class-Path");
            if (StringUtils.isBlank(val) == true) {
                return;
            }
            String[] entries = StringUtils.split(val, " \t\n");
            for (String entry : entries) {
                URL surl = new URL(entry);
                visitUrl(surl, collector, urlMatcher);
            }

        }

    } catch (IOException ex) {
        log.warn("JpaScan; Cannot open jar: " + url + ": " + ex.getMessage());
    }

}

From source file:org.moe.cli.executor.AbstractLinkExecutor.java

@Override
public void execute() throws IOException, URISyntaxException, InterruptedException, CheckArchitectureException,
        UnsupportedTypeException {//w  ww  .j  a va2s.c om

    //collect all header files
    List<String> headerList = new ArrayList<String>();
    if (headers != null) {
        for (String header : headers) {
            if (header != null && !header.isEmpty()) {
                File tmp = new File(header);
                if (tmp.isDirectory()) {
                    Collection<File> files = FileUtils.listFiles(tmp, new String[] { "h" }, true);
                    for (File file : files)
                        headerList.add(file.getAbsolutePath());
                } else {
                    headerList.add(header);
                }
            }
        }
    }

    List<String> frameworkList = new ArrayList<String>();
    Set<String> frameworksSearchPaths = new HashSet<String>();
    if (frameworks != null) {

        for (String framework : frameworks) {
            frameworkList.add(framework);
            File frFile = new File(framework);
            frameworksSearchPaths.add(frFile.getParent());
        }

    }

    // Initialize native libraries
    NatJGenNativeLoader.initNatives();

    // Read arguments
    MOEJavaProject project = new MOEJavaProject("", "/");

    boolean generated = true;
    File tmpDir = NatJFileUtils.getNewTempDirectory();
    if (javaSource == null) {

        //generate bindings for all frameworks
        String natJGenBody = NatjGenFrameworkConfig.generate(packageName, frameworksSearchPaths,
                tmpDir.getPath(), headerList);

        //generate bindings
        generated = generate(project, natJGenBody);
    } else {

        Set<URI> links = new HashSet<URI>();
        for (String jsource : javaSource) {
            links.add(new URI(jsource));
        }
        GrabUtils.downloadToFolder(links, tmpDir);
    }

    if (generated) {
        //try to compile generated jars
        File destinationJavacDir = new File(tmpDir, "result");
        destinationJavacDir.mkdir();

        String indePath = System.getenv("MOE_HOME");
        if (indePath != null && !indePath.isEmpty()) {
            String coreJar = indePath + File.separator + "sdk" + File.separator + "moe-core.jar";
            String iosJar = indePath + File.separator + "sdk" + File.separator + "moe-ios.jar";

            String compileList = createCompileFileList(tmpDir, javaSource != null ? null : packageName);

            String classPathArg = String.format("%s:%s", coreJar, iosJar);
            ProcessBuilder processBuilder = new ProcessBuilder("javac", "@" + compileList, "-cp", classPathArg,
                    "-d", destinationJavacDir.getPath());
            Process process = processBuilder.start();
            process.waitFor();

            if (process.exitValue() == 0 || headerList.size() == 0) {
                //try to create lib subdirectory
                File libTemp = new File(destinationJavacDir, "lib");
                if (!(libTemp.mkdir())) {
                    throw new IOException("Could not create temp directory: " + libTemp.getAbsolutePath());
                }

                //try to create bundle subdirectory
                File bundleTemp = new File(destinationJavacDir, "bundle");
                if (!(bundleTemp.mkdir())) {
                    throw new IOException("Could not create temp directory: " + bundleTemp.getAbsolutePath());
                }

                copyLibrary(libTemp, frameworkList);

                if (bundle != null) {
                    copyBundle(bundleTemp, bundle);
                }

                Map<String, String> flags = getManifestProperties(frameworkList);

                //create manifest file
                Manifest manifest = new Manifest();
                manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

                //Logic from CocoaPods; for more information visit https://github.com/CocoaPods/CocoaPods/issues/3537
                String moe_type = flags.get(MOE_TYPE);
                if (moe_type != null && moe_type.contains("static")) {
                    if (ldFlags != null && !ldFlags.isEmpty()) {
                        if (ldFlags.endsWith(";"))
                            ldFlags += "-ObjC;";
                        else
                            ldFlags += ";-ObjC;";
                    } else {
                        ldFlags = "-ObjC;";
                    }
                }

                if (ldFlags != null && !ldFlags.isEmpty()) {
                    flags.put("MOE_CUSTOM_LINKER_FLAGS", ldFlags);
                }

                for (Map.Entry<String, String> entry : flags.entrySet()) {
                    manifest.getMainAttributes().put(new Attributes.Name(entry.getKey()), entry.getValue());
                }

                //try to create manifest subdirectory
                File manifestTemp = new File(destinationJavacDir, "META-INF");
                if (!(manifestTemp.mkdir())) {
                    throw new IOException("Could not create temp directory: " + bundleTemp.getAbsolutePath());
                }

                String manifestFileName = "MANIFEST.MF";
                File manifestFile = new File(manifestTemp, manifestFileName);
                FileOutputStream manOut = new FileOutputStream(manifestFile);
                manifest.write(manOut);
                manOut.close();

                //try to pack custom content into jar
                File jarFile = new File(outFile);

                FileOutputStream jarFos = null;
                JarArchiveOutputStream target = null;
                try {
                    jarFos = new FileOutputStream(jarFile);
                    target = new JarArchiveOutputStream(jarFos);

                    for (File file : destinationJavacDir.listFiles()) {
                        ArchiveUtils.addFileToJar(destinationJavacDir, file, target);
                    }
                    target.close();

                } finally {
                    if (jarFos != null) {
                        jarFos.close();
                    }

                    if (target != null) {
                        target.close();
                    }
                }
            } else {
                throw new IOException("An error occured during process of bindings compilation");
            }
        } else {
            throw new IOException("Could not find system variable - MOE_HOME");
        }
    } else {
        throw new IOException("An error occured during process of bindings generation");
    }

}

From source file:org.nuxeo.runtime.reload.ReloadComponent.java

@Override
public String getOSGIBundleName(File file) {
    Manifest mf = JarUtils.getManifest(file);
    if (mf == null) {
        return null;
    }/*from w  ww  .  jav a  2s .  c  om*/
    String bundleName = mf.getMainAttributes().getValue("Bundle-SymbolicName");
    if (bundleName == null) {
        return null;
    }
    int index = bundleName.indexOf(';');
    if (index > -1) {
        bundleName = bundleName.substring(0, index);
    }
    return bundleName;
}

From source file:org.rhq.plugins.jbossas.util.FileContentDelegate.java

/**
 * Retrieves the SHA256 for a deployed application.
 * 1) If the app is exploded then return RHQ-Sha256 manifest attribute.
 *   1.1) If RHQ-Sha256 is missing then compute it, save it and return the result.
 * 2) If the app is an archive then compute SHA256 on fly and return it.
 *
 * @param deploymentFile deployment file
 * @return/*ww w  . j  av  a 2  s. c  o m*/
 */
public String getSHA(File deploymentFile) {
    String sha = null;
    try {
        if (deploymentFile.isDirectory()) {
            File manifestFile = new File(deploymentFile.getAbsolutePath(), MANIFEST_RELATIVE_PATH);
            if (manifestFile.exists()) {
                InputStream manifestStream = new FileInputStream(manifestFile);
                Manifest manifest = null;
                try {
                    manifest = new Manifest(manifestStream);
                    sha = manifest.getMainAttributes().getValue(RHQ_SHA_256);
                } finally {
                    manifestStream.close();
                }
            }

            if (sha == null || sha.trim().isEmpty()) {
                sha = computeAndSaveSHA(deploymentFile);
            }
        } else {
            sha = new MessageDigestGenerator(MessageDigestGenerator.SHA_256).calcDigestString(deploymentFile);
        }
    } catch (IOException ex) {
        throw new RuntimeException("Problem calculating digest of package [" + deploymentFile.getPath() + "].",
                ex);
    }

    return sha;
}

From source file:org.apache.struts2.osgi.BaseOsgiHost.java

/**
 * Gets the version used to export the packages. it tries to get it from MANIFEST.MF, or the file name
 *///  www  .  j a v  a  2  s  .  co  m
protected String getVersion(URL url) {
    if ("jar".equals(url.getProtocol())) {
        try {
            JarFile jarFile = new JarFile(new File(URLUtil.normalizeToFileProtocol(url).toURI()));
            Manifest manifest = jarFile.getManifest();
            if (manifest != null) {
                String version = manifest.getMainAttributes().getValue("Bundle-Version");
                if (StringUtils.isNotBlank(version)) {
                    return getVersionFromString(version);
                }
            } else {
                //try to get the version from the file name
                return getVersionFromString(jarFile.getName());
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled())
                LOG.error("Unable to extract version from [#0], defaulting to '1.0.0'", url.toExternalForm());

        }
    }

    return "1.0.0";
}

From source file:org.apache.brooklyn.util.core.ClassLoaderUtilsTest.java

@Test
public void testLoadClassInOsgiWhiteListWithInvalidBundlePresent() throws Exception {
    String bundlePath = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH;
    String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
    String classname = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_SIMPLE_ENTITY;

    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), bundlePath);

    mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build();
    Bundle bundle = installBundle(mgmt, bundleUrl);

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    JarOutputStream target = new JarOutputStream(buffer, manifest);
    target.close();//from  w w  w  .  j av a2s .  c  om

    OsgiManager osgiManager = ((ManagementContextInternal) mgmt).getOsgiManager().get();
    Framework framework = osgiManager.getFramework();
    Bundle installedBundle = framework.getBundleContext().installBundle("stream://invalid",
            new ByteArrayInputStream(buffer.toByteArray()));
    assertNotNull(installedBundle);

    Class<?> clazz = bundle.loadClass(classname);
    Entity entity = createSimpleEntity(bundleUrl, clazz);

    String whileList = bundle.getSymbolicName() + ":" + bundle.getVersion();
    System.setProperty(ClassLoaderUtils.WHITE_LIST_KEY, whileList);

    ClassLoaderUtils cluMgmt = new ClassLoaderUtils(getClass(), mgmt);
    ClassLoaderUtils cluClass = new ClassLoaderUtils(clazz);
    ClassLoaderUtils cluEntity = new ClassLoaderUtils(getClass(), entity);

    assertLoadSucceeds(classname, clazz, cluMgmt, cluClass, cluEntity);
    assertLoadSucceeds(bundle.getSymbolicName() + ":" + classname, clazz, cluMgmt, cluClass, cluEntity);
}

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. jav a2s  .  co  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());
}

From source file:org.eclipse.jubula.autagent.commands.AbstractStartJavaAut.java

/**
 * @param attributeName the attribute name in the manifest
 * @param jarFile the path and name of the jar file to examine
 * @return the String value of the specified attribute name, or null if
 *         not found.//  w w  w. j a  va 2  s .  c o  m
 */
protected String getAttributeFromManifest(String attributeName, String jarFile) {

    if (jarFile == null || jarFile.length() < 1) {
        return null;
    }
    String attribute = null;
    try (JarFile jar = new JarFile(jarFile)) {
        Manifest manifest = jar.getManifest();
        if (manifest != null) {
            attribute = manifest.getMainAttributes().getValue(attributeName);
        }
    } catch (FileNotFoundException e) {
        LOG.error("File not found: " + jarFile, e); //$NON-NLS-1$
    } catch (IOException e) {
        LOG.error("Error reading jar file: " + jarFile, e); //$NON-NLS-1$
    }
    return attribute;
}

From source file:org.eclipse.gemini.blueprint.test.FilteringProbeBuilder.java

private void appendManifest(TinyBundle bundle) throws IOException {

    DefaultResourceLoader loader = new DefaultResourceLoader();
    Manifest manifest = new Manifest(loader.getResource(manifestLocation).getInputStream());
    Attributes attr = manifest.getMainAttributes();
    for (Object key : attr.keySet()) {
        String k = key.toString();
        String v = attr.getValue(k);

        // append optional import for org.ops4j.pax.exam
        if (k.equalsIgnoreCase(Constants.IMPORT_PACKAGE)) {
            if (StringUtils.hasText(v)) {
                v = v + ",";
            }/*from   ww w. java 2  s  .  c om*/
        }
        v = v + "org.ops4j.pax.exam;resolution:=optional";
        bundle.set(k, v);
    }
}

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

public void loadMapPack(File mapPackFile, MapSourcesManager mapSourcesManager)
        throws CertificateException, IOException, MapSourceCreateException {
    // testMapPack(mapPackFile);
    URLClassLoader urlCl;/*from www  .  j a v  a  2 s .  c  om*/
    URL url = mapPackFile.toURI().toURL();
    urlCl = new MapPackClassLoader(url, ClassLoader.getSystemClassLoader());
    InputStream manifestIn = urlCl.getResourceAsStream("META-INF/MANIFEST.MF");
    String rev = null;
    if (manifestIn != null) {
        Manifest mf = new Manifest(manifestIn);
        rev = mf.getMainAttributes().getValue("MapPackRevision");
        manifestIn.close();
        if (rev != null) {
            if ("exported".equals(rev)) {
                rev = ProgramInfo.getRevisionStr();
            } else {
                rev = Integer.toString(Utilities.parseSVNRevision(rev));
            }
        }
        mf = null;
    }
    MapSourceLoaderInfo loaderInfo = new MapSourceLoaderInfo(LoaderType.MAPPACK, mapPackFile, rev);
    final Iterator<MapSource> iterator = ServiceLoader.load(MapSource.class, urlCl).iterator();

    while (iterator.hasNext()) {
        try {
            MapSource ms = iterator.next();
            ms.setLoaderInfo(loaderInfo);
            mapSourcesManager.addMapSource(ms);
            log.trace("Loaded map source: " + ms.toString() + " (name: " + ms.getName() + ")");
        } catch (Error e) {
            urlCl = null;
            throw new MapSourceCreateException("Failed to load a map sources from map pack: "
                    + mapPackFile.getName() + " " + e.getMessage(), e);
        }
    }
}