org.apache.brooklyn.api.mgmt.ManagementContext Java Examples

The following examples show how to use org.apache.brooklyn.api.mgmt.ManagementContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BrooklynRestApiLauncher.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private static Server startServer(ManagementContext mgmt, ContextHandler context, String summary, InetSocketAddress bindLocation) {
    Server server = new Server(bindLocation);

    initAuth(mgmt, server);

    server.setHandler(context);
    try {
        server.start();
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
    log.info("Brooklyn REST server started ("+summary+") on");
    log.info("  http://localhost:"+((NetworkConnector)server.getConnectors()[0]).getLocalPort()+"/");

    return server;
}
 
Example #2
Source File: CatalogUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Deprecated /** @deprecated since 0.9.0; we should now always have a registered type callers can pass instead of the catalog item id */
private static BrooklynClassLoadingContext newClassLoadingContext(@Nullable ManagementContext mgmt, String catalogItemId, Collection<? extends OsgiBundleWithUrl> libraries, BrooklynClassLoadingContext loader) {
    BrooklynClassLoadingContextSequential result = new BrooklynClassLoadingContextSequential(mgmt);

    if (libraries!=null && !libraries.isEmpty()) {
        result.add(new OsgiBrooklynClassLoadingContext(mgmt, catalogItemId, libraries));
    }

    if (loader !=null) {
        // TODO determine whether to support stacking
        result.add(loader);
    }
    BrooklynClassLoadingContext threadLocalLoader = BrooklynLoaderTracker.getLoader();
    if (threadLocalLoader != null) {
        // TODO and determine if this is needed/wanted
        result.add(threadLocalLoader);
    }

    result.addSecondary(JavaBrooklynClassLoadingContext.create(mgmt));
    return result;
}
 
Example #3
Source File: PortForwardManagerLocationResolver.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T create(ManagementContext mgmt, Class<T> type, AbstractBrooklynObjectSpec<?, ?> spec) {
    ConfigBag config = ConfigBag.newInstance(spec.getConfig());
    String scope = config.get(SCOPE);
    
    Optional<Location> result = findPortForwardManager(mgmt, scope);
    if (result.isPresent()) return (T) result.get();
    
    // have to create it, but first check again with synch lock
    synchronized (PortForwardManager.class) {
        result = findPortForwardManager(mgmt, scope);
        if (result.isPresent()) return (T) result.get();

        Object callerContext = config.get(CloudLocationConfig.CALLER_CONTEXT);
        LOG.info("Creating PortForwardManager(scope="+scope+")"+(callerContext!=null ? " for "+callerContext : ""));
        
        spec = LocationSpec.create((LocationSpec<?>)spec);
        // clear the special instruction to actually create it
        spec.configure(Config.SPECIAL_CONSTRUCTOR, (Class<SpecialBrooklynObjectConstructor>) null);
        spec.configure(PortForwardManager.SCOPE, scope);
        
        return (T) mgmt.getLocationManager().createLocation((LocationSpec<?>) spec);
    }
}
 
Example #4
Source File: RebindTestFixture.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected ManagementContext hotStandby(RebindOptions options) throws Exception {
    if (newApp != null || newManagementContext != null) {
        throw new IllegalStateException("already rebound - use switchOriginalToNewManagementContext() if you are trying to rebind multiple times");
    }
    if (options.haMode != null && options.haMode != HighAvailabilityMode.HOT_STANDBY) {
        throw new IllegalStateException("hotStandby called, but with HA Mode set to "+options.haMode);
    }
    if (options.terminateOrigManagementContext) {
        throw new IllegalStateException("hotStandby called with terminateOrigManagementContext==true");
    }
    
    options = RebindOptions.create(options);
    options.terminateOrigManagementContext(false);
    if (options.haMode == null) options.haMode(HighAvailabilityMode.HOT_STANDBY);
    if (options.classLoader == null) options.classLoader(classLoader);
    if (options.mementoDir == null) options.mementoDir(mementoDir);
    if (options.origManagementContext == null) options.origManagementContext(origManagementContext);
    if (options.newManagementContext == null) options.newManagementContext(createNewManagementContext(options.mementoDir, options.haMode, options.additionalProperties));
    
    RebindTestUtils.stopPersistence(origApp);
    
    newManagementContext = options.newManagementContext;
    RebindTestUtils.rebind(options);
    return newManagementContext;
}
 
Example #5
Source File: BrooklynEntityMirrorIntegrationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void setUpServer(ManagementContext mgmt, boolean skipSecurity) {
    try {
        if (serverMgmt!=null) throw new IllegalStateException("server already set up");
        
        serverMgmt = mgmt;
        server = new BrooklynWebServer(mgmt);
        server.skipSecurity(skipSecurity);
        server.start();
        
        serverMgmt.getHighAvailabilityManager().disabled(false);
        serverApp = TestApplication.Factory.newManagedInstanceForTests(serverMgmt);
        
        ((LocalManagementContextForTests)serverMgmt).noteStartupComplete();
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}
 
Example #6
Source File: Entities.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Starts managing the given (unmanaged) app, using the given management context.
 *
 * @see #startManagement(Entity)
 * 
 * @deprecated since 0.9.0; entities are automatically managed when created with 
 *             {@link EntityManager#createEntity(EntitySpec)}. For top-level apps, use code like
 *             {@code managementContext.getEntityManager().createEntity(EntitySpec.create(...))}.
 */
@Deprecated
public static ManagementContext startManagement(Application app, ManagementContext mgmt) {
    log.warn("Deprecated use of Entities.startManagement(Application, ManagementContext), for app "+app);
    
    if (isManaged(app)) {
        if (app.getManagementContext() == mgmt) {
            // no-op; app was presumably auto-managed
            return mgmt;
        } else {
            throw new IllegalStateException("Application "+app+" is already managed by "+app.getManagementContext()+", so cannot be managed by "+mgmt);
        }
    }

    mgmt.getEntityManager().manage(app);
    return mgmt;
}
 
Example #7
Source File: ScriptResourceTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testGroovy() {
    ManagementContext mgmt = LocalManagementContextForTests.newInstance();
    Application app = mgmt.getEntityManager().createEntity( EntitySpec.create(Application.class, RestMockApp.class) );
    try {
    
        Entities.start(app, Collections.<Location>emptyList());

        ScriptResource s = new ScriptResource();
        s.setManagementContext(mgmt);

        ScriptExecutionSummary result = s.groovy(null, "def apps = []; mgmt.applications.each { println 'app:'+it; apps << it.id }; apps");
        Assert.assertEquals(Collections.singletonList(app.getId()).toString(), result.getResult());
        Assert.assertTrue(result.getStdout().contains("app:RestMockApp"));
    
    } finally { Entities.destroyAll(mgmt); }
}
 
Example #8
Source File: BrooklynAssemblyTemplateInstantiator.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Application create(AssemblyTemplate template, CampPlatform platform) {
    ManagementContext mgmt = getManagementContext(platform);
    BrooklynClassLoadingContext loader = JavaBrooklynClassLoadingContext.create(mgmt);
    EntitySpec<? extends Application> spec = createApplicationSpec(template, platform, loader, MutableSet.<String>of());
    Application instance = mgmt.getEntityManager().createEntity(spec);
    log.info("CAMP created '{}'", instance);
    return instance;
}
 
Example #9
Source File: TypeTransformer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static BundleSummary bundleSummary(BrooklynRestResourceUtils brooklyn, ManagedBundle b, UriBuilder baseUriBuilder, ManagementContext mgmt, boolean detail) {
    BundleSummary result = new BundleSummary(b);
    if (detail) {
        result.setExtraField("osgiVersion", b.getOsgiVersionString());
        result.setExtraField("checksum", b.getChecksum());            
    }
    if (detail) {
        for (RegisteredType t: mgmt.getTypeRegistry().getMatching(RegisteredTypePredicates.containingBundle(b))) {
            result.addType(summary(brooklyn, t, baseUriBuilder));
        }
    }
    return result;
}
 
Example #10
Source File: DynamicClusterWithAvailabilityZonesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public SimulatedAvailabilityZoneExtension(ManagementContext managementContext, SimulatedLocation loc, 
        List<String> subLocNames, Map<String, ? extends Predicate<? super SimulatedLocation>> subLocFailCondition) {
    super(managementContext);
    this.loc = checkNotNull(loc, "loc");
    this.subLocNames = subLocNames;
    this.subLocFailConditions = subLocFailCondition;
}
 
Example #11
Source File: CorsFilterLauncherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void setCorsFilterFeature(boolean enable, List<String> allowedOrigins) {
    if (enable) {
        BrooklynFeatureEnablement.enable(BrooklynFeatureEnablement.FEATURE_CORS_CXF_PROPERTY);
    } else {
        BrooklynFeatureEnablement.disable(BrooklynFeatureEnablement.FEATURE_CORS_CXF_PROPERTY);
    }
    BrooklynRestApiLauncher apiLauncher = baseLauncher();
    ManagementContext mgmt = LocalManagementContextForTests.builder(true)
            .useAdditionalProperties(MutableMap.<String, Object>of(
                    BrooklynFeatureEnablement.FEATURE_CORS_CXF_PROPERTY, enable,
                    BrooklynFeatureEnablement.FEATURE_CORS_CXF_PROPERTY + "." + CorsImplSupplierFilter.ALLOW_ORIGINS.getName(), allowedOrigins)
            ).build();
    apiLauncher.managementContext(mgmt);
    useServerForTest(apiLauncher.start());
}
 
Example #12
Source File: XmlMementoSerializerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testEntity() throws Exception {
    final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
    ManagementContext managementContext = app.getManagementContext();
    try {
        serializer.setLookupContext(newEmptyLookupManagementContext(managementContext, true).add(app));
        assertSerializeAndDeserialize(app);
    } finally {
        Entities.destroyAll(managementContext);
    }
}
 
Example #13
Source File: CorsFilterLauncherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void test1CorsIsEnabledOnAllDomainsByDefaultPOST() throws IOException {
    final String shouldAllowOrigin = "http://foo.bar.com";
    BrooklynFeatureEnablement.enable(BrooklynFeatureEnablement.FEATURE_CORS_CXF_PROPERTY);
    BrooklynRestApiLauncher apiLauncher = baseLauncher().withoutJsgui();
    // In this test, management context has no value set for Allowed Origins.
    ManagementContext mgmt = LocalManagementContextForTests.builder(true)
            .useAdditionalProperties(MutableMap.<String, Object>of(
                    BrooklynFeatureEnablement.FEATURE_CORS_CXF_PROPERTY, true)
            ).build();
    apiLauncher.managementContext(mgmt);
    useServerForTest(apiLauncher.start());
    HttpClient client = client();
    // preflight request
    HttpToolResponse response = HttpTool.execAndConsume(client, httpOptionsRequest("script/groovy", "POST", shouldAllowOrigin));
    List<String> accessControlAllowOrigin = response.getHeaderLists().get(HEADER_AC_ALLOW_ORIGIN);
    assertEquals(accessControlAllowOrigin.size(), 1);
    assertEquals(accessControlAllowOrigin.get(0), "*", "Should allow POST requests made from " + shouldAllowOrigin);
    assertEquals(response.getHeaderLists().get(HEADER_AC_ALLOW_HEADERS).size(), 1);
    assertEquals(response.getHeaderLists().get(HEADER_AC_ALLOW_HEADERS).get(0), "x-csrf-token", "Should have asked and allowed x-csrf-token header from " + shouldAllowOrigin);
    assertOkayResponse(response, "");
    
    response = HttpTool.httpPost(
            client, URI.create(getBaseUriRest() + "script/groovy"),
            ImmutableMap.<String,String>of(
                    "Origin", shouldAllowOrigin,
                    HttpHeaders.CONTENT_TYPE, "application/text"),
            "return 0;".getBytes());
    accessControlAllowOrigin = response.getHeaderLists().get(HEADER_AC_ALLOW_ORIGIN);
    assertEquals(accessControlAllowOrigin.size(), 1);
    assertEquals(accessControlAllowOrigin.get(0), "*", "Should allow GET requests made from " + shouldAllowOrigin);
    assertOkayResponse(response, "{\"result\":\"0\"}");
}
 
Example #14
Source File: CleanOrphanedLocationsIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCleanedCopiedPersistedState() throws Exception {
    LOG.info(JavaClassNames.niceClassAndMethod()+" taking persistence from "+persistenceDirWithOrphanedLocations);
    BrooklynLauncher launcher = BrooklynLauncher.newInstance()
            .restServer(false)
            .brooklynProperties(OsgiManager.USE_OSGI, false)
            .persistMode(PersistMode.AUTO)
            .persistenceDir(persistenceDirWithOrphanedLocations)
            .highAvailabilityMode(HighAvailabilityMode.DISABLED);

    ManagementContext mgmtForCleaning = null;
    try {
        launcher.cleanOrphanedState(destinationDir.getAbsolutePath(), null);
        mgmtForCleaning = launcher.getManagementContext();
    } finally {
        launcher.terminate();
        if (mgmtForCleaning != null) Entities.destroyAll(mgmtForCleaning);
    }

    initManagementContextAndPersistence(destinationDir.getAbsolutePath());
    BrooklynMementoRawData mementoRawDataFromCleanedState = mgmt.getRebindManager().retrieveMementoRawData();
    Asserts.assertTrue(mementoRawDataFromCleanedState.getEntities().size() != 0);
    Asserts.assertTrue(mementoRawDataFromCleanedState.getLocations().size() != 0);

    initManagementContextAndPersistence(persistenceDirWithoutOrphanedLocations);
    BrooklynMementoRawData mementoRawData = mgmt.getRebindManager().retrieveMementoRawData();

    assertRawData(mementoRawData, mementoRawDataFromCleanedState);
}
 
Example #15
Source File: CatalogUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** @deprecated since it was introduced in 0.9.0; TBD where this should live */
@Deprecated
public static void setDisabled(ManagementContext mgmt, String symbolicNameAndOptionalVersion, boolean newValue) {
    RegisteredType item = mgmt.getTypeRegistry().get(symbolicNameAndOptionalVersion);
    Preconditions.checkNotNull(item, "No such item: "+symbolicNameAndOptionalVersion);
    setDisabled(mgmt, item.getSymbolicName(), item.getVersion(), newValue);
}
 
Example #16
Source File: AbstractBrooklynLauncherRebindTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static Application createAndStartApplication(ManagementContext mgmt, String input) throws Exception {
    EntitySpec<?> spec = 
        mgmt.getTypeRegistry().createSpecFromPlan(CampTypePlanTransformer.FORMAT, input, RegisteredTypeLoadingContexts.spec(Application.class), EntitySpec.class);
    final Entity app = mgmt.getEntityManager().createEntity(spec);
    app.invoke(Startable.START, MutableMap.of()).get();
    return (Application) app;
}
 
Example #17
Source File: BrooklynPersistenceUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static BrooklynMementoRawData newStateMemento(ManagementContext mgmt, MementoCopyMode source) {
    switch (source) {
    case LOCAL: 
        return newStateMementoFromLocal(mgmt); 
    case REMOTE: 
        return mgmt.getRebindManager().retrieveMementoRawData(); 
    case AUTO: 
        throw new IllegalStateException("Copy mode AUTO not supported here");
    }
    throw new IllegalStateException("Should not come here, unknown mode "+source);
}
 
Example #18
Source File: CatalogBundleDto.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static Maybe<CatalogBundle> resolve(ManagementContext mgmt, CatalogBundle b) {
    if (b.isNameResolved()) return Maybe.of(b);
    OsgiManager osgi = ((ManagementContextInternal)mgmt).getOsgiManager().orNull();
    if (osgi==null) return Maybe.absent("No OSGi manager");
    Maybe<Bundle> b2 = osgi.findBundle(b);
    if (b2.isAbsent()) return Maybe.absent("Nothing installed for "+b);
    return Maybe.of(new CatalogBundleDto(b2.get().getSymbolicName(), b2.get().getVersion().toString(), b.getUrl()));
}
 
Example #19
Source File: ServerResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public String getPlaneId() {
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SERVER_STATUS, null))
        throw WebResourceUtils.forbidden("User '%s' is not authorized to perform this operation", Entitlements.getEntitlementContext().user());

    Maybe<ManagementContext> mm = mgmtMaybe();
    Maybe<String> result = (mm.isPresent()) ? mm.get().getManagementPlaneIdMaybe() : Maybe.absent();
    return result.isPresent() ? result.get() : "";
}
 
Example #20
Source File: AbstractEntity.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public ManagementContext getManagementContext() {
    // NB Sept 2014 - removed synch keyword above due to deadlock;
    // it also synchs in ManagementSupport.getManagementContext();
    // no apparent reason why it was here also
    return getManagementSupport().getManagementContext();
}
 
Example #21
Source File: AbstractYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected ManagementContext setUpPlatform() {
    launcher = new BrooklynCampPlatformLauncherNoServer() {
        @Override
        protected LocalManagementContext newMgmtContext() {
            return newTestManagementContext();
        }
    };
    launcher.launch();
    platform = launcher.getCampPlatform();
    return launcher.getBrooklynMgmt();
}
 
Example #22
Source File: JcloudsRebindStubUnitTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
@AfterMethod(alwaysRun=true)
public void tearDown() throws Exception {
    try {
        List<Exception> exceptions = Lists.newArrayList();
        for (ManagementContext mgmt : mgmts) {
            try {
                if (mgmt.isRunning()) Entities.destroyAll(mgmt);
            } catch (Exception e) {
                LOG.warn("Error destroying management context", e);
                exceptions.add(e);
            }
        }
        
        super.tearDown();
        
        if (exceptions.size() > 0) {
            throw new CompoundRuntimeException("Error in tearDown of "+getClass(), exceptions);
        }
    } finally {
        mgmts.clear();
        origManagementContext = null;
        newManagementContext = null;
        origApp = null;
        newApp = null;
        RecordingSshTool.clear();
        RecordingWinRmTool.clear();
    }
}
 
Example #23
Source File: BundleUpgradeParser.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static String getItemUpgradedIfNecessary(ManagementContext mgmt, String vName, LookupFunction lookupF) {
    Set<VersionedName> r = lookupF.lookup(getFromManagementContext(mgmt), VersionedName.fromString(vName));
    if (!r.isEmpty()) return r.iterator().next().toString();
    
    if (log.isTraceEnabled()) {
        log.trace("Could not find '"+vName+"' and no upgrades specified; subsequent failure or warning possible unless that is a direct java class reference");
    }
    return vName;
}
 
Example #24
Source File: BrooklynMementoPersisterFileBasedTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected ManagementContext newPersistingManagementContext() {
    mementoDir = Os.newTempDir(JavaClassNames.cleanSimpleClassName(this));
    Os.deleteOnExitRecursively(mementoDir);
    return RebindTestUtils.managementContextBuilder(classLoader, new FileBasedObjectStore(mementoDir))
        .persistPeriod(Duration.millis(10)).buildStarted();
}
 
Example #25
Source File: Locations.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * As {@link LocationRegistry#getLocationManaged(String, Map)} but also accepting maps and yaml representations of maps.
 * <p>
 * The caller is responsible for ensuring the resulting {@link Location} is unmanaged. */
public static Location coerceToLocationManaged(ManagementContext mgmt, Object rawO) {
    if (rawO==null)
        return null;
    if (rawO instanceof Location)
        return (Location)rawO;
    
    Object raw = rawO;
    if (raw instanceof String)
        raw = Yamls.parseAll((String)raw).iterator().next();
    
    String name;
    Map<?, ?> flags = null;
    if (raw instanceof Map) {
        // for yaml, take the key, and merge with locationFlags
        Map<?,?> tm = ((Map<?,?>)raw);
        if (tm.size()!=1) {
            throw new IllegalArgumentException("Location "+rawO+" is invalid; maps must have only one key, being the location spec string");
        }
        name = (String) tm.keySet().iterator().next();
        flags = (Map<?, ?>) tm.values().iterator().next();
        
    } else if (raw instanceof String) {
        name = (String)raw;
        
    } else {
        throw new IllegalArgumentException("Location "+rawO+" is invalid; can only parse strings or maps");
    }
    return mgmt.getLocationRegistry().getLocationManaged(name, flags);
}
 
Example #26
Source File: BrooklynLauncherRebindCatalogOsgiTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void assertMasterEventually(BrooklynLauncher launcher) {
    ManagementContext mgmt = launcher.getManagementContext();
    Asserts.succeedsEventually(new Runnable() {
        public void run() {
            assertTrue(mgmt.isStartupComplete());
            assertTrue(mgmt.isRunning());
            assertEquals(mgmt.getNodeState(), ManagementNodeState.MASTER);
            Asserts.assertSize(((ManagementContextInternal)mgmt).errors(), 0);
        }});
}
 
Example #27
Source File: LdapSecurityProvider.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public LdapSecurityProvider(ManagementContext mgmt) {
    StringConfigMap properties = mgmt.getConfig();
    ldapUrl = properties.getConfig(BrooklynWebConfig.LDAP_URL);
    Strings.checkNonEmpty(ldapUrl, "LDAP security provider configuration missing required property "+BrooklynWebConfig.LDAP_URL);
    ldapRealm = CharMatcher.isNot('"').retainFrom(properties.getConfig(BrooklynWebConfig.LDAP_REALM));
    Strings.checkNonEmpty(ldapRealm, "LDAP security provider configuration missing required property "+BrooklynWebConfig.LDAP_REALM);

    if(Strings.isBlank(properties.getConfig(BrooklynWebConfig.LDAP_OU))) {
        LOG.info("Setting LDAP ou attribute to: Users");
        organizationUnit = "Users";
    } else {
        organizationUnit = CharMatcher.isNot('"').retainFrom(properties.getConfig(BrooklynWebConfig.LDAP_OU));
    }
    Strings.checkNonEmpty(ldapRealm, "LDAP security provider configuration missing required property "+BrooklynWebConfig.LDAP_OU);
}
 
Example #28
Source File: BundleUpgradeParser.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Beta
public static String getBundleUpgradedIfNecessary(ManagementContext mgmt, String vName) {
    // mgmt can be null in some edge cases, eg BasicCatalogItemRebindSupport.possiblyUpgradedBundle 
    if (vName==null || mgmt==null) return null;
    Maybe<OsgiManager> osgi = ((ManagementContextInternal)mgmt).getOsgiManager();
    if (osgi.isAbsent()) {
        // ignore upgrades if not osgi
        return vName;
    }
    if (osgi.get().getManagedBundle(VersionedName.fromString(vName))!=null) {
        // bundle installed, prefer that to upgrade 
        return vName;
    }
    return getItemUpgradedIfNecessary(mgmt, vName, (cu,vn) -> cu.getUpgradesForBundle(vn));
}
 
Example #29
Source File: BasicBrooklynCatalog.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated since 1.0.0; Catalog annotation is deprecated.
 */
@Deprecated
private Collection<CatalogItemDtoAbstract<?, ?>> scanAnnotationsInternal(ManagementContext mgmt, CatalogDo subCatalog, Map<?, ?> catalogMetadata, ManagedBundle containingBundle) {
    subCatalog.mgmt = mgmt;
    subCatalog.setClasspathScanForEntities(CatalogScanningModes.ANNOTATIONS);
    subCatalog.load();
    @SuppressWarnings({ "unchecked", "rawtypes" })
    Collection<CatalogItemDtoAbstract<?, ?>> result = (Collection)Collections2.transform(
            (Collection<CatalogItemDo<Object,Object>>)(Collection)subCatalog.getIdCache().values(), 
            itemDoToDtoAddingSelectedMetadataDuringScan(mgmt, catalogMetadata, containingBundle));
    return result;
}
 
Example #30
Source File: BasicLocationRegistry.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static void addNamedLocationLocalhost(ManagementContext mgmt) {
    if (!mgmt.getConfig().getConfig(LocalhostLocationResolver.LOCALHOST_ENABLED)) {
        throw new IllegalStateException("Localhost is disabled.");
    }
    
    // ensure localhost is added (even on windows, it's just for testing)
    LocationDefinition l = mgmt.getLocationRegistry().getDefinedLocationByName("localhost");
    if (l==null) mgmt.getLocationRegistry().updateDefinedLocation(
            BasicLocationRegistry.localhost(Identifiers.makeRandomId(8)) );
}