Java Code Examples for org.apache.brooklyn.api.entity.EntitySpec#create()

The following examples show how to use org.apache.brooklyn.api.entity.EntitySpec#create() . 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: MySqlClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
private EntitySpec<?> applyDefaults(EntitySpec<?> spec, Supplier<Integer> serverId, String configUrl) {
    boolean needsServerId = !isKeyConfigured(spec, MySqlNode.MYSQL_SERVER_ID);
    boolean needsConfigUrl = !isKeyConfigured(spec, MySqlNode.TEMPLATE_CONFIGURATION_URL.getConfigKey());
    if (needsServerId || needsConfigUrl) {
        EntitySpec<?> clonedSpec = EntitySpec.create(spec);
        if (needsServerId) {
            clonedSpec.configure(MySqlNode.MYSQL_SERVER_ID, serverId.get());
        }
        if (needsConfigUrl) {
            clonedSpec.configure(MySqlNode.TEMPLATE_CONFIGURATION_URL, configUrl);
        }
        return clonedSpec;
    } else {
        return spec;
    }
}
 
Example 2
Source File: InfrastructureDeploymentTestCaseTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testInfrastrucutreHasNoLocation() {
    EntitySpec<TestInfrastructure> infrastructureSpec = EntitySpec.create(TestInfrastructure.class);

    List<EntitySpec<? extends Startable>> testSpecs = ImmutableList.<EntitySpec<? extends Startable>>of(EntitySpec.create(BasicApplication.class));

    InfrastructureDeploymentTestCase infrastructureDeploymentTestCase = app.createAndManageChild(EntitySpec.create(InfrastructureDeploymentTestCase.class));
    infrastructureDeploymentTestCase.config().set(InfrastructureDeploymentTestCase.INFRASTRUCTURE_SPEC, infrastructureSpec);
    infrastructureDeploymentTestCase.config().set(InfrastructureDeploymentTestCase.ENTITY_SPEC_TO_DEPLOY, testSpecs);
    infrastructureDeploymentTestCase.config().set(InfrastructureDeploymentTestCase.DEPLOYMENT_LOCATION_SENSOR_NAME, DEPLOYMENT_LOCATION_SENSOR.getName());

    try {
        app.start(ImmutableList.of(app.newSimulatedLocation()));
        Asserts.shouldHaveFailedPreviously();
    } catch (Throwable throwable) {
        Asserts.expectedFailure(throwable);
    }

    assertThat(infrastructureDeploymentTestCase.sensors().get(SERVICE_UP)).isFalse();
}
 
Example 3
Source File: DeployBlueprintTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartsAppViaEffector() throws Exception {
    URI webConsoleUri = URI.create(ENDPOINT_ADDRESS_HTTP); // BrooklynNode will append "/v1" to it

    EntitySpec<BrooklynNode> spec = EntitySpec.create(BrooklynNode.class);
    EntityManager mgr = getManagementContext().getEntityManager(); // getManagementContextFromJettyServerAttributes(server).getEntityManager();
    BrooklynNode node = mgr.createEntity(spec);
    node.sensors().set(BrooklynNode.WEB_CONSOLE_URI, webConsoleUri);
    mgr.manage(node);
    Map<String, String> params = ImmutableMap.of(DeployBlueprintEffector.BLUEPRINT_CAMP_PLAN.getName(), "{ services: [ serviceType: \"java:"+BasicApplication.class.getName()+"\" ] }");
    String id = node.invoke(BrooklynNode.DEPLOY_BLUEPRINT, params).getUnchecked();

    log.info("got: "+id);

    String apps = HttpTool.getContent(getEndpointAddress() + "/applications");
    List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class);
    assertEquals(appType, ImmutableList.of(BasicApplication.class.getName()));

    String status = HttpTool.getContent(getEndpointAddress()+"/applications/"+id+"/entities/"+id+"/sensors/service.status");
    log.info("STATUS: "+status);
}
 
Example 4
Source File: UrlMappingTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@BeforeMethod(alwaysRun=true)
@Override
public void setUp() throws Exception {
    super.setUp();
    
    EntitySpec<StubAppServer> serverSpec = EntitySpec.create(StubAppServer.class);
    cluster = app().createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure(DynamicCluster.INITIAL_SIZE, initialClusterSize)
            .configure(DynamicCluster.MEMBER_SPEC, serverSpec));

    urlMapping = app().createAndManageChild(EntitySpec.create(UrlMapping.class)
            .configure("domain", "localhost")
            .configure("target", cluster));

    app().start( ImmutableList.of(
            mgmt().getLocationManager().createLocation(
                    LocationSpec.create(LocalhostMachineProvisioningLocation.class))
            ));
    log.info("app's location managed: "+mgmt().getLocationManager().isManaged(Iterables.getOnlyElement(app().getLocations())));
    log.info("clusters's location managed: "+mgmt().getLocationManager().isManaged(Iterables.getOnlyElement(cluster.getLocations())));
}
 
Example 5
Source File: HazelcastClusterImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
protected EntitySpec<?> getMemberSpec() {
    EntitySpec<?> spec = EntitySpec.create(config().get(HazelcastCluster.MEMBER_SPEC));
    
    spec.configure(HazelcastNode.NODE_CLUSTER_NAME, config().get(HazelcastCluster.CLUSTER_NAME));
    spec.configure(HazelcastNode.GROUP_NAME, config().get(HazelcastCluster.CLUSTER_NAME));
    
    if (LOG.isInfoEnabled()) {
        LOG.info("Cluster name : {} : used as a group name", getConfig(HazelcastNode.GROUP_NAME));
    }
    
    spec.configure(HazelcastNode.GROUP_PASSWORD, getClusterPassword());
    
    return spec;
}
 
Example 6
Source File: InfrastructureDeploymentTestCaseTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleSpec() {
    EntitySpec<TestInfrastructure> infrastructureSpec = EntitySpec.create(TestInfrastructure.class);
    infrastructureSpec.configure(DEPLOYMENT_LOCATION_SENSOR, infrastructureLoc);

    List<EntitySpec<? extends Startable>> testSpecs = ImmutableList.<EntitySpec<? extends Startable>>of
            (EntitySpec.create(BasicApplication.class),
                    (EntitySpec.create(BasicApplication.class)));

    InfrastructureDeploymentTestCase infrastructureDeploymentTestCase = app.createAndManageChild(EntitySpec.create(InfrastructureDeploymentTestCase.class));
    infrastructureDeploymentTestCase.config().set(InfrastructureDeploymentTestCase.INFRASTRUCTURE_SPEC, infrastructureSpec);
    infrastructureDeploymentTestCase.config().set(InfrastructureDeploymentTestCase.ENTITY_SPEC_TO_DEPLOY, testSpecs);
    infrastructureDeploymentTestCase.config().set(InfrastructureDeploymentTestCase.DEPLOYMENT_LOCATION_SENSOR_NAME, DEPLOYMENT_LOCATION_SENSOR.getName());

    app.start(ImmutableList.of(loc));

    assertThat(infrastructureDeploymentTestCase.sensors().get(SERVICE_UP)).isTrue();
    assertThat(infrastructureDeploymentTestCase.getChildren().size()).isEqualTo(3);

    boolean seenInfrastructure = false;
    int entitiesSeen = 0;

    for (Entity entity : infrastructureDeploymentTestCase.getChildren()) {
        assertThat(entity.sensors().get(SERVICE_UP)).isTrue();
        assertThat(entity.getLocations().size()).isEqualTo(1);

        if (entity instanceof TestInfrastructure && !seenInfrastructure) {
            assertThat(entity.getLocations().iterator().next().getDisplayName()).isEqualTo(LOC_NAME);
            seenInfrastructure = true;
        } else if (entity instanceof BasicApplication) {
            assertThat(entity.getLocations().iterator().next().getDisplayName()).isEqualTo(INFRASTRUCTURE_LOC_NAME);
            entitiesSeen++;
        } else {
            fail("Unknown child of InfrastructureDeploymentTestCase");
        }
    }

    assertThat(seenInfrastructure).isTrue();
    assertThat(entitiesSeen).isEqualTo(2);
}
 
Example 7
Source File: EntitySpecTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatingEntitySpecFromSpecCreatesDuplicate() {
    EntitySpec<TestEntity> originalChildSpec = EntitySpec.create(TestEntity.class);
    EntitySpec<TestEntity> originalEntitySpec = EntitySpec.create(TestEntity.class).child(originalChildSpec);
    EntitySpec<TestEntity> duplicateEntitySpec = EntitySpec.create(originalEntitySpec);
    EntitySpec<?> duplicateChildSpec = duplicateEntitySpec.getChildren().get(0);

    assertEquals(originalEntitySpec, duplicateEntitySpec);
    assertTrue(originalEntitySpec != duplicateEntitySpec);
    assertEquals(originalChildSpec, duplicateChildSpec);
    assertTrue(originalChildSpec != duplicateChildSpec);
}
 
Example 8
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 9
Source File: InfrastructureDeploymentTestCaseTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testVanilla() {
    EntitySpec<TestInfrastructure> infrastructureSpec = EntitySpec.create(TestInfrastructure.class);
    infrastructureSpec.configure(DEPLOYMENT_LOCATION_SENSOR, infrastructureLoc);

    List<EntitySpec<? extends Startable>> testSpecs = ImmutableList.<EntitySpec<? extends Startable>>of(EntitySpec.create(BasicApplication.class));

    InfrastructureDeploymentTestCase infrastructureDeploymentTestCase = app.createAndManageChild(EntitySpec.create(InfrastructureDeploymentTestCase.class));
    infrastructureDeploymentTestCase.config().set(InfrastructureDeploymentTestCase.INFRASTRUCTURE_SPEC, infrastructureSpec);
    infrastructureDeploymentTestCase.config().set(InfrastructureDeploymentTestCase.ENTITY_SPEC_TO_DEPLOY, testSpecs);
    infrastructureDeploymentTestCase.config().set(InfrastructureDeploymentTestCase.DEPLOYMENT_LOCATION_SENSOR_NAME, DEPLOYMENT_LOCATION_SENSOR.getName());

    app.start(ImmutableList.of(loc));

    assertThat(infrastructureDeploymentTestCase.sensors().get(SERVICE_UP)).isTrue();
    assertThat(infrastructureDeploymentTestCase.getChildren().size()).isEqualTo(2);

    boolean seenInfrastructure = false;
    boolean seenEntity = false;

    for (Entity entity : infrastructureDeploymentTestCase.getChildren()) {
        assertThat(entity.getLocations().size()).isEqualTo(1);
        assertThat(entity.sensors().get(SERVICE_UP)).isTrue();

        if (entity instanceof TestInfrastructure  && !seenInfrastructure) {
            assertThat(entity.getLocations().iterator().next().getDisplayName()).isEqualTo(LOC_NAME);
            seenInfrastructure = true;
        } else if (entity instanceof BasicApplication){
            assertThat(entity.getLocations().iterator().next().getDisplayName()).isEqualTo(INFRASTRUCTURE_LOC_NAME);
            seenEntity = true;
        } else {
            fail("Unknown child of InfrastructureDeploymentTestCase");
        }
    }

    assertThat(seenInfrastructure).isTrue();
    assertThat(seenEntity).isTrue();
}
 
Example 10
Source File: BrooklynClusterUpgradeEffectorBody.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Void call(ConfigBag parameters) {
    if (!upgradeInProgress.compareAndSet(false, true)) {
        throw new IllegalStateException("An upgrade is already in progress.");
    }

    EntitySpec<?> origMemberSpec = entity().getConfig(BrooklynCluster.MEMBER_SPEC);
    Preconditions.checkNotNull(origMemberSpec, BrooklynCluster.MEMBER_SPEC.getName() + " is required for " + UpgradeClusterEffector.class.getName());

    log.debug("Upgrading "+entity()+", changing "+BrooklynCluster.MEMBER_SPEC+" from "+origMemberSpec+" / "+origMemberSpec.getConfig());

    boolean success = false;
    try {
        String newDownloadUrl = parameters.get(DOWNLOAD_URL);
        
        EntitySpec<?> newMemberSpec = EntitySpec.create(origMemberSpec);
        
        ConfigBag newConfig = ConfigBag.newInstance();
        newConfig.putIfNotNull(DOWNLOAD_URL, newDownloadUrl);
        newConfig.put(BrooklynNode.DISTRO_UPLOAD_URL, inferUploadUrl(newDownloadUrl));
        newConfig.putAll(ConfigBag.newInstance(parameters.get(EXTRA_CONFIG)).getAllConfigAsConfigKeyMap());
        newMemberSpec.configure(newConfig.getAllConfigAsConfigKeyMap());
        
        entity().config().set(BrooklynCluster.MEMBER_SPEC, newMemberSpec);
        
        log.debug("Upgrading "+entity()+", new "+BrooklynCluster.MEMBER_SPEC+": "+newMemberSpec+" / "+newMemberSpec.getConfig()+" (adding: "+newConfig+")");
        
        upgrade(parameters);

        success = true;
    } finally {
        if (!success) {
            log.debug("Upgrading "+entity()+" failed, will rethrow after restoring "+BrooklynCluster.MEMBER_SPEC+" to: "+origMemberSpec);
            entity().config().set(BrooklynCluster.MEMBER_SPEC, origMemberSpec);
        }
        
        upgradeInProgress.set(false);
    }
    return null;
}
 
Example 11
Source File: WebAppConcurrentDeployTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@DataProvider(name = "basicEntities")
public Object[][] basicEntities() {
    return new Object[][]{
        {EntitySpec.create(TomcatServer.class)},
        // Hot Deploy not enabled?
        // {EntitySpec.create(JBoss6Server.class)},
        {EntitySpec.create(JBoss7Server.class)},
    };
}
 
Example 12
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 13
Source File: ApplicationLoggingTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUpApp() {
    LOG.info("setUpApp");
    EntitySpec<TestApplicationWithLogging> appSpec = EntitySpec.create(TestApplicationWithLogging.class);
    if (shouldSkipOnBoxBaseDirResolution()!=null)
        appSpec.configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, shouldSkipOnBoxBaseDirResolution());

    app = mgmt.getEntityManager().createEntity(appSpec);
}
 
Example 14
Source File: SoftwareProcessEntityTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test
public void testDoubleStopApp() {
    ReflectiveEntityDriverFactory f = ((BasicEntityDriverManager)mgmt.getEntityDriverManager()).getReflectiveDriverFactory();
    f.addClassFullNameMapping(EmptySoftwareProcessDriver.class.getName(), MinimalEmptySoftwareProcessTestDriver.class.getName());

    // Second stop on SoftwareProcess will return early, while the first stop is still in progress
    // This causes the app to shutdown prematurely, leaking machines.
    EntityManager emgr = mgmt.getEntityManager();
    EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class);
    final TestApplication app = emgr.createEntity(appSpec);
    emgr.manage(app);
    EntitySpec<?> latchEntitySpec = EntitySpec.create(EmptySoftwareProcess.class);
    final Entity entity = app.createAndManageChild(latchEntitySpec);

    final ReleaseLatchLocation loc = mgmt.getLocationManager().createLocation(LocationSpec.create(ReleaseLatchLocation.class));
    try {
        app.start(ImmutableSet.of(loc));
        EntityAsserts.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);

        final Task<Void> firstStop = app.invoke(Startable.STOP, ImmutableMap.<String, Object>of());
        // Wait until first task tries to release the location, at this point the entity's reference 
        // to the location is already cleared.
        Asserts.succeedsEventually(new Runnable() {
            @Override
            public void run() {
                assertTrue(loc.isBlocked());
            }
        });

        // Subsequent stops will end quickly - no location to release,
        // while the first one is still releasing the machine.
        final Task<Void> secondStop = app.invoke(Startable.STOP, ImmutableMap.<String, Object>of());;
        Asserts.succeedsEventually(new Runnable() {
            @Override
            public void run() {
                assertTrue(secondStop.isDone());
            }
        });

        // Since second stop succeeded the app will get unmanaged.
        Asserts.succeedsEventually(new Runnable() {
            @Override
            public void run() {
                assertTrue(!Entities.isManaged(entity));
                assertTrue(!Entities.isManaged(app));
            }
        });

        // Unmanage will cancel the first task
        Asserts.succeedsEventually(new Runnable() {
            @Override
            public void run() {
                assertTrue(firstStop.isDone());
            }
        });
    } finally {
        // We still haven't unblocked the location release, but entity is already unmanaged.
        // Double STOP on an application could leak locations!!!
        loc.unblock();
    }
}
 
Example 15
Source File: PostgreSqlSpecs.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
/** Requires {@code knife}. */
public static EntitySpec<PostgreSqlNode> specChef() {
    EntitySpec<PostgreSqlNode> spec = EntitySpec.create(PostgreSqlNode.class, PostgreSqlNodeChefImplFromScratch.class);
    spec.configure(ChefConfig.CHEF_MODE, ChefModes.KNIFE);
    return spec;
}
 
Example 16
Source File: VanillaSoftwareProcessTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test(groups = "Integration")
public void testVanillaSoftwareProcessCanUseResourcesInBundles() throws Exception {
    try {
        new ResourceUtils(this).getResourceAsString("classpath://org/apache/brooklyn/test/osgi/resources/message.txt");
        fail("classpath://org/apache/brooklyn/test/osgi/resources/message.txt should not be on classpath");
    } catch (Exception e) {/* expected */}
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), "/brooklyn/osgi/brooklyn-test-osgi-entities.jar");

    final String catalogItemUrl = "classpath://vanilla-software-process-with-resource.yaml";
    final String catalogYaml = ResourceUtils.create(this)
            .getResourceAsString(catalogItemUrl);

    final URI webConsoleUri = URI.create(getBaseUriRest(server));

    // Test setup
    final EntitySpec<BrooklynNode> spec = EntitySpec.create(BrooklynNode.class);
    final ManagementContext mgmt = getManagementContextFromJettyServerAttributes(server);
    final BrooklynNode node = mgmt.getEntityManager().createEntity(spec);
    node.sensors().set(BrooklynNode.WEB_CONSOLE_URI, webConsoleUri);

    // Add catalogue item.
    HttpToolResponse response = node.http().post(
            "/catalog",
            ImmutableMap.<String, String>of("Content-type", "application/yaml"),
            catalogYaml.getBytes());
    HttpAsserts.assertHealthyStatusCode(response.getResponseCode());

    // Deploy it.
    final String blueprint = "location: localhost\n" +
            "services:\n" +
            "- type: vanilla-software-resource-test:1.0";
    response = node.http().post(
            "/applications",
            ImmutableMap.of("Content-Type", "text/yaml"),
            blueprint.getBytes());
    HttpAsserts.assertHealthyStatusCode(response.getResponseCode());

    // Assert application is eventually running and not on fire.
    final Entity vanilla = mgmt.getApplications().iterator().next().getChildren().iterator().next();
    assertTrue(vanilla instanceof VanillaSoftwareProcess,
            "expected " + VanillaSoftwareProcess.class.getName() + ", found: " + vanilla);
    EntityAsserts.assertAttributeEqualsEventually(vanilla, SoftwareProcess.SERVICE_UP, true);

    // And check that the message was copied to rundir.
    SshMachineLocation machine = Machines.findUniqueMachineLocation(vanilla.getLocations(), SshMachineLocation.class).get();
    String file = Os.mergePaths(vanilla.sensors().get(SoftwareProcess.RUN_DIR), "message.txt");
    String message = Entities.submit(vanilla, SshTasks.newSshFetchTaskFactory(machine, file).newTask()).get();
    assertNotNull(message);
    assertTrue(message.startsWith("Licensed to the Apache Software Foundation"),
            "expected ASF license header, found: " + message);

}
 
Example 17
Source File: Tomcat8ServerRestartIntegrationTest.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
@Override
protected EntitySpec<? extends SoftwareProcess> newEntitySpec() {
    return EntitySpec.create(Tomcat8Server.class);
}
 
Example 18
Source File: ServerShutdownTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test
public void testStopAppThenShutdownAndStopAppsWaitsForFirstStop() throws InterruptedException {
    ReflectiveEntityDriverFactory f = ((BasicEntityDriverManager)getManagementContext().getEntityDriverManager()).getReflectiveDriverFactory();
    f.addClassFullNameMapping("org.apache.brooklyn.entity.software.base.EmptySoftwareProcessDriver", "org.apache.brooklyn.rest.resources.ServerResourceTest$EmptySoftwareProcessTestDriver");

    // Second stop on SoftwareProcess could return early, while the first stop is still in progress
    // This causes the app to shutdown prematurely, leaking machines.
    EntityManager emgr = getManagementContext().getEntityManager();
    EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class);
    TestApplication app = emgr.createEntity(appSpec);
    EntitySpec<StopLatchEntity> latchEntitySpec = EntitySpec.create(StopLatchEntity.class);
    final StopLatchEntity entity = app.createAndManageChild(latchEntitySpec);
    app.start(ImmutableSet.of(app.newLocalhostProvisioningLocation()));
    EntityAsserts.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);

    try {
        final Task<Void> firstStop = app.invoke(Startable.STOP, ImmutableMap.<String, Object>of());
        Asserts.succeedsEventually(new Runnable() {
            @Override
            public void run() {
                assertTrue(entity.isBlocked());
            }
        });

        final AtomicReference<Exception> shutdownError = new AtomicReference<>();
        // Can't use ExecutionContext as it will be stopped on shutdown
        Thread shutdownThread = new Thread() {
            @Override
            public void run() {
                try {
                    MultivaluedMap<String, String> formData = new MultivaluedHashMap<>();
                    formData.add("stopAppsFirst", "true");
                    formData.add("shutdownTimeout", "0");
                    formData.add("requestTimeout", "0");
                    formData.add("delayForHttpReturn", "0");
                    client().path("/server/shutdown").type(MediaType.APPLICATION_FORM_URLENCODED).post(formData);
                } catch (Exception e) {
                    log.error("Shutdown request error", e);
                    shutdownError.set(e);
                    throw Exceptions.propagate(e);
                }
            }
        };
        shutdownThread.start();

        //shutdown must wait until the first stop completes (or time out)
        Asserts.succeedsContinually(new Runnable() {
            @Override
            public void run() {
                assertFalse(firstStop.isDone());
                assertEquals(getManagementContext().getApplications().size(), 1);
                assertFalse(shutdownListener.isRequested());
            }
        });

        // NOTE test is not fully deterministic. Depending on thread scheduling this will
        // execute before or after ServerResource.shutdown does the app stop loop. This
        // means that the shutdown code might not see the app at all. In any case though
        // the test must succeed.
        entity.unblock();

        Asserts.succeedsEventually(new Runnable() {
            @Override
            public void run() {
                assertTrue(firstStop.isDone());
                assertTrue(shutdownListener.isRequested());
                assertFalse(getManagementContext().isRunning());
            }
        });

        shutdownThread.join();
        assertNull(shutdownError.get(), "Shutdown request error, logged above");
    } finally {
        // Be sure we always unblock entity stop even in the case of an exception.
        // In the success path the entity is already unblocked above.
        entity.unblock();
    }
}
 
Example 19
Source File: InternalEntityFactoryTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test
public void testSetsEntityId() throws Exception {
    EntitySpec<TestApplication> spec = EntitySpec.create(TestApplication.class);
    TestApplication app = factory.createEntity(spec, Optional.of("myentityid"));
    assertEquals(app.getId(), "myentityid");
}
 
Example 20
Source File: XmlMementoSerializerTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test
public void testEntitySpec() throws Exception {
    EntitySpec<?> obj = EntitySpec.create(TestEntity.class);
    assertSerializeAndDeserialize(obj);
}