Search in sources :

Example 66 with Version

use of org.osgi.framework.Version in project sling by apache.

the class PackageTransformer method checkForPackage.

/**
     * Check if the resource is a content package
     * @param resource The resource
     * @return {@code null} if not a content package, a result otherwise
     */
private TransformationResult[] checkForPackage(final RegisteredResource resource) {
    // first check if this is a zip archive
    try (final ZipInputStream zin = new ZipInputStream(new BufferedInputStream(resource.getInputStream()))) {
        if (zin.getNextEntry() == null) {
            return null;
        }
    } catch (final IOException ioe) {
        logger.debug("Unable to read resource.", ioe);
        return null;
    }
    Session session = null;
    JcrPackage pck = null;
    try {
        // create an admin session
        session = repository.loginAdministrative(null);
        final JcrPackageManager pckMgr = pkgSvc.getPackageManager(session);
        pck = pckMgr.upload(resource.getInputStream(), true, true);
        if (pck.isValid()) {
            final PackageId pid = pck.getDefinition().getId();
            final Map<String, Object> attrs = new HashMap<String, Object>();
            attrs.put(ATTR_PCK_ID, pid.toString());
            final TransformationResult tr = new TransformationResult();
            tr.setId(pid.getGroup() + ':' + pid.getName());
            tr.setResourceType(RESOURCE_TYPE);
            tr.setAttributes(attrs);
            // version
            final String version = pid.getVersionString();
            if (version.length() > 0) {
                tr.setVersion(new Version(cleanupVersion(version)));
            }
            return new TransformationResult[] { tr };
        }
    } catch (final Exception ioe) {
        logger.debug("Unable to check content package " + resource.getURL(), ioe);
    } finally {
        if (pck != null) {
            pck.close();
        }
        if (session != null) {
            session.logout();
        }
    }
    return null;
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) JcrPackageManager(org.apache.jackrabbit.vault.packaging.JcrPackageManager) IOException(java.io.IOException) ZipInputStream(java.util.zip.ZipInputStream) BufferedInputStream(java.io.BufferedInputStream) Version(org.osgi.framework.Version) JcrPackage(org.apache.jackrabbit.vault.packaging.JcrPackage) PackageId(org.apache.jackrabbit.vault.packaging.PackageId) TransformationResult(org.apache.sling.installer.api.tasks.TransformationResult) Session(javax.jcr.Session)

Example 67 with Version

use of org.osgi.framework.Version in project sling by apache.

the class SubsystemBaseTransformer method transform.

public TransformationResult[] transform(RegisteredResource resource) {
    // TODO start level of the subsystem
    if (resource.getType().equals(InstallableResource.TYPE_FILE)) {
        if (resource.getURL().endsWith("." + TYPE_SUBSYSTEM_BASE)) {
            logger.info("Found subsystem-base resource {}", resource);
            try {
                SubsystemData ssd = createSubsystemFile(resource);
                TransformationResult tr = new TransformationResult();
                Attributes mfAttributes = ssd.manifest.getMainAttributes();
                tr.setId(mfAttributes.getValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME));
                tr.setVersion(new Version(mfAttributes.getValue(SubsystemConstants.SUBSYSTEM_VERSION)));
                tr.setResourceType("esa");
                tr.setInputStream(new DeleteOnCloseFileInputStream(ssd.file));
                Map<String, Object> attr = new HashMap<String, Object>();
                attr.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, mfAttributes.getValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME));
                attr.put(SubsystemConstants.SUBSYSTEM_VERSION, mfAttributes.getValue(SubsystemConstants.SUBSYSTEM_VERSION));
                tr.setAttributes(attr);
                return new TransformationResult[] { tr };
            } catch (IOException ioe) {
                logger.error("Problem processing subsystem-base file " + resource, ioe);
            }
        }
    }
    return null;
}
Also used : Version(org.osgi.framework.Version) HashMap(java.util.HashMap) Attributes(java.util.jar.Attributes) IOException(java.io.IOException) TransformationResult(org.apache.sling.installer.api.tasks.TransformationResult)

Example 68 with Version

use of org.osgi.framework.Version in project sling by apache.

the class BundleInstallUpgradeExceptionRetryTest method testUpdateSuccedsWithLessThanMaxRetrys.

@Test
public void testUpdateSuccedsWithLessThanMaxRetrys() throws Exception {
    // install version 1.1 and fail activation with exception all attempts
    final Object listener = this.startObservingBundleEvents();
    final AtomicReference<ServiceRegistration<AtomicInteger>> ref = new AtomicReference<ServiceRegistration<AtomicInteger>>(null);
    final AtomicInteger counter = new AtomicInteger(3);
    bundleContext.addBundleListener(new SynchronousBundleListener() {

        @Override
        public void bundleChanged(org.osgi.framework.BundleEvent event) {
            if (event.getType() == org.osgi.framework.BundleEvent.STOPPED && event.getBundle().getSymbolicName().equals(symbolicName) && event.getBundle().getVersion().equals(new Version("1.0.0"))) {
                if (ref.get() == null) {
                    try {
                        event.getBundle().start();
                        ref.set(bundleContext.registerService(AtomicInteger.class, counter, null));
                    } catch (BundleException e) {
                    }
                } else {
                    ref.getAndSet(null).unregister();
                    if (counter.get() == 0) {
                        bundleContext.removeBundleListener(this);
                    }
                }
            }
        }
    });
    installer.updateResources(URL_SCHEME, getInstallableResource(createTestBundle(new Version("2.0.0"))), null);
    try {
        long time = 0;
        while (counter.get() >= 0 && time < 1000) {
            sleep(100);
            time += 100;
        }
        assertBundle("After installing", symbolicName, "2.0.0", Bundle.ACTIVE);
    } finally {
        if (ref.get() != null) {
            ref.get().unregister();
        }
    }
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Version(org.osgi.framework.Version) BundleException(org.osgi.framework.BundleException) SynchronousBundleListener(org.osgi.framework.SynchronousBundleListener) ServiceRegistration(org.osgi.framework.ServiceRegistration) Test(org.junit.Test)

Example 69 with Version

use of org.osgi.framework.Version in project sling by apache.

the class SubsystemInstaller method createTask.

/**
     * @see org.apache.sling.installer.api.tasks.InstallTaskFactory#createTask(org.apache.sling.installer.api.tasks.TaskResourceGroup)
     */
public InstallTask createTask(final TaskResourceGroup toActivate) {
    final InstallTask result;
    final TaskResource rsrc = toActivate.getActiveResource();
    if (rsrc.getType().equals(TYPE_SUBSYSTEM)) {
        // check if the required info is available
        final SubsystemInfo info = checkResource(toActivate);
        if (info == null) {
            // ignore as info is missing
            result = new ChangeStateTask(toActivate, ResourceState.IGNORED);
        } else {
            // search a subsystem with the symbolic name
            final ServiceReference<Subsystem> ref = this.getSubsystemReference(info.symbolicName);
            final Subsystem currentSubsystem = (ref != null ? this.bundleContext.getService(ref) : null);
            try {
                final Version newVersion = new Version(info.version);
                final Version oldVersion = (ref == null ? null : (Version) ref.getProperty("subsystem.version"));
                // Install
                if (rsrc.getState() == ResourceState.INSTALL) {
                    if (oldVersion != null) {
                        final int compare = oldVersion.compareTo(newVersion);
                        if (compare < 0) {
                            // installed version is lower -> update
                            result = new UpdateSubsystemTask(toActivate, this.bundleContext, ref, this.rootSubsystem);
                        } else if (compare == 0 && isSnapshot(newVersion)) {
                            // same version but snapshot -> update
                            result = new UpdateSubsystemTask(toActivate, this.bundleContext, ref, this.rootSubsystem);
                        } else if (compare == 0 && currentSubsystem != null && currentSubsystem.getState() != State.ACTIVE) {
                            // try to start the version
                            result = new StartSubsystemTask(toActivate, currentSubsystem);
                        } else {
                            logger.info("{} is not installed, subsystem with same or higher version is already installed: {}", info, newVersion);
                            result = new ChangeStateTask(toActivate, ResourceState.IGNORED);
                        }
                    } else {
                        result = new InstallSubsystemTask(toActivate, this.rootSubsystem);
                    }
                // Uninstall
                } else if (rsrc.getState() == ResourceState.UNINSTALL) {
                    if (oldVersion == null) {
                        logger.error("Nothing to uninstall. {} is currently not installed.", info);
                        result = new ChangeStateTask(toActivate, ResourceState.IGNORED);
                    } else {
                        final int compare = oldVersion.compareTo(newVersion);
                        if (compare == 0) {
                            result = new UninstallSubsystemTask(toActivate, this.bundleContext, ref);
                        } else {
                            logger.error("Nothing to uninstall. {} is currently not installed, different version is installed {}", info, oldVersion);
                            result = new ChangeStateTask(toActivate, ResourceState.IGNORED);
                        }
                    }
                } else {
                    result = null;
                }
            } finally {
                if (currentSubsystem != null) {
                    this.bundleContext.ungetService(ref);
                }
            }
        }
    } else {
        result = null;
    }
    return result;
}
Also used : TaskResource(org.apache.sling.installer.api.tasks.TaskResource) Version(org.osgi.framework.Version) Subsystem(org.osgi.service.subsystem.Subsystem) ChangeStateTask(org.apache.sling.installer.api.tasks.ChangeStateTask) InstallTask(org.apache.sling.installer.api.tasks.InstallTask)

Example 70 with Version

use of org.osgi.framework.Version in project bnd by bndtools.

the class OBRFragment method parse.

@SuppressWarnings("deprecation")
public static Reporter parse(Jar jar, ResourceBuilder resource) throws Exception {
    Manifest m = jar.getManifest();
    if (m == null)
        return null;
    Domain d = Domain.domain(m);
    d.setTranslation(jar);
    Entry<String, Attrs> bundleSymbolicName = d.getBundleSymbolicName();
    if (bundleSymbolicName == null)
        return null;
    boolean singleton = "true".equals(bundleSymbolicName.getValue().get(Constants.SINGLETON_DIRECTIVE + ":"));
    boolean isFragment = d.get(Constants.FRAGMENT_HOST) != null;
    Version version = d.getBundleVersion() == null ? Version.emptyVersion : new Version(d.getBundleVersion());
    CapReqBuilder identity = new CapReqBuilder(IdentityNamespace.IDENTITY_NAMESPACE);
    identity.addAttribute(IdentityNamespace.IDENTITY_NAMESPACE, bundleSymbolicName.getKey());
    identity.addAttribute(IdentityNamespace.CAPABILITY_COPYRIGHT_ATTRIBUTE, d.translate(Constants.BUNDLE_COPYRIGHT));
    identity.addAttribute(IdentityNamespace.CAPABILITY_DESCRIPTION_ATTRIBUTE, d.translate(Constants.BUNDLE_DESCRIPTION));
    identity.addAttribute(IdentityNamespace.CAPABILITY_DOCUMENTATION_ATTRIBUTE, d.translate(Constants.BUNDLE_DOCURL));
    identity.addAttribute(IdentityNamespace.CAPABILITY_LICENSE_ATTRIBUTE, d.translate(aQute.bnd.osgi.Constants.BUNDLE_LICENSE));
    if (singleton)
        identity.addAttribute(IdentityNamespace.CAPABILITY_SINGLETON_DIRECTIVE, "true");
    identity.addAttribute(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE, isFragment ? IdentityNamespace.TYPE_FRAGMENT : IdentityNamespace.TYPE_BUNDLE);
    identity.addAttribute(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE, new Version(d.getBundleVersion()));
    resource.addCapability(identity);
    if (isFragment) {
        //
        // Fragment-Host
        //
        Entry<String, Attrs> fragmentHost = d.getFragmentHost();
        CapReqBuilder fragment = new CapReqBuilder(HostNamespace.HOST_NAMESPACE);
        String v = fragmentHost.getValue().get("version");
        if (v == null)
            v = "0";
        Version fragmentVersion = new Version(v);
        String filter = filter(PackageNamespace.PACKAGE_NAMESPACE, fragmentHost.getKey(), fragmentHost.getValue());
        fragment.addDirective(HostNamespace.REQUIREMENT_FILTER_DIRECTIVE, filter);
        resource.addRequirement(fragment);
    } else {
        //
        // Bundle-SymbolicName
        //
        CapReqBuilder bundle = new CapReqBuilder(BundleNamespace.BUNDLE_NAMESPACE);
        CapReqBuilder host = new CapReqBuilder(HostNamespace.HOST_NAMESPACE);
        bundle.addAttribute("version", version);
        host.addAttribute("version", version);
        for (Entry<String, String> e : bundleSymbolicName.getValue().entrySet()) {
            String key = e.getKey();
            if (key.endsWith(":")) {
                String directive = key.substring(0, key.length() - 1);
                if (Constants.FRAGMENT_ATTACHMENT_DIRECTIVE.equalsIgnoreCase(directive)) {
                    if (Constants.FRAGMENT_ATTACHMENT_NEVER.equalsIgnoreCase(e.getValue()))
                        host = null;
                } else if (!Constants.SINGLETON_DIRECTIVE.equalsIgnoreCase(directive)) {
                    bundle.addDirective(directive, e.getValue());
                }
                if (host != null)
                    host.addDirective(directive, e.getValue());
                bundle.addDirective(directive, e.getValue());
            } else {
                if (host != null)
                    host.addAttribute(key, e.getValue());
                bundle.addAttribute(key, e.getValue());
            }
        }
        if (host != null)
            resource.addCapability(host);
        resource.addCapability(bundle);
    }
    //
    // Export-Package
    //
    Parameters exports = d.getExportPackage();
    for (Entry<String, Attrs> entry : exports.entrySet()) {
        CapReqBuilder exported = new CapReqBuilder(PackageNamespace.PACKAGE_NAMESPACE);
        String pkgName = Processor.removeDuplicateMarker(entry.getKey());
        exported.addAttribute(PackageNamespace.PACKAGE_NAMESPACE, pkgName);
        String versionStr = entry.getValue().get(Constants.VERSION_ATTRIBUTE);
        Version v = Version.parseVersion(entry.getValue().get("version"));
        exported.addAttribute(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE, version);
        for (Entry<String, String> attribEntry : entry.getValue().entrySet()) {
            String key = attribEntry.getKey();
            if (key.endsWith(":")) {
                String directive = key.substring(0, key.length() - 1);
                exported.addDirective(directive, attribEntry.getValue());
            } else {
                if (key.equals("specification-version") || key.equals("version"))
                    exported.addAttribute("version", Version.parseVersion(attribEntry.getValue()));
                else
                    exported.addAttribute(key, attribEntry.getValue());
            }
        }
        exported.addAttribute(PackageNamespace.CAPABILITY_BUNDLE_SYMBOLICNAME_ATTRIBUTE, bundleSymbolicName.getKey());
        exported.addAttribute(PackageNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE, version);
        resource.addCapability(exported);
    }
    //
    // Import-Package
    //
    Parameters imports = d.getImportPackage();
    for (Entry<String, Attrs> entry : imports.entrySet()) {
        CapReqBuilder imported = new CapReqBuilder(PackageNamespace.PACKAGE_NAMESPACE);
        String name = Processor.removeDuplicateMarker(entry.getKey());
        String filter = filter(PackageNamespace.PACKAGE_NAMESPACE, Processor.removeDuplicateMarker(entry.getKey()), entry.getValue());
        imported.addDirective(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter);
        resource.addRequirement(imported);
    }
    //
    // Require-Bundle
    //
    Parameters requires = d.getRequireBundle();
    for (Entry<String, Attrs> entry : requires.entrySet()) {
        CapReqBuilder req = new CapReqBuilder(BundleNamespace.BUNDLE_NAMESPACE);
        String bsn = Processor.removeDuplicateMarker(entry.getKey());
        String filter = filter(BundleNamespace.BUNDLE_NAMESPACE, bsn, entry.getValue());
        req.addDirective(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter);
        resource.addRequirement(req);
    }
    //
    // Bundle-RequiredExecutionEnvironment
    //
    Parameters brees = d.getBundleRequiredExecutionEnvironment();
    try (Formatter formatter = new Formatter()) {
        formatter.format("(|");
        for (Entry<String, Attrs> bree : brees.entrySet()) {
            String name = Processor.removeDuplicateMarker(bree.getKey());
            Matcher matcher = EE_PATTERN.matcher(name);
            if (matcher.matches()) {
                name = matcher.group(1);
                Version v = Version.parseVersion(matcher.group(2));
                formatter.format("%s", filter(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE, name, MAP.$("version", v.toString())));
            }
        }
        formatter.format(")");
        CapReqBuilder breeReq = new CapReqBuilder(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE);
        breeReq.addDirective(Namespace.REQUIREMENT_FILTER_DIRECTIVE, formatter.toString());
        for (Entry<String, Attrs> export : d.getParameters(Constants.EXPORT_SERVICE).entrySet()) {
            CapReqBuilder exportedService = new CapReqBuilder(ServiceNamespace.SERVICE_NAMESPACE);
            String service = Processor.removeDuplicateMarker(export.getKey());
            exportedService.addAttribute(ServiceNamespace.SERVICE_NAMESPACE, service);
            exportedService.addAttribute(ServiceNamespace.CAPABILITY_OBJECTCLASS_ATTRIBUTE, export.getValue().get("objectclass"));
            resource.addCapability(exportedService);
        }
        for (Entry<String, Attrs> imported : d.getParameters(Constants.IMPORT_SERVICE).entrySet()) {
            CapReqBuilder importedService = new CapReqBuilder(ServiceNamespace.SERVICE_NAMESPACE);
            String service = Processor.removeDuplicateMarker(imported.getKey());
            importedService.addDirective(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter(ServiceNamespace.SERVICE_NAMESPACE, service, imported.getValue()));
            resource.addRequirement(importedService);
        }
        for (Entry<String, Attrs> rc : d.getProvideCapability().entrySet()) {
            resource.addCapability(toCapability(rc.getKey(), rc.getValue()));
        }
        for (Entry<String, Attrs> rc : d.getRequireCapability().entrySet()) {
            resource.addCapability(toRequirement(rc.getKey(), rc.getValue()));
        }
    }
    return null;
}
Also used : CapReqBuilder(aQute.bnd.osgi.resource.CapReqBuilder) Parameters(aQute.bnd.header.Parameters) Version(org.osgi.framework.Version) Matcher(java.util.regex.Matcher) Formatter(java.util.Formatter) Attrs(aQute.bnd.header.Attrs) Manifest(java.util.jar.Manifest) Domain(aQute.bnd.osgi.Domain)

Aggregations

Version (org.osgi.framework.Version)222 Test (org.junit.Test)35 ArrayList (java.util.ArrayList)28 Bundle (org.osgi.framework.Bundle)27 File (java.io.File)23 HashMap (java.util.HashMap)21 Capability (org.osgi.resource.Capability)20 IOException (java.io.IOException)19 BundleException (org.osgi.framework.BundleException)15 Resource (org.osgi.resource.Resource)14 InputStream (java.io.InputStream)12 Map (java.util.Map)11 Manifest (java.util.jar.Manifest)11 List (java.util.List)10 URL (java.net.URL)8 HashSet (java.util.HashSet)8 Content (org.apache.aries.application.Content)8 AriesApplication (org.apache.aries.application.management.AriesApplication)8 VersionRange (org.apache.felix.utils.version.VersionRange)8 BundleRevision (org.osgi.framework.wiring.BundleRevision)8