org.apache.commons.configuration2.builder.fluent.Parameters类的使用及代码示例

x33g5p2x  于2022-01-26 转载在 其他  
字(14.9k)|赞(0)|评价(0)|浏览(152)

本文整理了Java中org.apache.commons.configuration2.builder.fluent.Parameters类的一些代码示例,展示了Parameters类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Parameters类的具体详情如下:
包路径:org.apache.commons.configuration2.builder.fluent.Parameters
类名称:Parameters

Parameters介绍

[英]A convenience class for creating parameter objects for initializing configuration builder objects.

For setting initialization properties of new configuration objects, a number of specialized parameter classes exists. These classes use inheritance to organize the properties they support in a logic way. For instance, parameters for file-based configurations also support the basic properties common to all configuration implementations, parameters for XML configurations also include file-based and basic properties, etc.

When constructing a configuration builder, an easy-to-use fluent API is desired to define specific properties for the configuration to be created. However, the inheritance structure of the parameter classes makes it surprisingly difficult to provide such an API. This class comes to rescue by defining a set of methods for the creation of interface-based parameter objects offering a truly fluent API. The methods provided can be called directly when setting up a configuration builder as shown in the following example code fragment:

Parameters params = new Parameters(); 
configurationBuilder.configure(params.fileBased() 
.setThrowExceptionOnMissing(true).setEncoding("UTF-8") 
.setListDelimiter('#').setFileName("test.xml"));

Using this class it is not only possible to create new parameters objects but also to initialize the newly created objects with default values. This is via the associated DefaultParametersManager object. Such an object can be passed to the constructor, or a new (uninitialized) instance is created. There are convenience methods for interacting with the associated DefaultParametersManager, namely to register or remove DefaultParametersHandler objects. On all newly created parameters objects the handlers registered at the associated DefaultParametersHandlerare automatically applied.

Implementation note: This class is thread-safe.
[中]一个方便的类,用于创建用于初始化configuration builder对象的参数对象。
为了设置新配置对象的初始化属性,存在许多专门的参数类。这些类使用继承以逻辑方式组织它们支持的属性。例如,基于文件的配置的参数还支持所有配置实现所共有的基本属性,XML配置的参数还包括基于文件的属性和基本属性等。
构造配置生成器时,需要一个易于使用的fluent API来定义要创建的配置的特定属性。然而,参数类的继承结构使得提供这样的API异常困难。这个类通过定义一组方法来帮助创建基于接口的参数对象,提供真正流畅的API。设置配置生成器时,可以直接调用提供的方法,如以下示例代码片段所示:

Parameters params = new Parameters(); 
configurationBuilder.configure(params.fileBased() 
.setThrowExceptionOnMissing(true).setEncoding("UTF-8") 
.setListDelimiter('#').setFileName("test.xml"));

使用该类不仅可以创建新的参数对象,还可以使用默认值初始化新创建的对象。这是通过关联的DefaultParametersManager对象实现的。这样的对象可以传递给构造函数,或者创建一个新的(未初始化的)实例。有一些方便的方法可以与关联的DefaultParametersManager交互,即注册或删除DefaultParametersHandler对象。在所有新创建的参数对象上,在关联的DefaultParametersHandleRear中注册的处理程序将自动应用。
实现说明:这个类是线程安全的。

代码示例

代码示例来源:origin: apache/nifi

@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);
  }
}

代码示例来源:origin: goldmansachs/obevo

public static DbDataComparisonConfig createFromProperties(String path) {
  try {
    URL url = DbDataComparisonConfigFactory.class.getClassLoader().getResource(path);
    if (url == null) {
      url = new File(path).toURI().toURL();
    }
    if (url == null) {
      throw new IllegalArgumentException("Could not find resource or file at path: " + path);
    }
    return createFromProperties(new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class).configure(new Parameters().properties()
        .setURL(url)
        .setListDelimiterHandler(new LegacyListDelimiterHandler(','))
    ).getConfiguration());
  } catch (ConfigurationException e) {
    throw new RuntimeException(e);
  } catch (MalformedURLException e) {
    throw new IllegalArgumentException("Could not find resource or file at path: " + path, e);
  }
}

代码示例来源:origin: goldmansachs/obevo

private HierarchicalConfiguration<ImmutableNode> loadPropertiesFromUrl(FileObject file) {
  try {
    return new FileBasedConfigurationBuilder<>(FixedYAMLConfiguration.class)
        .configure(new Parameters().hierarchical().setURL(file.getURLDa()))
        .getConfiguration();
  } catch (ConfigurationException e) {
    throw new DeployerRuntimeException(e);
  }
}

代码示例来源:origin: de.julielab/julielab-topic-modeling

public XMLConfiguration loadConfig(String configFile) throws ConfigurationException {
  Parameters params = new Parameters();
  FileBasedConfigurationBuilder<XMLConfiguration> builder =
      new FileBasedConfigurationBuilder<XMLConfiguration>(XMLConfiguration.class)
          .configure(params.xml()
              .setFileName(configFile));
  XMLConfiguration xmlConfig = builder.getConfiguration();
  return xmlConfig;
}

代码示例来源:origin: org.openksavi.sponge/sponge-core

new FallbackBasePathLocationStrategy(FileLocatorUtils.DEFAULT_LOCATION_STRATEGY, home);
FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<>(XMLConfiguration.class)
    .configure(new Parameters().xml().setLocationStrategy(locationStrategy).setFileName(fileName).setSchemaValidation(true)
        .setEntityResolver(new ResourceSchemaResolver()));
  propertiesConfiguration =
      new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
          .configure(new Parameters().properties().setLocationStrategy(propertiesLocationStrategy)
              .setFileName(propertiesFileName).setEncoding(Charsets.UTF_8.name()).setThrowExceptionOnMissing(false))
          .getConfiguration();

代码示例来源:origin: org.apache.commons/commons-configuration2

/**
 * Creates a new instance of {@code Configurations} and initializes it with
 * the specified {@code Parameters} object.
 *
 * @param params the {@code Parameters} (may be <b>null</b>, then a default
 *        instance is created)
 */
public Configurations(final Parameters params)
{
  parameters = (params != null) ? params : new Parameters();
}

代码示例来源:origin: org.apache.commons/commons-configuration2

/**
 * Convenience method for creating a parameters object for a file-based
 * configuration.
 *
 * @return the newly created parameters object
 */
private FileBasedBuilderParameters fileParams()
{
  return getParameters().fileBased();
}

代码示例来源:origin: com.goldmansachs.obevo/obevo-db

public static DbDataComparisonConfig createFromProperties(String path) {
  try {
    URL url = DbDataComparisonConfigFactory.class.getClassLoader().getResource(path);
    if (url == null) {
      url = new File(path).toURI().toURL();
    }
    if (url == null) {
      throw new IllegalArgumentException("Could not find resource or file at path: " + path);
    }
    return createFromProperties(new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class).configure(new Parameters().properties()
        .setURL(url)
        .setListDelimiterHandler(new LegacyListDelimiterHandler(','))
    ).getConfiguration());
  } catch (ConfigurationException e) {
    throw new RuntimeException(e);
  } catch (MalformedURLException e) {
    throw new IllegalArgumentException("Could not find resource or file at path: " + path, e);
  }
}

代码示例来源:origin: com.goldmansachs.obevo/obevo-core

private HierarchicalConfiguration<ImmutableNode> loadPropertiesFromUrl(FileObject file) {
  try {
    return new FileBasedConfigurationBuilder<>(FixedYAMLConfiguration.class)
        .configure(new Parameters().hierarchical().setURL(file.getURLDa()))
        .getConfiguration();
  } catch (ConfigurationException e) {
    throw new DeployerRuntimeException(e);
  }
}

代码示例来源:origin: com.cerner.beadledom/beadledom-configuration

private static FileBasedConfiguration createConfiguration(Reader reader)
  throws ConfigurationException {
 if (reader == null) {
  throw new NullPointerException("reader: null");
 }
 FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
   new FileBasedConfigurationBuilder<FileBasedConfiguration>(XMLConfiguration.class)
     .configure(new Parameters().xml());
 FileBasedConfiguration fileBasedConfiguration = builder.getConfiguration();
 FileHandler handler = new FileHandler(fileBasedConfiguration);
 handler.load(reader);
 return fileBasedConfiguration;
}

代码示例来源:origin: com.cerner.beadledom/beadledom-configuration

private static FileBasedConfiguration createPropertiesConfiguration(Reader reader)
  throws ConfigurationException, IOException {
 if (reader == null) {
  throw new NullPointerException("reader: null");
 }
 FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
   new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
     .configure(new Parameters()
       .properties()
       .setListDelimiterHandler(new DefaultListDelimiterHandler(',')));
 FileBasedConfiguration config = builder.getConfiguration();
 config.read(reader);
 return config;
}

代码示例来源:origin: de.julielab/jssf-commons

public ExternalToolService() throws ConfigurationException {
  ClasspathResource resource = new ClasspathResource(ExternalToolConstants.EXTERNAL_TOOL_VERSIONS_FILE);
  Parameters params = new Parameters();
  FileBasedConfigurationBuilder<JSONConfiguration> configBuilder =
      new FileBasedConfigurationBuilder<>(JSONConfiguration.class).configure(params.hierarchical()
          .setLocationStrategy(new ClasspathLocationStrategy())
          .setFileName(ExternalToolConstants.EXTERNAL_TOOL_VERSIONS_FILE));
  externalToolsConfiguration = configBuilder.getConfiguration();
}

代码示例来源:origin: demoiselle/framework

private void configureFileBuilder(Enumeration<URL> urlResources) {
  Parameters params = new Parameters();
  while (urlResources.hasMoreElements()) {
    BasicConfigurationBuilder<? extends Configuration> builder = createConfiguration();
    URL url = urlResources.nextElement();
    ((FileBasedConfigurationBuilder<?>) builder).configure(params.fileBased().setURL(url));
    try {
      configurations.add(builder.getConfiguration());
    } catch (ConfigurationException e) {
      logger.warning(message.failOnCreateApacheConfiguration(e.getMessage()));
    }
  }
}

代码示例来源:origin: de.julielab/julielab-java-utilities

/**
 * Loads the Apache Commons Configuration2 {@link XMLConfiguration} from the given file. By default,
 * the {@link XPathExpressionEngine} is set.
 * @param configurationFile
 * @return
 * @throws ConfigurationException
 */
public static XMLConfiguration loadXmlConfiguration(File configurationFile) throws ConfigurationException {
  try {
    Parameters params = new Parameters();
    FileBasedConfigurationBuilder<XMLConfiguration> configBuilder =
        new FileBasedConfigurationBuilder<>(XMLConfiguration.class).configure(params
            .xml()
            .setExpressionEngine(new XPathExpressionEngine())
            .setFile(configurationFile));
    return configBuilder.getConfiguration();
  } catch (org.apache.commons.configuration2.ex.ConfigurationException e) {
    throw new ConfigurationException(e);
  }
}

代码示例来源:origin: ga4gh/dockstore

/**
 * The singleton map os not entirely awesome, but this allows our legacy code to
 * benefit from live reloads for configuration while the application is running
 *
 * @param configFile the path to the config file which should be loaded
 * @return configuration file
 */
public static INIConfiguration parseConfig(String configFile) {
  if (!MAP.containsKey(configFile)) {
    ReloadingFileBasedConfigurationBuilder<INIConfiguration> builder = new ReloadingFileBasedConfigurationBuilder<>(
        INIConfiguration.class).configure(new Parameters().properties().setFileName(configFile));
    PeriodicReloadingTrigger trigger = new PeriodicReloadingTrigger(builder.getReloadingController(), null, 1, TimeUnit.MINUTES);
    trigger.start();
    MAP.put(configFile, builder);
  }
  try {
    return MAP.get(configFile).getConfiguration();
  } catch (ConfigurationException ex) {
    throw new RuntimeException("Could not read " + configFile);
  }
}

代码示例来源:origin: com.quinsoft.zeidon/zeidon-joe

private void loadZeidonIni( InputStream iniFile )
{
  if ( iniFile == null )
    throw new ZeidonException( "Could not find " + iniFileName );
  InputStreamReader reader = new InputStreamReader( iniFile );
  try
  {
    DefaultExpressionEngine engine = new DefaultExpressionEngine( DefaultExpressionEngineSymbols.DEFAULT_SYMBOLS,
                                   NodeNameMatchers.EQUALS_IGNORE_CASE );
    Parameters params = new Parameters();
    FileBasedConfigurationBuilder<INIConfiguration> builder =
        new FileBasedConfigurationBuilder<INIConfiguration>( INIConfiguration.class )
        .configure( params.hierarchical().setExpressionEngine( engine ) );
    iniConfObj = builder.getConfiguration();
    iniConfObj.read( reader );
    reader.close();
    sectionNameMap = new HashMap<>();
    for ( String sectionName : iniConfObj.getSections() )
      sectionNameMap.put( sectionName.toLowerCase(), sectionName );
  }
  catch ( Exception e )
  {
    throw ZeidonException.wrapException( e ).prependFilename( iniFileName );
  }
  finally
  {
    IOUtils.closeQuietly( reader );
  }
}

代码示例来源:origin: DSpace/DSpace

Parameters params = new Parameters();
  .configure(params.fileBased()
           .setFile(new File(this.configDefinition))
           .setListDelimiterHandler(listDelimiterHandler));

代码示例来源:origin: de.julielab/jssf-commons

/**
 * This default implementation constructs an empty {@link XMLConfiguration} with an {@link XPathExpressionEngine}
 * and a UTF-8 encoding. Note that when using this template generation method, the keys of the configuration
 * must be given in XPath form, i.e. 'key/subkey' instead of the default dotted notation 'key.subkey'.
 * @return An empty XMLConfiguration template.
 * @throws ConfigurationException If the template generation fails.
 */
default HierarchicalConfiguration<ImmutableNode> createConfigurationTemplate() throws ConfigurationException {
  Parameters params = new Parameters();
  FileBasedConfigurationBuilder<XMLConfiguration> builder =
      new FileBasedConfigurationBuilder<XMLConfiguration>(XMLConfiguration.class)
          .configure(params.xml()
              .setExpressionEngine(new XPathExpressionEngine())
              .setEncoding(StandardCharsets.UTF_8.name())
          );
  XMLConfiguration c;
  try {
    c = builder.getConfiguration();
    exposeParameters("", c);
  } catch (org.apache.commons.configuration2.ex.ConfigurationException e) {
    throw new ConfigurationException();
  }
  return c;
}

代码示例来源:origin: org.opencadc/cadc-web-util

public ApplicationConfiguration(final String filePath) {
  final CombinedConfiguration combinedConfiguration = new CombinedConfiguration(new MergeCombiner());
  // Prefer System properties.
  combinedConfiguration.addConfiguration(new SystemConfiguration());
  final Parameters parameters = new Parameters();
  final FileBasedConfigurationBuilder builder = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class).configure(parameters.properties()
    .setFileName(filePath));
  try {
    combinedConfiguration.addConfiguration((Configuration) builder.getConfiguration());
  } catch (ConfigurationException var5) {
    LOGGER.warn(String.format("No configuration found at %s.\nUsing defaults.", filePath));
  }
  this.configuration = combinedConfiguration;
}

代码示例来源:origin: goldmansachs/obevo

@Test
  public void yamlTest() throws Exception {
    ImmutableHierarchicalConfiguration configuration = new FileBasedConfigurationBuilder<>(FixedYAMLConfiguration.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);
  }

相关文章