Java Code Examples for org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder

The following examples show how to use org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder. These examples are extracted from open source projects. 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 Project: elepy   Source File: Elepy.java    License: Apache License 2.0 6 votes vote down vote up
public Elepy withProperties(URL url) {
    try {

        Parameters params = new Parameters();
        FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
                new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
                        .configure(params.properties()
                                .setURL(url)
                                .setListDelimiterHandler(new DefaultListDelimiterHandler(',')));
        var propertyConfig = builder.getConfiguration();

        propertyConfiguration.addConfiguration(
                propertyConfig
        );
    } catch (ConfigurationException e) {
        throw new ElepyConfigException("Failed to load properties", e);
    }
    return this;
}
 
Example 2
Source Project: obevo   Source File: DbEnvironmentXmlEnricherTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
    public void convert() throws Exception {
        XMLConfiguration configuration = new FileBasedConfigurationBuilder<>(XMLConfiguration.class)
                .configure(new Parameters().hierarchical()
                        .setFile(new File("./src/test/resources/DbEnvironmentXmlEnricher/system-config.xml"))
                ).getConfiguration();

        Map<String, Object> myMap = constructMap(configuration.getNodeModel().getNodeHandler().getRootNode());

        YAMLConfiguration yamlConfiguration = new YAMLConfiguration(configuration);
        StringWriter sw = new StringWriter();
//        yamlConfiguration.write();
        DumperOptions dumperOptions = new DumperOptions();
//        dumperOptions.setPrettyFlow(true);
        dumperOptions.setDefaultFlowStyle(FlowStyle.BLOCK);
        Yaml yaml = new Yaml(dumperOptions);
        yaml.dump(myMap, sw);

//        yamlConfiguration.dump(sw, new DumperOptions());
        System.out.println(sw.toString());
    }
 
Example 3
Source Project: obevo   Source File: DbFileMerger.java    License: Apache License 2.0 6 votes vote down vote up
public void execute(DbFileMergerArgs args) {
    PropertiesConfiguration config;
    RichIterable<DbMergeInfo> dbNameLocationPairs;
    try {
        config = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
                .configure(new Parameters().properties()
                        .setFile(args.getDbMergeConfigFile())
                        .setListDelimiterHandler(new LegacyListDelimiterHandler(','))
                )
                .getConfiguration();
        dbNameLocationPairs = DbMergeInfo.parseFromProperties(config);
    } catch (Exception e) {
        throw new DeployerRuntimeException("Exception reading configs from file " + args.getDbMergeConfigFile(), e);
    }

    Platform dialect = PlatformConfiguration.getInstance().valueOf(config.getString("dbType"));
    this.generateDiffs(dialect, dbNameLocationPairs, args.getOutputDir());
}
 
Example 4
@Test
void provideCassandraConfigurationShouldReturnRightConfigurationFile() throws ConfigurationException {
    FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
        .configure(new Parameters()
            .fileBased()
            .setURL(ClassLoader.getSystemResource("configuration-reader-test/cassandra.properties")));

    CassandraConfiguration configuration = CassandraConfiguration.from(builder.getConfiguration());

    assertThat(configuration)
        .isEqualTo(CassandraConfiguration.builder()
            .aclMaxRetry(1)
            .modSeqMaxRetry(2)
            .uidMaxRetry(3)
            .flagsUpdateMessageMaxRetry(4)
            .flagsUpdateMessageIdMaxRetry(5)
            .fetchNextPageInAdvanceRow(6)
            .messageReadChunkSize(7)
            .expungeChunkSize(8)
            .blobPartSize(9)
            .attachmentV2MigrationReadTimeout(10)
            .messageAttachmentIdsReadTimeout(11)
            .consistencyLevelRegular("LOCAL_QUORUM")
            .consistencyLevelLightweightTransaction("LOCAL_SERIAL")
            .build());
}
 
Example 5
/**
 * Tests whether listeners at managed builders are removed when the cache is
 * cleared.
 */
@Test
public void testRemoveBuilderListenerOnReset()
        throws ConfigurationException
{
    final BuilderEventListenerImpl listener = new BuilderEventListenerImpl();
    final Collection<FileBasedConfigurationBuilder<XMLConfiguration>> managedBuilders =
            new ArrayList<>();
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            createBuilderWithAccessToManagedBuilders(managedBuilders);
    switchToConfig(1);
    builder.addEventListener(ConfigurationBuilderEvent.RESET, listener);
    builder.getConfiguration();
    builder.resetParameters();
    managedBuilders.iterator().next().resetResult();
    listener.assertNoMoreEvents();
}
 
Example 6
Source Project: james-project   Source File: FileConfigurationProvider.java    License: Apache License 2.0 6 votes vote down vote up
public static XMLConfiguration getConfig(InputStream configStream) throws ConfigurationException {
    FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<>(XMLConfiguration.class)
        .configure(new Parameters()
            .xml()
            .setListDelimiterHandler(new DisabledListDelimiterHandler()));
    XMLConfiguration xmlConfiguration = builder.getConfiguration();
    FileHandler fileHandler = new FileHandler(xmlConfiguration);
    fileHandler.load(configStream);
    try {
        configStream.close();
    } catch (IOException ignored) {
        // Ignored
    }

    return xmlConfiguration;
}
 
Example 7
Source Project: data-prep   Source File: PropertiesEncryption.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Applies the specified function to the specified set of parameters contained in the input file.
 *
 * @param input The specified name of file to encrypt
 * @param mustBeModified the specified set of parameters
 * @param function the specified function to apply to the set of specified parameters
 */
private void modifyAndSave(String input, Set<String> mustBeModified, Function<String, String> function) {
    Path inputFilePath = Paths.get(input);
    if (Files.exists(inputFilePath) && Files.isRegularFile(inputFilePath) && Files.isReadable(inputFilePath)) {
        try {
            Parameters params = new Parameters();
            FileBasedConfigurationBuilder<PropertiesConfiguration> builder = //
                    new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class) //
                            .configure(params
                                    .fileBased() //
                                    .setFile(inputFilePath.toFile())); //
            PropertiesConfiguration config = builder.getConfiguration();
            mustBeModified.stream().filter(config::containsKey).forEach(
                    key -> config.setProperty(key, function.apply(config.getString(key))));

            builder.save();
        } catch (ConfigurationException e) {
            LOGGER.error("unable to read {} {}", input, e);
        }
    } else {
        LOGGER.debug("No readable file at {}", input);
    }
}
 
Example 8
/**
 * Test of read method with changed comment leading separator
 */
@Test
public void testCommentLeadingSeparatorUsedInINIInput() throws Exception
{
    final String inputCommentLeadingSeparator = ";";
    final String input = "[section]" + LINE_SEPARATOR
        + "key1=a;b;c" + LINE_SEPARATOR
        + "key2=a#b#c" + LINE_SEPARATOR
        + ";key3=value3" + LINE_SEPARATOR
        + "#key4=value4" + LINE_SEPARATOR;

    final INIConfiguration instance = new FileBasedConfigurationBuilder<>(
        INIConfiguration.class)
        .configure(new Parameters().ini()
            .setCommentLeadingCharsUsedInInput(inputCommentLeadingSeparator))
        .getConfiguration();
    load(instance, input);

    assertEquals("a;b;c", instance.getString("section.key1"));
    assertEquals("a#b#c", instance.getString("section.key2"));
    assertNull("", instance.getString("section.;key3"));
    assertEquals("value4", instance.getString("section.#key4"));
}
 
Example 9
/**
 * Creates the reloading controller used by this builder. This method
 * creates a specialized {@link CombinedReloadingController} which operates
 * on the reloading controllers of the managed builders created so far.
 *
 * @return the newly created {@code ReloadingController}
 */
private ReloadingController createReloadingController()
{
    final Set<ReloadingController> empty = Collections.emptySet();
    return new CombinedReloadingController(empty)
    {
        @Override
        public Collection<ReloadingController> getSubControllers()
        {
            final Collection<FileBasedConfigurationBuilder<T>> builders =
                    getManagedBuilders().values();
            final Collection<ReloadingController> controllers =
                    new ArrayList<>(builders.size());
            for (final FileBasedConfigurationBuilder<T> b : builders)
            {
                controllers.add(((ReloadingControllerSupport) b)
                        .getReloadingController());
            }
            return controllers;
        }
    };
}
 
Example 10
/**
 * Tests whether builder reset events are handled correctly.
 */
@Test
public void testBuilderListenerReset() throws ConfigurationException
{
    final BuilderEventListenerImpl listener = new BuilderEventListenerImpl();
    final Collection<FileBasedConfigurationBuilder<XMLConfiguration>> managedBuilders =
            new ArrayList<>();
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            createBuilderWithAccessToManagedBuilders(managedBuilders);
    switchToConfig(1);
    builder.addEventListener(ConfigurationBuilderEvent.RESET, listener);
    final XMLConfiguration configuration = builder.getConfiguration();
    managedBuilders.iterator().next().resetResult();
    final ConfigurationBuilderEvent event =
            listener.nextEvent(ConfigurationBuilderEvent.RESET);
    assertSame("Wrong event source", builder, event.getSource());
    assertNotSame("Configuration not reset", configuration,
            builder.getConfiguration());
}
 
Example 11
/**
 * {@inheritDoc} This implementation ensures that the listener is also
 * removed from managed configuration builders if necessary.
 */
@Override
public synchronized <E extends Event> boolean removeEventListener(
        final EventType<E> eventType, final EventListener<? super E> l)
{
    final boolean result = super.removeEventListener(eventType, l);
    if (isEventTypeForManagedBuilders(eventType))
    {
        for (final FileBasedConfigurationBuilder<T> b : getManagedBuilders()
                .values())
        {
            b.removeEventListener(eventType, l);
        }
        configurationListeners.removeEventListener(eventType, l);
    }
    return result;
}
 
Example 12
/**
 * Test of save method with changed separator
 */
@Test
public void testSeparatorUsedInINIOutput() throws Exception
{
	final String outputSeparator = ": ";
	final String input = MessageFormat.format(INI_DATA4, "=").trim();
	final String expectedOutput = MessageFormat.format(INI_DATA4, outputSeparator).trim();

	final INIConfiguration instance = new FileBasedConfigurationBuilder<>(
	        INIConfiguration.class)
            .configure(new Parameters().ini().setSeparatorUsedInOutput(outputSeparator))
            .getConfiguration();
    load(instance, input);

    final Writer writer = new StringWriter();
    instance.write(writer);
    final String result = writer.toString().trim();

    assertEquals("Wrong content of ini file", expectedOutput, result);
}
 
Example 13
/**
 * Tests whether the addNodes() method triggers an auto save.
 */
@Test
public void testAutoSaveAddNodes() throws ConfigurationException
{
    final FileBasedConfigurationBuilder<XMLConfiguration> builder =
            new FileBasedConfigurationBuilder<>(
                    XMLConfiguration.class);
    builder.configure(new FileBasedBuilderParametersImpl()
            .setFileName(testProperties));
    conf = builder.getConfiguration();
    builder.getFileHandler().setFile(testSaveConf);
    builder.setAutoSave(true);
    final ImmutableNode node = NodeStructureHelper.createNode(
            "addNodesTest", Boolean.TRUE);
    final Collection<ImmutableNode> nodes = new ArrayList<>(1);
    nodes.add(node);
    conf.addNodes("test.autosave", nodes);
    final XMLConfiguration c2 = new XMLConfiguration();
    load(c2, testSaveConf.getAbsolutePath());
    assertTrue("Added nodes are not saved", c2
            .getBoolean("test.autosave.addNodesTest"));
}
 
Example 14
/**
 * Tests whether the auto save mechanism is triggered by changes at a
 * subnode configuration.
 */
@Test
public void testAutoSaveWithSubnodeConfig() throws ConfigurationException
{
    final FileBasedConfigurationBuilder<XMLConfiguration> builder =
            new FileBasedConfigurationBuilder<>(
                    XMLConfiguration.class);
    builder.configure(new FileBasedBuilderParametersImpl()
            .setFileName(testProperties));
    conf = builder.getConfiguration();
    builder.getFileHandler().setFile(testSaveConf);
    builder.setAutoSave(true);
    final String newValue = "I am autosaved";
    final Configuration sub = conf.configurationAt("element2.subelement", true);
    sub.setProperty("subsubelement", newValue);
    assertEquals("Change not visible to parent", newValue,
            conf.getString("element2.subelement.subsubelement"));
    final XMLConfiguration conf2 = new XMLConfiguration();
    load(conf2, testSaveConf.getAbsolutePath());
    assertEquals("Change was not saved", newValue,
            conf2.getString("element2.subelement.subsubelement"));
}
 
Example 15
/**
 * Tests whether a subnode configuration created from another subnode
 * configuration of a XMLConfiguration can trigger the auto save mechanism.
 */
@Test
public void testAutoSaveWithSubSubnodeConfig() throws ConfigurationException
{
    final FileBasedConfigurationBuilder<XMLConfiguration> builder =
            new FileBasedConfigurationBuilder<>(
                    XMLConfiguration.class);
    builder.configure(new FileBasedBuilderParametersImpl()
            .setFileName(testProperties));
    conf = builder.getConfiguration();
    builder.getFileHandler().setFile(testSaveConf);
    builder.setAutoSave(true);
    final String newValue = "I am autosaved";
    final HierarchicalConfiguration<?> sub1 = conf.configurationAt("element2", true);
    final HierarchicalConfiguration<?> sub2 = sub1.configurationAt("subelement", true);
    sub2.setProperty("subsubelement", newValue);
    assertEquals("Change not visible to parent", newValue, conf
            .getString("element2.subelement.subsubelement"));
    final XMLConfiguration conf2 = new XMLConfiguration();
    load(conf2, testSaveConf.getAbsolutePath());
    assertEquals("Change was not saved", newValue, conf2
            .getString("element2.subelement.subsubelement"));
}
 
Example 16
/**
 * Tests constructing an XMLConfiguration from a non existing file and later
 * saving to this file.
 */
@Test
public void testLoadAndSaveFromFile() throws Exception
{
    // If the file does not exist, an empty config is created
    assertFalse("File exists", testSaveConf.exists());
    final FileBasedConfigurationBuilder<XMLConfiguration> builder =
            new FileBasedConfigurationBuilder<>(
                    XMLConfiguration.class, null, true);
    builder.configure(new FileBasedBuilderParametersImpl()
            .setFile(testSaveConf));
    conf = builder.getConfiguration();
    assertTrue(conf.isEmpty());
    conf.addProperty("test", "yes");
    builder.save();

    final XMLConfiguration checkConfig =
            createFromFile(testSaveConf.getAbsolutePath());
    assertEquals("yes", checkConfig.getString("test"));
}
 
Example 17
Source Project: carina   Source File: AliceRecognition.java    License: Apache License 2.0 6 votes vote down vote up
private AliceRecognition() {
    try {
        CombinedConfiguration config = new CombinedConfiguration(new MergeCombiner());
        config.addConfiguration(new SystemConfiguration());
        config.addConfiguration(new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
                .configure(new Parameters().properties().setFileName(ALICE_PROPERTIES)).getConfiguration());

        this.enabled = config.getBoolean(ALICE_ENABLED, false);
        String url = config.getString(ALICE_SERVICE_URL, null);
        String accessToken = config.getString(ALICE_ACCESS_TOKEN, null);
        String command = config.getString(ALICE_COMMAND, null);

        if (enabled && !StringUtils.isEmpty(url) && !StringUtils.isEmpty(accessToken)) {
            this.client = new AliceClient(url, command);
            this.client.setAuthToken(accessToken);
            this.enabled = this.client.isAvailable();
        }
    } catch (Exception e) {
        LOGGER.error("Unable to initialize Alice: " + e.getMessage(), e);
    }
}
 
Example 18
/**
 * Test of read method with changed separator.
 */
@Test
public void testSeparatorUsedInINIInput() throws Exception
{
    final String inputSeparator = "=";
    final String input = "[section]" + LINE_SEPARATOR
        + "k1:v1$key1=value1" + LINE_SEPARATOR
        + "k1:v1,k2:v2$key2=value2" + LINE_SEPARATOR
        + "key3:value3" + LINE_SEPARATOR
        + "key4 = value4" + LINE_SEPARATOR;

    final INIConfiguration instance = new FileBasedConfigurationBuilder<>(
        INIConfiguration.class)
        .configure(new Parameters().ini().setSeparatorUsedInInput(inputSeparator))
        .getConfiguration();
    load(instance, input);

    assertEquals("value1", instance.getString("section.k1:v1$key1"));
    assertEquals("value2", instance.getString("section.k1:v1,k2:v2$key2"));
    assertEquals("", instance.getString("section.key3:value3"));
    assertEquals("value4", instance.getString("section.key4").trim());
}
 
Example 19
/**
 * Tests a definition configuration which does not contain sources with
 * reloading support.
 */
@Test
public void testNoReloadableSources() throws ConfigurationException
{
    final File testFile =
            ConfigurationAssert
                    .getTestFile("testDigesterConfiguration.xml");
    builder.configure(new CombinedBuilderParametersImpl()
            .setDefinitionBuilder(
                    new FileBasedConfigurationBuilder<>(
                            XMLConfiguration.class))
            .setDefinitionBuilderParameters(
                    new FileBasedBuilderParametersImpl().setFile(testFile)));
    builder.getConfiguration();
    final CombinedReloadingController rc =
            (CombinedReloadingController) builder.getReloadingController();
    assertTrue("Got sub reloading controllers", rc.getSubControllers()
            .isEmpty());
}
 
Example 20
/**
 * Tests whether initialization parameters of managed builders are cloned
 * before they are applied.
 */
@Test
public void testGetManagedBuilderClonedParameters()
        throws ConfigurationException
{
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            createTestBuilder(new XMLBuilderParametersImpl());
    switchToConfig(1);
    final FileBasedConfigurationBuilder<XMLConfiguration> managedBuilder1 =
            builder.getManagedBuilder();
    switchToConfig(2);
    final FileBasedConfigurationBuilder<XMLConfiguration> managedBuilder2 =
            builder.getManagedBuilder();
    assertNotSame("Managed parameters not cloned",
            managedBuilder1.getFileHandler(),
            managedBuilder2.getFileHandler());
}
 
Example 21
/**
 * {@inheritDoc} This implementation creates a specialized reloading
 * builder which is associated with a mock reloading controller.
 */
@Override
protected FileBasedConfigurationBuilder<XMLConfiguration> createManagedBuilder(
        final String fileName, final Map<String, Object> params)
        throws ConfigurationException
{
    final ReloadingController ctrl =
            EasyMock.createMock(ReloadingController.class);
    reloadingControllers.add(ctrl);
    return new ReloadingFileBasedConfigurationBuilder<XMLConfiguration>(
            getResultClass(), params)
    {
        @Override
        public ReloadingController getReloadingController()
        {
            return ctrl;
        }
    };
}
 
Example 22
/**
 * Creates a test builder instance which allows access to the managed
 * builders created by it. The returned builder instance overrides the
 * method for creating managed builders. It stores newly created builders in
 * the passed in collection.
 *
 * @param managedBuilders a collection in which to store managed builders
 * @return the test builder instance
 */
private static MultiFileConfigurationBuilder<XMLConfiguration> createBuilderWithAccessToManagedBuilders(
        final Collection<FileBasedConfigurationBuilder<XMLConfiguration>> managedBuilders)
{
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            new MultiFileConfigurationBuilder<XMLConfiguration>(
                    XMLConfiguration.class)
            {
                @Override
                protected FileBasedConfigurationBuilder<XMLConfiguration> createInitializedManagedBuilder(
                        final String fileName,
                        final java.util.Map<String, Object> params)
                        throws ConfigurationException
                {
                    final FileBasedConfigurationBuilder<XMLConfiguration> result =
                            super.createInitializedManagedBuilder(fileName,
                                    params);
                    managedBuilders.add(result);
                    return result;
                }
            };
    builder.configure(createTestBuilderParameters(null));
    return builder;
}
 
Example 23
/**
 * Tests whether a reset of the builder configuration also flushes the
 * cache.
 */
@Test
public void testCachingWithReset() throws ConfigurationException
{
    final Collection<FileBasedConfigurationBuilder<XMLConfiguration>> managedBuilders =
            new ArrayList<>();
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            createBuilderWithAccessToManagedBuilders(managedBuilders);
    switchToConfig(1);
    builder.getConfiguration();
    builder.resetParameters();
    builder.configure(createTestBuilderParameters(null));
    builder.getConfiguration();
    assertEquals("Wrong number of managed builders", 2,
            managedBuilders.size());
}
 
Example 24
Source Project: t-io   Source File: ConfigUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param filename1
 * @param filename2
 * @param encoding
 * @param listDelimiter
 * @return
 * @throws FileNotFoundException
 * @author: tanyaowu
 */
public static PropertiesConfiguration initConfig(String filename1, String filename2, String encoding, char listDelimiter) throws FileNotFoundException {
	Parameters _parameters = new Parameters();
	PropertiesBuilderParameters parameters = _parameters.properties();
	String filename = filename1;
	ClassLoader cl = ConfigUtils.class.getClassLoader();
	URL url = null;
	if (StrUtil.isNotBlank(filename1)) {
		url = (cl != null ? cl.getResource(filename1) : ClassLoader.getSystemResource(filename1));
	}

	if (url == null) {
		url = (cl != null ? cl.getResource(filename2) : ClassLoader.getSystemResource(filename2));
		if (url == null) {
			throw new FileNotFoundException(filename1);
		}
		filename = filename2;
	}

	parameters.setFileName(filename);
	parameters.setThrowExceptionOnMissing(false);
	parameters.setEncoding(encoding);
	parameters.setListDelimiterHandler(new DefaultListDelimiterHandler(listDelimiter));
	parameters.setReloadingDetectorFactory(new DefaultReloadingDetectorFactory());
	parameters.setIncludesAllowed(true);
	FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class).configure(parameters);

	try {
		PropertiesConfiguration config = builder.getConfiguration();
		return config;
	} catch (ConfigurationException e) {
		log.error(e.toString(), e);
		return null;
	}
}
 
Example 25
/**
 * Tests whether an instance can be created using a file-based builder.
 */
@Test
public void testLoadFromBuilder() throws ConfigurationException,
        IOException
{
    final File file = writeTestFile(INI_DATA);
    final FileBasedConfigurationBuilder<INIConfiguration> builder =
            new FileBasedConfigurationBuilder<>(
                    INIConfiguration.class);
    builder.configure(new FileBasedBuilderParametersImpl()
            .setFile(file));
    final INIConfiguration config = builder.getConfiguration();
    checkContent(config);
}
 
Example 26
Source Project: obevo   Source File: DbEnvironmentXmlEnricherTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
    public void yamlTest() throws Exception {
        ImmutableHierarchicalConfiguration configuration = new FileBasedConfigurationBuilder<>(YAMLConfiguration.class)
                .configure(new Parameters().hierarchical()
                        .setFile(new File("./src/test/resources/DbEnvironmentXmlEnricher/system-config.yaml"))
//                        .setFile(new File("./src/test/resources/DbEnvironmentXmlEnricher/system-config.xml"))
                ).getConfiguration();
        System.out.println(configuration);
    }
 
Example 27
Source Project: obevo   Source File: PlatformConfigReader.java    License: Apache License 2.0 5 votes vote down vote up
private HierarchicalConfiguration<ImmutableNode> loadPropertiesFromUrl(FileObject file) {
    try {
        return new FileBasedConfigurationBuilder<>(YAMLConfiguration.class)
                .configure(new Parameters().hierarchical().setURL(file.getURLDa()))
                .getConfiguration();
    } catch (ConfigurationException e) {
        throw new DeployerRuntimeException(e);
    }
}
 
Example 28
Source Project: standalone-app   Source File: Helios.java    License: Apache License 2.0 5 votes vote down vote up
private static Configuration loadConfiguration() throws IOException, ConfigurationException {
    Configurations configurations = new Configurations();
    File file = Constants.SETTINGS_FILE_XML;
    if (!file.exists()) {
        XMLConfiguration tempConfiguration = new XMLConfiguration();
        new FileHandler(tempConfiguration).save(file);
    }
    FileBasedConfigurationBuilder<XMLConfiguration> builder = configurations.xmlBuilder(file);
    builder.setAutoSave(true);
    return builder.getConfiguration();
}
 
Example 29
Source Project: datacollector   Source File: SchAdmin.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Update dpm.properties file with new configuration.
 */
private static void updateDpmProperties(Context context, String dpmBaseURL, List<String> labels, boolean enableSch) {
  if(context.skipUpdatingDpmProperties) {
    return;
  }

  try {
    FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
        new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
            .configure(new Parameters().properties()
                .setFileName(context.runtimeInfo.getConfigDir() + "/dpm.properties")
                .setThrowExceptionOnMissing(true)
                .setListDelimiterHandler(new DefaultListDelimiterHandler(';'))
                .setIncludesAllowed(false));
    PropertiesConfiguration config;
    config = builder.getConfiguration();
    config.setProperty(RemoteSSOService.DPM_ENABLED, Boolean.toString(enableSch));
    config.setProperty(RemoteSSOService.DPM_BASE_URL_CONFIG, dpmBaseURL);
    config.setProperty(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG, APP_TOKEN_FILE_PROP_VAL);
    if (labels != null && labels.size() > 0) {
      config.setProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS, StringUtils.join(labels, ','));
    } else {
      config.setProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS, "");
    }
    builder.save();
  } catch (ConfigurationException e) {
    throw new RuntimeException(Utils.format("Updating dpm.properties file failed: {}", e.getMessage()), e);
  }
}
 
Example 30
Source Project: activemq-artemis   Source File: ArtemisTest.java    License: Apache License 2.0 5 votes vote down vote up
private void checkRole(String user, File roleFile, String... roles) throws Exception {
   Configurations configs = new Configurations();
   FileBasedConfigurationBuilder<PropertiesConfiguration> roleBuilder = configs.propertiesBuilder(roleFile);
   PropertiesConfiguration roleConfig = roleBuilder.getConfiguration();

   for (String r : roles) {
      String storedUsers = (String) roleConfig.getProperty(r);

      log.debug("users in role: " + r + " ; " + storedUsers);
      List<String> userList = StringUtil.splitStringList(storedUsers, ",");
      assertTrue(userList.contains(user));
   }
}