Search in sources :

Example 56 with Version

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

the class BundleUpdateTask method execute.

/**
     * @see org.apache.sling.installer.api.tasks.InstallTask#execute(org.apache.sling.installer.api.tasks.InstallationContext)
     */
@Override
public void execute(final InstallationContext ctx) {
    final String symbolicName = (String) getResource().getAttribute(Constants.BUNDLE_SYMBOLICNAME);
    final Bundle b = BundleInfo.getMatchingBundle(this.getBundleContext(), symbolicName, null);
    if (b == null) {
        String message = MessageFormat.format("Bundle to update ({0}) not found", symbolicName);
        this.getLogger().debug(message);
        this.setFinishedState(ResourceState.IGNORED, null, message);
        return;
    }
    final Version newVersion = new Version((String) getResource().getAttribute(Constants.BUNDLE_VERSION));
    // Do not update if same version, unless snapshot
    boolean snapshot = false;
    final Version currentVersion = b.getVersion();
    snapshot = BundleInfo.isSnapshot(newVersion);
    if (currentVersion.equals(newVersion) && !snapshot) {
        // TODO : Isn't this already checked in the task creator?
        String message = MessageFormat.format("Same version is already installed, and not a snapshot, ignoring update: {0}", getResource());
        this.getLogger().debug(message);
        this.setFinishedState(ResourceState.INSTALLED, null, message);
        return;
    }
    try {
        // If the bundle is active before the update - restart it once updated, but
        // in sequence, not right now
        final boolean reactivate = this.isBundleActive(b);
        // if this is not a fragment, stop the bundle
        final int state = b.getState();
        if (state == Bundle.ACTIVE || state == Bundle.STARTING) {
            b.stop();
        }
        // update bundle
        b.update(getResource().getInputStream());
        ctx.log("Updated bundle {} from resource {}", b, getResource());
        // start level handling - after update to avoid starting the bundle
        // just before the update
        final BundleStartLevel startLevelService = b.adapt(BundleStartLevel.class);
        final int newStartLevel = this.getBundleStartLevel();
        final int oldStartLevel = startLevelService.getStartLevel();
        if (newStartLevel != oldStartLevel && newStartLevel != 0) {
            startLevelService.setStartLevel(newStartLevel);
            ctx.log("Set start level for bundle {} to {}", b, newStartLevel);
        }
        if (reactivate) {
            if (BundleUtil.isSystemBundleFragment(b)) {
                this.setFinishedState(ResourceState.INSTALLED);
                ctx.addTaskToCurrentCycle(new SystemBundleUpdateTask(null, this.getTaskSupport()));
            } else if (BundleUtil.getFragmentHostHeader(b) != null) {
                // if this is a fragment, we're done after a refresh of the host
                final String fragmentHostHeader = BundleUtil.getFragmentHostHeader(b);
                this.getLogger().debug("Need to do a refresh of the bundle's {} host", b);
                for (final Bundle bundle : this.getBundleContext().getBundles()) {
                    if (fragmentHostHeader.equals(bundle.getSymbolicName())) {
                        this.getLogger().debug("Found host bundle for {} to refresh: {}", b, bundle);
                        RefreshBundlesTask.markBundleForRefresh(ctx, this.getTaskSupport(), bundle);
                        break;
                    }
                }
                this.setFinishedState(ResourceState.INSTALLED);
            } else {
                BundleUtil.markBundleStart(this.getResource());
                RefreshBundlesTask.markBundleForRefresh(ctx, this.getTaskSupport(), b);
                ctx.addTaskToCurrentCycle(new BundleStartTask(this.getResourceGroup(), b.getBundleId(), this.getTaskSupport()));
            }
        } else {
            this.setFinishedState(ResourceState.INSTALLED);
        }
    } catch (final Exception e) {
        int retries = 0;
        Object obj = getResource().getTemporaryAttribute(ATTR_UPDATE_RETRY);
        if (obj instanceof Integer) {
            retries = (Integer) obj;
        }
        getResource().setTemporaryAttribute(ATTR_UPDATE_RETRY, Integer.valueOf(++retries));
        if (retries > MAX_RETRIES) {
            String message = MessageFormat.format("Removing failing update task due to {0} - unable to retry: {1}", e.getLocalizedMessage(), this);
            this.getLogger().error(message, e);
            this.setFinishedState(ResourceState.IGNORED, null, message);
        } else {
            String message = MessageFormat.format("Failing update task due to {0} - will retry up to {1} more time(s) for {2} later", e.getLocalizedMessage(), MAX_RETRIES - (retries - 1), this);
            this.getLogger().warn(message, e);
        }
    }
}
Also used : BundleStartLevel(org.osgi.framework.startlevel.BundleStartLevel) Version(org.osgi.framework.Version) Bundle(org.osgi.framework.Bundle)

Example 57 with Version

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

the class DefaultTransformer method checkBundle.

/**
     * Check if the registered resource is a bundle.
     * @return
     */
private TransformationResult[] checkBundle(final RegisteredResource resource) {
    logger.debug("Checking headers for {}", resource);
    final Util.BundleHeaders headers = Util.readBundleHeaders(resource, logger);
    logger.debug("Found headers for {} : {}", resource, headers);
    if (headers != null) {
        // check the version for validity
        boolean validVersion = true;
        try {
            new Version(headers.version);
        } catch (final IllegalArgumentException iae) {
            logger.info("Rejecting bundle {} from {} due to invalid version information: {}.", new Object[] { headers.symbolicName, resource, headers.version });
            validVersion = false;
        }
        if (validVersion) {
            final Map<String, Object> attr = new HashMap<String, Object>();
            attr.put(Constants.BUNDLE_SYMBOLICNAME, headers.symbolicName);
            attr.put(Constants.BUNDLE_VERSION, headers.version);
            // check for activation policy
            if (headers.activationPolicy != null) {
                attr.put(Constants.BUNDLE_ACTIVATIONPOLICY, headers.activationPolicy);
            }
            final TransformationResult tr = new TransformationResult();
            tr.setId(headers.symbolicName);
            tr.setResourceType(InstallableResource.TYPE_BUNDLE);
            tr.setAttributes(attr);
            logger.debug("Transformed {} to {}", resource, tr);
            return new TransformationResult[] { tr };
        }
    }
    return null;
}
Also used : Version(org.osgi.framework.Version) HashMap(java.util.HashMap) TransformationResult(org.apache.sling.installer.api.tasks.TransformationResult)

Example 58 with Version

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

the class ResolveTest method getResource.

/**
	 * Check if we can resolve against capabilities defined on the -provided
	 */
// public static void testResolveWithProfile() throws Exception {
// Resolver resolver = new BndResolver(new ResolverLogger(4));
// MockRegistry registry = new MockRegistry();
// registry.addPlugin(createRepo(IO.getFile("testdata/repo3.index.xml")));
// BndEditModel model = new BndEditModel();
//
// //
// // Provided capabilities
// //
//
// model.setRunFw("org.apache.felix.framework");
// model.setGenericString(Constants.DISTRO,
// "testdata/repo1/org.apache.felix.gogo.runtime-0.10.0.jar;version=file");
//
// //
// // We require gogo, but now the gogo runtime is on the runpath
// // so should be excluded
// //
//
// Requirement erq =
// CapReqBuilder.createPackageRequirement("org.apache.felix.gogo.api",
// "0.10.0")
// .buildSyntheticRequirement();
//
// model.setRunRequires(Arrays.asList(erq));
//
// BndrunResolveContext context = new BndrunResolveContext(model, registry,
// log);
// context.setLevel(4);
// context.init();
//
// Map<Resource,List<Wire>> resolved = resolver.resolve(context);
// List<Wire> wires = resolved.get(context.getInputResource());
// assertNotNull(wires);
// boolean found = false;
// for ( Wire wire : wires ) {
// if (equals(wire.getRequirement(), erq)) {
// found = true;
// assertTrue(wire.getProvider().equals(context.getSystemResource()));
// }
// }
// assertTrue("System resource not found for wire", found);
//
// Set<Resource> resources = resolved.keySet();
// Resource resource = getResource(resources,
// "org.apache.felix.gogo.runtime", "0.10");
// assertNull(resource);
//
// }
// private static boolean equals(Requirement a, Requirement b) {
// if ( a== b)
// return true;
//
// if ( a == null || b == null)
// return false;
//
// if ( a.equals(b))
// return true;
//
// if ( !a.getNamespace().equals(b.getNamespace()))
// return false;
//
// return a.getDirectives().equals(b.getDirectives()) &&
// a.getAttributes().equals(b.getAttributes());
// }
private static Resource getResource(Set<Resource> resources, String bsn, String versionString) {
    for (Resource resource : resources) {
        List<Capability> identities = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE);
        if (identities != null && identities.size() == 1) {
            Capability idCap = identities.get(0);
            Object id = idCap.getAttributes().get(IdentityNamespace.IDENTITY_NAMESPACE);
            Object version = idCap.getAttributes().get(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE);
            if (bsn.equals(id)) {
                if (versionString == null) {
                    return resource;
                }
                Version requested = Version.parseVersion(versionString);
                Version current;
                if (version instanceof Version) {
                    current = (Version) version;
                } else {
                    current = Version.parseVersion((String) version);
                }
                if (requested.equals(current)) {
                    return resource;
                }
            }
        }
    }
    return null;
}
Also used : Capability(org.osgi.resource.Capability) Version(org.osgi.framework.Version) Resource(org.osgi.resource.Resource)

Example 59 with Version

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

the class R5LabelFormatter method appendResourceLabel.

public static void appendResourceLabel(StyledString label, Resource resource) {
    Capability identity = ResourceUtils.getIdentityCapability(resource);
    String name = ResourceUtils.getIdentity(identity);
    if (name == null) {
        if (resource != null) {
            name = resource.toString();
        } else {
            name = "<unknown>";
        }
    }
    label.append(name, BoldStyler.INSTANCE_DEFAULT);
    Version version = ResourceUtils.getVersion(identity);
    if (version != null)
        label.append(" " + version, StyledString.COUNTER_STYLER);
}
Also used : Capability(org.osgi.resource.Capability) Version(org.osgi.framework.Version) StyledString(org.eclipse.jface.viewers.StyledString)

Example 60 with Version

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

the class RequirementWithResourceLabelProvider method appendResourceLabel.

protected void appendResourceLabel(StyledString label, Resource resource) {
    Capability identity = ResourceUtils.getIdentityCapability(resource);
    String name = ResourceUtils.getIdentity(identity);
    if (name == null) {
        if (resource != null) {
            name = resource.toString();
        } else {
            name = "<unknown>";
        }
    }
    label.append(name);
    Version version = ResourceUtils.getVersion(identity);
    if (version != null)
        label.append(" " + version, StyledString.COUNTER_STYLER);
}
Also used : Capability(org.osgi.resource.Capability) Version(org.osgi.framework.Version) StyledString(org.eclipse.jface.viewers.StyledString)

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