本文整理了Java中io.helidon.config.Config
类的一些代码示例,展示了Config
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Config
类的具体详情如下:
包路径:io.helidon.config.Config
类名称:Config
[英]Configuration Immutable tree-structured configuration. Loading Configuration Load the default configuration using the #create method.
Config config = Config.create();
Use Config.Builder to construct a new Config instance from one or more specific ConfigSources using the #builder().
The application can affect the way the system loads configuration by implementing interfaces defined in the SPI, by explicitly constructing the Builder which assembles the Config, and by using other classes provided by the config system that influence loading.
Class.MethodApplication-implemented InterfacePurposeConfigSources#createConfigSourceLoads configuration from a different type of origin. Each ConfigSource implementation handles a type of location. Different instances of a given ConfigSource implementation represent separate sources of that location type.Builder#addParserConfigParserConverts one format of config representation into the corresponding Config tree. Builder#addFilterConfigFilterChanges the String representation of each config value from one String to another as the Config tree is built from its sources.OverrideSources methodsReplaces config String values during loading based on their keys. Programs provide overrides in Java property file format on the classpath, at a URL, or in a file, or by invoking OverrideSources#create and passing the name-matching expressions and the corresponding replacement value as a Map.Builder#addMapper(Class,Function)Implements conversion from a Config node (typically with children) to an application-specific Java type.
Navigating in a Configuration Tree Each loaded configuration is a tree of Config objects. The application can access an arbitrary node in the tree by passing its fully-qualified name to Config#get:
Config greeting = config.get("greeting");
Method #key() always returns fully-qualified Config.Key of a config node.
assert greeting.key().toString().equals("greeting")
These are equivalent ways of obtaining the same Configinstance, and the two assertions will succeed:
Config name1 = config.get("app.services.svc1.name");
The #get method always returns a Config object, even if no configuration is present using the corresponding key. The application can invoke the #type method to find out the type of the node, represented by one of the Type enum values. The #existsmethod tells whether or not the Config node represents existing configuration.
if (!config.get("very.rare.prop42").exists()) }
The #traverse method visits all nodes in a subtree. This example gathers all nodes with keys matching logging.**.level -- that is, all nodes within the "logging" subtree that have a key ending in "level" and also has a single value:
Map loggingLevels = config.get("logging") // find "logging" subtree
To retrieve children of a config node use #asNodeList()
To get node value, use #as(Class) to access this config node as a ConfigValue
Converting Configuration Values to Types
The interpretation of a configuration node, including what datatype to use, is up to the application. To interpret a node's value as a type other than String the application can invoke one of these convenience methods:
The ConfigValue can be used to access the value or use optional style methods. The config value provides access to the value in multiple ways. See ConfigValue for reference. Basic usages:
// throws a MissingValueException in case the config node does not exist
// throws a MissingValueException in case the config node does not exist
// throws a MissingValueException in case the config node does not exist
// throws a MissingValueException in case the config node does not existMap m1 = config.as(new GenericType() {}).get();
// throws a ConfigMappingException in case the config node cannot be converted to Map
Map m1 = config.as(new GenericType() {}).orElseGet(Collections::emptyMap);
// invokes the method "units(Map)" if the value exists
// throws a ConfigMappingException in case the config node cannot be converted to Map
config.as(new GenericType() {}).ifPresent(this::units);
}
To deal with application-specific types, the application can provide its own mapping logic by:
If there is no explicitly registered mapping function in a Builder for converting a given type then the config system throws ConfigMappingException, unless you use the config beans support, that can handle classes that fulfill some requirements (see documentation), such as a public constructor, static "create(Config)" method etc.
Handling Multiple Configuration Sources A Config instance, including the default Config returned by #create, might be associated with multiple ConfigSources. The config system deals with multiple sources as follows.
The ConfigSources.CompositeBuilder class handles multiple config sources; in fact the config system uses an instance of that builder automatically when your application invokes Config#create and Config#builder, for example. Each such composite builder has a merging strategy that controls how the config system will search the multiple config sources for a given key. By default each CompositeBuilder uses the FallbackMergingStrategy: configuration sources earlier in the list have a higher priority than the later ones. The system behaves as if, when resolving a value of a key, it checks each source in sequence order. As soon as one source contains a value for the key the system returns that value, ignoring any sources that fall later in the list.
Your application can set a different strategy by constructing its own CompositeBuilder and invoking ConfigSources.CompositeBuilder#mergingStrategy(ConfigSources.MergingStrategy), passing the strategy to be used:
Config.withSources(ConfigSources.create(source1, source2, source3)
.mergingStrategy(new MyMergingStrategy());
[中]配置不可变的树结构配置。加载配置使用#create方法加载默认配置
Config config = Config.create();
使用配置。生成器使用#Builder()从一个或多个特定的ConfigSources构造新的配置实例。
应用程序可以通过实现SPI中定义的接口、显式构造组装配置的构建器以及使用影响加载的配置系统提供的其他类来影响系统加载配置的方式。
班MethodApplication实现的InterfacePurposeConfigSources#CreateConfigSource从不同类型的源加载配置。每个ConfigSource实现处理一种类型的位置。给定ConfigSource实现的不同实例表示该位置类型的不同源。生成器#addParserConfigParserConvert将配置表示的一种格式转换到相应的配置树中。Builder#addFilterConfigFilterChanges将每个配置值的字符串表示形式从一个字符串更改为另一个字符串,因为配置树是从其源构建的。OverrideSources方法根据配置字符串的键在加载期间替换配置字符串值。程序以Java属性文件格式在类路径、URL或文件中提供重写,或者通过调用OverrideSources#创建并将名称匹配表达式和相应的替换值作为映射传递。Builder#addMapper(类、函数)实现了从配置节点(通常带有子节点)到特定于应用程序的Java类型的转换。
在配置树中导航每个加载的配置都是配置对象树。应用程序可以通过将其完全限定名传递给Config#get:
Config greeting = config.get("greeting");
Method#key()始终返回完全限定的配置来访问树中的任意节点。配置节点的键
assert greeting.key().toString().equals("greeting")
这些是获取相同Configinstance的等效方法,两个断言将成功:
Config name1 = config.get("app.services.svc1.name");
get方法始终返回一个Config对象,即使没有使用相应键的配置。应用程序可以调用#type方法来查找节点的类型,由类型枚举值之一表示。#existsmethod告诉配置节点是否表示现有配置
if (!config.get("very.rare.prop42").exists()) }
遍历方法访问子树中的所有节点。此示例收集具有匹配日志记录的密钥的所有节点。**。level——即“logging”子树中键以“level”结尾且具有单个值的所有节点:
Map loggingLevels = config.get("logging") // find "logging" subtree
要检索配置节点的子节点,请使用#asNodeList()
*在类型#对象节点上获取所有对象成员,
*在类型#列表节点上获取所有列表元素。
要获取节点值,请使用#as(类)作为ConfigValue访问此配置节点
将配置值转换为类型
####应用程序的显式转换
配置节点的解释(包括要使用的数据类型)取决于应用程序。要将节点的值解释为字符串以外的类型,应用程序可以调用以下方便方法之一:
*例如asBoolean、asDouble、asInt等,它们返回表示Java基本数据值(boolean、double、int等)的ConfigValue
ConfigValue可用于访问该值或使用可选样式方法。配置值以多种方式提供对该值的访问。请参阅ConfigValue以获取参考。基本用法:
// throws a MissingValueException in case the config node does not exist
*#as(Class)将配置节点转换为指定类的实例(如果存在支持该类的已配置映射程序)
// throws a MissingValueException in case the config node does not exist
*#as(函数)使用提供的函数转换配置节点。让我们假设在类Foo上有一个公共静态Foo create(Config)方法:
// throws a MissingValueException in case the config node does not exist
*#as(GenericType),将配置节点转换为指定泛型类型的实例(如果存在支持该泛型类型的已配置映射程序)
// throws a MissingValueException in case the config node does not existMap m1 = config.as(new GenericType() {}).get();
// throws a ConfigMappingException in case the config node cannot be converted to Map
Map m1 = config.as(new GenericType() {}).orElseGet(Collections::emptyMap);
// invokes the method "units(Map)" if the value exists
// throws a ConfigMappingException in case the config node cannot be converted to Map
config.as(new GenericType() {}).ifPresent(this::units);
}
要处理特定于应用程序的类型,应用程序可以通过以下方式提供自己的映射逻辑:
*调用Config#as(Function)方法变量,
*使用Builder#addMapper(类,函数)方法添加自定义映射函数实现,
*使用Builder#addStringMapper添加自定义映射函数(类,函数)
*使用Java服务加载程序机制注册自定义映射程序。(有关详细信息,请参阅ConfigMapperProvider。)
如果构建器中没有显式注册的映射函数用于转换给定类型,那么配置系统将抛出ConfigMappingException,除非您使用config beans支持,该支持可以处理满足某些要求的类(请参阅文档),例如公共构造函数、静态“create(config)”方法等。
Handling Multiple Configuration Sources一个配置实例,包括#create返回的默认配置,可能与多个ConfigSources关联。配置系统处理多个源,如下所示。
配置源。CompositeBuilder类处理多个配置源;事实上,例如,当应用程序调用config#create和config#builder时,配置系统会自动使用该生成器的实例。每个这样的复合生成器都有一个合并策略,控制配置系统如何在多个配置源中搜索给定的键。默认情况下,每个CompositeBuilder都使用FallbackMergingStrategy:列表中较早的配置源的优先级高于较晚的配置源。系统的行为就像在解析键的值时,它按顺序检查每个源。只要一个源包含键的值,系统就会返回该值,忽略列表中后面的任何源。
您的应用程序可以通过构建自己的CompositeBuilder并调用ConfigSources来设置不同的策略。CompositeBuilder#mergingStrategy(ConfigSources.mergingStrategy),传递要使用的策略:
Config.withSources(ConfigSources.create(source1, source2, source3)
.mergingStrategy(new MyMergingStrategy());
代码示例来源:origin: oracle/helidon
/**
* Update this builder from configuration.
*
* @param config Configuration at provider (security.provider.x) key
* @return updated builder instance
*/
public Builder config(Config config) {
config.get("optional").asBoolean().ifPresent(this::optional);
config.get("client-id").asString().ifPresent(this::clientId);
config.get("proxy-host").asString().ifPresent(this::proxyHost);
config.get("proxy-port").asInt().ifPresent(this::proxyPort);
config.get("realm").asString().ifPresent(this::realm);
config.get("token").as(TokenHandler::create).ifPresent(this::tokenProvider);
return this;
}
}
代码示例来源:origin: oracle/helidon
static ConfigUser create(Config config) {
ConfigUser cu = new ConfigUser();
cu.login = config.get("login").asString().get();
cu.password = config.get("password").asString().orElse("").toCharArray();
cu.roles.addAll(config.get("roles").asList(String.class).orElse(CollectionsHelper.listOf()));
return cu;
}
代码示例来源:origin: oracle/helidon
/**
* Update fields from configuration.
*
* @param config Configuration
* @return updated builder instance
*/
public Builder config(Config config) {
config.get("name").asString().ifPresent(this::name);
config.get("default").asBoolean().ifPresent(this::isDefault);
config.get("authentication").asList(FlaggedProvider::create)
.ifPresent(this.authenticators::addAll);
config.get("authorization").asList(FlaggedProvider::create)
.ifPresent(this.authorizers::addAll);
config.get("outbound").asNodeList()
.ifPresent(configs -> configs.forEach(outConfig -> addOutboundProvider(outConfig.get("name")
.asString()
.get())));
return this;
}
代码示例来源:origin: oracle/helidon
@Override
public Config get(Key key) {
if (key.isRoot()) {
return this;
} else {
return Config.empty().get(this.key).get(key);
}
}
代码示例来源:origin: oracle/helidon
/**
* Update this builder from configuration.
*
* @param config config instance located on the key {@link PolicyValidator#configKey()}
* @return updated builder instance
*/
public Builder config(Config config) {
config.get("inherit").asBoolean().ifPresent(this::inherit);
config.get("statement").asString().ifPresent(this::statement);
return this;
}
代码示例来源:origin: oracle/helidon
@Override
public <T> ConfigValue<List<T>> asList(Class<T> type) throws ConfigMappingException {
return ConfigValues.createList(this,
config -> config.as(type),
config -> config.asList(type));
}
代码示例来源:origin: oracle/helidon
/**
* Override default configuration.
*
* @param config configuration instance
* @return updated builder instance
* @see MetricsSupport for details about configuration keys
*/
public Builder config(Config config) {
this.config = config;
config.get("helidon.metrics.context").asString().ifPresent(this::context);
return this;
}
代码示例来源:origin: oracle/helidon
/**
* Load this builder from a configuration.
*
* @param config configuration to load from
* @return updated builder instance
*/
public Builder config(Config config) {
config.get("optional").as(Boolean.class).ifPresent(this::optional);
config.get("authenticate").as(Boolean.class).ifPresent(this::authenticate);
config.get("propagate").as(Boolean.class).ifPresent(this::propagate);
config.get("allow-impersonation").asBoolean().ifPresent(this::allowImpersonation);
config.get("principal-type").as(SubjectType.class).ifPresent(this::subjectType);
config.get("atn-token.handler").as(TokenHandler.class).ifPresent(this::atnTokenHandler);
config.get("atn-token").ifExists(this::verifyKeys);
config.get("atn-token.jwt-audience").asString().ifPresent(this::expectedAudience);
config.get("sign-token").ifExists(outbound -> outboundConfig(OutboundConfig.create(outbound)));
config.get("sign-token").ifExists(this::outbound);
return this;
}
代码示例来源:origin: oracle/helidon
/**
* Update builder from configuration. See
* {@link JwtProvider.JwtOutboundTarget#create(Config, TokenHandler)}
* for configuration options description.
*
* @param config to update builder from
* @return updated builder instance
*/
public Builder config(Config config) {
config.get("outbound-token")
.asNode()
.map(TokenHandler::create)
.ifPresent(this::tokenHandler);
config.get("jwt-kid").asString().ifPresent(this::jwtKid);
config.get("jwk-kid").asString().ifPresent(this::jwkKid);
config.get("jwt-audience").asString().ifPresent(this::jwtAudience);
config.get("jwt-not-before-seconds").asInt().ifPresent(this::notBeforeSeconds);
config.get("jwt-validity-seconds").asLong().ifPresent(this::validitySeconds);
return this;
}
代码示例来源:origin: oracle/helidon
/**
* Update builder from configuration and set the config to {@link #configuration(io.helidon.config.Config)}.
*
* @param config configuration placed on the key of this provider
* @return updated builder instance
*/
public Builder config(Config config) {
configuration(config);
config.get("fail-on-unvalidated").asBoolean().ifPresent(this::failOnUnvalidated);
config.get("fail-if-none-validated").asBoolean().ifPresent(this::failIfNoneValidated);
return this;
}
}
代码示例来源:origin: oracle/helidon
@Override
public ZipkinTracerBuilder config(Config config) {
config.get("service").asString().ifPresent(this::serviceName);
config.get("protocol").asString().ifPresent(this::collectorProtocol);
config.get("host").asString().ifPresent(this::collectorHost);
config.get("port").asInt().ifPresent(this::collectorPort);
config.get("path").asString().ifPresent(this::collectorPath);
config.get("api-version").asString().ifPresent(this::configApiVersion);
config.get("enabled").asBoolean().ifPresent(this::enabled);
config.get("tags").detach()
.asMap()
.orElseGet(CollectionsHelper::mapOf)
.forEach(this::addTracerTag);
config.get("boolean-tags")
.asNodeList()
.ifPresent(nodes -> {
nodes.forEach(node -> {
this.addTracerTag(node.key().name(), node.asBoolean().get());
});
});
config.get("int-tags")
.asNodeList()
.ifPresent(nodes -> {
nodes.forEach(node -> {
this.addTracerTag(node.key().name(), node.asInt().get());
});
});
return this;
}
代码示例来源:origin: oracle/helidon
/**
* Create a builder from configuration.
*
* @param config Config located at http-signatures key
* @return builder instance configured from config
*/
public Builder config(Config config) {
config.get("headers").asList(HttpSignHeader.class).ifPresent(list -> list.forEach(this::addAcceptHeader));
config.get("optional").asBoolean().ifPresent(this::optional);
config.get("realm").asString().ifPresent(this::realm);
config.get("sign-headers").as(SignedHeadersConfig::create).ifPresent(this::inboundRequiredHeaders);
outboundConfig = OutboundConfig.create(config);
config.get("inbound.keys")
.asList(InboundClientDefinition::create)
.ifPresent(list -> list.forEach(inbound -> inboundKeys.put(inbound.keyId(), inbound)));
return this;
}
代码示例来源:origin: oracle/helidon
@Override
public void init(Config config) {
config.get(PROVIDER_NAME + ".auth-method-mapping")
.asNodeList()
.ifPresent(nl -> {
nl.forEach(conf -> {
conf.get("key").asString().ifPresent(key -> {
if (LOGIN_CONFIG_METHOD.equals(key)) {
authenticator = conf.get("provider")
.asString()
.orElse(authenticator);
}
});
});
});
}
代码示例来源:origin: oracle/helidon
/**
* Update builder from config.
*
* @param config Configuration to update from
* @return update builder instance
*/
public Builder config(Config config) {
config.get("header").asString().ifPresent(this::tokenHeader);
config.get("prefix").asString().ifPresent(this::tokenPrefix);
config.get("regexp").as(Pattern.class).ifPresent(this::tokenPattern);
config.get("format").asString().ifPresent(this::tokenFormat);
return this;
}
代码示例来源:origin: oracle/helidon
/**
* Update this builder from configuration.
*
* @param config configuration instance located on {@link PolicyValidatorService#configKey()}
* @return updated builder instance
*/
public Builder config(Config config) {
this.config = config;
config.get("validators").asList(Config.class).ifPresent(configs -> {
for (Config validatorConfig : configs) {
validatorConfig.get("class").asString()
.ifPresentOrElse(clazz -> {
//attempt to instantiate
addExecutor(instantiate(clazz));
}, () -> {
throw new SecurityException(
"validators key may only contain an array of class to class names, at key: "
+ validatorConfig.key());
});
}
});
return this;
}
代码示例来源:origin: oracle/helidon
/**
* Creates new instance of builder from config.
*
* @param metaConfig config
* @return new builder instance
*/
public static MyConfigSourceBuilder2 from(Config metaConfig) {
return from(metaConfig.get("myProp1").asString().get(),
metaConfig.get("myProp2").asInt().get())
.init(metaConfig);
}
代码示例来源:origin: oracle/helidon
private SocketConfiguration.Builder configureSocket(Config config, SocketConfiguration.Builder soConfigBuilder) {
config.get("port").asInt().ifPresent(soConfigBuilder::port);
config.get("bind-address")
.asString()
.map(this::string2InetAddress)
.ifPresent(soConfigBuilder::bindAddress);
config.get("backlog").asInt().ifPresent(soConfigBuilder::backlog);
config.get("timeout").asInt().ifPresent(soConfigBuilder::timeoutMillis);
config.get("receive-buffer").asInt().ifPresent(soConfigBuilder::receiveBufferSize);
// ssl
Config sslConfig = config.get("ssl");
if (sslConfig.exists()) {
try {
soConfigBuilder.ssl(SSLContextBuilder.create(sslConfig));
} catch (IllegalStateException e) {
throw new ConfigException("Cannot load SSL configuration.", e);
}
}
return soConfigBuilder;
}
代码示例来源:origin: oracle/helidon
config.get("workers").asInt().ifPresent(this::workersCount);
Config socketsConfig = config.get("sockets");
if (socketsConfig.exists()) {
for (Config socketConfig : socketsConfig.asNodeList().orElse(CollectionsHelper.listOf())) {
String socketName = socketConfig.name();
sockets.put(socketName, configureSocket(socketConfig, SocketConfiguration.builder()).build());
Config experimentalConfig = config.get("experimental");
if (experimentalConfig.exists()) {
ExperimentalConfiguration.Builder experimentalBuilder = new ExperimentalConfiguration.Builder();
Config http2Config = experimentalConfig.get("http2");
if (http2Config.exists()) {
Http2Configuration.Builder http2Builder = new Http2Configuration.Builder();
http2Config.get("enable").asBoolean().ifPresent(http2Builder::enable);
http2Config.get("max-content-length").asInt().ifPresent(http2Builder::maxContentLength);
experimentalBuilder.http2(http2Builder.build());
代码示例来源:origin: oracle/helidon
private void registerRouting(Routing.Rules routing) {
Config wsConfig = config.get("web-server");
SecurityHandler defaults = SecurityHandler.create(wsConfig.get("defaults"), defaultHandler);
wsConfig.get("paths").asNodeList().ifPresent(configs -> {
for (Config pathConfig : configs) {
List<Http.RequestMethod> methods = pathConfig.get("methods").asNodeList().orElse(listOf())
.stream()
.map(Config::asString)
.map(ConfigValue::get)
.map(Http.RequestMethod::create)
.collect(Collectors.toList());
String path = pathConfig.get("path")
.asString()
.orElseThrow(() -> new SecurityException(pathConfig
.key() + " must contain path key with a path to "
+ "register to web server"));
if (methods.isEmpty()) {
routing.any(path, SecurityHandler.create(pathConfig, defaults));
} else {
routing.anyOf(methods, path, SecurityHandler.create(pathConfig, defaults));
}
}
});
}
}
代码示例来源:origin: oracle/helidon
private Object findArrayValue(String propertyName, Class<?> element) {
// there should not be io.helidon.Config[]
return findInMpSources(propertyName)
.map(value -> asArray(value, element))
.orElseGet(() -> {
Config arrayConfig = config.get().get(propertyName);
if (arrayConfig.isLeaf()) {
return asArray(arrayConfig.asString().get(), element);
}
List<?> objects = arrayConfig.asList(element).get();
Object array = Array.newInstance(element, objects.size());
for (int i = 0; i < objects.size(); i++) {
Array.set(array, i, objects.get(i));
}
return array;
});
}
内容来源于网络,如有侵权,请联系作者删除!