The two basic characteristics and abstractconfiguration of Commons configuration

Source: Internet
Author: User

The configuration interface defines a large stack of methods. It is very difficult to implement these methods from scratch. Because the Abstractconfiguration class exists. This class acts as a common base class for most configuration implementations in the Commons configuration and provides a number of functions required by the interface. Therefore, creating a custom configuration to implement the class will be a good starting point.
In addition to the basic implementation of the method declared in the configuration interface, the Abstractconfiguration class provides some additional convenience features. Because this class is the root of the Commons configuration class hierarchy, these attributes are valid for most specific implementations of the configuration interfaces that the class library provides.

1 Handling missing attributes

If you pass in a key to one of its get methods and cannot map to an existing property, what does the configuration object do? The default behavior of the Abstractconfiguration implementation is to return NULL if the return value is an object type. It is not possible for the original type to return null (or any particular value), so in this case a nosuchelementexception is thrown:

If no property with key "Nonexistingproperty" will return null
String strvalue = config.getstring ("Nonexistingproperty");

A Nosuchelementexception exception will be thrown if there is no property with the key "Nonexistingproperty"
Long Longvalue = Config.getlong ("Nonexistingproperty");

For object types, the default behavior, such as String, BigDecimal, or BigInteger, can be changed: if the Setthrowexceptiononmissing () method is called with a true parameter, these methods will be the same as the original type. Throws an exception if the passed-in property key cannot be resolved.

Note: Unfortunately support for the Throwexceptiononmisssing property is not always consistent: GetList () and Getstringarray () do not evaluate the token if the request attribute is not found to return an empty list or array. Perhaps this behavior will change in important versions of the future.

2 List Processing

Multi-valued properties are processed using the GetList () and Getstringarray () methods defined by the configuration interface. When a configuration source (such as a properties file, XML document, or Jndi context) processes the corresponding configuration implementation, it discovers a property with multiple values and ensures that the data is stored correctly.

The AddProperty () and SetProperty () methods of abstractconfiguration also implement specific list processing when properties are modified. The property values passed into these methods can be a list or an array that produces a multivalued property. If the property value is a string, it detects whether the string contains a list delimiter. If this is the case, the string is split and its individual parts are added. The list delimiter is a comma by default. When the configuration source is loaded, it is considered within (for example, the string value of the property will be detected to include a delimiter). You can set it to a different character by using the Setlistdelimiter () method.

Change list delimiter to slash
Config.setlistdelimiter ('/');
Now add some properties
Config.addproperty ("Greeting", "Hello, How is You?");
Config.addproperty ("Colors.pie", new string[] {"#FF0000", "#00FF00", "#0000FF"});
Config.addproperty ("Colors.graph", "#808080/#00FFCC/#6422FF");

accessing data
String Salut = config.getstring ("greeting");
list<object> Colpie = config.getlist ("Colors.pie");
string[] Colgraph = Config.getstringarray ("Colors.graph");

String Firstpiecolor = config.getstring ("Colors.pie");

In this example, the list delimiter changes from a comma to a slash. Because the Greeting property is not split, it is saved as a single string. The Colors.graph property that is passed in as a string contains the new delimiter and therefore produces a three-value property. Note that list is of type object. This is because the specific type of the property value is not known. For example, if you call AddProperty ("answer", 42), an integer object will be stored in the configuration.

Interesting is the last line of the example fragment. The GetString () method called has multiple values. This returns the first value of the list.

If you want to change the list delimiter for all configuration objects, you can use the Abstractconfiguration static Setdefaultlistdelimiter () method. You can also disable the slicing of string attributes for all configuration instances by calling the Setdelimiterparsingdisabled () method using True.

3 variable interpolation

If you are familiar with ant or Maven, you must have encountered a variable (like, ${token}) when the configuration file is loaded and the variable is automatically interpreted. These features are also supported by the Commons configuration.

Application.Name = Killer App
Application.Version = 1.6.2

Application.title = ${application.name} ${application.version}

If you now retrieve the Application.title property value, the result will be the killer App 1.6.2. So that each default variable is interpreted as the key of the other property. This is only a special case, the general syntax for variable names is ${prefix:name}. Prefix tells Commons that the configuration variable is calculated in a context. As we can see, if prefix is missing, the context is the current configuration instance. The following are the default supported prefix names.

Prefix
Describe
Sys
The prefix marks a variable as a system attribute. Commons the configuration will search for a system property with the specified name and replace the variable with that value. This is very easy to access the values of system properties in each configuration implementation.
Const The const prefix represents a variable that is interpreted as a constant member field of a class (for example, a field that uses the static final modifier). The name of the variable must be the form of < fully qualified class name >.< field name >. Specifies that the class will be loaded and that the value of the field will be fetched.
Env Variables can also refer to specific OS environment variables. This is represented by the EVN prefix.

Here are some examples, only for the properties file:

Propertiesconfiguration cfg = new Propertiesconfiguration ("Cfg/basic/vm.properties");
System.out.println (cfg.getstring ("Vm.name"));
System.out.println (cfg.getstring ("Vm.author"));
System.out.println (cfg.getstring ("Vm.home"));
System.out.println (cfg.getstring ("Vm.bin"));

Public interface Const {

public static final String AUTHOR = "Evan";

}


#相当于System. GetProperty ("Java.runtime.name")

Vm.name=${sys:java.runtime.name}
Vm.author=${const:cfg.basic.const.author}

#相当于System. GETENV ("Java_home")

Vm.home=${env:java_home}
Vm.bin=${vm.home}\bin

If a variable cannot be parsed, for example, because the name is invalid or an unknown prefix, it cannot be replaced, but the return includes the dollar sign and the curly brace.

3 Custom Interpolation

This section explains how you can add your own interpolation values. The interpolation engine is implemented using the Strsubstitutor class under the text package of Commons Lang. The class resolves variables using objects derived from the Strlookup class. The Strlookup defines a simple lookup () method that must be implemented by a custom implementation; it expects the variable name as a parameter and returns the corresponding value (more details can be found in the Commons lang document). We have introduced the standard prefix variable so far we have actually implemented a specific class derived from Strlookup.

You can now create your own strlookup implementation and make it valid for all configuration objects on a custom prefix. We'll show you how. The first step is to create a new class derivation strlookup, which must implement the lookup () method. As an example, we implement a simple query object that simply returns the receipt of an incoming variable:

Import Org.apache.commons.lang.text.StrLookup;

public class Echolookup extends Strlookup
{
public string Lookup (string varName)
{
Return "Value of variable" + varName;
}
}

Now, we want the class to use the prefix echo to invoke the variable. For this purpose the Echolookup class must be registered in the Configurationinterpolator class using the expected prefix. Configurationinterpolator implements a simple wrapper in the Strlookup API defined by Commons lang. It has a static registergloballookup () method, which we must call as follows:

Place the code where your application is initialized
Configurationinterpolator.registergloballookup ("echo", New Echolookup ());

Each Abstractconfiguration object created after that line of code will contain the new query class and can therefore resolve variables in the form of ${echo:my_variable}.

Each abstractconfiguration instance associates a Configurationinterpolator object. The object is created by the Createinterpolator () method at the time of the first access interpolation attribute. The interpolation mechanism may be more deeply intervened by overriding the method. For example, a custom implementation can add more advanced query objects to the insert.

4 using an expression (not here to understand how to use, please expert pointing twos)

In addition to the simple lookup mechanism described earlier, the Commons configuration provides exprlookup, using Apache Commons JEXL allows expression parsing whether a strlookup is allowed. If Exprlookup is configured, this example shows an alternative way to get system properties.

User.file = ${expr:system.getproperty ("User.home"}/settings.xml

Exprlookup is disabled by default and must be manually added or configured via Defaultconfigurationbuilder. Using MAVEN 2 to build and reference the Commons configuration will not include JEXL dependencies, so if the attribute is used you must manually add dependencies to the project.

Using Defaultconfigurationbuilder to add exprlookup is straightforward.

<configuration>
<result/>
<lookups>
<lookup config-prefix= "Expr"
config-class= "Org.apache.commons.configuration.interpol.ExprLookup" >
<variables>
<variable name= "System" value= "Class:java.lang.System"/>
<variable name "NET" value= "Class:java.net.InetAddress"/>
<variable name= "String" value= "Class:org.apache.commons.lang.StringUtils"/>
</variables>
</lookup>
</lookups>
<override>
<xml filename= "${expr:system.getproperty (' basepath ') +
String.lowercase (net.localHost.hostName) + '/testmulticonfiguration_default.xml '} "
Config-name= "Defaultconfig" delimiterparsingdisabled= "true" >
</xml>
</override>
</configuration>

The example above shows how to call a static method during an expression evaluation. The next example shows the use of a downlevel query mixed expression calculation to get the "BasePath" system property. Note the differences between the get system properties and the previous examples.

<configuration>
<result/>
<lookups>
<lookup config-prefix= "Expr"
config-class= "Org.apache.commons.configuration.interpol.ExprLookup" >
<variables>
<variable name "NET" value= "Class:java.net.InetAddress"/>
<variable name= "String" value= "Class:org.apache.commons.lang.StringUtils"/>
</variables>
</lookup>
</lookups>
<override>
<xml filename= "${expr:$[sys:basepath" +
String.lowercase (net.localHost.hostName) + '/testmulticonfiguration_default.xml '} "
Config-name= "Defaultconfig" delimiterparsingdisabled= "true" >
</xml>
</override>
</configuration>











The two basic characteristics and abstractconfiguration of Commons configuration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.