Java Code Examples for org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder#getConfiguration()

The following examples show how to use org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder#getConfiguration() . 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: TestConfigurations.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether a builder for a properties configuration can be created for
 * a given file path when an include is not found.
 */
@Test
public void testPropertiesBuilderFromPathIncludeNotFoundFail() throws ConfigurationException
{
    final Configurations configs = new Configurations();
    final FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
            configs.propertiesBuilder(absolutePath("include-not-found.properties"));
    try
    {
        builder.getConfiguration();
        Assert.fail("Expected ConfigurationException");
    }
    catch (ConfigurationException e) {
        // ignore
    }
}
 
Example 2
Source File: TestXMLConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 3
Source File: TestXMLConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 4
Source File: TestXMLConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 5
Source File: TestXMLConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 6
Source File: FileConfigurationProvider.java    From james-project with 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 File: Elepy.java    From elepy with 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 8
Source File: PropertiesEncryption.java    From data-prep with 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 9
Source File: LdapConfig.java    From ranger with Apache License 2.0 5 votes vote down vote up
public void updateInputPropFile(String ldapUrl, String bindDn, String bindPassword,
                                String userSearchBase, String userSearchFilter,
                                String authUser, String authPass) {
    try {
        Parameters params = new Parameters();
        FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
            new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
            .configure(params.fileBased().setFileName(CONFIG_FILE));
        FileBasedConfiguration config = builder.getConfiguration();
        // Update properties in memory and update the file as well
        prop.setProperty(LGSYNC_LDAP_URL, ldapUrl);
        prop.setProperty(LGSYNC_LDAP_BIND_DN, bindDn);
        prop.setProperty(LGSYNC_LDAP_BIND_PASSWORD, bindPassword);
        prop.setProperty(LGSYNC_USER_SEARCH_BASE, userSearchBase);
        prop.setProperty(LGSYNC_USER_SEARCH_FILTER, userSearchFilter);
        prop.setProperty(AUTH_USERNAME, authUser);
        prop.setProperty(AUTH_PASSWORD, authPass);
        config.setProperty(LGSYNC_LDAP_URL, ldapUrl);
        config.setProperty(LGSYNC_LDAP_BIND_DN, bindDn);
        //config.setProperty(LGSYNC_LDAP_BIND_PASSWORD, bindPassword);
        config.setProperty(LGSYNC_USER_SEARCH_BASE, userSearchBase);
        config.setProperty(LGSYNC_USER_SEARCH_FILTER, userSearchFilter);
        config.setProperty(AUTH_USERNAME, authUser);
        //config.setProperty(AUTH_PASSWORD, authPass);
        builder.save();
    } catch (ConfigurationException e) {
        System.out.println("Failed to update " + CONFIG_FILE + ": " + e);
    }
}
 
Example 10
Source File: TestINIConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * 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 11
Source File: TestXMLConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
@Test
public void testConcurrentGetAndReload() throws ConfigurationException,
        InterruptedException
{
    final FileBasedConfigurationBuilder<XMLConfiguration> builder =
            new FileBasedConfigurationBuilder<>(
                    XMLConfiguration.class);
    builder.configure(new FileBasedBuilderParametersImpl()
            .setFileName(testProperties));
    XMLConfiguration config = builder.getConfiguration();
    assertTrue("Property not found",
            config.getProperty("test.short") != null);

    final Thread testThreads[] = new Thread[THREAD_COUNT];
    for (int i = 0; i < testThreads.length; ++i)
    {
        testThreads[i] = new ReloadThread(builder);
        testThreads[i].start();
    }

    for (int i = 0; i < LOOP_COUNT; i++)
    {
        config = builder.getConfiguration();
        assertTrue("Property not found", config.getProperty("test.short") != null);
    }

    for (final Thread testThread : testThreads) {
        testThread.join();
    }
}
 
Example 12
Source File: TestPropertiesConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether the correct file system is used when loading an include
 * file. This test is related to CONFIGURATION-609.
 */
@Test
public void testLoadIncludeFileViaFileSystem() throws ConfigurationException
{
    conf.clear();
    conf.addProperty("include", "include.properties");
    saveTestConfig();

    final FileSystem fs = new DefaultFileSystem()
    {
        @Override
        public InputStream getInputStream(final URL url)
                throws ConfigurationException
        {
            if (url.toString().endsWith("include.properties"))
            {
                try
                {
                    return new ByteArrayInputStream(
                            "test.outcome = success".getBytes("UTF-8"));
                }
                catch (final UnsupportedEncodingException e)
                {
                    throw new ConfigurationException("Unsupported encoding",
                            e);
                }
            }
            return super.getInputStream(url);
        }
    };
    final Parameters params = new Parameters();
    final FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
            new FileBasedConfigurationBuilder<>(
                    PropertiesConfiguration.class);
    builder.configure(params.fileBased().setFile(testSavePropertiesFile)
            .setBasePath(ConfigurationAssert.OUT_DIR.toURI().toString())
            .setFileSystem(fs));
    final PropertiesConfiguration configuration = builder.getConfiguration();
    assertEquals("success", configuration.getString("test.outcome"));
}
 
Example 13
Source File: ConfigurationProviderImpl.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Load the xmlConfiguration from the given resource.
 * 
 * @param r
 * @return
 * @throws ConfigurationException
 * @throws IOException
 */
private XMLConfiguration getConfig(Resource r) throws ConfigurationException, IOException {
    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(r.getInputStream());

    return xmlConfiguration;
}
 
Example 14
Source File: PropertiesProvider.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Configuration getConfiguration(File propertiesFile) throws ConfigurationException {
    FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
        .configure(new Parameters()
            .fileBased()
            .setListDelimiterHandler(new DefaultListDelimiterHandler(COMMA))
            .setFile(propertiesFile));

    return new DelegatedPropertiesConfiguration(COMMA_STRING, builder.getConfiguration());
}
 
Example 15
Source File: MailetConfigImplTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<>(XMLConfiguration.class)
        .configure(new Parameters()
            .xml()
            .setListDelimiterHandler(new DisabledListDelimiterHandler()));
    xmlConfiguration = builder.getConfiguration();
    fileHandler = new FileHandler(xmlConfiguration);

    config = new MailetConfigImpl();
}
 
Example 16
Source File: ArtemisTest.java    From activemq-artemis with 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));
   }
}
 
Example 17
Source File: SchAdmin.java    From datacollector with 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 18
Source File: Helios.java    From standalone-app with 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 19
Source File: ConfigUtils.java    From t-io with 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 20
Source File: ArtemisTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private String getStoredPassword(String user, File userFile) throws Exception {
   Configurations configs = new Configurations();
   FileBasedConfigurationBuilder<PropertiesConfiguration> userBuilder = configs.propertiesBuilder(userFile);
   PropertiesConfiguration userConfig = userBuilder.getConfiguration();
   return (String) userConfig.getProperty(user);
}