org.apache.commons.configuration2.builder.fluent.Parameters Java Examples

The following examples show how to use org.apache.commons.configuration2.builder.fluent.Parameters. 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: AliceRecognition.java    From carina with 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 #2
Source File: CommonsConfigurationLookupService.java    From nifi with Apache License 2.0 6 votes vote down vote up
@OnEnabled
public void onEnabled(final ConfigurationContext context) throws InitializationException {
    final String config = context.getProperty(CONFIGURATION_FILE).evaluateAttributeExpressions().getValue();
    final FileBasedBuilderParameters params = new Parameters().fileBased().setFile(new File(config));
    this.builder = new ReloadingFileBasedConfigurationBuilder<>(resultClass).configure(params);
    builder.addEventListener(ConfigurationBuilderEvent.CONFIGURATION_REQUEST,
        new EventListener<ConfigurationBuilderEvent>() {
            @Override
            public void onEvent(ConfigurationBuilderEvent event) {
                if (builder.getReloadingController().checkForReloading(null)) {
                    getLogger().debug("Reloading " + config);
                }
            }
        });

    try {
        // Try getting configuration to see if there is any issue, for example wrong file format.
        // Then throw InitializationException to keep this service in 'Enabling' state.
        builder.getConfiguration();
    } catch (ConfigurationException e) {
        throw new InitializationException(e);
    }
}
 
Example #3
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 #4
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 #5
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 #6
Source File: TestFileBasedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether HomeDirectoryLocationStrategy can be properly initialized
 * and that it shouldn't throw {@code ConfigurationException} when
 * everything is correctly in place. Without the code fix for
 * <a href="https://issues.apache.org/jira/browse/CONFIGURATION-634">CONFIGURATION-634</a>,
 * this test will throw {@code ConfigurationException}
 * @throws IOException              Shouldn't happen
 * @throws ConfigurationException   Shouldn't happen
 */
@Test
public void testFileBasedConfigurationBuilderWithHomeDirectoryLocationStrategy()
        throws IOException, ConfigurationException
{
    final String folderName = "test";
    final String fileName = "sample.properties";
    folder.newFolder(folderName);
    folder.newFile(folderName + File.separatorChar + fileName);
    final FileBasedConfigurationBuilder<FileBasedConfiguration> homeDirConfigurationBuilder =
            new FileBasedConfigurationBuilder<>(
                    PropertiesConfiguration.class);
    final PropertiesBuilderParameters homeDirProperties =
            new Parameters().properties();
    final HomeDirectoryLocationStrategy strategy =
            new HomeDirectoryLocationStrategy(
                    folder.getRoot().getAbsolutePath(), true);
    final FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
            homeDirConfigurationBuilder.configure(homeDirProperties
                    .setLocationStrategy(strategy).setBasePath(folderName)
                    .setListDelimiterHandler(
                            new DefaultListDelimiterHandler(','))
                    .setFileName(fileName));
    builder.getConfiguration();
}
 
Example #7
Source File: CassandraConfigurationReadingTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: TestCombinedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether builder properties can be inherited by child builders.
 */
@Test
public void testInheritProperties() throws ConfigurationException
{
    final Parameters params = new Parameters();
    final XMLBuilderParameters xmlParams =
            prepareParamsForInheritanceTest(params);
    builder.configure(xmlParams);
    final CombinedConfiguration config = builder.getConfiguration();

    List<String> list = config.getList(String.class, "test/mixed/array");
    assertTrue("Wrong number of elements in list", list.size() > 2);
    final String[] stringArray = config.getStringArray("test/mixed/array");
    assertTrue("Wrong number of elements in array", stringArray.length > 2);
    final XMLConfiguration xmlConfig =
            (XMLConfiguration) config.getConfiguration("xml");
    list = xmlConfig.getList(String.class, "split/list1");
    assertEquals("Wrong number of elements in XML list", 3, list.size());
}
 
Example #9
Source File: TestCombinedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether the inheritance of builder properties can be disabled.
 */
@Test
public void testSuppressChildBuilderPropertyInheritance()
        throws ConfigurationException
{
    final Parameters params = new Parameters();
    final CombinedBuilderParameters combinedParams =
            params.combined().setInheritSettings(false);
    builder.configure(combinedParams,
            prepareParamsForInheritanceTest(params));
    final CombinedConfiguration config = builder.getConfiguration();

    final XMLConfiguration xmlConfig =
            (XMLConfiguration) config.getConfiguration("xml");
    final List<String> list = xmlConfig.getList(String.class, "split.list1");
    assertEquals("Wrong number of elements in XML list", 1, list.size());
}
 
Example #10
Source File: DbFileMerger.java    From obevo with 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 #11
Source File: TestINIConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #12
Source File: TestINIConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #13
Source File: DbEnvironmentXmlEnricherTest.java    From obevo with 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 #14
Source File: TestINIConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #15
Source File: TableSyncher.java    From obevo with Apache License 2.0 6 votes vote down vote up
public void execute(DbFileMergerArgs args) {
    Configuration config;
    try {
        config = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
                .configure(new Parameters().properties()
                        .setFile(args.getDbMergeConfigFile())
                        .setListDelimiterHandler(new LegacyListDelimiterHandler(','))
                ).getConfiguration();
    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }
    RichIterable<DbMergeInfo> dbMergeInfos = DbMergeInfo.parseFromProperties(config);

    RichIterable<TableSyncSide> tableSyncSides = dbMergeInfos.collect(new Function<DbMergeInfo, TableSyncSide>() {
        @Override
        public TableSyncSide valueOf(DbMergeInfo dbMergeInfo) {
            DataSource ds = ds(dbMergeInfo.getDriverClassName(), dbMergeInfo.getUrl(), dbMergeInfo.getUsername(),
                    dbMergeInfo.getPassword());
            return new TableSyncSide(ds, PhysicalSchema.parseFromString(dbMergeInfo.getPhysicalSchema()));
        }
    });

    this.syncSchemaTables(DbPlatformConfiguration.getInstance().valueOf(config.getString("dbType")), tableSyncSides, args.getOutputDir());
}
 
Example #16
Source File: TestCombinedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Prepares a parameters object for a test for properties inheritance.
 * @param params the {@code Parameters} object
 * @return the builder parameters
 */
private static XMLBuilderParameters prepareParamsForInheritanceTest(final Parameters params) {
    final DefaultExpressionEngineSymbols symbols = new DefaultExpressionEngineSymbols.Builder(
            DefaultExpressionEngineSymbols.DEFAULT_SYMBOLS)
            .setPropertyDelimiter("/").create();
    final DefaultExpressionEngine engine = new DefaultExpressionEngine(symbols);
    final DefaultListDelimiterHandler listDelimiterHandler = new DefaultListDelimiterHandler(',');
    return params.xml()
            .setExpressionEngine(engine)
            .setListDelimiterHandler(listDelimiterHandler).setFile(TEST_FILE);
}
 
Example #17
Source File: TestCombinedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception
{
    System.setProperty("java.naming.factory.initial",
            "org.apache.commons.configuration2.MockInitialContextFactory");
    System.setProperty("test_file_xml", TEST_SUB_XML);
    System.setProperty("test_file_combine", "testcombine1.xml");
    parameters = new Parameters();
    builder = new CombinedConfigurationBuilder();
}
 
Example #18
Source File: TestFileBasedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether a configuration can be created and associated with a file that does
 * not yet exist. Later the configuration is saved to this file.
 */
@Test
public void testCreateConfigurationNonExistingFileAndThenSave()
        throws ConfigurationException {
    final File outFile = ConfigurationAssert.getOutFile("save.properties");
    final Parameters parameters = new Parameters();
    final FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(
            PropertiesConfiguration.class, null, true).configure(parameters
            .properties().setFile(outFile));
    final Configuration config = builder.getConfiguration();
    config.setProperty(PROP, 1);
    builder.save();
    checkSavedConfig(outFile, 1);
    assertTrue("Could not remove test file", outFile.delete());
}
 
Example #19
Source File: DatabaseConfigurationTestHelper.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a parameters object with default settings.
 *
 * @return the parameters object
 */
public DatabaseBuilderParameters setUpDefaultParameters()
{
    return new Parameters().database().setDataSource(getDatasource())
            .setTable(TABLE).setKeyColumn(COL_KEY)
            .setValueColumn(COL_VALUE).setAutoCommit(isAutoCommit());
}
 
Example #20
Source File: FileTokenRepository.java    From TNT4J with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize property configuration based on a configured configuration file name. The method attempts to load it
 * from URL if given config is URL, then load it from class path and then from file system.
 *
 * @throws MalformedURLException
 *             if malformed configuration file name
 */
protected void initConfig() throws MalformedURLException {
	int urlIndex = configName.indexOf("://");

	PropertiesBuilderParameters params = new Parameters().properties();

	if (urlIndex > 0) {
		params.setURL(new URL(configName));
	} else {
		URL configResource = getClass().getResource("/" + configName);
		if (configResource != null) {
			params.setURL(configResource);
		} else {
			params.setFileName(configName);
		}
	}

	if (refDelay > 0) {
		params.setReloadingRefreshDelay(refDelay);
		ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration> builder = new ReloadingFileBasedConfigurationBuilder<>(PropertiesConfiguration.class);
		builder.configure(params);
		cfgReloadTrigger = new PeriodicReloadingTrigger(builder.getReloadingController(), null, refDelay, TimeUnit.MILLISECONDS);
		config = builder;
	} else {
		config = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class);
		config.configure(params);
	}

}
 
Example #21
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 #22
Source File: ConfigUtils.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
public static HierarchicalConfiguration<ImmutableNode> readXmlConfiguration(InputStream input)
        throws ConfigurationException {
    Parameters params = new Parameters();
    FileBasedConfigurationBuilder<XMLConfiguration> builder =
            new FileBasedConfigurationBuilder<>(XMLConfiguration.class);
    XMLConfiguration config = builder.configure(params.xml()).getConfiguration();
    FileHandler fileHandler = new FileHandler(config);

    fileHandler.setEncoding("UTF-8");
    fileHandler.load(input);

    return config;
}
 
Example #23
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 #24
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 #25
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 #26
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 #27
Source File: GraphFactory.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private static org.apache.commons.configuration2.Configuration getConfiguration(final File configurationFile) {
    if (!configurationFile.isFile())
        throw new IllegalArgumentException(String.format("The location configuration must resolve to a file and [%s] does not", configurationFile));

    try {
        final String fileName = configurationFile.getName();
        final String fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);

        final Configuration conf;
        final Configurations configs = new Configurations();

        switch (fileExtension) {
            case "yml":
            case "yaml":
                final Parameters params = new Parameters();
                final FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
                        new FileBasedConfigurationBuilder<FileBasedConfiguration>(YAMLConfiguration.class).
                                configure(params.fileBased().setFile(configurationFile));

                final org.apache.commons.configuration2.Configuration copy = new org.apache.commons.configuration2.BaseConfiguration();
                ConfigurationUtils.copy(builder.configure(params.fileBased().setFile(configurationFile)).getConfiguration(), copy);
                conf = copy;
                break;
            case "xml":
                conf = configs.xml(configurationFile);
                break;
            default:
                conf = configs.properties(configurationFile);
        }
        return conf;
    } catch (ConfigurationException e) {
        throw new IllegalArgumentException(String.format("Could not load configuration at: %s", configurationFile), e);
    }
}
 
Example #28
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 #29
Source File: PlatformConfigReader.java    From obevo with 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 #30
Source File: DbEnvironmentXmlEnricherTest.java    From obevo with 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);
    }