Example usage for org.apache.commons.configuration CompositeConfiguration CompositeConfiguration

List of usage examples for org.apache.commons.configuration CompositeConfiguration CompositeConfiguration

Introduction

In this page you can find the example usage for org.apache.commons.configuration CompositeConfiguration CompositeConfiguration.

Prototype

public CompositeConfiguration() 

Source Link

Document

Creates an empty CompositeConfiguration object which can then be added some other Configuration files

Usage

From source file:org.apache.bookkeeper.stream.server.StorageServer.java

static int doMain(String[] args) {
    // register thread uncaught exception handler
    Thread.setDefaultUncaughtExceptionHandler((thread, exception) -> log
            .error("Uncaught exception in thread {}: {}", thread.getName(), exception.getMessage()));

    // parse the commandline
    ServerArguments arguments = new ServerArguments();
    JCommander jCommander = new JCommander(arguments);
    jCommander.setProgramName("StorageServer");
    jCommander.parse(args);/* ww w.jav  a 2  s . c o  m*/

    if (arguments.help) {
        jCommander.usage();
        return ExitCode.INVALID_CONF.code();
    }

    CompositeConfiguration conf = new CompositeConfiguration();
    if (null != arguments.serverConfigFile) {
        loadConfFile(conf, arguments.serverConfigFile);
    }

    int grpcPort = arguments.port;

    LifecycleComponent storageServer;
    try {
        storageServer = buildStorageServer(conf, grpcPort);
    } catch (ConfigurationException e) {
        log.error("Invalid storage configuration", e);
        return ExitCode.INVALID_CONF.code();
    } catch (UnknownHostException e) {
        log.error("Unknonw host name", e);
        return ExitCode.UNKNOWN_HOSTNAME.code();
    }

    CompletableFuture<Void> liveFuture = ComponentStarter.startComponent(storageServer);
    try {
        liveFuture.get();
    } catch (InterruptedException e) {
        // the server is interrupted.
        Thread.currentThread().interrupt();
        log.info("Storage server is interrupted. Exiting ...");
    } catch (ExecutionException e) {
        log.info("Storage server is exiting ...");
    }
    return ExitCode.OK.code();
}

From source file:org.apache.bookkeeper.stream.storage.conf.TestStorageConfiguration.java

@Test(timeout = 60000)
public void testGetStorageSettings() {
    CompositeConfiguration conf = new CompositeConfiguration();
    conf.setProperty("xxx.key", "xxx.value");
    conf.setProperty("storage.key", "storage.value");
    conf.setProperty("storage-key", "storage-value");

    StorageConfiguration storageConf = new StorageConfiguration(conf);
    assertEquals("storage.value", storageConf.getString("key"));
    assertTrue(storageConf.containsKey("key"));
    assertFalse(storageConf.containsKey("xxx.key"));
    assertFalse(storageConf.containsKey("storage.key"));
    assertFalse(storageConf.containsKey("storage-key"));
}

From source file:org.apache.bookkeeper.stream.storage.impl.cluster.ClusterControllerImplTest.java

@Before
public void setup() {
    this.leaderSelector = mock(ClusterControllerLeaderSelector.class);
    this.service = new ClusterControllerImpl(mock(ClusterMetadataStore.class), mock(RegistrationClient.class),
            mock(StorageContainerController.class), leaderSelector,
            new StorageConfiguration(new CompositeConfiguration()));
}

From source file:org.apache.bookkeeper.stream.storage.impl.sc.ZkStorageContainerManagerTest.java

@Before
public void setup() {
    curatorClient = CuratorFrameworkFactory.newClient(zkServers, new ExponentialBackoffRetry(200, 10, 5000));
    curatorClient.start();//from w  w  w.  j  av a  2  s .co m

    clusterMetadataStore = spy(
            new ZkClusterMetadataStore(curatorClient, zkServers, "/" + runtime.getMethodName()));
    clusterMetadataStore.initializeCluster(NUM_STORAGE_CONTAINERS);

    mockScFactory = mock(StorageContainerFactory.class);
    scRegistry = spy(new StorageContainerRegistryImpl(mockScFactory));

    scManager = new ZkStorageContainerManager(
            myEndpoint, new StorageConfiguration(new CompositeConfiguration())
                    .setClusterControllerScheduleInterval(1, TimeUnit.SECONDS),
            clusterMetadataStore, scRegistry, NullStatsLogger.INSTANCE);
}

From source file:org.apache.bookkeeper.stream.storage.impl.sc.ZkStorageContainerManagerTest.java

@Test
public void testStartContainerOnFailures() throws Exception {
    scManager.close();/*  w  w  w  .j  a  v a  2 s  .  c  o  m*/

    long containerId = 11L;
    AtomicBoolean returnGoodContainer = new AtomicBoolean(false);

    CompletableFuture<StorageContainer> startFuture = new CompletableFuture<>();
    StorageContainer goodSc = createStorageContainer(containerId, startFuture, FutureUtils.Void());
    mockScFactory = (scId) -> {
        if (returnGoodContainer.get()) {
            return goodSc;
        } else {
            return createStorageContainer(scId, FutureUtils.exception(new Exception("Failed to start")),
                    FutureUtils.Void());
        }
    };
    scRegistry = spy(new StorageContainerRegistryImpl(mockScFactory));

    scManager = new ZkStorageContainerManager(
            myEndpoint, new StorageConfiguration(new CompositeConfiguration())
                    .setClusterControllerScheduleInterval(1, TimeUnit.SECONDS),
            clusterMetadataStore, scRegistry, NullStatsLogger.INSTANCE);

    // start the storage container manager
    scManager.start();

    // update assignment map
    ClusterAssignmentData cad = ClusterAssignmentData.newBuilder()
            .putServers(NetUtils.endpointToString(myEndpoint),
                    ServerAssignmentData.newBuilder().addContainers(containerId).build())
            .build();
    clusterMetadataStore.updateClusterAssignmentData(cad);

    // wait until container start is called and verify it is not started.
    verify(scRegistry, timeout(10000).atLeastOnce()).startStorageContainer(eq(containerId));
    assertEquals(0, scManager.getLiveContainers().size());

    // flip the flag to return a good container to simulate successful startup
    returnGoodContainer.set(true);
    FutureUtils.complete(startFuture, goodSc);

    // wait until container start is called again and the container is started
    MoreAsserts.assertUtil(ignored -> scManager.getLiveContainers().size() >= 1, () -> null);
    assertEquals(1, scManager.getLiveContainers().size());
    assertTrue(scManager.getLiveContainers().containsKey(containerId));
}

From source file:org.apache.bookkeeper.tools.cli.helpers.BookieShellCommandTest.java

@SuppressWarnings("unchecked")
@Test/*from  www .  j ava 2 s .  co m*/
public void testShellCommand() throws Exception {
    BKCommand<CliFlags> command = mock(BKCommand.class);
    String shellCommandName = "test-shell-command";
    CompositeConfiguration conf = new CompositeConfiguration();
    BookieShellCommand<CliFlags> shellCommand = new BookieShellCommand<>(shellCommandName, command, conf);

    // test `description`
    assertEquals(shellCommandName + " [options]", shellCommand.description());

    // test `printUsage`
    shellCommand.printUsage();
    verify(command, times(1)).usage();

    // test `runCmd`
    String[] args = new String[] { "arg-1", "arg-2" };
    shellCommand.runCmd(args);
    verify(command, times(1)).apply(same(shellCommandName), same(conf), same(args));
}

From source file:org.apache.bookkeeper.tools.common.BKCommand.java

protected boolean apply(BKFlags bkFlags, CommandFlagsT cmdFlags) {
    ServiceURI serviceURI = null;//  www  .jav  a2 s .co m

    if (null != bkFlags.serviceUri) {
        serviceURI = ServiceURI.create(bkFlags.serviceUri);
        if (!acceptServiceUri(serviceURI)) {
            log.error("Unresolvable service uri by command '{}' : {}", path(), bkFlags.serviceUri);
            return false;
        }
    }

    CompositeConfiguration conf = new CompositeConfiguration();
    if (!Strings.isNullOrEmpty(bkFlags.configFile)) {
        try {
            URL configFileUrl = Paths.get(bkFlags.configFile).toUri().toURL();
            PropertiesConfiguration loadedConf = new PropertiesConfiguration(configFileUrl);
            conf.addConfiguration(loadedConf);
        } catch (MalformedURLException e) {
            log.error("Could not open configuration file : {}", bkFlags.configFile, e);
            throw new IllegalArgumentException(e);
        } catch (ConfigurationException e) {
            log.error("Malformed configuration file : {}", bkFlags.configFile, e);
            throw new IllegalArgumentException(e);
        }
    }

    return apply(serviceURI, conf, bkFlags, cmdFlags);
}

From source file:org.apache.cassandra.CassandraServiceController.java

public synchronized void startup() throws Exception {
    LOG.info("Starting up cluster...");

    config = new CompositeConfiguration();
    if (System.getProperty("whirr.config") != null) {
        config.addConfiguration(new PropertiesConfiguration(System.getProperty("whirr.config")));
    }/*from w  w  w . ja va2s .  c  o  m*/
    config.addConfiguration(new PropertiesConfiguration("whirr-default.properties"));

    clusterSpec = new ClusterSpec(config);
    if (clusterSpec.getPrivateKey() == null) {
        Map<String, String> pair = KeyPair.generate();
        clusterSpec.setPublicKey(pair.get("public"));
        clusterSpec.setPrivateKey(pair.get("private"));
    }

    // if a local tarball is available deploy it to the blobstore where it will be available to cassandra
    if (System.getProperty("whirr.cassandra_tarball") != null) {
        Pair<BlobMetadata, URI> blob = BlobUtils.storeBlob(config, clusterSpec,
                System.getProperty("whirr.cassandra_tarball"));
        tarball = blob.left;
        config.setProperty(CassandraClusterActionHandler.BIN_TARBALL, blob.right.toURL().toString());
        // TODO: parse the CassandraVersion property file instead
        config.setProperty(CassandraClusterActionHandler.MAJOR_VERSION, "0.8");
    }

    service = new ServiceFactory().create(clusterSpec.getServiceName());
    cluster = service.launchCluster(clusterSpec);
    computeService = ComputeServiceContextBuilder.build(clusterSpec).getComputeService();
    hosts = new ArrayList<InetAddress>();
    for (Instance instance : cluster.getInstances()) {
        hosts.add(instance.getPublicAddress());
    }

    ShutdownHook shutdownHook = new ShutdownHook(this);
    Runtime.getRuntime().addShutdownHook(shutdownHook);

    waitForClusterInitialization();

    running = true;
}

From source file:org.apache.distributedlog.common.config.TestConfigurationSubscription.java

@Test(timeout = 60000)
public void testReloadConfiguration() throws Exception {
    PropertiesWriter writer = new PropertiesWriter();
    FileConfigurationBuilder builder = new PropertiesConfigurationBuilder(writer.getFile().toURI().toURL());
    ConcurrentConstConfiguration conf = new ConcurrentConstConfiguration(new CompositeConfiguration());
    DeterministicScheduler executorService = new DeterministicScheduler();
    List<FileConfigurationBuilder> fileConfigBuilders = Lists.newArrayList(builder);
    ConfigurationSubscription confSub = new ConfigurationSubscription(conf, fileConfigBuilders, executorService,
            100, TimeUnit.MILLISECONDS);
    final AtomicReference<ConcurrentBaseConfiguration> confHolder = new AtomicReference<>();
    confSub.registerListener(new org.apache.distributedlog.common.config.ConfigurationListener() {
        @Override//from  w ww  .j a v a2  s.  co  m
        public void onReload(ConcurrentBaseConfiguration conf) {
            confHolder.set(conf);
        }
    });
    assertEquals(null, conf.getProperty("prop1"));

    // add
    writer.setProperty("prop1", "1");
    writer.save();
    // ensure the file change reloading event can be triggered
    ensureConfigReloaded();
    // reload the config
    confSub.reload();
    assertNotNull(confHolder.get());
    assertTrue(conf == confHolder.get());
    assertEquals("1", conf.getProperty("prop1"));
}

From source file:org.apache.distributedlog.common.config.TestConfigurationSubscription.java

@Test(timeout = 60000)
public void testAddReloadBasicsConfig() throws Exception {
    PropertiesWriter writer = new PropertiesWriter();
    DeterministicScheduler mockScheduler = new DeterministicScheduler();
    FileConfigurationBuilder builder = new PropertiesConfigurationBuilder(writer.getFile().toURI().toURL());
    ConcurrentConstConfiguration conf = new ConcurrentConstConfiguration(new CompositeConfiguration());
    List<FileConfigurationBuilder> fileConfigBuilders = Lists.newArrayList(builder);
    ConfigurationSubscription confSub = new ConfigurationSubscription(conf, fileConfigBuilders, mockScheduler,
            100, TimeUnit.MILLISECONDS);
    assertEquals(null, conf.getProperty("prop1"));

    // add//from   ww w.  j  a  v a  2  s  .  co m
    writer.setProperty("prop1", "1");
    writer.save();
    // ensure the file change reloading event can be triggered
    ensureConfigReloaded();
    mockScheduler.tick(100, TimeUnit.MILLISECONDS);
    assertEquals("1", conf.getProperty("prop1"));

}