org.apache.brooklyn.core.entity.EntityInternal Java Examples

The following examples show how to use org.apache.brooklyn.core.entity.EntityInternal. 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: EntityExecutionManagerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public void testGcDynamicTaskAtNormalTagLimit() throws Exception {
    TestEntity e = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    
    ((BrooklynProperties)app.getManagementContext().getConfig()).put(
        BrooklynGarbageCollector.MAX_TASKS_PER_TAG, 2);

    AtomicBoolean stopCondition = new AtomicBoolean();
    scheduleRecursiveTemporaryTask(stopCondition, e, "foo");
    scheduleRecursiveTemporaryTask(stopCondition, e, "foo");

    for (int count=0; count<5; count++) {
        TaskBuilder<Object> tb = Tasks.builder().displayName("task-"+count).dynamic(true).body(new Runnable() { @Override public void run() {}})
            .tag(ManagementContextInternal.NON_TRANSIENT_TASK_TAG).tag("foo");
        ((EntityInternal)e).getExecutionContext().submit(tb.build()).getUnchecked();
    }

    // Makes sure there's a GC while the transient tasks are running
    forceGc();
    stopCondition.set(true);

    assertTaskMaxCountForEntityEventually(e, 2);
}
 
Example #2
Source File: EntityConfigResource.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void set(String application, String entityToken, String configName, Boolean recurse, Object newValue) {
    final Entity entity = brooklyn().getEntity(application, entityToken);
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) {
        throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'",
                Entitlements.getEntitlementContext().user(), entity);
    }

    ConfigKey ck = findConfig(entity, configName);
    LOG.debug("REST setting config " + configName + " on " + entity + " to " + newValue);
    ((EntityInternal) entity).config().set(ck, TypeCoercions.coerce(newValue, ck.getTypeToken()));
    if (Boolean.TRUE.equals(recurse)) {
        for (Entity e2 : Entities.descendantsWithoutSelf(entity)) {
            ((EntityInternal) e2).config().set(ck, newValue);
        }
    }
}
 
Example #3
Source File: DslParseComponentsTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testEntityReferenceAndAttributeWhenReady() throws Exception {
    app();
    find("one").sensors().set(Attributes.ADDRESS, "1");
    find("two").sensors().set(Attributes.ADDRESS, "2");
    
    Object y1 = parseDslExpression("$brooklyn:formatString(\"%s-%s\", "
        + "parent().attributeWhenReady(\"host.address\"), "
        + "$brooklyn:attributeWhenReady(\"host.address\"))");
    Assert.assertEquals(y1.toString(), "$brooklyn:formatString(\"%s-%s\", "
        + "parent().attributeWhenReady(\"host.address\"), "
        + "attributeWhenReady(\"host.address\"))");
    
    String y2 = Tasks.resolveValue(y1, String.class, ((EntityInternal) find("two")).getExecutionContext());
    Assert.assertEquals(y2.toString(), "1-2");
    
    Object z1 = parseDslExpression("$brooklyn:formatString(\"%s-%s\", "
        + "entity(\"one\").descendant(\"two\").attributeWhenReady(\"host.address\"), "
        + "component(\"two\").entity(entityId()).attributeWhenReady(\"host.address\"))");
    Assert.assertEquals(z1.toString(), "$brooklyn:formatString(\"%s-%s\", "
        + "entity(\"one\").descendant(\"two\").attributeWhenReady(\"host.address\"), "
        + "entity(entityId()).attributeWhenReady(\"host.address\"))");
    
    String z2 = Tasks.resolveValue(z1, String.class, ((EntityInternal) find("one")).getExecutionContext());
    Assert.assertEquals(z2.toString(), "2-1");
}
 
Example #4
Source File: LocationConfigMap.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected ExecutionContext getExecutionContext(BrooklynObject bo) {
    // Support DSL in location config. DSL expects to be resolved in the execution context of an entity.
    // Since there's no location-entity relation try to infer it from the context of the caller.
    Entity contextEntity = BrooklynTaskTags.getTargetOrContextEntity(Tasks.current());
    if (contextEntity != null) {
        return ((EntityInternal)contextEntity).getExecutionContext();
    } else {
        // Known places we get called without entity context:
        // * unmanaging entity and subsequently its location
        // * EntityResource.listTasks(String, String) returning a Task<SshMachineLocation> and calling toString() on the return value
        log.trace("No resolving context found, will use global execution context. Could lead to NPE on DSL resolving.");
        if (bo==null) return null;
        ManagementContext mgmt = ((AbstractLocation)bo).getManagementContext();
        if (mgmt==null) return null;
        return mgmt.getServerExecutionContext();
    }
}
 
Example #5
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 #6
Source File: ConfigKeyDeprecationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups="Broken")
public void testSetAndGetDynamicConfigUsingDeprecatedNameOverwritesExistingValue() throws Exception {
    // Using BasicEntity, which doesn't know about KEY_1
    EntityInternal entity = (EntityInternal) app.addChild(EntitySpec.create(BasicEntity.class));
    
    // Set using strongly typed key
    entity.config().set(KEY_1, "myval");
    assertEquals(entity.config().get(KEY_1), "myval");
    
    // Set using correct string
    entity.config().putAll(ImmutableMap.of("key1", "myval2"));
    assertEquals(entity.config().get(KEY_1), "myval2");
    
    // Set using deprecated name
    entity.config().putAll(ImmutableMap.of("oldKey1", "myval3"));
    assertEquals(entity.config().get(KEY_1), "myval3");
    
    // Set using pseudo-generated strongly typed key with deprecated name
    entity.config().set(ConfigKeys.newConfigKey(Object.class, "oldKey1"), "myval4");
    assertEquals(entity.config().get(KEY_1), "myval4");
}
 
Example #7
Source File: DslYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private static <T> T getConfigEventually(final Entity entity, final ConfigKey<T> configKey) throws Exception {
    // Use an executor, in case config().get() blocks forever, waiting for the config value.
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        Future<T> future = executor.submit(new Callable<T>() {
            public T call() {
                T blockingValue = entity.config().get(configKey);
                Maybe<T> immediateValue = ((EntityInternal)entity).config().getNonBlocking(configKey);
                assertEquals(immediateValue.get(), blockingValue);
                return blockingValue;
            }});
        return future.get(Asserts.DEFAULT_LONG_TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
    } finally {
        executor.shutdownNow();
    }
}
 
Example #8
Source File: EntityConfigResourceTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
    // Deploy an application that we'll use to read the configuration of
    final ApplicationSpec simpleSpec = ApplicationSpec.builder().name("simple-app").
              entities(ImmutableSet.of(new EntitySpec("simple-ent", RestMockSimpleEntity.class.getName(), ImmutableMap.of("install.version", "1.0.0")))).
              locations(ImmutableSet.of("localhost")).
              build();

    startServer();
    Response response = clientDeploy(simpleSpec);
    int status = response.getStatus();
    assertTrue(status >= 200 && status <= 299, "expected HTTP Response of 2xx but got " + status);
    applicationUri = response.getLocation();
    log.debug("Built app: application");
    waitForApplicationToBeRunning(applicationUri);
    
    entity = (EntityInternal) Iterables.find(getManagementContext().getEntityManager().getEntities(), EntityPredicates.displayNameEqualTo("simple-ent"));
}
 
Example #9
Source File: AdjunctResource.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Response destroy(String application, String entityToken, String adjunctId) {
    Entity entity = brooklyn().getEntity(application, entityToken);
    EntityAdjunct adjunct = brooklyn().getAdjunct(entity, adjunctId);

    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.DELETE_ADJUNCT, adjunct)) {
        throw WebResourceUtils.forbidden("User '%s' is not authorized to delete adjuncts '%s'",
                Entitlements.getEntitlementContext().user(), adjunct);
    }

    if (adjunct instanceof Policy) {
        ((Policy)adjunct).suspend();
        entity.policies().remove((Policy) adjunct);
    } else if (adjunct instanceof Enricher) {
        entity.enrichers().remove((Enricher) adjunct);
    } else if (adjunct instanceof Feed) {
        ((Feed)adjunct).suspend();
        ((EntityInternal)entity).feeds().remove((Feed) adjunct);
    } else {
        // shouldn't come here
        throw WebResourceUtils.badRequest("Unexpected adjunct type %s", adjunct);
    }
    
    return Response.status(Response.Status.NO_CONTENT).build();
}
 
Example #10
Source File: TestSensorAndEffectorInitializer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(@SuppressWarnings("deprecation") org.apache.brooklyn.api.entity.EntityLocal entity) {
    Effector<String> eff = Effectors.effector(String.class, EFFECTOR_SAY_HELLO).parameter(String.class, "name").impl(
        new EffectorBody<String>() {
            @Override
            public String call(ConfigBag parameters) {
                Object name = parameters.getStringKey("name");
                entity().sensors().set(Sensors.newStringSensor(SENSOR_LAST_HELLO), Strings.toString(name));
                return helloWord()+" "+name;
            }
        }).build();
    ((EntityInternal)entity).getMutableEntityType().addEffector(eff);
    
    ((EntityInternal)entity).getMutableEntityType().addSensor(Sensors.newStringSensor(SENSOR_HELLO_DEFINED));
    
    AttributeSensor<String> emitted = Sensors.newStringSensor(SENSOR_HELLO_DEFINED_EMITTED);
    ((EntityInternal)entity).getMutableEntityType().addSensor(emitted);
    entity.sensors().set(emitted, "1");
}
 
Example #11
Source File: EntityConfigResource.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void setFromMap(String application, String entityToken, Boolean recurse, Map newValues) {
    final Entity entity = brooklyn().getEntity(application, entityToken);
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) {
        throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'",
                Entitlements.getEntitlementContext().user(), entity);
    }

    if (LOG.isDebugEnabled())
        LOG.debug("REST user " + Entitlements.getEntitlementContext() + " setting configs " + newValues);
    for (Object entry : newValues.entrySet()) {
        String configName = Strings.toString(((Map.Entry) entry).getKey());
        Object newValue = ((Map.Entry) entry).getValue();

        ConfigKey ck = findConfig(entity, configName);
        ((EntityInternal) entity).config().set(ck, TypeCoercions.coerce(newValue, ck.getTypeToken()));
        if (Boolean.TRUE.equals(recurse)) {
            for (Entity e2 : Entities.descendantsWithoutSelf(entity)) {
                ((EntityInternal) e2).config().set(ck, newValue);
            }
        }
    }
}
 
Example #12
Source File: WindowsPerformanceCounterSensors.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(EntityLocal entity) {
    WindowsPerformanceCounterFeed.Builder builder = WindowsPerformanceCounterFeed.builder()
            .period(period)
            .entity(entity);
    for (Map<String, String> sensorConfig : sensors) {
        String name = sensorConfig.get("name");
        String sensorType = sensorConfig.get("sensorType");
        Class<?> clazz;
        try {
            clazz = Strings.isNonEmpty(sensorType)
                    ? ((EntityInternal)entity).getManagementContext().getCatalog().getRootClassLoader().loadClass(sensorType) 
                    : String.class;
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Could not load type "+sensorType+" for sensor "+name, e);
        }
        builder.addSensor(sensorConfig.get("counter"), Sensors.newSensor(clazz, name, sensorConfig.get("description")));
    }
    entity.addFeed(builder.build());
}
 
Example #13
Source File: LocalEntityManager.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void recursively(Entity e, Predicate<EntityInternal> action) {
    Entity otherPreregistered = preRegisteredEntitiesById.get(e.getId());
    if (otherPreregistered!=null) {
        // if something has been pre-registered, prefer it
        // (e.g. if we recursing through children, we might have a proxy from previous iteration;
        // the most recent will have been pre-registered)
        e = otherPreregistered;
    }
        
    boolean success = action.apply( (EntityInternal)e );
    if (!success) {
        return; // Don't manage children if action false/unnecessary for parent
    }
    for (Entity child : e.getChildren()) {
        recursively(child, action);
    }
}
 
Example #14
Source File: ServiceStateLogic.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private static void waitBrieflyForServiceUpIfStateIsRunning(Entity entity, Lifecycle state) {
    if (state==Lifecycle.RUNNING) {
        Boolean up = ((EntityInternal)entity).getAttribute(Attributes.SERVICE_UP);
        if (!Boolean.TRUE.equals(up) && !Boolean.TRUE.equals(Entities.isReadOnly(entity))) {
            // pause briefly to allow any recent problem-clearing processing to complete
            Stopwatch timer = Stopwatch.createStarted();
            boolean nowUp = Repeater.create()
                    .every(ValueResolver.REAL_QUICK_PERIOD)
                    .limitTimeTo(ValueResolver.PRETTY_QUICK_WAIT)
                    .until(entity, EntityPredicates.attributeEqualTo(Attributes.SERVICE_UP, true))
                    .run();
            if (nowUp) {
                log.debug("Had to wait "+Duration.of(timer)+" for "+entity+" "+Attributes.SERVICE_UP+" to be true before setting "+state);
            } else {
                log.warn("Service is not up when setting "+state+" on "+entity+"; delayed "+Duration.of(timer)+" "
                        + "but "+Attributes.SERVICE_UP+" did not recover from "+up+"; not-up-indicators="+entity.getAttribute(Attributes.SERVICE_NOT_UP_INDICATORS));
            }
        }
    }
}
 
Example #15
Source File: BrooklynEntityMirrorIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")
public void testServiceMirroring() throws Exception {
    setUpServer();
    
    String catalogItemId = "test-catalog-item:1.0";
    String catalogItemIdGA = "test-catalog-item:1.0-GA";
    serverApp.sensors().set(TestApplication.MY_ATTRIBUTE, "austria");
    serverApp.setCatalogItemId(catalogItemId);

    String serviceId = serverApp.getId();
    Entity mirror = localApp.addChild(EntitySpec.create(BrooklynEntityMirror.class)
        .configure(BrooklynEntityMirror.POLL_PERIOD, Duration.millis(100))
        .configure(BrooklynEntityMirror.MIRRORED_ENTITY_ID, serviceId)
        .configure(BrooklynEntityMirror.MIRRORED_ENTITY_URL, 
            getBaseUri()+"/v1/applications/"+serviceId+"/entities/"+serviceId)
    );

    EntityAsserts.assertAttributeEqualsEventually(mirror, TestApplication.MY_ATTRIBUTE, "austria");
    EntityAsserts.assertAttributeEqualsEventually(mirror, BrooklynEntityMirror.MIRROR_CATALOG_ITEM_ID, catalogItemId);
    assertTrue(mirror.getAttribute(BrooklynEntityMirror.MIRROR_SUMMARY) != null, "entity summary is null");
    log.info("Sensors mirrored are: "+((EntityInternal)mirror).sensors().getAll());
    
    serverApp.sensors().set(TestApplication.MY_ATTRIBUTE, "bermuda");
    serverApp.setCatalogItemId(catalogItemIdGA);
    EntityAsserts.assertAttributeEqualsEventually(mirror, TestApplication.MY_ATTRIBUTE, "bermuda");
    EntityAsserts.assertAttributeEqualsEventually(mirror, BrooklynEntityMirror.MIRROR_CATALOG_ITEM_ID, catalogItemIdGA);

    serverApp.stop();
    assertUnmanagedEventually(mirror);
}
 
Example #16
Source File: AbstractControllerImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public static <K, V> V put(Entity entity, AttributeSensor<Map<K,V>> attribute, K key, V value) {
    Map<K, V> oldMap = entity.getAttribute(attribute);
    Map<K, V> newMap = MutableMap.copyOf(oldMap);
    V oldVal = newMap.put(key, value);
    ((EntityInternal)entity).sensors().set(attribute, newMap);
    return oldVal;
}
 
Example #17
Source File: BrooklynEntityMirrorIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")
public void testServiceMirroringHttps() throws Exception {
    LocalManagementContextForTests mgmtHttps = new LocalManagementContextForTests();
    mgmtHttps.getBrooklynProperties().put("brooklyn.webconsole.security.https.required", true);
    mgmtHttps.getBrooklynProperties().put("brooklyn.webconsole.security.users", "admin");
    mgmtHttps.getBrooklynProperties().put("brooklyn.webconsole.security.user.admin.password", "P5ssW0rd");

    setUpServer(mgmtHttps, false);
    Assert.assertTrue(getBaseUri().startsWith("https:"), "URL is not https: "+getBaseUri());
    // check auth is required
    HttpTestUtils.assertHttpStatusCodeEquals(getBaseUri(), 401);
    
    serverApp.sensors().set(TestApplication.MY_ATTRIBUTE, "austria");

    String serviceId = serverApp.getId();
    Entity mirror = localApp.addChild(EntitySpec.create(BrooklynEntityMirror.class)
        .configure(BrooklynEntityMirror.POLL_PERIOD, Duration.millis(100))
        .configure(BrooklynEntityMirror.MANAGEMENT_USER, "admin")
        .configure(BrooklynEntityMirror.MANAGEMENT_PASSWORD, "P5ssW0rd")
        .configure(BrooklynEntityMirror.MIRRORED_ENTITY_ID, serviceId)
        .configure(BrooklynEntityMirror.MIRRORED_ENTITY_URL, 
            getBaseUri()+"/v1/applications/"+serviceId+"/entities/"+serviceId)
    );

    EntityAsserts.assertAttributeEqualsEventually(mirror, TestApplication.MY_ATTRIBUTE, "austria");
    log.info("Sensors mirrored are: "+((EntityInternal)mirror).sensors().getAll());
    
    serverApp.sensors().set(TestApplication.MY_ATTRIBUTE, "bermuda");
    EntityAsserts.assertAttributeEqualsEventually(mirror, TestApplication.MY_ATTRIBUTE, "bermuda");

    serverApp.stop();
    assertUnmanagedEventually(mirror);
}
 
Example #18
Source File: JmxSupport.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public String getJmxAgentJarDestinationFilePath() {
    // cache the local path so we continue to work post-rebind to a different version
    String result = getEntity().getAttribute(JMX_AGENT_LOCAL_PATH);
    if (Strings.isNonBlank(result)) return result;
    result = getJmxAgentJarDestinationFilePathDefault();
    ((EntityInternal)getEntity()).sensors().set(JMX_AGENT_LOCAL_PATH, result);
    return result;
}
 
Example #19
Source File: BrooklynTaskTags.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static ExecutionContext getExecutionContext(Collection<?> tags) {
    EntityAdjunct ea = getUnwrappedObjectTagOfType(tags, CONTEXT_ADJUNCT, EntityAdjunct.class);
    if (ea instanceof AbstractEntityAdjunct) {
        return ((AbstractEntityAdjunct)ea).getExecutionContext();
    }
    Entity e = getWrappedEntityOfType(tags, CONTEXT_ENTITY);
    if (e==null) e= getWrappedEntityOfType(tags, TARGET_ENTITY);
    if (e instanceof EntityInternal) {
        return ((EntityInternal)e).getExecutionContext();
    }
    
    return null;
}
 
Example #20
Source File: EnrichersYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void checkReferences(final Enricher enricher, Map<ConfigKey<Entity>, Entity> keyToEntity) throws Exception {
    for (final ConfigKey<Entity> key : keyToEntity.keySet()) {
        final Entity entity = keyToEntity.get(key); // Grab an entity whose execution context we can use
        Entity fromConfig = ((EntityInternal)entity).getExecutionContext().submit(MutableMap.of(), new Callable<Entity>() {
            @Override
            public Entity call() throws Exception {
                return enricher.getConfig(key);
            }
        }).get();
        Assert.assertEquals(fromConfig, keyToEntity.get(key));
    }
}
 
Example #21
Source File: NginxSshDriver.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public void postLaunch() {
    entity.sensors().set(NginxController.PID_FILE, getRunDir() + "/" + AbstractSoftwareProcessSshDriver.PID_FILENAME);
    if (((AbstractController)entity).isSsl()) {
        entity.sensors().set(Attributes.HTTPS_PORT, getPort());
        ((EntityInternal)entity).sensors().remove(Attributes.HTTP_PORT);
    } else {
        entity.sensors().set(Attributes.HTTP_PORT, getPort());
        ((EntityInternal)entity).sensors().remove(Attributes.HTTPS_PORT);
    }
    super.postLaunch();
}
 
Example #22
Source File: AbstractControllerImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public static <K, V> V remove(Entity entity, AttributeSensor<Map<K,V>> attribute, K key) {
    Map<K, V> oldMap = entity.getAttribute(attribute);
    Map<K, V> newMap = MutableMap.copyOf(oldMap);
    V oldVal = newMap.remove(key);
    ((EntityInternal)entity).sensors().set(attribute, newMap);
    return oldVal;
}
 
Example #23
Source File: BrooklynRestResourceUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public Task<?> destroy(final Application application) {
    return mgmt.getExecutionManager().submit(
            MutableMap.of("displayName", "destroying "+application,
                    "description", "REST call to destroy application "+application.getDisplayName()+" ("+application+")"),
            new Runnable() {
        @Override
        public void run() {
            ((EntityInternal)application).destroy();
            mgmt.getEntityManager().unmanage(application);
        }
    });
}
 
Example #24
Source File: AbstractManagementContext.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends BrooklynObject> Collection<T> lookupAll(Predicate<? super T> filter, boolean justOne) {
    List<T> result = MutableList.of();

    final class Scanner {
        public boolean scan(Iterable<? extends BrooklynObject> items) {
            for (BrooklynObject i: items) {
                try {
                    if (filter.apply((T)i)) {
                        result.add((T)i);
                        if (justOne) return true;
                    }
                } catch (Exception exc) {
                    Exceptions.propagateIfFatal(exc);
                    // just assume filter isn't for this type, class cast
                    return false;
                }
            }
            return false;
        }
    }
    Scanner scanner = new Scanner();
    if (scanner.scan( getEntityManager().getEntities() ) && justOne) return result;
    if (scanner.scan( getLocationManager().getLocations() ) && justOne) return result;
    for (Entity e: getEntityManager().getEntities()) {
        if (scanner.scan( e.policies() ) && justOne) return result;
        if (scanner.scan( e.enrichers() ) && justOne) return result;
        if (scanner.scan( ((EntityInternal)e).feeds() ) && justOne) return result;
    }
    
    return result;
}
 
Example #25
Source File: ConfigNestedYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void checkTemplates(EntityInternal ent) {
    Map<String, Object> substitutions = MutableMap.copyOf(ent.config().get(SoftwareProcess.TEMPLATE_SUBSTITUTIONS)).asUnmodifiable();
    String out0 = TemplateProcessor.processTemplateContents("hello "+"${field}", substitutions);
    Assert.assertEquals(out0, "hello val");
    
    String out1 = TemplateProcessor.processTemplateContents("hello "+"${config['template.substitutions']['field']}", ent, substitutions);
    Assert.assertEquals(out1, "hello val");
}
 
Example #26
Source File: EntityExecutionManagerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void assertTaskMaxCountForEntityEventually(final Entity entity, final int expectedMaxCount) {
    // Dead task (and initialization task) should have been GC'd on completion.
    // However, the GC'ing happens in a listener, executed in a different thread - the task.get()
    // doesn't block for it. Therefore can't always guarantee it will be GC'ed by now.
    Asserts.succeedsEventually(new Runnable() {
        @Override public void run() {
            forceGc();
            Collection<Task<?>> tasks = removeSystemTasks( BrooklynTaskTags.getTasksInEntityContext(((EntityInternal)entity).getManagementContext().getExecutionManager(), entity) );
            Assert.assertTrue(tasks.size() <= expectedMaxCount,
                    "Expected tasks count max of " + expectedMaxCount + ". Tasks were "+tasks);
        }});
}
 
Example #27
Source File: SensorResourceTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
static void addAmphibianSensor(EntityInternal entity) {
    // Add new sensor
    entity.getMutableEntityType().addSensor(SENSOR);
    entity.sensors().set(SENSOR, 12345);

    // Register display value hint
    RendererHints.register(SENSOR, RendererHints.displayValue(Functions.compose(StringFunctions.append(" frogs"), Functions.toStringFunction())));
}
 
Example #28
Source File: ElectPrimaryPolicy.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void checkAndMaybeAddEffector(@SuppressWarnings("deprecation") org.apache.brooklyn.api.entity.EntityLocal entity) {
    String effName = config().get(EFFECTOR_NAME);
    if (((EntityInternal)entity).getEffector(effName)==null) {
        // effector not defined
        if (config().getRaw(EFFECTOR_NAME).isAbsent()) {
            log.debug("No effector '"+effName+"' present at "+entity+"; creating default");
            // if not set, we can create the default
            new ElectPrimaryEffector(config().getBag()).apply(entity);
            
        } else {
            // otherwise it's an error, fail
            throw new IllegalStateException("No such effector '"+effName+"' on "+entity);
        }
    }
}
 
Example #29
Source File: MapConfigKeyAndFriendsDeprecationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeprecatedKeyNotReinheritedIfNotSupposedToBe() throws Exception {
    EntityInternal entity = app.addChild(EntitySpec.create(MyEntity.class)
            .configure("oldConfMapNotReinherited", ImmutableMap.of("mykey", "myval")));
    EntityInternal child = entity.addChild(EntitySpec.create(MyEntity.class));
    assertEquals(entity.config().get(MyEntity.CONF_MAP_NOT_REINHERITED), ImmutableMap.of("mykey", "myval"));
    assertEquals(child.config().get(MyEntity.CONF_MAP_NOT_REINHERITED), null);
}
 
Example #30
Source File: ClassLoaderCacheTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testSameLoader() throws Exception {
    Class<BasicEntityImpl> clazz = BasicEntityImpl.class;
    ImmutableSet<Class<? extends Object>> interfaces = ImmutableSet.of(EntityProxy.class, Entity.class, EntityInternal.class, BasicEntity.class);
    
    AggregateClassLoader loader = cache.getClassLoaderForProxy(clazz, interfaces);
    assertLoader(loader, Iterables.concat(ImmutableList.of(clazz), interfaces));
    
    AggregateClassLoader loader2 = cache.getClassLoaderForProxy(clazz, interfaces);
    assertSame(loader, loader2);
}