org.apache.brooklyn.core.internal.BrooklynProperties Java Examples

The following examples show how to use org.apache.brooklyn.core.internal.BrooklynProperties. 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: ExternalConfigYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testWhenExternalisedConfigSupplierDoesNotExist() throws Exception {
    BrooklynProperties props = BrooklynProperties.Factory.newEmpty();
    props.put("brooklyn.external.myprovider", "wrong.classname.DoesNotExist");

    try {
        LocalManagementContextForTests.builder(true)
                .useProperties(props)
                .build();
        fail();
    } catch (Exception e) {
        if (Exceptions.getFirstThrowableOfType(e, ClassNotFoundException.class) == null) {
            throw e;
        }
    }
}
 
Example #2
Source File: RubyRepRackspaceLiveTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
public void test(String osRegex) throws Exception {
    PostgreSqlNode db1 = app.createAndManageChild(EntitySpec.create(PostgreSqlNode.class)
            .configure(DatastoreCommon.CREATION_SCRIPT_CONTENTS, PostgreSqlIntegrationTest.CREATION_SCRIPT)
            .configure(PostgreSqlNode.POSTGRESQL_PORT, PortRanges.fromInteger(9111)));
    PostgreSqlNode db2 = app.createAndManageChild(EntitySpec.create(PostgreSqlNode.class)
            .configure(DatastoreCommon.CREATION_SCRIPT_CONTENTS, PostgreSqlIntegrationTest.CREATION_SCRIPT)
            .configure(PostgreSqlNode.POSTGRESQL_PORT, PortRanges.fromInteger(9111)));

    BrooklynProperties brooklynProperties = mgmt.getBrooklynProperties();
    brooklynProperties.put("brooklyn.location.jclouds.rackspace-cloudservers-uk.imageNameRegex", osRegex);
    brooklynProperties.remove("brooklyn.location.jclouds.rackspace-cloudservers-uk.image-id");
    brooklynProperties.remove("brooklyn.location.jclouds.rackspace-cloudservers-uk.imageId");
    brooklynProperties.put("brooklyn.location.jclouds.rackspace-cloudservers-uk.inboundPorts", Arrays.asList(22, 9111));
    Location loc = mgmt.getLocationRegistry().getLocationManaged("jclouds:rackspace-cloudservers-uk");
    
    startInLocation(app, db1, db2, loc);

    //hack to get the port for mysql open; is the inbounds property not respected on rackspace??
    for (DatastoreCommon node : ImmutableSet.of(db1, db2)) {
        SshMachineLocation l = (SshMachineLocation) node.getLocations().iterator().next();
        l.execCommands("add iptables rule", ImmutableList.of(IptablesCommands.insertIptablesRule(Chain.INPUT, Protocol.TCP, 9111, Policy.ACCEPT)));
    }

    testReplication(db1, db2);
}
 
Example #3
Source File: BrooklynPropertiesFactoryHelperTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartsWithBrooklynPropertiesPermissionsX00() throws Exception {
    File globalPropsFile = File.createTempFile("testChecksLocalBrooklynPropertiesPermissionsX00_global", ".properties");
    Files.write(getMinimalLauncherPropertiesString()+"key_in_global=1", globalPropsFile, Charset.defaultCharset());
    File localPropsFile = File.createTempFile("testChecksLocalBrooklynPropertiesPermissionsX00_local", ".properties");
    Files.write("key_in_local=2", localPropsFile, Charset.defaultCharset());
    FileUtil.setFilePermissionsTo600(globalPropsFile);
    FileUtil.setFilePermissionsTo600(localPropsFile);
    try {
        BrooklynProperties props = new BrooklynPropertiesFactoryHelper(
                globalPropsFile.getAbsolutePath(),
                localPropsFile.getAbsolutePath())
            .createPropertiesBuilder()
            .build();
        
        assertEquals(props.getFirst("key_in_global"), "1");
        assertEquals(props.getFirst("key_in_local"), "2");
    } finally {
        globalPropsFile.delete();
        localPropsFile.delete();
    }
}
 
Example #4
Source File: GeoscalingWebClientTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
    // Want to load username and password from user's properties.
    mgmt = LocalManagementContextForTests.newInstance(BrooklynProperties.Factory.newDefault());

    String username = getBrooklynProperty(mgmt, "brooklyn.geoscaling.username");
    String password = getBrooklynProperty(mgmt, "brooklyn.geoscaling.password");
    if (username == null || password == null) {
        throw new SkipException("Set brooklyn.geoscaling.username and brooklyn.geoscaling.password in brooklyn.properties to enable test");
    }

    // Insecurely use "trustAll" so that don't need to import signature into trust store
    // before test will work on jenkins machine.
    HttpClient httpClient = HttpTool.httpClientBuilder().uri(GEOSCALING_URL).trustAll().build();
    geoscaling = new GeoscalingWebClient(httpClient);
    geoscaling.login(username, password);
    super.setUp();
}
 
Example #5
Source File: MySqlLiveRackspaceTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
public void test(String osRegex) throws Exception {
    MySqlNode mysql = app.createAndManageChild(EntitySpec.create(MySqlNode.class)
            .configure(DatastoreCommon.CREATION_SCRIPT_CONTENTS, CREATION_SCRIPT)
            .configure("test.table.name", "COMMENTS"));

    BrooklynProperties brooklynProperties = mgmt.getBrooklynProperties();
    brooklynProperties.put("brooklyn.location.jclouds.rackspace-cloudservers-uk.imageNameRegex", osRegex);
    brooklynProperties.remove("brooklyn.location.jclouds.rackspace-cloudservers-uk.image-id");
    brooklynProperties.remove("brooklyn.location.jclouds.rackspace-cloudservers-uk.imageId");
    brooklynProperties.put("brooklyn.location.jclouds.rackspace-cloudservers-uk.inboundPorts", Arrays.asList(22, 3306));
    JcloudsLocation jcloudsLocation = (JcloudsLocation) mgmt.getLocationRegistry().getLocationManaged("jclouds:rackspace-cloudservers-uk");

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

    SshMachineLocation l = (SshMachineLocation) mysql.getLocations().iterator().next();
    l.execCommands("add iptables rule", ImmutableList.of(IptablesCommands.insertIptablesRule(Chain.INPUT, Protocol.TCP, 3306, Policy.ACCEPT)));

    new VogellaExampleAccess("com.mysql.jdbc.Driver", mysql.getAttribute(DatastoreCommon.DATASTORE_URL)).readModifyAndRevertDataBase();
}
 
Example #6
Source File: BrooklynGarbageCollector.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public BrooklynGarbageCollector(BrooklynProperties brooklynProperties, BasicExecutionManager executionManager, BrooklynStorage storage) {
    this.executionManager = executionManager;
    this.storage = storage;
    this.brooklynProperties = brooklynProperties;

    if (brooklynProperties.getConfig(TRACK_SOFT_MAYBE_USAGE))
        SoftlyPresent.getUsageTracker().enable();
    
    executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            @Override public Thread newThread(Runnable r) {
                return new Thread(r, "brooklyn-gc");
            }});
    
    executionManager.addListener(new ExecutionListener() {
            @Override public void onTaskDone(Task<?> task) {
                BrooklynGarbageCollector.this.onTaskDone(task);
            }});

    scheduleCollector(true);
}
 
Example #7
Source File: OsgiLauncherImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected void startingUp() {
    super.startingUp();
    ManagementContext managementContext = getManagementContext();
    BrooklynProperties brooklynProperties = (BrooklynProperties) managementContext.getConfig();
    if (BrooklynWebConfig.hasNoSecurityOptions(brooklynProperties)) {
        LOG.info("No security provider options specified. Define a security provider or users to prevent a random password being created and logged.");
        // Deprecated in 0.11.0. Add to release notes and remove in next release.
        brooklynProperties.put(
                BrooklynWebConfig.SECURITY_PROVIDER_INSTANCE,
                new BrooklynUserWithRandomPasswordSecurityProvider(managementContext));
        managementContext.getScratchpad().put(
                BrooklynWebConfig.SECURITY_PROVIDER_INSTANCE,
                new BrooklynUserWithRandomPasswordSecurityProvider(managementContext));
    }
}
 
Example #8
Source File: BrooklynWebServerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void verifyHttpsFromConfig(BrooklynProperties brooklynProperties) throws Exception {
    webServer = new BrooklynWebServer(MutableMap.of(), newManagementContext(brooklynProperties));
    webServer.skipSecurity();
    webServer.start();
    
    try {
        KeyStore keyStore = load("client.ks", "password");
        KeyStore trustStore = load("client.ts", "password");
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, "password", trustStore, (SecureRandom)null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpToolResponse response = HttpTool.execAndConsume(
                HttpTool.httpClientBuilder()
                        .port(webServer.getActualPort())
                        .https(true)
                        .socketFactory(socketFactory)
                        .build(),
                new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 200);
    } finally {
        webServer.stop();
    }
}
 
Example #9
Source File: WebAppRunnerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartWithLauncher() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), "/hello-world.war");

    BrooklynLauncher launcher = BrooklynLauncher.newInstance()
            .brooklynProperties(BrooklynProperties.Factory.newEmpty())
            .brooklynProperties("brooklyn.webconsole.security.provider","org.apache.brooklyn.rest.security.provider.AnyoneSecurityProvider")
            .webapp("/hello", "hello-world.war")
            .start();
    BrooklynServerDetails details = launcher.getServerDetails();
    
    try {
        details.getWebServer().deploy("/hello2", "hello-world.war");

        assertRootPageAvailableAt(details.getWebServerUrl());
        HttpAsserts.assertContentEventuallyContainsText(details.getWebServerUrl()+"hello", "This is the home page for a sample application");
        HttpAsserts.assertContentEventuallyContainsText(details.getWebServerUrl()+"hello2", "This is the home page for a sample application");
        HttpAsserts.assertHttpStatusCodeEventuallyEquals(details.getWebServerUrl()+"hello0", 404);

    } finally {
        details.getWebServer().stop();
        ((ManagementContextInternal)details.getManagementContext()).terminate();
    }
}
 
Example #10
Source File: LocalUsageManagerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddMultipleUsageListenersViaProperties() throws Exception {
    BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty();
    brooklynProperties.put(UsageManager.USAGE_LISTENERS, RecordingStaticUsageListener.class.getName() + "," + RecordingStaticUsageListener.class.getName());
    replaceManagementContext(LocalManagementContextForTests.newInstance(brooklynProperties));
    
    final List<RecordingStaticUsageListener> listeners = RecordingStaticUsageListener.getInstances();
    assertEquals(listeners.size(), 2);
    assertTrue(listeners.get(0) instanceof RecordingStaticUsageListener, "listeners="+listeners);
    assertTrue(listeners.get(1) instanceof RecordingStaticUsageListener, "listeners="+listeners);
    
    app = TestApplication.Factory.newManagedInstanceForTests(mgmt);

    Asserts.succeedsEventually(new Runnable() {
        @Override public void run() {
            assertHasAppEvents(listeners.get(0));
            assertHasAppEvents(listeners.get(1));
        }
        private void assertHasAppEvents(RecordingStaticUsageListener listener) {
            List<List<?>> events = listener.getApplicationEvents();
            assertTrue(listeners.get(0).getApplicationEvents().size() > 0, "events="+events); // expect some events
        }});
}
 
Example #11
Source File: AbstractGoogleComputeLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected BrooklynProperties getBrooklynProperties() {
    // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
    List<String> propsToRemove = ImmutableList.of("imageId", "imageDescriptionRegex", "imageNameRegex", "inboundPorts", "hardwareId", "minRam");
    BrooklynProperties result = BrooklynProperties.Factory.newDefault();
    for (String propToRemove : propsToRemove) {
        for (String propVariant : ImmutableList.of(propToRemove, CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propToRemove))) {
            result.remove("brooklyn.locations.jclouds."+PROVIDER+"."+propVariant);
            result.remove("brooklyn.locations."+propVariant);
            result.remove("brooklyn.jclouds."+PROVIDER+"."+propVariant);
            result.remove("brooklyn.jclouds."+propVariant);
        }
    }

    // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
    result.remove("brooklyn.ssh.config.scriptHeader");
    
    return result;
}
 
Example #12
Source File: BrooklynLauncherRebindTestFixture.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testRebindRespectsPersistenceDirSetInProperties() throws Exception {
    String persistenceDir2 = newTempPersistenceContainerName();
    
    BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newDefault();
    brooklynProperties.put(BrooklynServerConfig.PERSISTENCE_DIR, persistenceDir2);
    LocalManagementContextForTests mgmt = newManagementContextForTests(brooklynProperties);
    
    // Rebind to the app we started last time
    newLauncherBase()
            .persistMode(PersistMode.AUTO)
            .persistPeriod(Duration.millis(10))
            .managementContext(mgmt)
            .start();
    
    checkPersistenceContainerNameIs(persistenceDir2);
}
 
Example #13
Source File: BrooklynFeatureEnablement.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Initialises the feature-enablement from brooklyn properties. For each
 * property, prefer a system-property if present; otherwise use the value 
 * from brooklyn properties.
 */
public static void init(BrooklynProperties props) {
    boolean found = false;
    synchronized (MUTEX) {
        for (Map.Entry<String, Object> entry : props.asMapWithStringKeys().entrySet()) {
            String property = entry.getKey();
            if (property.startsWith(FEATURE_PROPERTY_PREFIX)) {
                found = true;
                Boolean oldVal = isEnabled(property);
                boolean val = Boolean.parseBoolean(""+entry.getValue());
                FEATURE_ENABLEMENTS_PROPERTIES.put(property, val);
                Boolean newVal = isEnabled(property);
                
                if (Objects.equal(oldVal, newVal)) {
                    LOG.debug("Enablement of "+property+" set to "+val+" from brooklyn properties (no-op as continues to resolve to "+oldVal+")");
                } else {
                    LOG.debug("Enablement of "+property+" set to "+val+" from brooklyn properties (resolved value previously "+oldVal+")");
                }
            }
        }
        if (!found) {
            LOG.debug("Init feature enablement did nothing, as no settings in brooklyn properties");
        }
    }
}
 
Example #14
Source File: ExternalConfigBrooklynPropertiesTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void runExternalisedConfigGetters(BrooklynProperties props, String property, String expectedVal, boolean testSubMap) throws Exception {
    ExecutionContext exec = mgmt().getServerExecutionContext();

    String val1 = props.getConfig(ConfigKeys.newStringConfigKey(property));
    assertEquals(val1, expectedVal);
    
    DeferredSupplier<?> val2 = (DeferredSupplier<?>) props.getConfigRaw(ConfigKeys.newStringConfigKey(property)).get();
    assertEquals(Tasks.resolveValue(val2, String.class, exec), expectedVal);
    
    DeferredSupplier<?> val3 = (DeferredSupplier<?>) props.getConfigLocalRaw(ConfigKeys.newStringConfigKey(property)).get();
    assertEquals(Tasks.resolveValue(val3, String.class, exec), expectedVal);

    DeferredSupplier<?> val4 = (DeferredSupplier<?>) props.getAllConfigLocalRaw().get(ConfigKeys.newStringConfigKey(property));
    assertEquals(Tasks.resolveValue(val4, String.class, exec), expectedVal);
    
    String val5 = props.getFirst(property);
    assertTrue(val5.startsWith("$brooklyn:external"), "val="+val5);
    
    if (testSubMap) {
        BrooklynProperties submap = props.submap(ConfigPredicates.nameEqualTo(property));
        runExternalisedConfigGetters(submap, property, expectedVal, false);
    }
}
 
Example #15
Source File: LocalManagementContextTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testReloadPropertiesFromBuilder() throws IOException {
    String globalPropertiesContents = toMapString( LocalManagementContextForTests.builder(true)
        .useAdditionalProperties(MutableMap.of("brooklyn.location.localhost.displayName", "myname"))
        .buildProperties() );
    Files.write(globalPropertiesContents, globalPropertiesFile, Charsets.UTF_8);
    
    Builder propsBuilder = BrooklynProperties.Factory.builderDefault()
        .globalPropertiesFile(globalPropertiesFile.getAbsolutePath());
    // no builder support in LocalManagementContextForTests (we are testing that the builder's files are reloaded so we need it here)
    context = new LocalManagementContext(propsBuilder);
    Location location = context.getLocationRegistry().getLocationManaged("localhost");
    assertEquals(location.getDisplayName(), "myname");
    
    String newGlobalPropertiesContents = toMapString( LocalManagementContextForTests.builder(true)
        .useAdditionalProperties(MutableMap.of("brooklyn.location.localhost.displayName", "myname2"))
        .buildProperties() );
    Files.write(newGlobalPropertiesContents, globalPropertiesFile, Charsets.UTF_8);
    context.reloadBrooklynProperties();
    Location location2 = context.getLocationRegistry().getLocationManaged("localhost");
    assertEquals(location.getDisplayName(), "myname");
    assertEquals(location2.getDisplayName(), "myname2");
}
 
Example #16
Source File: BasicLocationRegistry.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public void updateDefinedLocations() {
    synchronized (definedLocations) {
        // first read all properties starting  brooklyn.location.named.xxx
        // (would be nice to move to a better way, e.g. yaml, then deprecate this approach, but first
        // we need ability/format for persisting named locations, and better support for adding+saving via REST/GUI)
        int count = 0; 
        String NAMED_LOCATION_PREFIX = "brooklyn.location.named.";
        StringConfigMap namedLocationProps = mgmt.getConfig().submap(ConfigPredicates.nameStartsWith(NAMED_LOCATION_PREFIX));
        for (String k: namedLocationProps.asMapWithStringKeys().keySet()) {
            String name = k.substring(NAMED_LOCATION_PREFIX.length());
            // If has a dot, then is a sub-property of a named location (e.g. brooklyn.location.named.prod1.user=bob)
            if (!name.contains(".")) {
                // this is a new named location
                String spec = (String) namedLocationProps.asMapWithStringKeys().get(k);
                // make up an ID
                String id = Identifiers.makeRandomId(8);
                BrooklynProperties config = ConfigUtils.filterForPrefixAndStrip(namedLocationProps.asMapWithStringKeys(), k+".");
                definedLocations.put(id, new BasicLocationDefinition(id, name, spec, config.asMapWithStringKeys()));
                count++;
            }
        }
        if (log.isDebugEnabled())
            log.debug("Found "+count+" defined locations from properties (*.named.* syntax): "+definedLocations.values());
    }
}
 
Example #17
Source File: Entitlements.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static EntitlementManager load(@Nullable ManagementContext mgmt, BrooklynProperties brooklynProperties, String type) {
    if ("root".equalsIgnoreCase(type)) {
        return root();
    } else if ("readonly".equalsIgnoreCase(type) || "read_only".equalsIgnoreCase(type)) {
        return readOnly();
    } else if ("minimal".equalsIgnoreCase(type)) {
        return minimal();
    } else if ("user".equalsIgnoreCase(type)) {
        return user();
    }
    if (Strings.isNonBlank(type)) {
        try {
            Class<?> clazz = new ClassLoaderUtils(Entitlements.class, mgmt).loadClass(DeserializingClassRenamesProvider.INSTANCE.findMappedName(type));
            return (EntitlementManager) instantiate(clazz, ImmutableList.of(
                    new Object[] {mgmt, brooklynProperties},
                    new Object[] {mgmt},
                    new Object[] {brooklynProperties},
                    new Object[0]));
        } catch (Exception e) { 
            throw Exceptions.propagate(e); 
        }
    }
    throw new IllegalStateException("Invalid entitlement manager specified: '"+type+"'");
}
 
Example #18
Source File: JcloudsExpect100ContinueTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    // It's important to disable jclouds debug logging
    // as it "fixes" the issue.
    setInfoLevel(Logger.ROOT_LOGGER_NAME);
    setInfoLevel("jclouds");
    setInfoLevel("org.jclouds");

    mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());
    JcloudsLocation jcloudsLocation = (JcloudsLocation) mgmt.getLocationRegistry().getLocationManaged(LOCATION_SPEC);
    
    context = BlobStoreContextFactoryImpl.INSTANCE.newBlobStoreContext(jcloudsLocation);

    containerName = BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(8);
    context.getBlobStore().createContainerInLocation(null, containerName);
}
 
Example #19
Source File: EntityExecutionManagerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public void testGcTaskAtEntityLimit() throws Exception {
    final TestEntity e = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    
    ((BrooklynProperties)app.getManagementContext().getConfig()).put(
        BrooklynGarbageCollector.MAX_TASKS_PER_ENTITY, 2);
    
    AtomicBoolean stopCondition = new AtomicBoolean();
    scheduleRecursiveTemporaryTask(stopCondition, e, "boring-tag");
    scheduleRecursiveTemporaryTask(stopCondition, e, "boring-tag");
    scheduleRecursiveTemporaryTask(stopCondition, app, "boring-tag");
    scheduleRecursiveTemporaryTask(stopCondition, app, "boring-tag");

    for (int count=0; count<5; count++)
        runEmptyTaskWithNameAndTags(e, "task-e-"+count, ManagementContextInternal.NON_TRANSIENT_TASK_TAG, "boring-tag");
    for (int count=0; count<5; count++)
        runEmptyTaskWithNameAndTags(app, "task-app-"+count, ManagementContextInternal.NON_TRANSIENT_TASK_TAG, "boring-tag");

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

    assertTaskMaxCountForEntityEventually(app, 2);
    assertTaskMaxCountForEntityEventually(e, 2);
}
 
Example #20
Source File: ExternalConfigYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected LocalManagementContext newTestManagementContext() {
    BrooklynProperties props = BrooklynProperties.Factory.newEmpty();
    props.put("brooklyn.external.myprovider", MyExternalConfigSupplier.class.getName());
    props.put("brooklyn.external.myprovider.mykey", "myval");
    props.put("brooklyn.external.myproviderWithoutMapArg", MyExternalConfigSupplierWithoutMapArg.class.getName());

    props.put("brooklyn.external.myprovider.myCatalogId", "myId");
    props.put("brooklyn.external.myprovider.myCatalogItemType", "template");
    props.put("brooklyn.external.myprovider.myCatalogVersion", "1.2");
    props.put("brooklyn.external.myprovider.myCatalogDescription", "myDescription");
    props.put("brooklyn.external.myprovider.myCatalogDisplayName", "myDisplayName");
    props.put("brooklyn.external.myprovider.myCatalogIconUrl", "classpath:///myIconUrl.png");
    props.put("brooklyn.external.myprovider.myCatalogLibraryUrl", LIBRARY_URL);
    props.put("brooklyn.external.myprovider.myCatalogLibraryName", LIBRARY_SYMBOLIC_NAME);
    props.put("brooklyn.external.myprovider.myCatalogLibraryVersion", LIBRARY_VERSION);

    return LocalManagementContextForTests.builder(true)
            .useProperties(props)
            .enableOsgiReusable()
            .build();
}
 
Example #21
Source File: RebindTestUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Dumps out the persisted mementos that are at the given directory.
 * 
 * Binds to the persisted state (as a "hot standby") to load the raw data (as strings), and to write out the
 * entity, location, policy, enricher, feed and catalog-item data.
 * 
 * @param dir The directory containing the persisted state
 */
public static void dumpMementoDir(File dir) {
    LocalManagementContextForTests mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newEmpty());
    FileBasedObjectStore store = null;
    BrooklynMementoPersisterToObjectStore persister = null;
    try {
        store = new FileBasedObjectStore(dir);
        store.injectManagementContext(mgmt);
        store.prepareForSharedUse(PersistMode.AUTO, HighAvailabilityMode.HOT_STANDBY);
        persister = new BrooklynMementoPersisterToObjectStore(store, mgmt, RebindTestUtils.class.getClassLoader());
        BrooklynMementoRawData data = persister.loadMementoRawData(RebindExceptionHandlerImpl.builder().build());
        List<BrooklynObjectType> types = ImmutableList.of(BrooklynObjectType.ENTITY, BrooklynObjectType.LOCATION, 
                BrooklynObjectType.POLICY, BrooklynObjectType.ENRICHER, BrooklynObjectType.FEED, 
                BrooklynObjectType.CATALOG_ITEM, BrooklynObjectType.MANAGED_BUNDLE);
        for (BrooklynObjectType type : types) {
            LOG.info(type+" ("+data.getObjectsOfType(type).keySet()+"):");
            for (Map.Entry<String, String> entry : data.getObjectsOfType(type).entrySet()) {
                LOG.info("\t"+type+" "+entry.getKey()+": "+entry.getValue());
            }
        }
    } finally {
        if (persister != null) persister.stop(false);
        if (store != null) store.close();
        mgmt.terminate();
    }
}
 
Example #22
Source File: RebindTestFixture.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected LocalManagementContext createNewManagementContext(File mementoDir, HighAvailabilityMode haMode, Map<?, ?> additionalProperties) {
    if (mementoDir==null) mementoDir = this.mementoDir;
    BrooklynProperties brooklynProperties = createBrooklynProperties();
    if (additionalProperties != null) {
        brooklynProperties.addFrom(additionalProperties);
    }
    return RebindTestUtils.managementContextBuilder(mementoDir, classLoader)
            .forLive(useLiveManagementContext())
            .haMode(haMode)
            .emptyCatalog(useEmptyCatalog())
            .properties(brooklynProperties)
            .setOsgiEnablementAndReuse(useOsgi(), !disallowOsgiReuse())
            .buildUnstarted();
}
 
Example #23
Source File: LocalUsageManagerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddUsageListenerInstance() throws Exception {
    BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty();
    brooklynProperties.put(UsageManager.USAGE_LISTENERS, ImmutableList.of(new RecordingStaticUsageListener()));
    replaceManagementContext(LocalManagementContextForTests.newInstance(brooklynProperties));
    assertUsageListenerCalledWhenApplicationStarted();
}
 
Example #24
Source File: LocalManagementContextTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testScratchpadSurvivesReload() throws Exception {
    String globalPropertiesContents = "brooklyn.location.localhost.displayName=myname";
    Files.write(globalPropertiesContents, globalPropertiesFile, Charsets.UTF_8);
    BrooklynProperties brooklynProperties = BrooklynProperties.Factory.builderDefault()
        .globalPropertiesFile(globalPropertiesFile.getAbsolutePath())
        .build();
    context = LocalManagementContextForTests.builder(true).useProperties(brooklynProperties).build();
    ConfigKey<String> myKey = ConfigKeys.newStringConfigKey("my");
    context.getScratchpad().put(myKey, "key");
    assertEquals(context.getScratchpad().get(myKey), "key");
    context.reloadBrooklynProperties();
    assertEquals(context.getScratchpad().get(myKey), "key");
}
 
Example #25
Source File: BrooklynLauncherRebindManagementNodeStateListenerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected BrooklynLauncher newLauncherForTests(PersistMode persistMode, HighAvailabilityMode haMode) {
    BrooklynProperties brooklynProperties = LocalManagementContextForTests.builder(true).buildProperties();
    brooklynProperties.put(BrooklynServerConfig.MANAGEMENT_NODE_STATE_LISTENERS, RecordingStaticManagementNodeStateListener.class.getName());
    
    // If latches are set, then blocks startup
    CatalogInitialization catInit = new CatalogInitialization() {
        @Override
        public void populateInitialAndPersistedCatalog(ManagementNodeState mode, PersistedCatalogState persistedState, RebindExceptionHandler exceptionHandler, RebindLogger rebindLogger) {
            awaitIfNotNull(populateInitialAndPersistedCatalogLatch);
            super.populateInitialAndPersistedCatalog(mode, persistedState, exceptionHandler, rebindLogger);
        }
        @Override
        public void populateInitialCatalogOnly() {
            awaitIfNotNull(populateInitialCatalogOnlyLatch);
            super.populateInitialCatalogOnly();
        }
        private void awaitIfNotNull(AtomicReference<CountDownLatch> latchRef) {
            CountDownLatch latch = latchRef.get();
            if (latch != null) {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    throw Exceptions.propagate(e);
                }
            }
        }
    };

    return super.newLauncherForTests(persistMode, haMode)
            .brooklynProperties(brooklynProperties)
            .catalogInitialization(catInit);
}
 
Example #26
Source File: MongoDBWinEc2LiveTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
    mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault());

    location = WindowsTestFixture.setUpWindowsLocation(mgmt);
    machine = location.obtain(ImmutableMap.of());
}
 
Example #27
Source File: CatalogScanTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private synchronized void loadAnnotationsOnlyCatalog() {
    if (annotsCatalog!=null) return;
    BrooklynProperties props = BrooklynProperties.Factory.newEmpty();
    props.put(BrooklynServerConfig.BROOKLYN_CATALOG_URL.getName(),
            "data:,"+URLEncoder.encode("brooklyn.catalog: {scanJavaAnnotations: true}"));
    LocalManagementContext mgmt = newManagementContext(props);
    annotsCatalog = mgmt.getCatalog();
    log.info("ENTITIES loaded with annotation: "+annotsCatalog.getCatalogItems(Predicates.alwaysTrue()));
}
 
Example #28
Source File: BrooklynMementoPersisterJcloudsObjectStoreTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected LocalManagementContext newPersistingManagementContext() {
    objectStore = new JcloudsBlobStoreBasedObjectStore(
        BlobStoreTest.PERSIST_TO_OBJECT_STORE_FOR_TEST_SPEC, BlobStoreTest.CONTAINER_PREFIX+"-"+Identifiers.makeRandomId(4));
    return RebindTestUtils.managementContextBuilder(classLoader, objectStore)
        .persistPeriod(Duration.ONE_MILLISECOND)
        .properties(BrooklynProperties.Factory.newDefault())
        .buildStarted();
}
 
Example #29
Source File: CatalogScanTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private synchronized void loadTheDefaultCatalog(boolean lookOnDiskForDefaultCatalog) {
    if (defaultCatalog!=null) return;
    BrooklynProperties props = BrooklynProperties.Factory.newEmpty();
    props.put(BrooklynServerConfig.BROOKLYN_CATALOG_URL.getName(),
        // if default catalog is picked up from the system, we might get random stuff from ~/.brooklyn/ instead of the default;
        // useful as an integration check that we default correctly, but irritating for people to use if they have such a catalog installed
        (lookOnDiskForDefaultCatalog ? "" :
            "data:,"+Urls.encode(new ResourceUtils(this).getResourceAsString("classpath:/brooklyn/default.catalog.bom"))));
    LocalManagementContext mgmt = newManagementContext(props);
    defaultCatalog = mgmt.getCatalog();
    log.info("ENTITIES loaded for DEFAULT: "+defaultCatalog.getCatalogItems(Predicates.alwaysTrue()));
}
 
Example #30
Source File: ExternalConfigBrooklynPropertiesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected LocalManagementContext newTestManagementContext() {
    BrooklynProperties props = BrooklynProperties.Factory.newEmpty();
    props.put("brooklyn.external.myprovider", MyExternalConfigSupplier.class.getName());
    props.put("brooklyn.external.myprovider.mykey", "myval");
    props.put("brooklyn.external.myprovider.mykey2", "myval2");
    props.put("brooklyn.external.myproviderWithoutMapArg", MyExternalConfigSupplierWithoutMapArg.class.getName());
    props.put("myproperty", "$brooklyn:external(\"myprovider\", \"mykey\")");

    return LocalManagementContextForTests.builder(true)
            .useProperties(props)
            .build();
}