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

The following examples show how to use org.apache.brooklyn.api.entity.Entity. 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: EffectorUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes a method effector so that its progress is tracked. For internal use only, when we know the effector is backed by a method which is local.
 */
public static <T> T invokeMethodEffector(Entity entity, Effector<T> eff, Map<String,?> args) {
    Object[] parametersArray = EffectorUtils.prepareArgsForEffector(eff, args);
    String name = eff.getName();

    try {
        if (log.isDebugEnabled()) log.debug("Invoking effector {} on {}", new Object[] {name, entity});
        if (log.isTraceEnabled()) log.trace("Invoking effector {} on {} with args {}", new Object[] {name, entity, Sanitizer.sanitize(args)});
        EntityManagementSupport mgmtSupport = ((EntityInternal)entity).getManagementSupport();
        if (!mgmtSupport.isDeployed()) {
            mgmtSupport.attemptLegacyAutodeployment(name);
        }
        ManagementContextInternal mgmtContext = (ManagementContextInternal) ((EntityInternal) entity).getManagementContext();

        mgmtSupport.getEntityChangeListener().onEffectorStarting(eff, parametersArray);
        try {
            return mgmtContext.invokeEffectorMethodSync(entity, eff, args);
        } finally {
            mgmtSupport.getEntityChangeListener().onEffectorCompleted(eff);
        }
    } catch (Exception e) {
        throw handleEffectorException(entity, eff, e);
    }
}
 
Example #2
Source File: BrooklynRestResourceUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** finds the entity indicated by the given ID or name
 * <p>
 * prefers ID based lookup in which case appId is optional, and if supplied will be enforced.
 * optionally the name can be supplied, for cases when paths should work across versions,
 * in which case names will be searched recursively (and the application is required). 
 * 
 * @throws 404 or 412 (unless input is null in which case output is null) */
public Entity getEntity(String application, String entity) {
    if (entity==null) return null;
    Application app = application!=null ? getApplication(application) : null;
    Entity e = mgmt.getEntityManager().getEntity(entity);
    
    if (e!=null) {
        if (!Entitlements.isEntitled(mgmt.getEntitlementManager(), Entitlements.SEE_ENTITY, e)) {
            throw WebResourceUtils.notFound("Cannot find entity '%s': no known ID and application not supplied for searching", entity);
        }
        
        if (app==null || app.equals(findTopLevelApplication(e))) return e;
        throw WebResourceUtils.preconditionFailed("Application '%s' specified does not match application '%s' to which entity '%s' (%s) is associated", 
                application, e.getApplication()==null ? null : e.getApplication().getId(), entity, e);
    }
    if (application==null)
        throw WebResourceUtils.notFound("Cannot find entity '%s': no known ID and application not supplied for searching", entity);
    
    assert app!=null : "null app should not be returned from getApplication";
    e = searchForEntityNamed(app, entity);
    if (e!=null) return e;
    throw WebResourceUtils.notFound("Cannot find entity '%s' in application '%s' (%s)", entity, application, app);
}
 
Example #3
Source File: CatalogYamlVersioningTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testVersionedReference() throws Exception {
    String symbolicName = "sampleId";
    String parentName = "parentId";
    String v1 = "0.1.0";
    String v2 = "0.2.0";
    String expectedType = BasicApplication.class.getName();

    addCatalogEntity(symbolicName, v1, expectedType);
    addCatalogEntity(symbolicName, v2);
    addCatalogEntity(parentName, v1, symbolicName + ":" + v1);

    Entity app = createAndStartApplication(
            "services:",
            "- type: " + parentName + ":" + v1);

    assertEquals(app.getEntityType().getName(), expectedType);
}
 
Example #4
Source File: HotStandbyTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testHotStandbyDoesNotStartFeeds() throws Exception {
    HaMgmtNode n1 = createMaster(Duration.PRACTICALLY_FOREVER);
    TestApplication app = createFirstAppAndPersist(n1);
    TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).impl(MyEntityWithFunctionFeedImpl.class));
    forcePersistNow(n1);
    Assert.assertTrue(entity.feeds().getFeeds().size() > 0, "Feeds: "+entity.feeds().getFeeds());
    for (Feed feed : entity.feeds().getFeeds()) {
        assertTrue(feed.isRunning(), "Feed expected running, but it is non-running");
    }

    HaMgmtNode n2 = createHotStandby(Duration.PRACTICALLY_FOREVER);
    TestEntity entityRO = (TestEntity) n2.mgmt.lookup(entity.getId(), Entity.class);
    Assert.assertTrue(entityRO.feeds().getFeeds().size() > 0, "Feeds: "+entity.feeds().getFeeds());
    for (Feed feedRO : entityRO.feeds().getFeeds()) {
        assertFalse(feedRO.isRunning(), "Feed expected non-active, but it is running");
    }
}
 
Example #5
Source File: CatalogOsgiYamlPolicyTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testLaunchApplicationReferencingPolicy() throws Exception {
    String symbolicName = "my.catalog.policy.id.launch";
    addCatalogOsgiPolicy(symbolicName, SIMPLE_POLICY_TYPE);
    Entity app = createAndStartApplication(
        "name: simple-app-yaml",
        "location: localhost",
        "services: ",
        "  - type: " + BasicEntity.class.getName(), 
        "    brooklyn.policies:\n" +
        "    - type: " + ver(symbolicName),
        "      brooklyn.config:",
        "        config2: config2 override",
        "        config3: config3");

    Entity simpleEntity = Iterables.getOnlyElement(app.getChildren());
    Policy policy = Iterables.getOnlyElement(simpleEntity.policies());
    assertEquals(policy.getPolicyType().getName(), SIMPLE_POLICY_TYPE);
    assertEquals(policy.getConfig(new BasicConfigKey<String>(String.class, "config1")), "config1");
    assertEquals(policy.getConfig(new BasicConfigKey<String>(String.class, "config2")), "config2 override");
    assertEquals(policy.getConfig(new BasicConfigKey<String>(String.class, "config3")), "config3");

    deleteCatalogEntity(symbolicName);
}
 
Example #6
Source File: InvokeEffectorOnCollectionSensorChangeRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testEffectorMaintainsPreviousCollectionThroughRebind() throws Exception {
    final Set<Integer> input1 = ImmutableSet.of(1, 2);
    final Set<Integer> input2 = ImmutableSet.of(2, 3);
    final Set<Integer> input3 = ImmutableSet.of(3, 4);

    Entity testEntity = app().createAndManageChild(EntitySpec.create(TestEntity.class)
            .policy(PolicySpec.create(InvokeEffectorOnCollectionSensorChange.class)
                    .configure(InvokeEffectorOnCollectionSensorChange.TRIGGER_SENSOR, SENSOR)
                    .configure(InvokeEffectorOnCollectionSensorChange.ON_REMOVED_EFFECTOR_NAME, "on-removed-effector"))
            .addInitializer(new AddEffector(Effectors.effector(Void.class, "on-removed-effector")
                    .impl(new PublishingEffector())
                    .build())));
    testEntity.sensors().set(SENSOR, input1);
    testEntity.sensors().set(SENSOR, input2);
    EntityAsserts.assertAttributeEqualsEventually(testEntity, REMOVED_EFFECTOR_VALUES, ImmutableSet.<Object>of(1));

    newApp = rebind();

    testEntity = Iterables.getOnlyElement(newApp.getChildren());
    testEntity.sensors().set(SENSOR, input3);
    EntityAsserts.assertAttributeEqualsEventually(testEntity, REMOVED_EFFECTOR_VALUES, ImmutableSet.<Object>of(1, 2));
}
 
Example #7
Source File: DslYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testDslAttributeWhenReadyOnEntity() throws Exception {
    final Entity app = createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  brooklyn.config:",
            "    dest: $brooklyn:entity(\"sourceEntity\").attributeWhenReady(\"source\")",
            "  brooklyn.children:",
            "  - type: " + BasicEntity.class.getName(),
            "    id: sourceEntity",
            "    brooklyn.initializers:",
            "    - type: org.apache.brooklyn.core.sensor.StaticSensor",
            "      brooklyn.config:",
            "        name: source",
            "        static.value: myvalue");
    assertEquals(getConfigEventually(app, DEST), "myvalue");
}
 
Example #8
Source File: ReloadBrooklynPropertiesTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testReloadBrooklynPropertiesDeploy() {
    brooklynMgmt.reloadBrooklynProperties();
    CampPlatform reloadedPlatform = brooklynMgmt.getScratchpad().get(BrooklynCampConstants.CAMP_PLATFORM);
    Assert.assertNotNull(reloadedPlatform);
    Reader input = Streams.reader(new ResourceUtils(this).getResourceFromUrl("test-entity-basic-template.yaml"));
    AssemblyTemplate template = reloadedPlatform.pdp().registerDeploymentPlan(input);
    try {
        Assembly assembly = template.getInstantiator().newInstance().instantiate(template, reloadedPlatform);
        LOG.info("Test - created " + assembly);
        final Entity app = brooklynMgmt.getEntityManager().getEntity(assembly.getId());
        LOG.info("App - " + app);
        Assert.assertEquals(app.getDisplayName(), "test-entity-basic-template");
        EntityAsserts.assertAttributeEqualsEventually(app, Startable.SERVICE_UP, true);
    } catch (Exception e) {
        LOG.warn("Unable to instantiate " + template + " (rethrowing): " + e);
        throw Exceptions.propagate(e);
    }
}
 
Example #9
Source File: ClassLoaderFromStackOfBrooklynClassLoadingContextTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadClassReturningDifferentlyNamedClass() throws Exception {
    final String specialClassName = "my.madeup.Clazz";
    
    ClassLoader classLoader = new ClassLoader() {
        @Override
        protected Class<?> findClass(String name) throws ClassNotFoundException {
            if (name != null && name.equals(specialClassName)) {
                return Entity.class;
            }
            return getClass().getClassLoader().loadClass(name);
        }
    };
    
    ClassLoaderFromStackOfBrooklynClassLoadingContext ocl = new ClassLoaderFromStackOfBrooklynClassLoadingContext(classLoader);
    ocl.setManagementContext(mgmt);
    assertEquals(ocl.loadClass(specialClassName), Entity.class);
    
    // TODO The line below fails: java.lang.ClassNotFoundException: my/madeup/Clazz
    //assertEquals(Class.forName(specialClassName, false, ocl).getName(), Entity.class.getName());
}
 
Example #10
Source File: ApplicationsYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testNameInCatalogMetadata() throws Exception {
    String yaml = Joiner.on("\n").join(
            "brooklyn.catalog:",
            "  version: 0.1.2",
            "  itemType: entity",
            "  name: My name in top-level",
            "  items:",
            "  - id: app1",
            "    item:",
            "      type: " + BasicApplication.class.getName());
    
    addCatalogItems(yaml);

    Entity app1 = createAndStartApplication("services: [ {type: app1} ]");
    assertDoesNotWrap(app1, BasicApplication.class, "My name in top-level");
}
 
Example #11
Source File: ApplicationLifecycleStateTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void assertUpAndRunningEventually(Entity entity) {
    try {
        EntityAsserts.assertAttributeEventually(entity, Attributes.SERVICE_NOT_UP_INDICATORS, CollectionFunctionals.<String>mapEmptyOrNull());
        EntityAsserts.assertAttributeEventually(entity, ServiceStateLogic.SERVICE_PROBLEMS, CollectionFunctionals.<String>mapEmptyOrNull());
        EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
        EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, true);
    } catch (Throwable t) {
        Dumper.dumpInfo(entity);
        String err = "(Dumped entity info - see log); entity=" + entity + "; " + 
                "state=" + entity.sensors().get(Attributes.SERVICE_STATE_ACTUAL) + "; " + 
                "up="+entity.sensors().get(Attributes.SERVICE_UP) + "; " +
                "notUpIndicators="+entity.sensors().get(Attributes.SERVICE_NOT_UP_INDICATORS) + "; " +
                "serviceProblems="+entity.sensors().get(Attributes.SERVICE_PROBLEMS);
        throw new AssertionError(err, t);
    }
}
 
Example #12
Source File: ReferencedYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups="Broken")  // reference to co-bundled items work also in nested url yaml as a type (but only in OSGi subclass)
public void testYamlReferencingEarlierItemInUrlAsType() throws Exception {
    addCatalogItems(
        "brooklyn.catalog:",
        "  itemType: entity",
        "  items:",
        "  - id: yaml.basic",
        "    version: " + TEST_VERSION,
        "    item:",
        "      type: org.apache.brooklyn.entity.stock.BasicEntity",
        "  - id: yaml.reference",
        "    version: " + TEST_VERSION,
        "    item:",
        "      type: classpath://yaml-ref-catalog.yaml");  // this references yaml.basic above

    String entityName = "YAML -> catalog item -> yaml url";
    Entity app = createAndStartApplication(
        "services:",
        "- name: " + entityName,
        "  type: " + ver("yaml.reference"));
    
    checkChildEntitySpec(app, entityName);
}
 
Example #13
Source File: ConfigInheritanceYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testInheritsRuntimeParentConfigOfTypeMapWithOneBigVal() throws Exception {
    String yaml = Joiner.on("\n").join(
            "services:",
            "- type: org.apache.brooklyn.entity.stock.BasicApplication",
            "  brooklyn.config:",
            "    test.confMapThing:",
            "      mykey: myval",
            "      mykey2: $brooklyn:config(\"myOtherConf\")",
            "    myOtherConf: myOther",
            "  brooklyn.children:",
            "  - type: org.apache.brooklyn.core.test.entity.TestEntity");

    final Entity app = createStartWaitAndLogApplication(yaml);
    TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
 
    assertEquals(entity.config().get(TestEntity.CONF_MAP_THING), ImmutableMap.of("mykey", "myval", "mykey2", "myOther"));
}
 
Example #14
Source File: ItemsInContainersGroupTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    super.setUp();
    loc = mgmt.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class)
            .configure("name", "loc"));
    
    containerGroup = app.createAndManageChild(EntitySpec.create(DynamicGroup.class)
            .displayName("containerGroup")
            .configure(DynamicGroup.ENTITY_FILTER, new Predicate<Entity>() {
                @Override
                public boolean apply(Entity input) {
                    return input instanceof MockContainerEntity && 
                            input.getConfig(MockContainerEntity.MOCK_MEMBERSHIP) == "ingroup";
                }}));
    itemGroup = app.createAndManageChild(EntitySpec.create(ItemsInContainersGroup.class)
            .displayName("itemGroup"));
    itemGroup.setContainers(containerGroup);
    
    app.start(ImmutableList.of(loc));
}
 
Example #15
Source File: BalancingNodePlacementStrategy.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Map<Location,Integer> toMutableLocationSizes(Multimap<Location, Entity> currentMembers, Iterable<? extends Location> otherLocs) {
    Map<Location,Integer> result = Maps.newLinkedHashMap();
    for (Location key : currentMembers.keySet()) {
        result.put(key, currentMembers.get(key).size());
    }
    for (Location otherLoc : otherLocs) {
        if (!result.containsKey(otherLoc)) {
            result.put(otherLoc, 0);
        }
    }
    return result;
}
 
Example #16
Source File: RebindDslTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDslConfigSupplier_2016_07() throws Exception {
    String entityId = "klcueb1ide";
    doAddEntityMemento("2016-07", entityId);
    
    rebind();
    Entity newEntity = mgmt().getEntityManager().getEntity(entityId);
    
    String val = newEntity.config().get(configSupplier1);
    assertEquals(val, "myval");
}
 
Example #17
Source File: AbstractAbstractControllerTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
protected Collection<String> locationsToAddresses(int port, Collection<Entity> entities) {
    Set<String> result = MutableSet.of();
    for (Entity e : entities) {
        SshMachineLocation machine = Machines.findUniqueMachineLocation(e.getLocations(), SshMachineLocation.class).get();
        result.add(machine.getAddress().getHostName()+":"+port);
    }
    return result;
}
 
Example #18
Source File: Entities.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the entity, its children, and all its children, and so on.
 *
 * @see #descendants(Entity, Predicate, boolean)
 */
public static Iterable<Entity> descendantsAndSelf(Entity root) {
    Set<Entity> result = Sets.newLinkedHashSet();
    result.add(root);
    descendantsWithoutSelf(root, result);
    return result;
}
 
Example #19
Source File: SelectMasterEffectorBody.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void toggleNodePriority(Entity node, int newPriority) {
    Integer oldPriority = DynamicTasks.queue(
            Effectors.invocation(
                node,
                BrooklynNode.SET_HIGH_AVAILABILITY_PRIORITY,
                MutableMap.of(SetHighAvailabilityPriorityEffector.PRIORITY, newPriority))
        ).asTask().getUnchecked();

    Integer expectedPriority = (newPriority == HA_MASTER_PRIORITY ? HA_STANDBY_PRIORITY : HA_MASTER_PRIORITY);
    if (oldPriority != expectedPriority) {
        LOG.warn("The previous HA priority on node " + node.getId() + " was " + oldPriority +
                ", while the expected value is " + expectedPriority + " (while setting priority " +
                newPriority + ").");
    }
}
 
Example #20
Source File: ApplicationResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private List<String> entitiesIdAsArray(Iterable<? extends Entity> entities) {
    List<String> ids = Lists.newArrayList();
    for (Entity entity : entities) {
        if (Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
            ids.add(entity.getId());
        }
    }
    return ids;
}
 
Example #21
Source File: KubernetesLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the {@code BROOKLYN_ROOT_PASSWORD} variable in the container environment if appropriate.
 * This is (approximately) the same behaviour as the {@link DockerJcloudsLocation} used for
 * Swarm.
 * <p>
 * Side-effects the location {@code config} to set the {@link KubernetesLocationConfig#LOGIN_USER_PASSWORD loginUser.password}
 * if one is auto-generated. Note that this injected value overrides any other settings configured for the
 * container environment.
 */
protected Map<String, String> findEnvironmentVariables(Entity entity, ConfigBag setup, String imageName) {
    String loginUser = setup.get(LOGIN_USER);
    String loginPassword = setup.get(LOGIN_USER_PASSWORD);
    Map<String, String> injections = Maps.newLinkedHashMap();

    // Check if login credentials should be injected
    Boolean injectLoginCredentials = setup.get(INJECT_LOGIN_CREDENTIAL);
    if (injectLoginCredentials == null) {
        for (String regex : IMAGE_DESCRIPTION_REGEXES_REQUIRING_INJECTED_LOGIN_CREDS) {
            if (imageName != null && imageName.matches(regex)) {
                injectLoginCredentials = true;
                break;
            }
        }
    }

    if (Boolean.TRUE.equals(injectLoginCredentials)) {
        if ((Strings.isBlank(loginUser) || "root".equals(loginUser))) {
            loginUser = "root";
            setup.configure(LOGIN_USER, loginUser);

            if (Strings.isBlank(loginPassword)) {
                loginPassword = Identifiers.makeRandomPassword(12);
                setup.configure(LOGIN_USER_PASSWORD, loginPassword);
            }

            injections.put(BROOKLYN_ROOT_PASSWORD, loginPassword);
        }
    }

    Map<String, Object> rawEnv = MutableMap.<String, Object>builder()
            .putAll(MutableMap.copyOf(setup.get(ENV)))
            .putAll(MutableMap.copyOf(entity.config().get(DockerContainer.CONTAINER_ENVIRONMENT)))
            .putAll(injections)
            .build();
    return Maps.transformValues(rawEnv, Functions.toStringFunction());
}
 
Example #22
Source File: EntityTypeTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomSimpleName() throws Exception {
    CustomTypeNamedEntity.typeName = "a.b.with space";
    Entity entity2 = app.addChild(EntitySpec.create(Entity.class).impl(CustomTypeNamedEntity.class));
    assertEquals(entity2.getEntityType().getSimpleName(), "with_space");
    
    CustomTypeNamedEntity.typeName = "a.b.with$dollar";
    Entity entity3 = app.addChild(EntitySpec.create(Entity.class).impl(CustomTypeNamedEntity.class));
    assertEquals(entity3.getEntityType().getSimpleName(), "with_dollar");
    
    CustomTypeNamedEntity.typeName = "a.nothingafterdot.";
    Entity entity4 = app.addChild(EntitySpec.create(Entity.class).impl(CustomTypeNamedEntity.class));
    assertEquals(entity4.getEntityType().getSimpleName(), "a.nothingafterdot.");
}
 
Example #23
Source File: AbstractNonProvisionedControllerImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
protected boolean belongsInServerPool(Entity member) {
    if (!groovyTruth(member.getAttribute(Startable.SERVICE_UP))) {
        if (LOG.isTraceEnabled()) LOG.trace("Members of {}, checking {}, eliminating because not up", this, member);
        return false;
    }
    if (!getServerPool().getMembers().contains(member)) {
        if (LOG.isTraceEnabled()) LOG.trace("Members of {}, checking {}, eliminating because not member", this, member);
        return false;
    }
    if (LOG.isTraceEnabled()) LOG.trace("Members of {}, checking {}, approving", this, member);
    return true;
}
 
Example #24
Source File: ElectPrimaryTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailover() throws Exception {
    Entity app = runSetPreferredViaWeightConfigOnB();
    Entity b = (Entity)mgmt().<Entity>lookup(EntityPredicates.displayNameEqualTo("b"));
    
    Entities.unmanage(b);
    EntityAsserts.assertAttributeEventually(app, PRIMARY, EntityPredicates.displayNameEqualTo("a"));
}
 
Example #25
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 #26
Source File: EntityAutomanagedTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartManagementOfEntityIsNoop() throws Exception {
    Entity app2 = mgmt.getEntityManager().createEntity(EntitySpec.create(TestApplication.class));
    assertTrue(Entities.isManaged(app2));
    
    Entities.startManagement(app2);
    assertTrue(Entities.isManaged(app2));
    listener.assertEventsEqualsEventually(ImmutableList.of(new ChangeEvent(ChangeType.ADDED, app2)));
}
 
Example #27
Source File: DynamicGroupImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * @return
 *      The filter configured in {@link #ENTITY_FILTER} ANDed with a check that the
 *      entity has the same application ID.
 */
protected Predicate<? super Entity> getEntityFilter() {
    Predicate<? super Entity> entityFilter = getConfig(ENTITY_FILTER);
    if (entityFilter == null) {
        entityFilter = Predicates.alwaysFalse();
    }
    return Predicates.and(
            EntityPredicates.applicationIdEqualTo(getApplicationId()),
            entityFilter);
}
 
Example #28
Source File: InternalEntityFactory.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private <T extends Entity> Class<? extends T> getImplementedBy(EntitySpec<T> spec) {
    if (spec.getImplementation() != null) {
        return spec.getImplementation();
    } else {
        return entityTypeRegistry.getImplementedBy(spec.getType());
    }
}
 
Example #29
Source File: DslTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigWithDsl() throws Exception {
    ConfigKey<?> configKey = ConfigKeys.newConfigKey(Entity.class, "testConfig");
    BrooklynDslDeferredSupplier<?> dsl = BrooklynDslCommon.config(configKey.getName());
    Supplier<ConfigValuePair> valueSupplier = new Supplier<ConfigValuePair>() {
        @Override public ConfigValuePair get() {
            return new ConfigValuePair(BrooklynDslCommon.root(), app);
        }
    };
    new ConfigTestWorker(app, configKey, valueSupplier, dsl).run();
}
 
Example #30
Source File: EffectorTaskTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void checkTags(Task<Integer> t, Entity entity, Effector<?> eff, boolean shouldHaveChild) {
    Assert.assertEquals(BrooklynTaskTags.getContextEntity(t), app);
    Assert.assertTrue(t.getTags().contains(BrooklynTaskTags.EFFECTOR_TAG), "missing effector tag; had: "+t.getTags());
    Assert.assertTrue(t.getDescription().contains(eff.getName()), "description missing effector name: "+t.getDescription());
    Assert.assertTrue(BrooklynTaskTags.isInEffectorTask(t, entity, eff, false));
    Assert.assertTrue(BrooklynTaskTags.isInEffectorTask(t, null, null, false));
    Assert.assertFalse(BrooklynTaskTags.isInEffectorTask(t, entity, Startable.START, false));
    
    if (shouldHaveChild) {
        Task<?> subtask = ((HasTaskChildren)t).getChildren().iterator().next();
        Assert.assertTrue(BrooklynTaskTags.isInEffectorTask(subtask, entity, eff, false));
        Assert.assertTrue(BrooklynTaskTags.isInEffectorTask(subtask, null, null, false));
    }
}