下面列出了java.util.Properties#getProperty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
static void verifyProperites(Properties prop) {
try {
for (String key : prop.stringPropertyNames()) {
String val = prop.getProperty(key);
if (key.equals("Key1")) {
if (!val.equals("value1")) {
fail("Key:" + key + "'s value: \nExpected: value1\nFound: " + val);
}
} else if (key.equals("Key2")) {
if (!val.equals("<value2>")) {
fail("Key:" + key + "'s value: \nExpected: <value2>\nFound: " + val);
}
} else if (key.equals("Key3")) {
if (!val.equals("value3")) {
fail("Key:" + key + "'s value: \nExpected: value3\nFound: " + val);
}
}
}
} catch (Exception e) {
fail(e.getMessage());
}
}
private static Map<String, String> extractCubertParams(Properties executorProps)
{
Map<String, String> cubertParams = new HashMap<String, String>();
int stripLen = CUBERT_PROP_IDENTIFIER.length();
String regEx = CUBERT_PROP_IDENTIFIER + "*";
for (String p : executorProps.stringPropertyNames())
{
if (!p.matches(regEx))
continue;
String key = p.substring(stripLen, p.length());
String value = executorProps.getProperty(p);
cubertParams.put(key, value);
}
return cubertParams;
}
public DataKB(Properties props, boolean create_writers, boolean plainkb) {
this.dcurl = props.getProperty("ont.data.url");
this.onturl = props.getProperty("ont.domain.data.url");
this.liburl = props.getProperty("lib.domain.data.url");
this.datadir = props.getProperty("lib.domain.data.storage");
String hash = "#";
this.dcns = dcurl + hash;
this.dcdomns = onturl + hash;
this.dclibns = liburl + hash;
this.sparqlFactory = new SparqlFactory();
this.tdbRepository = props.getProperty("tdb.repository.dir");
if (tdbRepository == null) {
this.ontologyFactory = new OntFactory(OntFactory.JENA);
} else {
this.ontologyFactory = new OntFactory(OntFactory.JENA, this.tdbRepository);
}
KBUtils.createLocationMappings(props, this.ontologyFactory);
this.initializeAPI(create_writers, false, plainkb);
}
public void configure(Type type, Properties params, Dialect dialect) {
tableName = PropertiesHelper.getString(TABLE, params, DEFAULT_TABLE_NAME);
columnName = PropertiesHelper.getString(COLUMN, params, DEFAULT_COLUMN_NAME);
String schemaName = params.getProperty(SCHEMA);
String catalogName = params.getProperty(CATALOG);
if ( tableName.indexOf( '.' )<0 ) {
tableName = Table.qualify( catalogName, schemaName, tableName );
}
query = "select " +
columnName +
" from " +
dialect.appendLockHint(LockMode.UPGRADE, tableName) +
dialect.getForUpdateString();
update = "update " +
tableName +
" set " +
columnName +
" = ? where " +
columnName +
" = ?";
}
ShardConsumer(LogDataFetcher<T> fetcher,
LogDeserializationSchema<T> deserializer,
int subscribedShardStateIndex,
Properties configProps,
LogClientProxy logClient,
CheckpointCommitter committer) {
this.fetcher = fetcher;
this.deserializer = deserializer;
this.subscribedShardStateIndex = subscribedShardStateIndex;
// TODO Move configs to a class
this.fetchSize = LogUtil.getNumberPerFetch(configProps);
this.fetchIntervalMs = LogUtil.getFetchIntervalMillis(configProps);
this.logClient = logClient;
this.committer = committer;
this.logProject = fetcher.getProject();
this.initialPosition = configProps.getProperty(ConfigConstants.LOG_CONSUMER_BEGIN_POSITION, Consts.LOG_BEGIN_CURSOR);
this.consumerGroup = configProps.getProperty(ConfigConstants.LOG_CONSUMERGROUP);
if (Consts.LOG_FROM_CHECKPOINT.equalsIgnoreCase(initialPosition)
&& (consumerGroup == null || consumerGroup.isEmpty())) {
throw new IllegalArgumentException("Missing parameter: " + ConfigConstants.LOG_CONSUMERGROUP);
}
defaultPosition = LogUtil.getDefaultPosition(configProps);
if (Consts.LOG_FROM_CHECKPOINT.equalsIgnoreCase(defaultPosition)) {
throw new IllegalArgumentException(Consts.LOG_FROM_CHECKPOINT + " cannot be used as default position");
}
}
@Override
public Object parseProperties(Properties properties) throws AttributeNotFoundException {
String data = properties.getProperty(VALUE_ATTRIBUTE);
String charset = properties.getProperty(CHARSET_ATTRIBUTE);
if (data == null) {
throw new AttributeNotFoundException(VALUE_ATTRIBUTE, "Attribute " + VALUE_ATTRIBUTE + " is not available in a Readable channel dictionary element.");
}
try {
if (StringUtils.isEmpty(charset)) {
return data.getBytes(Defaults.DataFormatter.DEFAULT_CHARSET_ENCODER);
} else {
return data.getBytes(charset);
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Error parse byte with charset"+charset, e);
}
}
public void reload(Properties p) {
ArrayList<Config> configs = new ArrayList<>();
int i = 1;
for (; ; i++) {
String configName = p.getProperty(i + ".type");
if (configName == null) {
break;
}
if (!_configsMap.containsKey(configName)) {
logger.error("Can not find config '{}', check that config is added in plugin.xml", configName);
}
try {
Class<Config> clazz = _configsMap.get(configName);
Config config = clazz.getConstructor(SIG).newInstance(i, p);
configs.add(config);
} catch (Exception e) {
throw new FatalException(i + ".type = " + configName, e);
}
}
configs.trimToSize();
_configs = configs;
}
@Test
public void testParseSnapshotExeName() throws Exception {
log("testParseSnapshotExeName");
File mdFile = new File("src/test/resources/maven-metadata-snapshot.xml");
String name = MavenUtil.parseSnapshotExeName(mdFile);
Properties props = new Properties();
new PlatformDetector().detect(props, null);
String osName = props.getProperty(PlatformDetector.DETECTED_NAME);
assertEquals(String.format("protoc-2.4.1-20180823.052533-7-%s-x86_64.exe", osName), name);
}
public String getFormField(String [] formDefinition, String fieldName)
{
for (String formField : formDefinition) {
Properties info = parseFormString(formField);
String field = info.getProperty("field", null);
if ( fieldName.equals(field) ) return formField;
}
return null;
}
private boolean checkAllowedExtension(String file) {
if (_sfvFirstAllowNoExt && !file.contains(".")) {
return true;
}
Properties cfg = ConfigLoader.loadPluginConfig("zipscript.conf");
String allowedExts = cfg.getProperty("allowedexts", "") + " sfv";
StringTokenizer st = new StringTokenizer(allowedExts);
while (st.hasMoreElements()) {
String ext = "." + st.nextElement().toString().toLowerCase();
if (file.toLowerCase().endsWith(ext)) {
return true;
}
}
return false;
}
@Nullable
private static String readVersion() {
Properties properties = new Properties();
try {
properties.load(
Resource.class.getResourceAsStream("/io/opentelemetry/sdk/version.properties"));
} catch (Exception e) {
// we left the attribute empty
return "unknown";
}
return properties.getProperty("sdk.version");
}
private static String loadValue(Properties props, String name, String defaultValue) {
String data = props.getProperty(name);
if ( data==null ) {
if ( defaultValue==null ) {
throw new IllegalArgumentException("Missing " + name);
} else {
data=defaultValue;
}
}
return StringUtils.strip(data);
}
/**
* Gets a string.
*
* @param key
* The name of the string
* @return The localized string
*/
public String getSingleString(String key) {
Properties labels = getLabels();
if (labels != null) {
String value = labels.getProperty(key);
if (value != null) {
return value;
}
}
return key;
}
@Override
public Map<String, Object> getBaseConfiguration(String graphName, Class<?> test, String testMethodName, LoadGraphWith.GraphData loadGraphWith) {
logger.info("MariaDB, Starting test: " + test.getSimpleName() + "." + testMethodName);
Map<String, Object> m = new HashMap<String, Object>() {{
put("gremlin.graph", SqlgGraph.class.getName());
put("jdbc.url", "jdbc:mariadb://localhost:3306/?useSSL=false");
put("jdbc.username", "mariadb");
put("jdbc.password", "mariadb");
put("maxPoolSize", 10);
}};
InputStream sqlProperties = Thread.currentThread().getContextClassLoader().getResourceAsStream("sqlg.properties");
if (sqlProperties != null) {
Properties p = new Properties();
try {
p.load(sqlProperties);
sqlProperties.close();
for (String k : p.stringPropertyNames()) {
String v = p.getProperty(k);
// if (k.equals("jdbc.url")) {
// v = v.substring(0, v.lastIndexOf("/") + 1);
// v = v + graphName;
// }
m.put(k, v);
}
} catch (IOException ioe) {
LoggerFactory.getLogger(getClass()).error("Cannot read properties from sqlg.properties", ioe.getMessage());
}
}
return m;
}
/**
* 解析testng listener参数
* @param properties
*/
private void parseTestngLinstenerVals(Properties properties) {
if (properties != null) {
String sRetryCount = null;
Enumeration<?> en = properties.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
if(key.toLowerCase().equals(RETRYCOUNT)) {
sRetryCount = properties.getProperty(key);
}
if(key.toLowerCase().equals(SOURCEDIR)) {
sourceCodeDir = properties.getProperty(key);
}
if(key.toLowerCase().equals(SOURCEENCODING)) {
sourceCodeEncoding = properties.getProperty(key);
}
}
if (sRetryCount != null) {
sRetryCount = sRetryCount.trim();
try {
retryCount = Integer.parseInt(sRetryCount);
} catch (final NumberFormatException e) {
throw new NumberFormatException("Parse " + RETRYCOUNT + " [" + sRetryCount + "] from String to Int Exception");
}
}
}
}
public static ClassVisitor make(ClassVisitor cv, TreeMap<String,Integer> methodToLargestLocal,
Properties options, Properties state) {
if (options.containsKey(LOG_START)) {
String startMethod = options.getProperty(LOG_START);
String stopMethod = options.getProperty(LOG_STOP);
if (stopMethod != null) {
cv = new LogInstrument(cv, methodToLargestLocal, options, state, startMethod, stopMethod);
} else {
cv = new LogInstrument(cv, methodToLargestLocal, options, state, startMethod);
}
}
return cv;
}
private void init() {
// GET APPLETVIEWER USER-SPECIFIC PROPERTIES
Properties avProps = getAVProps();
// ADD OTHER RANDOM PROPERTIES
// XXX 5/18 need to revisit why these are here, is there some
// standard for what is available?
// Standard browser properties
avProps.put("browser", "sun.applet.AppletViewer");
avProps.put("browser.version", "1.06");
avProps.put("browser.vendor", "Oracle Corporation");
avProps.put("http.agent", "Java(tm) 2 SDK, Standard Edition v" + theVersion);
// Define which packages can be extended by applets
// XXX 5/19 probably not needed, not checked in AppletSecurity
avProps.put("package.restrict.definition.java", "true");
avProps.put("package.restrict.definition.sun", "true");
// Define which properties can be read by applets.
// A property named by "key" can be read only when its twin
// property "key.applet" is true. The following ten properties
// are open by default. Any other property can be explicitly
// opened up by the browser user by calling appletviewer with
// -J-Dkey.applet=true
avProps.put("java.version.applet", "true");
avProps.put("java.vendor.applet", "true");
avProps.put("java.vendor.url.applet", "true");
avProps.put("java.class.version.applet", "true");
avProps.put("os.name.applet", "true");
avProps.put("os.version.applet", "true");
avProps.put("os.arch.applet", "true");
avProps.put("file.separator.applet", "true");
avProps.put("path.separator.applet", "true");
avProps.put("line.separator.applet", "true");
// Read in the System properties. If something is going to be
// over-written, warn about it.
Properties sysProps = System.getProperties();
for (Enumeration e = sysProps.propertyNames(); e.hasMoreElements(); ) {
String key = (String) e.nextElement();
String val = (String) sysProps.getProperty(key);
String oldVal;
if ((oldVal = (String) avProps.setProperty(key, val)) != null)
System.err.println(lookup("main.warn.prop.overwrite", key,
oldVal, val));
}
// INSTALL THE PROPERTY LIST
System.setProperties(avProps);
// Create and install the security manager
if (!noSecurityFlag) {
System.setSecurityManager(new AppletSecurity());
} else {
System.err.println(lookup("main.nosecmgr"));
}
// REMIND: Create and install a socket factory!
}
private static synchronized void startRemoteManagementAgent(String args) throws Exception {
if (jmxServer != null) {
throw new RuntimeException(getText(INVALID_STATE, "Agent already started"));
}
Properties argProps = parseString(args);
Properties configProps = new Properties();
// Load the management properties from the config file
// if config file is not specified readConfiguration implicitly
// reads <java.home>/lib/management/management.properties
String fname = System.getProperty(CONFIG_FILE);
readConfiguration(fname, configProps);
// management properties can be overridden by system properties
// which take precedence
Properties sysProps = System.getProperties();
synchronized (sysProps) {
configProps.putAll(sysProps);
}
// if user specifies config file into command line for either
// jcmd utilities or attach command it overrides properties set in
// command line at the time of VM start
String fnameUser = argProps.getProperty(CONFIG_FILE);
if (fnameUser != null) {
readConfiguration(fnameUser, configProps);
}
// arguments specified in command line of jcmd utilities
// override both system properties and one set by config file
// specified in jcmd command line
configProps.putAll(argProps);
// jcmd doesn't allow to change ThreadContentionMonitoring, but user
// can specify this property inside config file, so enable optional
// monitoring functionality if this property is set
final String enableThreadContentionMonitoring =
configProps.getProperty(ENABLE_THREAD_CONTENTION_MONITORING);
if (enableThreadContentionMonitoring != null) {
ManagementFactory.getThreadMXBean().
setThreadContentionMonitoringEnabled(true);
}
String jmxremotePort = configProps.getProperty(JMXREMOTE_PORT);
if (jmxremotePort != null) {
jmxServer = ConnectorBootstrap.
startRemoteConnectorServer(jmxremotePort, configProps);
startDiscoveryService(configProps);
}
}
protected Connection getLoadBalancedConnection(int customHostLocation, String customHost, Properties props) throws SQLException {
Properties parsedProps = new NonRegisteringDriver().parseURL(dbUrl, null);
String defaultHost = parsedProps.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY);
if (!NonRegisteringDriver.isHostPropertiesList(defaultHost)) {
String port = parsedProps.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY, "3306");
defaultHost = defaultHost + ":" + port;
}
removeHostRelatedProps(parsedProps);
if (customHost != null && customHost.length() > 0) {
customHost = customHost + ",";
} else {
customHost = "";
}
String hostsString = null;
switch (customHostLocation) {
case 1:
hostsString = customHost + defaultHost;
break;
case 2:
hostsString = defaultHost + "," + customHost + defaultHost;
break;
case 3:
hostsString = defaultHost + "," + customHost;
hostsString = hostsString.substring(0, hostsString.length() - 1);
break;
default:
throw new IllegalArgumentException();
}
if (props != null) {
parsedProps.putAll(props);
}
Connection lbConn = DriverManager.getConnection("jdbc:mysql:loadbalance://" + hostsString, parsedProps);
return lbConn;
}
/**
*
* @param row
* @param fieldinfo
* @param loader
* @return
*/
public String formOutput(Object row, String fieldinfo, Object loader) {
Properties info = parseFormString(fieldinfo);
String field = info.getProperty("field", null);
String type = info.getProperty("type", null);
Object value = getField(row, field);
if (field == null || type == null) {
throw new IllegalArgumentException(
"All model elements must include field name and type");
}
String hidden = info.getProperty("hidden", null);
if ("true".equals(hidden))
return "";
String label = info.getProperty("label", field);
if ("key".equals(type))
return ""; // Key will be handled by the caller
if ("autodate".equals(type))
return "";
if ("integer".equals(type))
return formOutputInteger(getLongNull(value), field, label, loader);
if ("text".equals(type))
return formOutputText((String) value, field, label, loader);
if ("url".equals(type))
return formOutputURL((String) value, field, label, loader);
if ("id".equals(type))
return formOutputId((String) value, field, label, loader);
if ("textarea".equals(type))
return formOutputTextArea((String) value, field, label, loader);
if ("checkbox".equals(type)) {
return formOutputCheckbox(getLongNull(value), field, label, loader);
}
if ("radio".equals(type)) {
String choices = info.getProperty("choices", null);
if (choices == null)
return "\n<!-- Foorm.formOutput() requires choices=on,off,part -->\n";
String[] choiceList = choices.split(",");
if (choiceList.length < 1)
return "\n<!-- Foorm.formOutput() requires choices=on,off,part -->\n";
return formOutputRadio(getLongNull(value), field, label, choiceList, loader);
}
return "\n<!-- Foorm.formOutput() unrecognized type " + type + " field=" + field
+ " -->\n";
}