下面列出了java.util.Properties#propertyNames ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
throws BeansException {
for (Enumeration<?> names = props.propertyNames(); names.hasMoreElements();) {
String key = (String) names.nextElement();
try {
processKey(beanFactory, key, props.getProperty(key));
}
catch (BeansException ex) {
String msg = "Could not process key '" + key + "' in PropertyOverrideConfigurer";
if (!this.ignoreInvalidKeys) {
throw new BeanInitializationException(msg, ex);
}
if (logger.isDebugEnabled()) {
logger.debug(msg, ex);
}
}
}
}
void parse(Properties entries) {
// first, strip out the platform-specific temp file template
String tempFileTemplate = (String)entries.get("temp.file.template");
if (tempFileTemplate != null) {
entries.remove("temp.file.template");
MimeTable.tempFileTemplate = tempFileTemplate;
}
// now, parse the mime-type spec's
Enumeration<?> types = entries.propertyNames();
while (types.hasMoreElements()) {
String type = (String)types.nextElement();
String attrs = entries.getProperty(type);
parse(type, attrs);
}
}
/**
* @param prefix Prefix of the property key
* @param propertiesWithFullKeys Set of properties which needs to be converted to single word key properties
* @return Set of properties which has keys containing single word.
*/
public static Properties buildSingleWordKeyProperties(String prefix, Properties propertiesWithFullKeys) {
// Stop proceeding if required arguments are not present
if (StringUtils.isEmpty(prefix) || propertiesWithFullKeys == null) {
throw new IllegalArgumentException("Prefix and properties should not be null to get properties with " +
"single word keys.");
}
propertiesWithFullKeys = NotificationManagementUtils.getPropertiesWithPrefix(prefix, propertiesWithFullKeys);
Properties properties = new Properties();
Enumeration propertyNames = propertiesWithFullKeys.propertyNames();
while (propertyNames.hasMoreElements()) {
String key = (String) propertyNames.nextElement();
String newKey = key.substring(key.lastIndexOf(".") + 1, key.length());
if (!newKey.trim().isEmpty()) {
// Remove from original properties to hold property schema. ie need to get the set of properties which
// remains after consuming all required specific properties
properties.put(newKey, propertiesWithFullKeys.remove(key));
}
}
return properties;
}
private void mapStartsWith(Map<String, String> map,
Properties properties,
String startsWith,
boolean includeSubProperties) {
Enumeration< ? > enumeration = properties.propertyNames();
while ( enumeration.hasMoreElements() ) {
String key = (String) enumeration.nextElement();
if ( key.startsWith( startsWith ) ) {
if ( !includeSubProperties && key.substring( startsWith.length() + 1 ).indexOf( '.' ) > 0 ) {
// +1 to the length, as we do allow the direct property, just not ones below it
// This key has sub properties beyond the given startsWith, so skip
continue;
}
if ( !map.containsKey( key ) ) {
map.put( key,
properties.getProperty( key ) );
}
}
}
}
@SuppressWarnings("unchecked")
private void printOlatLocalProperties() {
final Resource overwritePropertiesRes = new ClassPathResource("olat.local.properties");
try {
final Properties overwriteProperties = new Properties();
overwriteProperties.load(overwritePropertiesRes.getInputStream());
final Enumeration<String> propNames = (Enumeration<String>) overwriteProperties.propertyNames();
System.out.println("### olat.local.properties : ###");
while (propNames.hasMoreElements()) {
final String propName = propNames.nextElement();
System.out.println("++" + propName + "='" + overwriteProperties.getProperty(propName) + "'");
}
} catch (final IOException e) {
System.err.println("Could not load properties files from classpath! Exception=" + e);
}
}
/**
* Verify the passed memory parameters are set in the session
*/
@Test
public void testClientMemoryParameters() throws Exception
{
Properties paramProperties = new Properties();
paramProperties.put("CLIENT_PREFETCH_THREADS", "6");
paramProperties.put("CLIENT_RESULT_CHUNK_SIZE", 48);
paramProperties.put("CLIENT_MEMORY_LIMIT", 1000);
Connection connection = getConnection(paramProperties);
for (Enumeration<?> enums = paramProperties.propertyNames();
enums.hasMoreElements(); )
{
String key = (String) enums.nextElement();
ResultSet rs = connection.createStatement().executeQuery(
String.format("show parameters like '%s'", key));
rs.next();
String value = rs.getString("value");
assertThat(key, value, equalTo(paramProperties.get(key).toString()));
}
}
/**
* Connects the interface with the work catalog implementation. The choice of backend is
* configured through properties. This class is useful for non-singleton instances that may
* require changing properties.
*
* @param props is an instance of properties to use.
* @exception ClassNotFoundException if the schema for the database cannot be loaded. You might
* want to check your CLASSPATH, too.
* @exception NoSuchMethodException if the schema's constructor interface does not comply with
* the database driver API.
* @exception InstantiationException if the schema class is an abstract class instead of a
* concrete implementation.
* @exception IllegalAccessException if the constructor for the schema class it not publicly
* accessible to this package.
* @exception InvocationTargetException if the constructor of the schema throws an exception
* while being dynamically loaded.
* @see org.griphyn.common.util.CommonProperties
*/
public static WorkCatalog loadInstance(CommonProperties props) throws WorkFactoryException {
// sanity check
if (props == null) throw new NullPointerException("invalid properties");
Properties connect = props.matchingSubset(WorkCatalog.c_prefix, false);
// get the default db driver properties in first pegasus.catalog.*.db.driver.*
Properties db = props.matchingSubset(WorkCatalog.DB_ALL_PREFIX, false);
// now overload with the work catalog specific db properties.
// pegasus.catalog.work.db.driver.*
db.putAll(props.matchingSubset(WorkCatalog.DB_PREFIX, false));
// to make sure that no confusion happens.
// add the db prefix to all the db properties
for (Enumeration e = db.propertyNames(); e.hasMoreElements(); ) {
String key = (String) e.nextElement();
connect.put("db." + key, db.getProperty(key));
}
// put the driver property back into the DB property
// String driver = props.getProperty( WorkCatalog.DBDRIVER_PREFIX );
// if( driver == null ){ driver = props.getProperty( WorkCatalog.DBDRIVER_ALL_PREFIX
// ); }
// connect.put( "db.driver", driver );
// determine the class that implements the work catalog
return loadInstance(props.getProperty(WorkCatalog.c_prefix), connect);
}
public String getStartCommand() {
if (!isSqlFire) {
StringBuilder sb = new StringBuilder();
sb.append(this.controller.getProductExecutable(this, GFE_LAUNCHER_NAME));
sb.append(" start-locator -q -dir=");
sb.append(this.getConfig().getWorkingDirectory());
sb.append(" -port=");
sb.append(this.getConfig().getPort());
Properties props = config.getDistributedSystemProperties();
Enumeration en = props.propertyNames();
while (en.hasMoreElements()) {
String pn = (String)en.nextElement();
sb.append(" -Dgemfire." + pn + "=" + props.getProperty(pn));
}
String bindAddress = this.getConfig().getBindAddress();
if (bindAddress != null && bindAddress.length() > 0) {
sb.append(" -address=");
sb.append(this.getConfig().getBindAddress());
}
sb.append(" ");
String sslArgs =
this.controller.buildSSLArguments(this.system.getConfig());
if (sslArgs != null) {
sb.append(sslArgs);
}
return sb.toString().trim();
} else {
return getGfxdStartCommand();
}
}
/**
* Merge the given Properties instance into the given Map,
* copying all properties (key-value pairs) over.
* <p>Uses {@code Properties.propertyNames()} to even catch
* default properties linked into the original Properties instance.
* @param props the Properties instance to merge (may be {@code null})
* @param map the target Map to merge the properties into
*/
@SuppressWarnings("unchecked")
public static <K, V> void mergePropertiesIntoMap(@Nullable Properties props, Map<K, V> map) {
if (props != null) {
for (Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) {
String key = (String) en.nextElement();
Object value = props.get(key);
if (value == null) {
// Allow for defaults fallback or potentially overridden accessor...
value = props.getProperty(key);
}
map.put((K) key, (V) value);
}
}
}
/**
* Parse the driver URL and extract the properties.
*
* @param url the URL to parse
* @param info any existing properties already loaded in a
* <code>Properties</code> object
* @return the URL properties as a <code>Properties</code> object
*/
public static Properties parseURL(String url, Properties info) {
if ((url == null) || !url.toLowerCase().startsWith(driverPrefix)) {
return null; // throws exception ?!
}
Properties props = new Properties(info);
// take local copy of existing properties
Enumeration<?> en = info.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = info.getProperty(key);
if (value != null) {
props.setProperty(key.toUpperCase(), value);
}
}
String tmp = url.substring(driverPrefix.length());
String[] tokens = tmp.split(";");
if (tokens.length != 2) {
return null; // datasource missing
}
try {
new URL(tokens[0]);
} catch (MalformedURLException e) {
return null; // url invalid
}
props.setProperty(SERVER_URL, tokens[0]);
props.setProperty(DATASOURCE_PATH, tokens[1]);
return props;
}
private void setProperties(Properties values)
throws PrivilegedActionException
{
for (Enumeration e = values.propertyNames(); e.hasMoreElements();)
{
String key = (String) e.nextElement();
String value = values.getProperty(key);
String old = BaseTestCase.getSystemProperty(key);
boolean change;
if (old != null)
{
// set, might need to be changed.
change = !old.equals(value);
// If we are not processing the oldValues
// then store in the oldValues. Reference equality is ok here.
if (change && (values != oldValues))
oldValues.setProperty(key, old);
}
else {
// notset, needs to be set
change = true;
}
if (change) {
BaseTestCase.setSystemProperty(key, value);
}
}
}
protected void setupAliases() {
try {
Properties aliases = new Properties();
FileInputStream fis = new FileInputStream(new File(getServer().getConfig().CONFIG_DIR, "aliases.xml"));
aliases.loadFromXML(fis);
for (Enumeration<?> e = aliases.propertyNames(); e.hasMoreElements(); ) {
String alias = (String) e.nextElement();
Class<?> c = Class.forName((String) aliases.get(alias));
xstream.alias(alias, c);
}
} catch (Exception ioe) {
LOGGER.catching(ioe);
}
}
/**
* Creates a set of protected properties from a set of normal ones.
*
* @param props the properties to be stored and protected.
*/
public ProtectedProperties(Properties props)
{
Enumeration propEnum = props.propertyNames();
while (propEnum.hasMoreElements()) {
String propName = (String) propEnum.nextElement();
String propValue = props.getProperty(propName);
super.setProperty(propName, propValue);
}
closed = true; // no modifications allowed from now on
}
/**
* Internal method to get the default properties from the
* serializer factory and set them on the property object.
* @param props a java.util.Property object on which the properties are set.
* @param method The output method type, one of "xml", "text", "html" ...
*/
private void setDefaults(Properties props, String method)
{
final Properties method_props =
OutputPropertiesFactory.getDefaultMethodProperties(method);
{
final Enumeration names = method_props.propertyNames();
while (names.hasMoreElements())
{
final String name = (String)names.nextElement();
props.setProperty(name, method_props.getProperty(name));
}
}
}
/**
* properties convert to string
*
* @param properties config properties
* @return config string
* @throws ApiBootException ApiBoot Exception
*/
protected String fromProperties(Properties properties) throws ApiBootException {
Enumeration enumeration = properties.propertyNames();
StringBuffer buffer = new StringBuffer();
while (enumeration.hasMoreElements()) {
String propertyKey = String.valueOf(enumeration.nextElement());
String propertyValue = properties.getProperty(propertyKey);
buffer.append(propertyKey);
buffer.append(PROPERTIES_KEY_VALUE_SPLIT);
buffer.append(propertyValue);
buffer.append("\n");
}
return buffer.toString();
}
/**
separate from the constructor so that connection
failure does not prevent object creation.
*/
void init(LocalizedOutput out) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
Connection c = util.startJBMS(null,null);
// only load up ij.connection.* properties if there is
// only one ConnectionEnv in the system.
if (only) {
Properties p = (Properties) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return System.getProperties();
}
});
protocol = p.getProperty(ij.PROTOCOL_PROPERTY);
String prefix = CONNECTION_PROPERTY + ".";
for (Enumeration e = p.propertyNames(); e.hasMoreElements(); )
{
String key = (String)e.nextElement();
if (key.startsWith(prefix)) {
String name = key.substring(prefix.length());
installConnection(name.toUpperCase(java.util.Locale.ENGLISH),
p.getProperty(key), out);
}
}
}
if (c!=null) // have a database from the startup?
{
String sname=Session.DEFAULT_NAME+sessions.size();
Session s = new Session(c,tag,sname);
sessions.put(sname,s);
currSession = s;
}
}
/**
* -DXMLIngester.userCnt=176 will override the userCnt in property files.
* @param props
*/
private void systemPropertiesOverride(Properties props) {
Enumeration<?> names = props.propertyNames();
Object nameObject;
String name;
while (names.hasMoreElements()) {
nameObject = names.nextElement();
if (nameObject instanceof String) {
name = (String)nameObject;
props.setProperty(name, System.getProperty("XMLIngester." + name, props.getProperty(name)));
}
}
}
/**
* Implements JAXP's Transformer.setOutputProperties().
* Set the output properties for the transformation. These properties
* will override properties set in the Templates with xsl:output.
* Unrecognised properties will be quitely ignored.
*
* @param properties The properties to use for the Transformer
* @throws IllegalArgumentException Never, errors are ignored
*/
@Override
public void setOutputProperties(Properties properties)
throws IllegalArgumentException
{
if (properties != null) {
final Enumeration names = properties.propertyNames();
while (names.hasMoreElements()) {
final String name = (String) names.nextElement();
// Ignore lower layer properties
if (isDefaultProperty(name, properties)) continue;
if (validOutputProperty(name)) {
_properties.setProperty(name, properties.getProperty(name));
}
else {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_PROP_ERR, name);
throw new IllegalArgumentException(err.toString());
}
}
}
else {
_properties = _propertiesClone;
}
}
/**
* Sorts property list and print out each key=value pair prepended with
* specific indentation. If indent is null, do not prepend with
* indentation.
*
* The output string shows up in two styles, style 1 looks like
* { key1=value1, key2=value2, key3=value3 }
*
* style 2 looks like
* key1=value1
* key2=value2
* key3=value3
* where indent goes between the new line and the keys
*
* To get style 1, pass in a null indent
* To get sytle 2, pass in non-null indent (whatever you want to go before
* the key value)
*/
public static String sortProperties( Properties list, String indent )
{
int size = list == null ? 0 : list.size();
int count = 0;
String[] array = new String[size];
String key;
String value;
StringBuffer buffer;
// Calculate the number of properties in the property list and
// build an array of all the property names.
// We need to go thru the enumeration because Properties has a
// recursive list of defaults.
if (list != null)
{
for (Enumeration propertyNames = list.propertyNames();
propertyNames.hasMoreElements(); )
{
if (count == size)
{
// need to expand the array
size = size*2;
String[] expandedArray = new String[size];
System.arraycopy(array, 0, expandedArray, 0, count);
array = expandedArray;
}
key = (String) propertyNames.nextElement();
array[ count++ ] = key;
}
// now sort the array
java.util.Arrays.sort(array, 0, count);
}
// now stringify the array
buffer = new StringBuffer();
if (indent == null)
buffer.append( "{ " );
for ( int ictr = 0; ictr < count; ictr++ )
{
if ( ictr > 0 && indent == null)
buffer.append( ", " );
key = array[ ictr ];
if (indent != null)
buffer.append( indent );
buffer.append( key ); buffer.append( "=" );
value = list.getProperty( key, "MISSING_VALUE" );
buffer.append( value );
if (indent != null)
buffer.append( "\n" );
}
if (indent == null)
buffer.append( " }" );
return buffer.toString();
}
/**
* Adds new properties to an existing set of properties while substituting variables. This
* function will allow value substitutions based on other property values. Value substitutions
* may not be nested. A value substitution will be ${property.key}, where the dollar-brace and
* close-brace are being stripped before looking up the value to replace it with. Note that the
* ${..} combination must be escaped from the shell.
*
* @param a is the initial set of known properties (besides System ones)
* @param b is the set of properties to add to a
* @return the combined set of properties from a and b.
*/
protected static Properties addProperties(Properties a, Properties b) {
// initial
Properties result = new Properties(a);
Properties sys = System.getProperties();
Pattern pattern = Pattern.compile("\\$\\{[-a-zA-Z0-9._]+\\}");
for (Enumeration e = b.propertyNames(); e.hasMoreElements(); ) {
String key = (String) e.nextElement();
String value = b.getProperty(key);
// unparse value ${prop.key} inside braces
Matcher matcher = pattern.matcher(value);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
// extract name of properties from braces
String newKey = value.substring(matcher.start() + 2, matcher.end() - 1);
// try to find a matching value in result properties
String newVal = result.getProperty(newKey);
/*
* // if not found, try b's properties
* if ( newVal == null ) newVal = b.getProperty(newKey);
*/
// try myself
if (newVal == null) newVal = result.getProperty(newKey);
// if still not found, try system properties
if (newVal == null) newVal = sys.getProperty(newKey);
// replace braced string with the actual value or empty string
matcher.appendReplacement(sb, newVal == null ? "" : newVal);
}
matcher.appendTail(sb);
result.setProperty(key, sb.toString());
}
// final
return result;
}