org.apache.brooklyn.api.entity.Application Java Examples

The following examples show how to use org.apache.brooklyn.api.entity.Application. 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: SpecParameterUnwrappingTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnresolvedCatalogItemParameters() {
    // Insert template which is not instantiatable during catalog addition due to
    // missing dependencies, but the spec can be created (the
    // dependencies are already parsed).
    addCatalogItems(
            "brooklyn.catalog:",
            "  version: " + TEST_VERSION,
            "  items:",
            "  - id: " + SYMBOLIC_NAME,
            "    itemType: template",
            "    item:",
            "      services:",
            "      - type: basic-app",
            "  - id: basic-app",
            "    itemType: entity",
            "    item:",
            "      type: " + ConfigAppForTest.class.getName());
    EntitySpec<? extends Application> spec = createAppSpec(
            "services:",
            "- type: " + ver(SYMBOLIC_NAME));
    List<SpecParameter<?>> params = spec.getParameters();
    assertEquals(params.size(), NUM_APP_DEFAULT_CONFIG_KEYS + ConfigAppForTest.NUM_CONFIG_KEYS_DEFINED_HERE, "params="+params);
    assertEquals(ImmutableSet.copyOf(params), ImmutableSet.copyOf(BasicSpecParameter.fromClass(mgmt(), ConfigAppForTest.class)));
}
 
Example #2
Source File: BrooklynLauncherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartsAppFromYAML() throws Exception {
    String yaml = "name: example-app\n" +
            "services:\n" +
            "- serviceType: org.apache.brooklyn.core.test.entity.TestEntity\n" +
            "  name: test-app";
    launcher = newLauncherForTests(true)
            .restServer(false)
            .application(yaml)
            .start();

    assertEquals(launcher.getApplications().size(), 1, "apps="+launcher.getApplications());
    Application app = Iterables.getOnlyElement(launcher.getApplications());
    assertEquals(app.getChildren().size(), 1, "children=" + app.getChildren());
    assertTrue(Iterables.getOnlyElement(app.getChildren()) instanceof TestEntity);
}
 
Example #3
Source File: HotStandbyTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private Application expectRebindSequenceNumber(HaMgmtNode master, HaMgmtNode hotStandby, Application app, int expectedSensorSequenceValue, boolean immediate) {
    Application appRO = hotStandby.mgmt.lookup(app.getId(), Application.class);

    if (immediate) {
        forcePersistNow(master);
        forceRebindNow(hotStandby);
        EntityAsserts.assertAttributeEquals(appRO, TestEntity.SEQUENCE, expectedSensorSequenceValue);
    } else {
        EntityAsserts.assertAttributeEqualsEventually(appRO, TestEntity.SEQUENCE, expectedSensorSequenceValue);
    }
    
    log.info("got sequence number "+expectedSensorSequenceValue+" from "+appRO);
    
    // make sure the instance (proxy) is unchanged
    Application appRO2 = hotStandby.mgmt.lookup(app.getId(), Application.class);
    Assert.assertTrue(appRO2==appRO);
    
    return appRO;
}
 
Example #4
Source File: InternalEntityFactoryTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreatesProxy() throws Exception {
    EntitySpec<Application> spec = EntitySpec.create(Application.class).impl(TestApplicationImpl.class);
    Application app = factory.createEntity(spec, Optional.absent());
    Application proxy = factory.createEntityProxy(spec, app);
    TestApplicationImpl deproxied = (TestApplicationImpl) Entities.deproxy(proxy);
    
    assertTrue(app instanceof TestApplicationImpl, "app="+app);
    
    assertFalse(proxy instanceof TestApplicationImpl, "proxy="+proxy);
    assertTrue(proxy instanceof EntityProxy, "proxy="+proxy);
    assertTrue(proxy instanceof Application, "proxy="+proxy);
    
    assertTrue(deproxied instanceof TestApplicationImpl, "deproxied="+deproxied);
    assertFalse(deproxied instanceof EntityProxy, "deproxied="+deproxied);
}
 
Example #5
Source File: ApplicationResourceTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = {"testListEffectors", "testFetchApplicationsAndEntity", "testApplicationDetailsAndEntity", "testTriggerSampleEffector", "testListApplications","testReadEachSensor","testPolicyWhichCapitalizes","testLocatedLocation"})
public void testDeleteApplication() throws TimeoutException, InterruptedException {
    waitForPageFoundResponse("/applications/simple-app", ApplicationSummary.class);
    Collection<Application> apps = getManagementContext().getApplications();
    log.info("Deleting simple-app from " + apps);
    int size = apps.size();

    Response response = client().path("/applications/simple-app")
            .delete();

    assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode());
    TaskSummary task = response.readEntity(TaskSummary.class);
    assertTrue(task.getDescription().toLowerCase().contains("destroy"), task.getDescription());
    assertTrue(task.getDescription().toLowerCase().contains("simple-app"), task.getDescription());

    waitForPageNotFoundResponse("/applications/simple-app", ApplicationSummary.class);

    log.info("App appears gone, apps are: " + getManagementContext().getApplications());
    // more logging above, for failure in the check below

    Asserts.eventually(
            EntityFunctions.applications(getManagementContext()),
            Predicates.compose(Predicates.equalTo(size-1), CollectionFunctionals.sizeFunction()) );
}
 
Example #6
Source File: EntitiesYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testEntitySpecInUnmatchedConfig() throws Exception {
    String yaml =
            "services:\n"+
            "- serviceType: org.apache.brooklyn.core.test.entity.TestEntity\n"+
            "  brooklyn.config:\n"+
            "   key.does.not.match:\n"+
            "     $brooklyn:entitySpec:\n"+
            "       type: org.apache.brooklyn.core.test.entity.TestEntity\n"+
            "       brooklyn.config:\n"+
            "         test.confName: inchildspec\n";
    
    Application app = (Application) createStartWaitAndLogApplication(yaml);
    TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
    Object entitySpecOrSupplier = entity.config().getBag().getStringKey("key.does.not.match");
    if (BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_PERSIST_ENTITY_SPEC_AS_SUPPLIER)) {
        Asserts.assertInstanceOf(entitySpecOrSupplier, DeferredSupplier.class);
        entitySpecOrSupplier = entity.config().get(ConfigKeys.newConfigKey(Object.class, "key.does.not.match"));
    }
    EntitySpec<?> entitySpec = (EntitySpec<?>) entitySpecOrSupplier;
    assertEquals(entitySpec.getType(), TestEntity.class);
    assertEquals(entitySpec.getConfig(), ImmutableMap.of(TestEntity.CONF_NAME, "inchildspec"));
}
 
Example #7
Source File: BrooklynLauncher.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected void startApps() {
    if ((stopWhichAppsOnShutdown==StopWhichAppsOnShutdown.ALL) ||
        (stopWhichAppsOnShutdown==StopWhichAppsOnShutdown.ALL_IF_NOT_PERSISTED && getPersistMode()==PersistMode.DISABLED)) {
        BrooklynShutdownHooks.invokeStopAppsOnShutdown(getManagementContext());
    }

    for (Application app : getApplications()) {
        if (app instanceof Startable) {

            if ((stopWhichAppsOnShutdown==StopWhichAppsOnShutdown.THESE) || 
                (stopWhichAppsOnShutdown==StopWhichAppsOnShutdown.THESE_IF_NOT_PERSISTED && getPersistMode()==PersistMode.DISABLED)) {
                BrooklynShutdownHooks.invokeStopOnShutdown(app);
            }
        }
    }
    super.startApps();
}
 
Example #8
Source File: RebindTestUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Walks the contents of a ManagementContext, to create a corresponding memento.
 */
protected static BrooklynMemento newBrooklynMemento(ManagementContext managementContext) {
    BrooklynMementoImpl.Builder builder = BrooklynMementoImpl.builder();
            
    for (Application app : managementContext.getApplications()) {
        builder.applicationId(app.getId());
    }
    for (Entity entity : managementContext.getEntityManager().getEntities()) {
        builder.entity(((EntityInternal)entity).getRebindSupport().getMemento());
    }
    for (Location location : managementContext.getLocationManager().getLocations()) {
        builder.location(((LocationInternal)location).getRebindSupport().getMemento());
        if (location.getParent() == null) {
            builder.topLevelLocationId(location.getId());
        }
    }

    BrooklynMemento result = builder.build();
    MementoValidators.validateMemento(result);
    return result;
}
 
Example #9
Source File: BrooklynRestResourceUtilsTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private void createAppFromCatalog(String type, boolean expectCatalogItemIdSet) {
    CatalogTemplateItemDto item = CatalogItemBuilder.newTemplate("app.noop", "0.0.1")
        .javaType(SampleNoOpApplication.class.getName())
        .build();
    managementContext.getCatalog().addItem(item);
    
    ApplicationSpec spec = ApplicationSpec.builder()
            .name("myname")
            .type(type)
            .locations(ImmutableSet.of("localhost"))
            .build();
    Application app = util.create(spec);

    if (expectCatalogItemIdSet) {
        assertEquals(app.getCatalogItemId(), "app.noop:0.0.1");
    } else {
        // since 0.12.0 we no longer reverse-lookup java types to try to find a registered type
        // (as per warnings in several previous versions)
        Assert.assertNull(app.getCatalogItemId());
    }
}
 
Example #10
Source File: OpenShiftYamlTest.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
public void deployWebappWithServicesFromYaml(){
    SimpleYamlLauncher launcher = new SimpleYamlLauncher();
    launcher.setShutdownAppsOnExit(false);
    Application app = launcher.launchAppYaml("openShift-webapp-db.yaml").getApplication();

    final OpenShiftWebApp server = (OpenShiftWebApp)
            findEntityChildByDisplayName(app, "Web AppServer HelloWorld");


    Asserts.succeedsEventually(new Runnable() {
        public void run() {
            assertNotNull(server);

            assertTrue(server.getAttribute(Startable.SERVICE_UP));
            assertTrue(server.getAttribute(OpenShiftWebApp
                    .SERVICE_PROCESS_IS_RUNNING));
        }
    });
}
 
Example #11
Source File: CatalogYamlTemplateTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetadataOnSpecCreatedFromItem() throws Exception {
    addCatalogItem("t1", TestEntity.class.getName());

    EntitySpec<? extends Application> spec = EntityManagementUtils.createEntitySpecForApplication(
            mgmt(),
            Joiner.on("\n").join(
                    "location: localhost",
                    "services:",
                    "- type: t1"));
    
    List<NamedStringTag> yamls = BrooklynTags.findAll(BrooklynTags.YAML_SPEC_KIND, spec.getTags());
    Assert.assertEquals(yamls.size(), 1, "Expected 1 yaml tag; instead had: "+yamls);
    String yaml = Iterables.getOnlyElement(yamls).getContents();
    Asserts.assertStringContains(yaml, "services:", "t1", "localhost");
    
    EntitySpec<?> child = Iterables.getOnlyElement( spec.getChildren() );
    Assert.assertEquals(child.getType().getName(), TestEntity.class.getName());
    Assert.assertEquals(child.getCatalogItemId(), "t1:"+TEST_VERSION);
}
 
Example #12
Source File: Entities.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Brings this entity under management only if its ancestor is managed.
 * <p>
 * Returns true if successful, otherwise returns false in the expectation that the ancestor
 * will become managed, or throws exception if it has no parent or a non-application root.
 *
 * @throws IllegalStateException if {@literal e} is an {@link Application}.
 * @see #startManagement(Entity)
 * 
 * @deprecated since 0.9.0; entities are automatically managed when created via {@link Entity#addChild(EntitySpec)},
 *             or with {@link EntityManager#createEntity(EntitySpec)} (it is strongly encouraged to include the parent
 *             if using the latter for anything but a top-level app).
 */
@Deprecated
public static boolean manage(Entity e) {
    if (Entities.isManaged(e)) {
        return true; // no-op
    }
    
    log.warn("Deprecated use of Entities.manage(Entity), for unmanaged entity "+e);
    Entity o = e.getParent();
    Entity eum = e; // Highest unmanaged ancestor
    if (o==null) throw new IllegalArgumentException("Can't manage "+e+" because it is an orphan");
    while (o.getParent()!=null) {
        if (!isManaged(o)) eum = o;
        o = o.getParent();
    }
    if (isManaged(o)) {
        ((EntityInternal)o).getManagementContext().getEntityManager().manage(eum);
        return true;
    }
    if (!(o instanceof Application)) {
        throw new IllegalStateException("Can't manage "+e+" because it is not rooted at an application");
    }
    return false;
}
 
Example #13
Source File: ApplicationResource.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** @deprecated since 0.7.0 see #create */ @Deprecated
protected Response createFromAppSpec(ApplicationSpec applicationSpec) {
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.DEPLOY_APPLICATION, applicationSpec)) {
        throw WebResourceUtils.forbidden("User '%s' is not authorized to start application %s",
            Entitlements.getEntitlementContext().user(), applicationSpec);
    }

    checkApplicationTypesAreValid(applicationSpec);
    checkLocationsAreValid(applicationSpec);
    List<Location> locations = brooklyn().getLocationsManaged(applicationSpec);
    Application app = brooklyn().create(applicationSpec);
    Task<?> t = brooklyn().start(app, locations);
    waitForStart(app, Duration.millis(100));
    TaskSummary ts = TaskTransformer.fromTask(ui.getBaseUriBuilder()).apply(t);
    URI ref = serviceAbsoluteUriBuilder(uriInfo.getBaseUriBuilder(), ApplicationApi.class, "get")
            .build(app.getApplicationId());
    return created(ref).entity(ts).build();
}
 
Example #14
Source File: BrooklynRestResourceUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private <T extends Entity> org.apache.brooklyn.api.entity.EntitySpec<?> toCoreEntitySpec(Class<T> clazz, String name, Map<String,String> configO, String catalogItemId) {
    Map<String, String> config = (configO == null) ? Maps.<String,String>newLinkedHashMap() : Maps.newLinkedHashMap(configO);
    
    org.apache.brooklyn.api.entity.EntitySpec<? extends Entity> result;
    if (clazz.isInterface()) {
        result = org.apache.brooklyn.api.entity.EntitySpec.create(clazz);
    } else {
        // If this is a concrete class, particularly for an Application class, we want the proxy
        // to expose all interfaces it implements.
        Class interfaceclazz = (Application.class.isAssignableFrom(clazz)) ? Application.class : Entity.class;
        Set<Class<?>> additionalInterfaceClazzes = Reflections.getInterfacesIncludingClassAncestors(clazz);
        result = org.apache.brooklyn.api.entity.EntitySpec.create(interfaceclazz).impl(clazz).additionalInterfaces(additionalInterfaceClazzes);
    }
    
    result.catalogItemId(catalogItemId);
    if (!Strings.isEmpty(name)) result.displayName(name);
    result.configure( convertFlagsToKeys(result.getImplementation(), config) );
    return result;
}
 
Example #15
Source File: ApplicationTransformer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static Status statusFromApplication(Application application) {
    if (application == null) return UNKNOWN;
    Lifecycle state = application.getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    if (state != null) return statusFromLifecycle(state);
    Boolean up = application.getAttribute(Startable.SERVICE_UP);
    if (up != null && up.booleanValue()) return RUNNING;
    return UNKNOWN;
}
 
Example #16
Source File: RecordingUsageListener.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public void assertLocEvent(int index, Location expectedLoc, Application expectedApp, Lifecycle expectedState, String errMsg) {
    List<?> actual = getLocationEvents().get(index);
    LocationMetadata locMetadata = (LocationMetadata) actual.get(1);
    LocationEvent locEvent = (LocationEvent) actual.get(2);
    
    assertEquals(locMetadata.getLocation(), expectedLoc, errMsg);
    assertEquals(locMetadata.getLocationId(), expectedLoc.getId(), errMsg);
    assertNotNull(locMetadata.getMetadata(), errMsg);
    assertEquals(locEvent.getApplicationId(), expectedApp.getId(), errMsg);
    assertEquals(locEvent.getState(), Lifecycle.CREATED, errMsg);
}
 
Example #17
Source File: EntityManagementUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** As {@link #canUnwrapEntity(EntitySpec)}
 * but additionally requiring that the wrapped item is an {@link Application},
 * for use when the context requires an {@link Application} ie a root of a spec.
 * @see #WRAPPER_APP_MARKER */
public static boolean canUnwrapApplication(EntitySpec<? extends Application> wrapperApplication) {
    if (!canUnwrapEntity(wrapperApplication)) return false;

    EntitySpec<?> childSpec = Iterables.getOnlyElement(wrapperApplication.getChildren());
    return (childSpec.getType()!=null && Application.class.isAssignableFrom(childSpec.getType()));
}
 
Example #18
Source File: XmlPlanToSpecTransformer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public EntitySpec<? extends Application> createApplicationSpec(String plan) {
    Document dom = parseXml(plan);
    EntitySpec<?> result = toEntitySpec(dom, 0);
    if (Application.class.isAssignableFrom(result.getType())) {
        return (EntitySpec<Application>) result;
    } else {
        return EntityManagementUtils.newWrapperApp().child(result);
    }
}
 
Example #19
Source File: JcloudsRebindWithYamlDslTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected JcloudsLocation newJcloudsLocation(ComputeServiceRegistry computeServiceRegistry) throws Exception {
    ByonComputeServiceStaticRef.setInstance(computeServiceRegistry);
    
    String symbolicName = "my.catalog.app.id.load";
    String catalogYaml = Joiner.on("\n").join(
        "brooklyn.catalog:",
        "  id: " + symbolicName,
        "  version: \"0.1.2\"",
        "  itemType: entity",
        "  item:",
        "    brooklyn.parameters:",
        "    - name: password",
        "      default: myYamlPassword",
        "    type: "+ MachineEntity.class.getName());
    mgmt().getCatalog().addItems(catalogYaml, true, true);

    String yaml = Joiner.on("\n").join(
            "location: " + LOCATION_CATALOG_ID,
            "services:\n"+
            "- type: "+symbolicName,
            "  brooklyn.config:",
            "    onbox.base.dir.skipResolution: true",
            "    sshMonitoring.enabled: false",
            "    metrics.usage.retrieve: false",
            "    provisioning.properties:",
            "      password: $brooklyn:config(\"password\")");
    
    EntitySpec<?> spec = 
            mgmt().getTypeRegistry().createSpecFromPlan(CampTypePlanTransformer.FORMAT, yaml, RegisteredTypeLoadingContexts.spec(Application.class), EntitySpec.class);
    origApp = mgmt().getEntityManager().createEntity(spec);
    
    return (JcloudsLocation) Iterables.getOnlyElement(origApp.getLocations());
}
 
Example #20
Source File: EntityManagementUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** adds entities from the given yaml, under the given parent; but does not start them */
public static List<Entity> addChildrenUnstarted(final Entity parent, String yaml) {
    log.debug("Creating child of "+parent+" from yaml:\n{}", yaml);

    ManagementContext mgmt = parent.getApplication().getManagementContext();

    EntitySpec<? extends Application> specA = createEntitySpecForApplication(mgmt, yaml);

    // see whether we can promote children
    List<EntitySpec<?>> specs = MutableList.of();
    if (!canUnwrapEntity(specA)) {
        // if not promoting, set a nice name if needed
        if (Strings.isEmpty(specA.getDisplayName())) {
            int size = specA.getChildren().size();
            String childrenCountString = size+" "+(size!=1 ? "children" : "child");
            specA.displayName("Dynamically added "+childrenCountString);
        }
    }
    
    specs.add(unwrapEntity(specA));

    final List<Entity> children = MutableList.of();
    for (EntitySpec<?> spec: specs) {
        Entity child = parent.addChild(spec);
        children.add(child);
    }

    return children;
}
 
Example #21
Source File: EntitiesYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void doTestLeak(String yaml) throws Exception {
    CampPlatform camp = BrooklynCampPlatform.findPlatform(mgmt());

    Application app = (Application) createStartWaitAndLogApplication(yaml);
    ((StartableApplication)app).stop();

    Assert.assertEquals(camp.assemblyTemplates().links().size(), 0);
    Assert.assertEquals(camp.assemblies().links().size(), 0);
    Assert.assertEquals(camp.applicationComponentTemplates().links().size(), 0);
    Assert.assertEquals(camp.applicationComponents().links().size(), 0);
    Assert.assertEquals(camp.platformComponentTemplates().links().size(), 0);
    Assert.assertEquals(camp.platformComponents().links().size(), 0);
}
 
Example #22
Source File: Main.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method that gets an instance of a brooklyn {@link EntitySpec}.
 * Guaranteed to be non-null result (throwing exception if app not appropriate).
 * 
 * @throws FatalConfigurationRuntimeException if class is not an {@link Application} or {@link Entity}
 */
@SuppressWarnings("unchecked")
protected EntitySpec<? extends Application> loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
    
    Class<?> clazz;
    log.debug("Loading application as class on classpath: {}", app);
    try {
        clazz = loader.loadClass(app, true, false);
    } catch (ClassNotFoundException cnfe) { // Not a class on the classpath
        throw new IllegalStateException("Unable to load app class '"+app+"'", cnfe);
    }
    
    if (Application.class.isAssignableFrom(clazz)) {
        if (clazz.isInterface()) {
            return EntitySpec.create((Class<? extends Application>)clazz);
        } else {
            return EntitySpec.create(Application.class)
                    .impl((Class<? extends Application>) clazz)
                    .additionalInterfaces(Reflections.getAllInterfaces(clazz));
        }
        
    } else if (Entity.class.isAssignableFrom(clazz)) {
        // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented!
        EntitySpec<?> childSpec;
        if (clazz.isInterface()) {
            childSpec = EntitySpec.create((Class<? extends Entity>)clazz);
        } else {
            childSpec = EntitySpec.create(Entity.class)
                    .impl((Class<? extends Application>) clazz)
                    .additionalInterfaces(Reflections.getAllInterfaces(clazz));
        }
        return EntitySpec.create(BasicApplication.class).child(childSpec);
        
    } else {
        throw new FatalConfigurationRuntimeException("Application class "+clazz+" must be an Application or Entity");
    }
}
 
Example #23
Source File: JcloudsExternalConfigYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testJcloudsInheritanceAndPasswordSecret() throws Exception {
    String yaml = Joiner.on("\n").join(
            "location:",
            "  " + LOCATION_CATALOG_ID + ":",
            "    password: $brooklyn:external(\"myprovider\", \"mykey\")",
            "    my.config.key: $brooklyn:external(\"myprovider\", \"mykey\")",
            "services:",
            "- type: "+EmptySoftwareProcess.class.getName());

    Application app = (StartableApplication) createAndStartApplication(new StringReader(yaml));

    Entity entity = Iterables.getOnlyElement( app.getChildren() );
    Location l = Iterables.getOnlyElement( entity.getLocations() );
    log.info("Location: "+l);
    assertEquals(l.config().get(MY_CONFIG_KEY), "myval");

    Maybe<Object> rawConfig = ((BrooklynObjectInternal.ConfigurationSupportInternal)l.config()).getRaw(MY_CONFIG_KEY);
    log.info("Raw config: "+rawConfig);
    Assert.assertTrue(rawConfig.isPresentAndNonNull());
    Assert.assertTrue(rawConfig.get() instanceof DeferredSupplier, "Expected deferred raw value; got "+rawConfig.get());

    rawConfig = ((BrooklynObjectInternal.ConfigurationSupportInternal)l.config()).getRaw(SshTool.PROP_PASSWORD);
    log.info("Raw config password: "+rawConfig);
    Assert.assertTrue(rawConfig.isPresentAndNonNull());
    Assert.assertTrue(rawConfig.get() instanceof DeferredSupplier, "Expected deferred raw value; got "+rawConfig.get());
}
 
Example #24
Source File: RebindConfigInheritanceTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void doReadConfigInheritance(String label, String entityId) throws Exception {
    String mementoFilename = "config-inheritance-"+label+"-"+entityId;
    origMemento = Streams.readFullyString(getClass().getResourceAsStream(mementoFilename));
    
    File persistedEntityFile = new File(mementoDir, Os.mergePaths("entities", entityId));
    Files.write(origMemento.getBytes(), persistedEntityFile);
    
    // we'll make assertions on what we've loaded
    rebind();
    rebindedApp = (Application) newManagementContext.lookup(entityId);
    
    // we'll also make assertions on the contents written out
    RebindTestUtils.waitForPersisted(mgmt());
    newMemento = Joiner.on("\n").join(Files.readLines(persistedEntityFile, Charsets.UTF_8));
}
 
Example #25
Source File: Entities.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Starts managing the given (unmanaged) app, setting the given brooklyn properties on the new
 * management context.
 *
 * @see #startManagement(Entity)
 * 
 * @deprecated since 0.9.0; entities are automatically managed when created via {@link Entity#addChild(EntitySpec)},
 *             or 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, BrooklynProperties props) {
    log.warn("Deprecated use of Entities.startManagement(Application, BrooklynProperties), for app "+app);
    
    if (isManaged(app)) {
        throw new IllegalStateException("Application "+app+" is already managed, so can't set brooklyn properties");
    }
    ManagementContext mgmt = new LocalManagementContext(props);
    mgmt.getEntityManager().manage(app);
    return mgmt;
}
 
Example #26
Source File: NonDeploymentUsageManager.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void recordApplicationEvent(Application app, Lifecycle state) {
    if (isInitialManagementContextReal()) {
        initialManagementContext.getUsageManager().recordApplicationEvent(app, state);
    } else {
        throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation");
    }
}
 
Example #27
Source File: InternalEntityFactoryTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatesEntity() throws Exception {
    EntitySpec<TestApplication> spec = EntitySpec.create(TestApplication.class);
    TestApplicationImpl app = (TestApplicationImpl) factory.createEntity(spec, Optional.absent());
    
    Entity proxy = app.getProxy();
    assertTrue(proxy instanceof Application, "proxy="+app);
    assertFalse(proxy instanceof TestApplicationImpl, "proxy="+app);
    
    assertEquals(proxy.getParent(), null);
    assertSame(proxy.getApplication(), proxy);
}
 
Example #28
Source File: ApplicationTransformer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static Function<? super Application, ApplicationSummary> fromApplication(final UriBuilder ub) {
    return new Function<Application, ApplicationSummary>() {
        @Override
        public ApplicationSummary apply(Application application) {
            return summaryFromApplication(application, ub);
        }
    };
}
 
Example #29
Source File: CloudFoundryYamlLiveTest.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private Entity findChildEntitySpecByPlanId(Application app, String planId) {
    for (Entity child : app.getChildren()) {
        String childPlanId = child.getConfig(BrooklynCampConstants.PLAN_ID);
        if ((childPlanId != null) && (childPlanId.equals(planId))) {
            return child;
        }
    }
    return null;
}
 
Example #30
Source File: RebindConfigInheritanceTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void checkNewAppNonInheritingKey1(Application app) {
    // check key
    EntityAsserts.assertConfigEquals(app, key1, "1");
    
    // check not inherited
    TestEntity entity = app.addChild(EntitySpec.create(TestEntity.class));
    EntityAsserts.assertConfigEquals(entity, key1, null);
}