Search in sources :

Example 1 with CapabilityBuilder

use of aQute.bnd.osgi.resource.CapabilityBuilder in project bnd by bndtools.

the class P2Indexer method readRepository.

private Repository readRepository() throws Exception {
    P2Impl p2 = new P2Impl(client, this.url, Processor.getExecutor());
    List<Artifact> artifacts = p2.getArtifacts();
    List<Promise<Resource>> fetched = new ArrayList<>(artifacts.size());
    Set<URI> visitedURIs = new HashSet<>(artifacts.size());
    Set<ArtifactID> visitedArtifacts = new HashSet<>(artifacts.size());
    Map<ArtifactID, Resource> knownResources = new HashMap<>();
    if (getBridge() != null) {
        for (Capability capability : getBridge().getRepository().findProviders(singleton(MD5_REQUIREMENT)).get(MD5_REQUIREMENT)) {
            Resource resource = capability.getResource();
            IdentityCapability identity = ResourceUtils.getIdentityCapability(resource);
            ArtifactID artifact = new ArtifactID(identity.osgi_identity(), identity.version(), (String) capability.getAttributes().get(MD5_ATTRIBUTE));
            knownResources.put(artifact, resource);
        }
    }
    for (final Artifact a : artifacts) {
        if (!visitedURIs.add(a.uri))
            continue;
        if (a.md5 != null) {
            ArtifactID id = new ArtifactID(a.id, toVersion(a.version), a.md5);
            if (!visitedArtifacts.add(id))
                continue;
            if (knownResources.containsKey(id)) {
                fetched.add(Promises.resolved(knownResources.get(id)));
                continue;
            }
        }
        Promise<Resource> promise = client.build().useCache(MAX_STALE).async(a.uri.toURL()).map(new Function<File, Resource>() {

            @Override
            public Resource apply(File file) {
                try {
                    ResourceBuilder rb = new ResourceBuilder();
                    rb.addFile(file, a.uri);
                    if (a.md5 != null)
                        rb.addCapability(new CapabilityBuilder(P2_CAPABILITY_NAMESPACE).addAttribute(MD5_ATTRIBUTE, a.md5));
                    return rb.build();
                } catch (Exception e) {
                    logger.debug("{}: Failed to create resource for %s from {}", name, a, file, e);
                    return RECOVERY;
                }
            }
        }).recover(new Function<Promise<?>, Resource>() {

            @Override
            public Resource apply(Promise<?> failed) {
                try {
                    logger.debug("{}: Failed to create resource for {}", name, a, failed.getFailure());
                } catch (InterruptedException e) {
                // impossible
                }
                return RECOVERY;
            }
        });
        fetched.add(promise);
    }
    Promise<List<Resource>> all = Promises.all(fetched);
    return all.map(new Function<List<Resource>, ResourcesRepository>() {

        @Override
        public ResourcesRepository apply(List<Resource> resources) {
            ResourcesRepository rr = new ResourcesRepository();
            for (Resource resource : resources) {
                if (resource != RECOVERY) {
                    rr.add(resource);
                }
            }
            return rr;
        }
    }).getValue();
}
Also used : P2Impl(aQute.p2.provider.P2Impl) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CapabilityBuilder(aQute.bnd.osgi.resource.CapabilityBuilder) URI(java.net.URI) Function(org.osgi.util.function.Function) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) ResourceBuilder(aQute.bnd.osgi.resource.ResourceBuilder) Capability(org.osgi.resource.Capability) ContentCapability(aQute.bnd.osgi.resource.ResourceUtils.ContentCapability) IdentityCapability(aQute.bnd.osgi.resource.ResourceUtils.IdentityCapability) Resource(org.osgi.resource.Resource) Artifact(aQute.p2.api.Artifact) IdentityCapability(aQute.bnd.osgi.resource.ResourceUtils.IdentityCapability) IOException(java.io.IOException) DownloadListenerPromise(aQute.bnd.util.repository.DownloadListenerPromise) Promise(org.osgi.util.promise.Promise) File(java.io.File) ResourcesRepository(aQute.bnd.osgi.repository.ResourcesRepository)

Example 2 with CapabilityBuilder

use of aQute.bnd.osgi.resource.CapabilityBuilder in project bnd by bndtools.

the class IndexerMojo method execute.

public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {
        logger.debug("skip project as configured");
        return;
    }
    if (scopes == null || scopes.isEmpty()) {
        scopes = Arrays.asList("compile", "runtime");
    }
    logger.debug("Indexing dependencies with scopes: {}", scopes);
    logger.debug("Including Transitive dependencies: {}", includeTransitive);
    logger.debug("Local file URLs permitted: {}", localURLs);
    logger.debug("Adding mvn: URLs as alternative content: {}", addMvnURLs);
    DependencyResolver dependencyResolver = new DependencyResolver(project, session, resolver, system, scopes, includeTransitive, new RemotePostProcessor(session, system, metadataReader, localURLs));
    Map<File, ArtifactResult> dependencies = dependencyResolver.resolve();
    Map<String, ArtifactRepository> repositories = new HashMap<>();
    for (ArtifactRepository artifactRepository : project.getRemoteArtifactRepositories()) {
        logger.debug("Located an artifact repository {}", artifactRepository.getId());
        repositories.put(artifactRepository.getId(), artifactRepository);
    }
    ArtifactRepository deploymentRepo = project.getDistributionManagementArtifactRepository();
    if (deploymentRepo != null) {
        logger.debug("Located a deployment repository {}", deploymentRepo.getId());
        if (repositories.get(deploymentRepo.getId()) == null) {
            repositories.put(deploymentRepo.getId(), deploymentRepo);
        } else {
            logger.info("The configured deployment repository {} has the same id as one of the remote artifact repositories. It is assumed that these repositories are the same.", deploymentRepo.getId());
        }
    }
    RepositoryURLResolver repositoryURLResolver = new RepositoryURLResolver(repositories);
    MavenURLResolver mavenURLResolver = new MavenURLResolver();
    ResourcesRepository resourcesRepository = new ResourcesRepository();
    XMLResourceGenerator xmlResourceGenerator = new XMLResourceGenerator();
    logger.debug("Indexing artifacts: {}", dependencies.keySet());
    try {
        IO.mkdirs(outputFile.getParentFile());
        for (Entry<File, ArtifactResult> entry : dependencies.entrySet()) {
            File file = entry.getKey();
            ResourceBuilder resourceBuilder = new ResourceBuilder();
            resourceBuilder.addFile(entry.getKey(), repositoryURLResolver.resolver(file, entry.getValue()));
            if (addMvnURLs) {
                CapabilityBuilder c = new CapabilityBuilder(ContentNamespace.CONTENT_NAMESPACE);
                c.addAttribute(ContentNamespace.CONTENT_NAMESPACE, SHA256.digest(file).asHex());
                c.addAttribute(ContentNamespace.CAPABILITY_URL_ATTRIBUTE, mavenURLResolver.resolver(file, entry.getValue()));
                c.addAttribute(ContentNamespace.CAPABILITY_SIZE_ATTRIBUTE, file.length());
                c.addAttribute(ContentNamespace.CAPABILITY_MIME_ATTRIBUTE, MavenURLResolver.MIME);
                resourceBuilder.addCapability(c);
            }
            resourcesRepository.add(resourceBuilder.build());
        }
        if (includeJar && project.getPackaging().equals("jar")) {
            File current = new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".jar");
            if (current.exists()) {
                ResourceBuilder resourceBuilder = new ResourceBuilder();
                resourceBuilder.addFile(current, current.toURI());
                resourcesRepository.add(resourceBuilder.build());
            }
        }
        xmlResourceGenerator.repository(resourcesRepository).save(outputFile);
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
    if (fail) {
        throw new MojoExecutionException("One or more URI lookups failed");
    }
    attach(outputFile, "osgi-index", "xml");
    if (includeGzip) {
        File gzipOutputFile = new File(outputFile.getPath() + ".gz");
        try {
            xmlResourceGenerator.save(gzipOutputFile);
        } catch (Exception e) {
            throw new MojoExecutionException("Unable to create the gzipped output file");
        }
        attach(gzipOutputFile, "osgi-index", "xml.gz");
    }
}
Also used : RemotePostProcessor(aQute.bnd.maven.lib.resolve.RemotePostProcessor) ResourceBuilder(aQute.bnd.osgi.resource.ResourceBuilder) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) HashMap(java.util.HashMap) ArtifactRepository(org.apache.maven.artifact.repository.ArtifactRepository) CapabilityBuilder(aQute.bnd.osgi.resource.CapabilityBuilder) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) FileNotFoundException(java.io.FileNotFoundException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) DependencyResolver(aQute.bnd.maven.lib.resolve.DependencyResolver) ArtifactResult(org.eclipse.aether.resolution.ArtifactResult) XMLResourceGenerator(aQute.bnd.osgi.repository.XMLResourceGenerator) File(java.io.File) ResourcesRepository(aQute.bnd.osgi.repository.ResourcesRepository)

Example 3 with CapabilityBuilder

use of aQute.bnd.osgi.resource.CapabilityBuilder in project bnd by bndtools.

the class RemoteCommand method _distro.

public void _distro(DistroOptions opts) throws Exception {
    List<String> args = opts._arguments();
    String bsn;
    String version;
    bsn = args.remove(0);
    if (!Verifier.isBsn(bsn)) {
        error("Not a bundle symbolic name %s", bsn);
    }
    if (args.isEmpty())
        version = "0";
    else {
        version = args.remove(0);
        if (!Version.isVersion(version)) {
            error("Invalid version %s", version);
        }
    }
    File output = getFile(opts.output("distro.jar"));
    if (output.getParentFile() == null || !output.getParentFile().isDirectory()) {
        error("Cannot write to %s because parent not a directory", output);
    }
    if (output.isFile() && !output.canWrite()) {
        error("Cannot write to %s", output);
    }
    logger.debug("Starting distro {};{}", bsn, version);
    List<BundleRevisionDTO> bundleRevisons = agent.getBundleRevisons();
    logger.debug("Found {} bundle revisions", bundleRevisons.size());
    Parameters packages = new Parameters();
    List<Parameters> provided = new ArrayList<>();
    for (BundleRevisionDTO brd : bundleRevisons) {
        for (CapabilityDTO c : brd.capabilities) {
            CapabilityBuilder cb = new CapabilityBuilder(c.namespace);
            for (Entry<String, Object> e : c.attributes.entrySet()) {
                String key = e.getKey();
                Object value = e.getValue();
                if (key.equals("version")) {
                    if (value instanceof Collection || value.getClass().isArray())
                        value = Converter.cnv(tref, value);
                    else
                        value = new Version((String) value);
                }
                cb.addAttribute(key, value);
            }
            cb.addDirectives(c.directives);
            Attrs attrs = cb.toAttrs();
            if (cb.isPackage()) {
                attrs.remove(Constants.BUNDLE_SYMBOLIC_NAME_ATTRIBUTE);
                attrs.remove(Constants.BUNDLE_VERSION_ATTRIBUTE);
                String pname = attrs.remove(PackageNamespace.PACKAGE_NAMESPACE);
                if (pname == null) {
                    warning("Invalid package capability found %s", c);
                } else
                    packages.put(pname, attrs);
                logger.debug("P: {};{}", pname, attrs);
            } else if (NativeNamespace.NATIVE_NAMESPACE.equals(c.namespace)) {
                Attrs newAttrs = new Attrs();
                for (Entry<String, String> entry : attrs.entrySet()) {
                    if (entry.getKey().startsWith(NativeNamespace.NATIVE_NAMESPACE)) {
                        newAttrs.put(entry.getKey(), entry.getValue());
                    }
                }
                Parameters p = new Parameters();
                p.put(c.namespace, newAttrs);
                provided.add(p);
            } else if (!IGNORED_NAMESPACES.contains(c.namespace)) {
                logger.debug("C {};{}", c.namespace, attrs);
                Parameters p = new Parameters();
                p.put(c.namespace, attrs);
                provided.add(p);
            }
        }
    }
    if (isOk()) {
        Manifest m = new Manifest();
        Attributes main = m.getMainAttributes();
        main.putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
        main.putValue(Constants.BUNDLE_SYMBOLICNAME, bsn);
        main.putValue(Constants.BUNDLE_VERSION, version);
        main.putValue(Constants.EXPORT_PACKAGE, packages.toString());
        // Make distro unresolvable
        Parameters unresolveable = new Parameters("osgi.unresolvable; filter:='(&(must.not.resolve=*)(!(must.not.resolve=*)))'");
        main.putValue(Constants.REQUIRE_CAPABILITY, unresolveable.toString());
        provided.add(new Parameters("osgi.unresolvable"));
        StringBuilder sb = new StringBuilder();
        for (Parameters parameter : provided) {
            sb.append(parameter.toString());
            sb.append(",");
        }
        String capabilities = sb.toString().substring(0, sb.length() - 1);
        main.putValue(Constants.PROVIDE_CAPABILITY, capabilities);
        if (opts.description() != null)
            main.putValue(Constants.BUNDLE_DESCRIPTION, opts.description());
        if (opts.license() != null)
            main.putValue(Constants.BUNDLE_LICENSE, opts.license());
        if (opts.copyright() != null)
            main.putValue(Constants.BUNDLE_COPYRIGHT, opts.copyright());
        if (opts.vendor() != null)
            main.putValue(Constants.BUNDLE_VENDOR, opts.vendor());
        Jar jar = new Jar("distro");
        jar.setManifest(m);
        Verifier v = new Verifier(jar);
        v.setProperty(Constants.FIXUPMESSAGES, "osgi.* namespace must not be specified with generic capabilities");
        v.verify();
        v.getErrors();
        if (isFailOk() || v.isOk()) {
            jar.updateModified(System.currentTimeMillis(), "Writing distro jar");
            jar.write(output);
        } else
            getInfo(v);
    }
}
Also used : Parameters(aQute.bnd.header.Parameters) BundleRevisionDTO(org.osgi.framework.wiring.dto.BundleRevisionDTO) ArrayList(java.util.ArrayList) Attrs(aQute.bnd.header.Attrs) Attributes(java.util.jar.Attributes) CapabilityBuilder(aQute.bnd.osgi.resource.CapabilityBuilder) Manifest(java.util.jar.Manifest) Verifier(aQute.bnd.osgi.Verifier) Entry(java.util.Map.Entry) CapabilityDTO(org.osgi.resource.dto.CapabilityDTO) Version(aQute.bnd.version.Version) Collection(java.util.Collection) Jar(aQute.bnd.osgi.Jar) File(java.io.File)

Example 4 with CapabilityBuilder

use of aQute.bnd.osgi.resource.CapabilityBuilder in project bnd by bndtools.

the class Traverser method addReserveIdentity.

private void addReserveIdentity(ResourceBuilder rb, String bsn, Version version) {
    try {
        CapabilityBuilder c = new CapabilityBuilder(IDENTITY_NAMESPACE);
        c.addAttribute(IDENTITY_NAMESPACE, bsn);
        c.addAttribute(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE, version);
        c.addAttribute(CAPABILITY_TYPE_ATTRIBUTE, "application/java-archive");
        rb.addCapability(c);
    } catch (Exception ee) {
        ee.printStackTrace();
    }
}
Also used : CapabilityBuilder(aQute.bnd.osgi.resource.CapabilityBuilder)

Example 5 with CapabilityBuilder

use of aQute.bnd.osgi.resource.CapabilityBuilder in project bnd by bndtools.

the class CapReqFilterTest method testReqNoFilterCapWithAttr.

public void testReqNoFilterCapWithAttr() throws Exception {
    Capability cap = new CapabilityBuilder("foobar").addAttribute("blah", "baz").addAttribute("version", "42").buildSyntheticCapability();
    Requirement req = new RequirementBuilder("foobar").buildSyntheticRequirement();
    assertTrue(ResourceUtils.matches(req, cap));
}
Also used : Requirement(org.osgi.resource.Requirement) Capability(org.osgi.resource.Capability) CapabilityBuilder(aQute.bnd.osgi.resource.CapabilityBuilder) RequirementBuilder(aQute.bnd.osgi.resource.RequirementBuilder)

Aggregations

CapabilityBuilder (aQute.bnd.osgi.resource.CapabilityBuilder)12 Capability (org.osgi.resource.Capability)8 RequirementBuilder (aQute.bnd.osgi.resource.RequirementBuilder)5 Requirement (org.osgi.resource.Requirement)5 File (java.io.File)4 ResourcesRepository (aQute.bnd.osgi.repository.ResourcesRepository)2 ResourceBuilder (aQute.bnd.osgi.resource.ResourceBuilder)2 URI (java.net.URI)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 Project (aQute.bnd.build.Project)1 Attrs (aQute.bnd.header.Attrs)1 Parameters (aQute.bnd.header.Parameters)1 DependencyResolver (aQute.bnd.maven.lib.resolve.DependencyResolver)1 RemotePostProcessor (aQute.bnd.maven.lib.resolve.RemotePostProcessor)1 Jar (aQute.bnd.osgi.Jar)1 Verifier (aQute.bnd.osgi.Verifier)1 SimpleIndexer (aQute.bnd.osgi.repository.SimpleIndexer)1 XMLResourceGenerator (aQute.bnd.osgi.repository.XMLResourceGenerator)1