下面列出了java.util.Properties#getOrDefault ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Configure the TomEE runtime
*/
private void configureTomeeServer(List<AbstractBoosterConfig> boosterConfigurators) throws Exception {
try {
TomeeServerConfigGenerator tomeeConfig = new TomeeServerConfigGenerator(configDir,
BoostLogger.getInstance());
tomeeConfig.addJarsDirToSharedLoader();
// Configure HTTP endpoint
Properties boostConfigProperties = BoostProperties.getConfiguredBoostProperties(BoostLogger.getInstance());
String hostname = (String) boostConfigProperties.getOrDefault(BoostProperties.ENDPOINT_HOST, "localhost");
tomeeConfig.addHostname(hostname);
String httpPort = (String) boostConfigProperties.getOrDefault(BoostProperties.ENDPOINT_HTTP_PORT, "8080");
tomeeConfig.addHttpPort(httpPort);
// Loop through configuration objects and add config
for (AbstractBoosterConfig configurator : boosterConfigurators) {
tomeeConfig.addServerConfig(configurator);
}
} catch (Exception e) {
throw new MojoExecutionException("Unable to generate server configuration for the Tomee server.", e);
}
}
private static Properties resolveReferences(Properties properties) {
// Any value that looks like ${REF} will need to be replaced by the value of REF in source.
final String pattern = "^\\$\\{(.+)\\}$";
val resolved = new Properties();
for (val e : properties.entrySet()) {
// Fetch reference value.
String existingValue = e.getValue().toString();
String newValue = existingValue; // Default to existing value (in case it's not a reference).
if (existingValue.matches(pattern)) {
// Only include the referred value if it resolves to anything; otherwise exclude this altogether.
String lookupKey = existingValue.replaceAll(pattern, "$1");
newValue = (String) properties.getOrDefault(lookupKey, null);
if (newValue != null) {
log.info("Config property '{}={}' resolved to '{}'.", e.getKey(), existingValue, newValue);
}
}
if (newValue != null) {
resolved.put(e.getKey().toString(), newValue);
}
}
return resolved;
}
private OpenApiConfiguration extractOpenApiConfiguration(
Properties applicationProperties) {
String prefix = (String) applicationProperties.getOrDefault(PREFIX,
DEFAULT_PREFIX);
String server = GeneratorUtils.removeEnd((String) applicationProperties
.getOrDefault(SERVER, DEFAULT_SERVER), "/");
String serverDescription = (String) applicationProperties
.getOrDefault(SERVER_DESCRIPTION, DEFAULT_SERVER_DESCRIPTION);
String applicationTitle = (String) applicationProperties
.getOrDefault(APPLICATION_TITLE, DEFAULT_APPLICATION_TITLE);
String applicationApiVersion = (String) applicationProperties
.getOrDefault(APPLICATION_API_VERSION,
DEFAULT_APPLICATION_API_VERSION);
return new OpenApiConfiguration(applicationTitle, applicationApiVersion,
server + prefix, serverDescription);
}
public BaseRegion(RMapCache<Object, Object> mapCache, ConnectionManager connectionManager, RegionFactory regionFactory, CacheDataDescription metadata, Properties properties, String defaultKey) {
super();
this.mapCache = mapCache;
this.regionFactory = regionFactory;
this.metadata = metadata;
this.connectionManager = connectionManager;
String maxEntries = getProperty(properties, mapCache.getName(), defaultKey, RedissonRegionFactory.MAX_ENTRIES_SUFFIX);
if (maxEntries != null) {
mapCache.setMaxSize(Integer.valueOf(maxEntries));
}
String timeToLive = getProperty(properties, mapCache.getName(), defaultKey, RedissonRegionFactory.TTL_SUFFIX);
if (timeToLive != null) {
ttl = Integer.valueOf(timeToLive);
}
String maxIdleTime = getProperty(properties, mapCache.getName(), defaultKey, RedissonRegionFactory.MAX_IDLE_SUFFIX);
if (maxIdleTime != null) {
maxIdle = Integer.valueOf(maxIdleTime);
}
String fallbackValue = (String) properties.getOrDefault(RedissonRegionFactory.FALLBACK, "false");
fallback = Boolean.valueOf(fallbackValue);
}
public BaseRegion(RMapCache<Object, Object> mapCache, ConnectionManager connectionManager, RegionFactory regionFactory, CacheDataDescription metadata, Properties properties, String defaultKey) {
super();
this.mapCache = mapCache;
this.regionFactory = regionFactory;
this.metadata = metadata;
this.connectionManager = connectionManager;
String maxEntries = getProperty(properties, mapCache.getName(), defaultKey, RedissonRegionFactory.MAX_ENTRIES_SUFFIX);
if (maxEntries != null) {
mapCache.setMaxSize(Integer.valueOf(maxEntries));
}
String timeToLive = getProperty(properties, mapCache.getName(), defaultKey, RedissonRegionFactory.TTL_SUFFIX);
if (timeToLive != null) {
ttl = Integer.valueOf(timeToLive);
}
String maxIdleTime = getProperty(properties, mapCache.getName(), defaultKey, RedissonRegionFactory.MAX_IDLE_SUFFIX);
if (maxIdleTime != null) {
maxIdle = Integer.valueOf(maxIdleTime);
}
String fallbackValue = (String) properties.getOrDefault(RedissonRegionFactory.FALLBACK, "false");
fallback = Boolean.valueOf(fallbackValue);
}
public BaseRegion(RMapCache<Object, Object> mapCache, ConnectionManager connectionManager, RegionFactory regionFactory, CacheDataDescription metadata, Properties properties, String defaultKey) {
super();
this.mapCache = mapCache;
this.regionFactory = regionFactory;
this.metadata = metadata;
this.connectionManager = connectionManager;
String maxEntries = getProperty(properties, mapCache.getName(), defaultKey, RedissonRegionFactory.MAX_ENTRIES_SUFFIX);
if (maxEntries != null) {
mapCache.setMaxSize(Integer.valueOf(maxEntries));
}
String timeToLive = getProperty(properties, mapCache.getName(), defaultKey, RedissonRegionFactory.TTL_SUFFIX);
if (timeToLive != null) {
ttl = Integer.valueOf(timeToLive);
}
String maxIdleTime = getProperty(properties, mapCache.getName(), defaultKey, RedissonRegionFactory.MAX_IDLE_SUFFIX);
if (maxIdleTime != null) {
maxIdle = Integer.valueOf(maxIdleTime);
}
String fallbackValue = (String) properties.getOrDefault(RedissonRegionFactory.FALLBACK, "false");
fallback = Boolean.valueOf(fallbackValue);
}
/**
* Gets a property from the configuration. If it is missing it will load it from the properties provided. If it cannot
* be found there the default value provided will be used.
*
* @param conf Configuration to check for property first.
* @param properties Properties to check for property second.
* @param propertyName Name of the property to return
* @param defaultValue Default value to use if no property by the given name could be found in {@code conf} or {@code
* properties}
* @return Value of {@code propertyName}
*/
public static String getProperty( Configuration conf, Properties properties, String propertyName,
String defaultValue ) {
String fromConf = conf.get( propertyName );
if ( Utils.isEmpty( fromConf ) ) {
Object objectValue = properties.getOrDefault( propertyName, null );
if ( objectValue != null ) {
if ( objectValue instanceof String ) {
return objectValue.toString();
} else if ( objectValue instanceof List ) {
String strObjectValue = String.join( ",", (List) objectValue );
if ( strObjectValue.equals( "" ) ) {
return defaultValue;
} else {
return strObjectValue;
}
} else {
// shouldn't happen
return defaultValue;
}
} else {
return defaultValue;
}
}
return fromConf;
}
/**
* Derive the application.id from the stream. Will use the following order to attempt to get name for stream.
* <p>
* application.id -> client.id -> threadName -> kafkaStream.toString()
*
* @param kafkaStreams The kafka stream
* @return Application id
*/
private String getApplicationId(final KafkaStreams kafkaStreams) {
try {
ConfiguredStreamBuilder configuredStreamBuilder = kafkaStreamsFactory.getStreams().get(kafkaStreams);
if (configuredStreamBuilder != null) {
Properties configuration = configuredStreamBuilder.getConfiguration();
return (String) configuration.getOrDefault(StreamsConfig.APPLICATION_ID_CONFIG, configuration.getProperty(StreamsConfig.CLIENT_ID_CONFIG));
} else {
return getDefaultStreamName(kafkaStreams);
}
} catch (Exception e) {
return getDefaultStreamName(kafkaStreams);
}
}
/**
* Configure the Liberty runtime
*
* @param boosterConfigurators
* @throws Exception
*/
private void generateLibertyServerConfig(List<AbstractBoosterConfig> boosterConfigurators) throws Exception {
List<String> warNames = getWarNames();
LibertyServerConfigGenerator libertyConfig = new LibertyServerConfigGenerator(libertyServerPath,
BoostLogger.getInstance());
// Add default http endpoint configuration
Properties boostConfigProperties = BoostProperties.getConfiguredBoostProperties(BoostLogger.getInstance());
String host = (String) boostConfigProperties.getOrDefault(BoostProperties.ENDPOINT_HOST, "*");
libertyConfig.addHostname(host);
String httpPort = (String) boostConfigProperties.getOrDefault(BoostProperties.ENDPOINT_HTTP_PORT, "9080");
libertyConfig.addHttpPort(httpPort);
String httpsPort = (String) boostConfigProperties.getOrDefault(BoostProperties.ENDPOINT_HTTPS_PORT, "9443");
libertyConfig.addHttpsPort(httpsPort);
// Add war configuration if necessary
if (!warNames.isEmpty()) {
for (String warName : warNames) {
libertyConfig.addApplication(warName);
}
} else {
throw new Exception(
"No war files were found. The project must have a war packaging type or specify war dependencies.");
}
// Loop through configuration objects and add config and
// the corresponding Liberty feature
for (AbstractBoosterConfig configurator : boosterConfigurators) {
if (configurator instanceof LibertyBoosterI) {
((LibertyBoosterI) configurator).addServerConfig(libertyConfig);
libertyConfig.addFeature(((LibertyBoosterI) configurator).getFeature());
}
}
libertyConfig.writeToServer();
}
@Test
public void testGetProperties() {
Properties properties = PropertiesUtil.getProperties("fast");
String fastFrameworkName = properties.getProperty("fast.framework.name");
String authorName = properties.getProperty("fast.framework.author");
Object age = properties.getOrDefault("fast.framework.age", 10);
Object defaultVal = properties.getOrDefault("fast.framework.null", 10);
System.out.println(fastFrameworkName);
System.out.println(authorName);
System.out.println(age.toString());
System.out.println(defaultVal.toString());
}
private static String loadClientVersion() {
try (InputStream is = ClientVersion.class.getResourceAsStream("version.properties");
Reader r = new InputStreamReader(is, UTF_8)) {
Properties props = new Properties();
props.load(r);
return (String) props.getOrDefault("projectVersion", "unknown");
} catch (Throwable t) {
t.printStackTrace();
return "unknown";
}
}
/**
* Creates the generator, getting the data needed for the generation out of
* the application properties.
*
* @param applicationProperties
* the properties with the data required for the generation
*/
public VaadinConnectClientGenerator(
Properties applicationProperties) {
final String prefix =
(String)applicationProperties.getOrDefault(PREFIX,
DEFAULT_PREFIX);
final String urlMapping = (String) applicationProperties
.getOrDefault(URL_MAPPING, DEFAULT_URL_MAPPING);
this.endpointPrefix = relativizeEndpointPrefixWithUrlMapping(prefix, urlMapping);
}
/** Replies the captured value.
*
* @param context the parsing context.
* @param tagName the name of the tag.
* @return the captured value.
*/
protected static String getCapturedValue(ParsingContext context, String tagName) {
String replacement = null;
if (!Strings.isNullOrEmpty(tagName)) {
replacement = context.getReplacement(tagName);
if (replacement == null) {
for (final Properties provider : context.getParser().getPropertyProvidersByPriority()) {
if (provider != null) {
final Object obj = provider.getOrDefault(tagName, null);
if (obj != null) {
replacement = obj.toString();
break;
}
}
}
}
if (replacement == null) {
replacement = System.getProperty(tagName);
}
if (replacement == null) {
replacement = System.getenv(tagName);
}
}
if (replacement == null) {
reportError(context, Messages.SarlDocumentationParser_4, tagName);
return null;
}
return replacement;
}
@Override
public void init(Properties p) {
// At first call init from AbstractWorker!
super.init(p);
this.service = p.getProperty(CONSTANTS.SPARQL_CURRENT_ENDPOINT);
this.timeOut = (double)p.getOrDefault(CONSTANTS.SPARQL_TIMEOUT, 180000D);
String timerStrategy = p.getProperty(CONSTANTS.STRESSTEST_UPDATE_TIMERSTRATEGY);
// use updateStrategy if set, otherwise use default: none
this.updateStrategy = UpdateStrategy
.valueOf(p.getOrDefault(CONSTANTS.STRESSTEST_UPDATE_STRATEGY, "NONE").toString());
setUpdateTimer(timerStrategy);
}
@Override
public void initialize(Properties properties, ConfigurationFileHolder configurationFileHolder, ConfigurationChangeNotifier configurationChangeNotifier) {
super.initialize(properties, configurationFileHolder, configurationChangeNotifier);
pollingPeriodMS.set(Integer.parseInt(properties.getProperty(PULL_HTTP_POLLING_PERIOD_KEY, DEFAULT_POLLING_PERIOD)));
if (pollingPeriodMS.get() < 1) {
throw new IllegalArgumentException("Property, " + PULL_HTTP_POLLING_PERIOD_KEY + ", for the polling period ms must be set with a positive integer.");
}
final String host = properties.getProperty(HOST_KEY);
if (host == null || host.isEmpty()) {
throw new IllegalArgumentException("Property, " + HOST_KEY + ", for the hostname to pull configurations from must be specified.");
}
final String path = properties.getProperty(PATH_KEY, "/");
final String query = properties.getProperty(QUERY_KEY, "");
final String portString = (String) properties.get(PORT_KEY);
final Integer port;
if (portString == null) {
throw new IllegalArgumentException("Property, " + PORT_KEY + ", for the hostname to pull configurations from must be specified.");
} else {
port = Integer.parseInt(portString);
}
portReference.set(port);
hostReference.set(host);
pathReference.set(path);
queryReference.set(query);
final String useEtagString = (String) properties.getOrDefault(USE_ETAG_KEY, "false");
if ("true".equalsIgnoreCase(useEtagString) || "false".equalsIgnoreCase(useEtagString)) {
useEtag = Boolean.parseBoolean(useEtagString);
} else {
throw new IllegalArgumentException("Property, " + USE_ETAG_KEY + ", to specify whether to use the ETag header, must either be a value boolean value (\"true\" or \"false\") or left to " +
"the default value of \"false\". It is set to \"" + useEtagString + "\".");
}
final String overrideSecurityProperties = (String) properties.getOrDefault(OVERRIDE_SECURITY, "false");
if ("true".equalsIgnoreCase(overrideSecurityProperties) || "false".equalsIgnoreCase(overrideSecurityProperties)) {
overrideSecurity = Boolean.parseBoolean(overrideSecurityProperties);
} else {
throw new IllegalArgumentException("Property, " + OVERRIDE_SECURITY + ", to specify whether to override security properties must either be a value boolean value (\"true\" or \"false\")" +
" or left to the default value of \"false\". It is set to \"" + overrideSecurityProperties + "\".");
}
httpClientReference.set(null);
final OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
// Set timeouts
okHttpClientBuilder.connectTimeout(Long.parseLong(properties.getProperty(CONNECT_TIMEOUT_KEY, DEFAULT_CONNECT_TIMEOUT_MS)), TimeUnit.MILLISECONDS);
okHttpClientBuilder.readTimeout(Long.parseLong(properties.getProperty(READ_TIMEOUT_KEY, DEFAULT_READ_TIMEOUT_MS)), TimeUnit.MILLISECONDS);
// Set whether to follow redirects
okHttpClientBuilder.followRedirects(true);
String proxyHost = properties.getProperty(PROXY_HOST_KEY, "");
if (!proxyHost.isEmpty()) {
String proxyPort = properties.getProperty(PROXY_PORT_KEY);
if (proxyPort == null || proxyPort.isEmpty()) {
throw new IllegalArgumentException("Proxy port required if proxy specified.");
}
okHttpClientBuilder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort))));
String proxyUsername = properties.getProperty(PROXY_USERNAME);
if (proxyUsername != null) {
String proxyPassword = properties.getProperty(PROXY_PASSWORD);
if (proxyPassword == null) {
throw new IllegalArgumentException("Must specify proxy password with proxy username.");
}
okHttpClientBuilder.proxyAuthenticator((route, response) -> response.request().newBuilder().addHeader("Proxy-Authorization", Credentials.basic(proxyUsername, proxyPassword)).build());
}
}
// check if the ssl path is set and add the factory if so
if (properties.containsKey(KEYSTORE_LOCATION_KEY)) {
try {
setSslSocketFactory(okHttpClientBuilder, properties);
connectionScheme = "https";
} catch (Exception e) {
throw new IllegalStateException(e);
}
} else {
connectionScheme = "http";
}
httpClientReference.set(okHttpClientBuilder.build());
final String differentiatorName = properties.getProperty(DIFFERENTIATOR_KEY);
if (differentiatorName != null && !differentiatorName.isEmpty()) {
Supplier<Differentiator<ByteBuffer>> differentiatorSupplier = DIFFERENTIATOR_CONSTRUCTOR_MAP.get(differentiatorName);
if (differentiatorSupplier == null) {
throw new IllegalArgumentException("Property, " + DIFFERENTIATOR_KEY + ", has value " + differentiatorName + " which does not " +
"correspond to any in the PullHttpChangeIngestor Map:" + DIFFERENTIATOR_CONSTRUCTOR_MAP.keySet());
}
differentiator = differentiatorSupplier.get();
} else {
differentiator = WholeConfigDifferentiator.getByteBufferDifferentiator();
}
differentiator.initialize(properties, configurationFileHolder);
}
/**
* 根据key,获取属性值
*
* @param properties
* @param key
* @param defaultValue
* @param <V>
* @return
*/
public static <V> V getOrDefault(Properties properties, String key, V defaultValue) {
return (V) properties.getOrDefault(key, defaultValue);
}