Keywords: Jakarta Commons Source: CCID Jakarta Commons: Using class and component 2 Author: Vikram Goyal; cactus studio Translation dispatch time: 2003.08.07 15:34:00 In the last article, we'll Jakarta Commons components are divided into five categories, and introduce the web classes and other classes. This article describes the XML classes and packaging classes, the next last article will introduce the tool class. Note that Commons itself does not perform this classification, and it is purely for organization convenience.
First, packaging class
This category contains two components of CODEC and Modeler.
1.1 CODEC
■ Overview: Provides commonly used encoders and decoders.
■ Official resources: home page, binary, source code.
■ When applies: When you need the standard implementation of the Base64 and HEX encoding functions.
■ Example Application: CodecDemo.java. The ClassPath must contain commons-codec-1.1.jar.
■ Description:
The class in CODEC is divided into two packets, one of which is implemented for common Base64 and HEX encoding mechanisms, and the other package is the language, voice coding. The usage of the two packages is similar, in view of the language, voice coding is not very common, so the first package is mainly introduced.
Base64 encoding is mainly used for Email transmission. Defining the RFC of the MIME document to specify the base 64 encoding, so that any binary data can be converted to a printable ASCII character set is securely transmitted. For example, suppose you want to transfer a graphic file via email, the Email client software will use the base64 encoding to convert the binary data of the graphic file to the ASCII code. In the base64 encoding, every three 8-bit bytes are encoded into a 4-character group, each character contains 6 digits in the original 24 bits, and the encoded string size is 1.3 times, the end of the file. Add "=" symbol. In addition to the MIME document, Base64 encoding technology is also used in the "User: Password" string of the HTTP certification head in the Basic authentication mechanism.
Base64 class is quite simple, the main two static methods are: base64.encodebase64 (byte [] ByteArray), execute Base64 encoding in the content specified in the byte array; base64.Decodebase64 (byte [] byterray), Used to perform Base64 decoding in the content specified in the byte array. In addition, Base64 also has a static method base64.isArrayBytebase64 (Byte [] ByteArray), which is used to detect whether the specified byte array can be tested through the base64 (ie, data encoded through the base64, as mentioned, Base64 encoded) The result contains only the printable ASCII characters).
byte [] encodedBytes = Base64.encodeBase64 (testString.getBytes ()); String decodedString = new String (Base64.decodeBase64 (encodedBytes)); System.err.println ( "/ '^ /' is a valid Base64 characters? " Base64.isaRrayBytebase64 (InvalidBytes);
HEX encoding / decoding is the conversion between hexadecimal representations of byte data and equivalent. The HEX encoded encoding, the decoding process, and the base64 are similar, and details are not described here.
1.2 Modeler
■ Overview: The configuration and instantiation of MODEL MBEAN (Managed Bean) are supported according to the definition of the JMX (Java Management Extensions specification). ■ Official resources: home page, binary, source code.
■ When applies: When you want to create and manage Model MBean to manage applications with standard management APIs.
■ Sample application: ModelerDemo.java, DemomanagedBean.java and MBeans-Descriptors.xml. ClassPath is required to include Commons-Modeler-1.0.jar, Commons-Logging.jar, Commons-Digester.jar, Commons-Collections.jar, and SUN JMX Reference Implement JMXri.jar.
■ Description:
The following description requires the reader to have a certain understanding of JMX.
The Managed Bean is referred to as MBean, is a bean associated with the managed components in the application is an abstraction of resources. Model MBean is a special MBean with high dynamic and configurable features, but this capability of Model MBean is cost. The programmer needs to set a lot of meta information to tell JMX how to create Model MBean, which includes Component properties, operations, and other information. The purpose of Modeler is to reduce the workload of programmers to implement Model MBean, which is convenient for processing metadata information. In addition, Modeler also provides a registration tool and a basic Model MBean.
Modeler allows metadata information to be defined in the form of an XML file, which should comply with the DTD definition provided with Modeler. Metadata information is used to create registration information at runtime, and the registration information is the central knowledge base of all Model MBeans, which is actually equivalent to a factory that creates such beans.
Below we first create this XML file for a Managed Bean. DemomanageDbean has a name property that is readily read.
XML Version = "1.0" Encoding = "GB2312"?> >
It can be seen that this XML file provides information about MANAGEDBEAN, including its properties, constructor, and its operation (but this example is not displayed), this is the so-called metadata information. If you plan to extend the standard MBean (called Basemodelmbean) provided with Modeler, you can specify the class name of Model MBean in the MBEAN element:. In the previous example, the standard Model MBean simply passes all calls directly to the ManageDbean class. Next, we have to register the above information. Note that after describing the registration information by describing the file, we extract formatted registration information through a static method:
// Create a RegistryRegistry registry = null; try {URL url = ModelerDemo.class.getResource ( "mbeans-descriptors.xml"); InputStream stream = url.openStream (); Registry.loadRegistry (stream); stream.close () Registry = registry.getregistry ();} catch (throwable t) {T.PrintStackTrace (System.out); System.exit (1);
After creating Registry, we have to create a Model MBean and register it to the default management server. In this way, any JMX client can call the Managed Bean through Model MBean.
// Get a handle of a Managed Bean instance DemomanagedBean MBean = new demomanagedbean ();
// Create a Model MBean and register it to the MBean server mbeanserver mserver = registry.getrserver (); managedbean management = registry.FindManageDbean ("managedbean");
try {ModelMBean modelMBean = managed.createMBean (mBean); String domain = mServer.getDefaultDomain (); ObjectName oName = new ObjectName (domain ": type = ManagedBean"); mServer.registerMBean (modelMBean, oName);} catch (Exception e) {system.err.println (e); system.exit (0);
try {ObjectName name = new ObjectName (mServer.getDefaultDomain () ": type = ManagedBean");. ModelMBeanInfo info = (ModelMBeanInfo) mServer getMBeanInfo (name); System.err.println ( "className =" info.getClassName ( ))); System.err.println ("description =" info.getdescription ()); system.err.println ("mbeandescriptor =" info.getmbeescriptor ()); system.rr.println ("==== Test ==== "); System.err.Println (" Name of the original value: " mserver.getattribute (name," name ")); MSERVER.SetAttribute (Name, New Attribute (" Name "," Vikram " ))); System.err.println ("NAME's new value:" mserver.getattribute (name, "name");} catch (exception e) {system.err.println (E); system.exit (0 Although this example is relatively simple, it still clearly illustrates the convenience of using Modeler, and may wish to create a similar Model MBean without using Modeler. Description ModelMbeanInfo is not only flexible, but also is also easy to expand, but also to scale this type of information than manually.
Second, XML class
The XML class contains classes related to Java, XML technology, including: BetWixt, Digester, Jelly, and JXPath.
2.1 Betwixt
■ Overview: Implementation of XML and JavaBean mapping.
■ Official resources: home page, binary, source code.
■ When you apply: When you want to implement XML and beans mappings in a flexible manner, you need a data binding framework.
■ Sample application: Betwixtdemo.java, Mortgage.java, Mortgage.xml. It is required to include Commons-Betwixt-1.0-alpha-1.jar, commons-beanutils.jar, commons-colors.jar, and commons-colorster.jar must be included in CLASSPATH.
■ Description:
If you have used Castor to bind data, you will definitely enjoy the flexibility of BetWixt. CASTOR is suitable for executing the conversion between beans and XML on a predefined mode (Schema); but if you only want to perform data and XML conversion, the best choice is Betwixt. Betwixt features flexible, convenient to output data to human readable XML.
The usage of BetWixt is quite simple. If you want to convert the bean into XML, first create an instance of BeanWriter, set its properties, then output; if you want to convert XML to bean, first create an instance of BeanReader, set its properties, and perform conversion with Digester. Convert BEAN to XML:
// convert the bean to XML with BETWixT must have instances of BeanWriter. / / Since BeanWriter's constructor has a writer object, // So we start StringWriter outputWriter = new stringWriter () from creating a StringWriter (); // Note that the output is not formatted, so you need to start //// Write the following: OutputWriter.write (" Convert XML to bean: // Create // bean based on BetWixt and create // bean based on this, and must be used to use the BeanReader class. Note the BeanReader class extends the Digester class of the // Digester package. Beanreader Reader = new beanreader (); // Register Try {reader.registerBeanClass (Mortgage.Class); // and parsing it ... Mortgage MortgageConverted = (Mortgage) Reader.Parse (New File ("Mortgage.xml")); // Check if the converted Mortgage is The value in the file contains system.rr.println ("Rate:" MortgageConverted.Getrate () ", Years:" MortGageConverted.GetyEars ());} Catch (Exception EE) {EE.PRINTSTACKTRACE ();} Note that when the class is registered by the BeanReader, if the name of the top element is different, you must register and specify an accurate path with another method, such as Reader.RegisterBeanclass ("TopLeleElementName", Mortgage.Class). 2.2 Digester ■ Overview: Provides a friendly, event-driven advanced XML document processing API. ■ Official resources: home page, binary, source code. ■ When you apply: When you want to process an XML document, and you want to perform some operations based on a set of rules triggered in the XML document. ■ Sample application: DigesterDemo.java, Employe.java, Company.java, Rules.xml, and Company.xml. ClassPath must be included in Commons-Digester.jar, Commons-Logging.jar, Commons-BeanuTils.jar, and Commons-Collections.jar. ■ Description: Digester is the most useful when parsing the configuration file. In fact, Digester is initially developed for reading the Struts profile, and then moved to the CommONS package. Digester is a powerful mode matching tool that allows developers to process XML documents at a higher level than SAX or DOM APIs, which can trigger a set of rules when they find specific patterns (or find modes). Basic ideas using Digester are: First create an instance of Digester, then use it to register a range of modes and rules, and finally pass the XML document to it. Thereafter, Digester will analyze the XML document, trigger rules according to the registration order. If an element in the XML document matches one or more rules, all rules will be triggered in order according to the order of registration. Digester itself has 12 predefined rules. When you find a specific mode in the XML document, do you want to call a method? Very simple, use predefined CallMethodRule! In addition, you don't have to use a predetermined rule, Digester allows users to define their own rules by extending the Rule class. When specified mode, the element must be given by absolute name. For example, the root element is specified directly with the name, and the next layer element is drawn from the "/" symbol. For example, suppose companies are root elements, and Company / Employee is a mode that matches one of the child elements. Digester allows wildcards, such as * / Employee, will match all EMPLOYEEEE elements that appear in the XML document. When you find a match mode, there are four callback methods that are associated with the matching mode, they are: begin, end, body, and finish. These methods are called by the time as indicated by their name, such as when the time to call Begin and End is when the start tag and end tag are encountered. It is called after the processing of the matching mode is completed. Finally, the mode can be specified in an external rule XML document (using digester-rules.dtd), or specified within the code, the following is the first approach, because this method is more common. Create two XML documents before using Digester. The first is a data or configuration file, that is, we prepare a file for its application rules. Here is an example (Company.xml) XML Version = "1.0" encoding = "GB2312"?> XML Version = "1.0" encoding = "gb2312"?> What meanings do this file? The first rule, The last pattern match is worth noting that it is nested in the matching mode. The way two setting rules and patterns are Digester Accepted, and we can choose anything according to your needs. In this example, the rules defined in the mode create an object of the Employee class when encountering the Company / Employee mode, sets its properties, and finally uses set-next-rule to add this employee to the top layer. Once you have created the above two XML files, you can call Digester as long as you use two lines: Digester Digester = digesterLoader.creatediGester (rules.tourl ()); Company company = (company) Digester.Parse (InputXMLFile); The first line of code is loaded into the rule file and creates a Digester. The second line of code uses the Digester to apply the rules. See DigesterDemo.java provided later in this article. 2.3 jelly ■ Overview: A scripting language based on Java and XML. ■ Official resources: home page, binary, source code. ■ When applies: Simply say, when you want a flexible, scalable XML script tool. ■ Example App: JellyDemo.java, JellyDemo.xml, and TrivialTag.java. It is required to have commons-jelly-1.0-dev.jar, dom4j.jar, commons-logging.jar, commons-beanutils.jar, and commons-collections.jar must be required in ClassPath. ■ Description: To make it clear that Jelly is what role is it is very difficult. Jelly attempts to provide a universal XML script engine that can be mapped by developers through custom action and tag extensions, and the elements in the XML document are mapped to JavaBean, and the properties of the XML element are mapped to the properties of the JavaBean. In a sense, Jelly is a tool combined with BetWixt and Digester, but Jelly is more powerful and has better scalability. A Jelly system consists of multiple components. The first component is a Jelly script, which is an XML document parsed by Jelly Engine, and the parsed XML document element is bound to jelly tag dynamic processing. The second component is Jelly tag, which is a Javabean that implements Jelly Tag interface. Any Jelly tag can implement a dotag method. This DOTAG method is how the method performed when the scripting is encountered in the XML document. . Jelly is a dynamic script processing capability through this mechanism. From a sense, it is a bit similar to Digester's working mechanism. Jelly has many predefined tags, some of which provide core Jelly support, other tags are used to provide support for resolution, loop, condition execution code. In addition, Jelly also provides a wide range of support for Ant tasks. To use Jelly in a Java application, first create an example of JellyContext, for example: JellyContext context = new jellyContext () ;. We can see JellyContext objects as a running environment compiling and run Jelly scripts. With JellyContext, you can run Jelly scripts. The output of JellyContext is actually an instance of an XMLOUTPUT class: Context.Runscript (New File ("JellyDemo.xml"), Output) ;. When you create a custom tag, we can overwrite the DOTAG methods mentioned above (as shown in the following example), or provide an execution method, such as invoke () or Run (): Public void dotag (xmloutput output) throws exception {// Add to the action you want to perform, //, for example, set an attribute, access file system, etc. ... this.intprop = 3;} The following is an example of an XML file for defining Jelly scripts: This example uses Jelly: Define and Jelly: Core tags, and a TRIVIALTAG tag. When encountering a TRIVIAL tag instance, Jelly creates an instance of the corresponding JavaBean, execute the DOTAG method (or can be a RUN or INVOKE.). Jelly has many other features that can be run directly from the command line or Ant script, or within the code of the application, see the Jelly documentation for details. 2.4 JXPATH ■ Overview: XPath interpreter in Java. ■ Official resources: home page, binary, source code. ■ When applies: When you want to apply XPath queries in the structure composed of JavaBean, DOM, or other objects. ■ Sample application: jxpathdemo.java, book.java, author.java. The ClassPath must contain common-jxpath-1.1.jar. ■ Description: The following description requires the reader already have basic XPath knowledge. XPath is a language that queries an XML document. JXPath applies the same concept to other Java object queries, such as JavaBean, Collection, Array, and Map. JXPathContext is the core class in JXPath, which uses a factory method to locate and create an instance of a context. Because of this mechanism, the developer can insert a new JXPath implementation when necessary. To use JXPathContext, just simply pass a JavaBean, Collection or Map, for example: jxpathcontext context = jxpathcontext.newcontext (book) ;. Many tasks can be implemented using JXPathContext. Of course, attributes can be set, such as access attributes or nested properties. System.err.println ("Title"); system.rr.println ("Author / AuthorID"); Context.SetValue ("Author / AuthorID", "1001"); With JXPath, you can also find other types of objects, but the way to create a context object is the same, you have obtained a new context with the static method described above, and it is incoming that the object you want to query. Conclusion: The introduction of the package and XML classes is over here. In the next article, we will learn about the tool class. Please download this text here: jakartacommons2code.zip. (Editor: Zhang Mingyan)