JAKARTA Commons Project Group Introduction

zhaozj2021-02-16  73

Jakarta Commons: Use class and components Jakarta Commons are Jakarta sub-projects, which creates and maintains many independent packages, which are generally with other frameworks or products.

Norway, a large number of small, practical components are collected, and most of them are programmed for server-side.

The package of Commons is divided into two parts: Sandbox, the Commons Code Base. Sandbox is a test platform for verifying various ideas.

plan. The components introduced in this article belong to the Commons Code Base. The article will show the functions, applicable occasions of each component, and through simple example

Introduce its usage.

I. Overview

Reusability is the soul of the Jakarta Commons project. These packages have considered a reusability problem in the design phase. among them

Some packages, such as the logging package used to record the logs, which is originally designed for other projects, such as Jakarta Struts.

Project, when people discovering that these packages are also very useful for other projects, they can greatly help other projects, they decided to be these packages.

Construct a "public" storage location, this is the Jakarta Commons project.

In order to truly improve reusability, each package must not depend on other large frames or projects. Therefore, the package of the Commons project

It is basically independent, not only to independence with other projects, but also independent of most other packages inside the Commons. although

There are some exceptions, such as the BaETWixT package to use the XML API, but most of them use the most basic API, the main purpose

It is necessary to be able to easily call via a simple interface.

However, due to the brief admiral, many packages have become too simple, lack maintenance and support, even some of the wrong links,

The document is also very poor. Most packages need us to find out their usage, and sometimes we need to analyze their applicable occasions.

This article will introduce these packages one by one, hoping to help you quickly master this free code base that has accumulated many people.

Note: Jakarta Commons and Apache Commons are different, the latter is one of Apache Software Foundation.

The top project, the former is a sub-project of the Jakarta project, and the protagonist to be discussed herein. This article is mentioned in Commons

Wherever the place, Jakarta's Commons.

In order to facilitate explanation, this article divides the 18 finished components of the Commons project (excluded EL, LATKA and JEXL) into Type 5.

As shown in the following table.

It must be pointed out that this classification is only for the convenience of the article, and there is no such classification in the Commons project.

There is sometimes a certain overlap between these categories.

This article first introduces the components in the Web related class and other classes, the next article will involve XML related, packaging these two categories, the last one

The article specifically introduces a package that belongs to the tool class.

Second, other classes

CLI, Discovery, Lang and Collectes are incorporated into other classes, because they are all for a certain, practical

Small goals can be described as decentralized.

2.1 CLI

■ Overview: CLI, Command Line Interface, is also "command line interface", it is accessible and parsing the command line for Java programs

The parameters provide a unified interface.

■ Official resources: home page, binary, source code

■ When you apply: When you need to access the command line parameters in a unified manner.

■ Example App: Clidemo.java. Commons-cli-1.0.jar must be included in ClassPath. ■ Description:

How many times you have to redesign a new command line parameter processing method for a new application? If you can only use a single one

Interface, uniform completion, such as defining input parameters (whether it is forced parameters, numerical or strings, etc.), according to a series of rule analysis

Parameters, determine the task such as the path to be used, then how good! The answer is in the CLI.

In the CLI, each of the parameters you want to specify in the command is an Option object. First create an Options object, will

Each Option object adds to an Options object, and then uses the method provided by the CLI to resolve the user's input parameters. Option object

The user must enter a parameter, such as the file name must be provided on the command line. If a parameter is necessary, create an Option pair

It is necessary to explicitly specify when it is like.

Here is the steps using the CLI.

// ...

// 1 Create a Options:

Options options = new options ();

Options.addoption ("T", False, "Current Time");

// ...

// 2 Create a parser and analyze the input:

CommandLineParser Parser = New BasicParser ();

CommandLine CMD;

Try {

CMD = Parser.Parse (Options, Args);

} catch (parseException pe) {

USAGE (Options);

Return;

}

// ...

// 3 Finally, according to the user's input, take the corresponding operation:

IF (cmd.hasoption ("n")) {

System.err.println ("Nice to meet you:"

CMD.GetoptionValue ('n'));

}

This is the complete process using the CLI. Of course, the CLI provides other advanced options, such as control formats and parsing processes, etc.

But basic use ideas is still consistent. See the sample program provided in this article.

2.2 Discovery

■ Overview: Discovery Components is an implementation of discovery pattern, its goal is to follow a unity

Ways positioning and instantiating classes and other resources.

■ Official resources: home page, binary, source code.

■ When applies: When you want to use the best algorithm to find various implementations of the Java interface in the Java program.

■ Application example: DiscoveryDemo.java, MyInterface.java, MyImpl1.java, MyImpl2.java, MyInterface.

It is required to include Commons-Discovery.jar and Commons-Logging.jar in ClassPath.

■ Description:

Discovery means "discovery", it tries to find all known implementations of an interface with the best algorithm. Service

In addition, the Discovery component is especially useful when we want to find all known providers of a service.

Consider this situation: We wrote an interface for a particularly complex task, all the implementations of the interface are different.

The way this complex task is completed, and the end user can select the specific way to complete the task as needed. Then, in this case, what should the end user use to find all the available implementations of the interface (ie possible way to complete the task)?

The situation described above is the so-called service-service provider system. The function of the service is described by the interface, and the service provider provides specific

Realization. The current problem is that end users should use some way to find which service providers have installed in the system. In this case,

The Discovery component is useful, but it can not only find classes that implement specific interfaces, but also to find resources.

For example, a picture or other file, etc. DISCOVERY follows the rules defined by the Sun's service provider system when performing these operations.

For this reason, the use of Discovery components really brings a lot of convenience. Please read the interface to the interface in the sample program in this article

MyInterface.java and two implementation class MyImpl1.java, MyIMple2.java, learn the details of the following example. Use discovery

When you provide myInterface file, put it into the meta-inf / service directory, pay attention to the full interface of the file.

The Fully Qualified Name, if the interface belongs to a package, the name of the file must also change accordingly.

// ...

// 1 Create an instance of a class equipment.

ClassLoaders loadingers =

ClassLoaders.Getapploaders (MyInterface.class, getClass (), FALSE;

// ...

// 2 Use discoverclass to find the implementation class.

Discoverclass Discover = New DiscoverClass (loadingers);

// ...

// 3 Find the class that implements the specified interface:

Class Implclass = discover.find (MyInterface.class);

System.err.Println ("Implementing Provider:" Implclass.getName ());

Run the above code, you can get the class registered in the MyInterface file. Remind again, if your implementation is packaged in the package

Inside, the name registered here should also be modified accordingly, if the file is not placed in the correct position, or the implementation of the name

The class cannot be found or instantiated, and the program will throw discoverexception, indicating that the eligible implementation is not found. Here is MyInterface

An example of the file content: MyImpl2 # Implementation 2.

Of course, the registration method for realizing the class is not only one, otherwise the practicality of Discovery is a big discount! In fact,

Follow the Class search mechanism within Discovery, the class registered according to this method will be the final found in Discovery. Another common

The registration method is to pass the name of the implementation class through system properties or user-defined properties, for example, give up

Meta-inf / service

The file is changed to execute the java -dmyinterface = myImpl1 discoveryDemo command to run sample programs, the system properties here

It is the name of the interface, the value is the provider of the interface, and the result of the run is exactly the same.

Discovery can also be used to create a SINGLETON instance and call its method, the syntax is as follows:

(MyInterface) discover.newinstance (MyInterface.class)). Mymethod () ;. Note In this example, we don't know which service provider has implemented myMethod, and even we don't have to care at all. Specific situation and run this paragraph

The way the code is registered in the operating environment, and the active service is available in different environments.

Perspective may be different.

2.3 lang

■ Overview: LANG is an extension package of java.lang, adds a number of operation String features, and also supports the amount of enumeration in C.

■ Official resources: home page, binary, source code.

■ When applies: When the method provided by the java.lang package does not meet the needs, you want more features to handle string, value, and

When the System property; also, when you want to use a C style enumeration amount.

■ Sample application: langDemo.java, Mortgage.java, Ontv.java. Commons-lang.jar must be included in ClassPath.

■ Description:

This package provides a number of methods provided for convenient purposes, most of them are static, simplified daily encoding.

The Stringutils class is one of the representatives that make developers can deal with the standard Java.lang.String package to process strings.

Using these methods is simple, usually as long as the appropriate parameters are provided when calling a static method. For example, if you want a word

The first character is changed to uppercase, simply call: StringUtils.capitalise ("name"), the output result called the called is Name. Please browse

StringUtils API documentation understands other static methods, maybe you will find some code that can be used directly. Examples provided herein

The program demonstrates the use of some of these methods.

Another worthless class is randomstringutils, which provides a method of generating a random string to create a random relative

It is too convenient.

The NumberUtils class provides a method of processing numerical data. Many methods are worthwhile, such as looking for maximum, minimum methods, will

String is converted into a numerical method, and so on. NumberRange and Charrange class provide creation and operating numerical ranges, word symbols

Method.

The class in the Builder package provides some special methods, which can be used to construct a class of Tostring, Hashcode, Compareto and Equals.

Method, its basic idea is to construct high quality Tostring, Hashcode, Compareto, and Equals methods, thereby eliminating

The user defines these methods, as long as the method in the Builder package is called. For example, we can use

TostringBuilder to construct the TOSTRING description of the class, as shown in the following example:

Public class mortgage {

PRIVATE FLOAT RATE;

Private int years;

....

Public string toString () {

Return New TostringBuilder (this).

Append ("rate", this.rate).

Append ("Years", this.Year.

Tostring ();

}

}

What is the benefit of using this type of method? Obviously, it makes us possible to handle all data types in a unified manner. all

The usage of the Builder method is similar to the above example.

Java does not have a C style enumeration. To this end, the lang package provides a type of secure ENUM type and fills the blank. The Enum class is abstract. If you want to create an enumeration, you will extend the Enum class. The following example clearly illustrates the use of Enum.

Import org.apache.commons.lang.enum.enum;

Import java.util.map;

Import java.util.list;

Import java.util.iterator;

Public Final Class Ontv Extends Enum {

Public Static Final ONTV IDOL =

NEW ONTV ("IDOL");

Public Static Final ONTV SURVIVOR =

New ONTV ("Survivor");

Public Static Final ONTV SEINFELD =

New ONTV ("Seinfeld");

Private ONTV (String Show) {

Super (show);

}

Public Static ONTV GETENUM (STRING SHOW) {

Return (ONTV) Getenum (onTv.class, Show);

}

Public static map geternal mapp () {

Return getenummap (palv.class);

}

Public static list genumlist () {

Return genumlist (ontv.class);

}

Public static iterator iterator () {

Return Iterator (ONTV.CLASS);

}

}

In the future, we can use the enumerated variables as follows: ONTV.GETENUM ("Idol"). This call from the enumeration data created in front

Type Returns IDOL. This example is relatively simple. In fact, the ENUM class also provides many useful methods, see later provided later.

Complete instance.

2.4 Collectes

■ Overview: Extension the Java Collection framework, add new data structures, iterative mechanisms, and comparison operators.

■ Official resources: home page, binary, source code.

■ When applies: Almost all important Java development projects that need to operate data structures can use the Collections API. Java

Compared to the standard implementation, the Collections API has many advantages.

■ Sample application: CollectionsDemo.java. Require ClassPath contains commons-collections.jar.

■ Description:

It is too difficult to introduce the Collections API to be more difficult to introduce the Collections API within a limited article. However, it will still cover most.

The most important class, I hope to cause your interest and carefully understand the rest of the class. Collectes itself has a lot of money.

The usage of each class is explained.

The BAG interface extension standard Java Collection allows the generator to track all elements in BAG. When you want to track

BAG is very useful when entering and exiting an element of an element. Since the Bag itself is an interface, actually use

Should be real

The class of this interface, such as Hashbag or Treebag - from these classes, it can also be seen that Hashbag implements a

Hashmap's Bag, while Treebag is realized by TreeMap's BAG. Two most important methods in the BAG interface are:

GetCount (Object O),

Used to return the number of occurrences of specific objects in BAG; uniqueSet (), returns all unique elements.

The Buffer interface allows the object in the collection in the predefined order, and the deletion may be LIFO (Last In First Out,

Afterwards, first out), or FIRST IN First Out, advanced first out, and can also be custom order. Let's take a look

How to implement a buffer, delete elements in the natural order.

The BinaryHeap class implements the buffer interface that can be deleted in the natural order. If you want to reverse the order, you must be in turn

False telling Heap to use the inverse order of the natural order.

BinaryHeap Heap = new binaryheap ();

// ...

// Add the elements to this Heap

Heap.add (new integer (-1));

Heap.add (new integer (-10));

Heap.add (new integer (0));

HEAP.ADD (New Integer (-3));

HEAP.ADD (New Integer (5));

// ...

/ / Delete an element

HEAP.Remove ();

Remove of the Heap, according to the natural order, -10 in the elements will be deleted. If we ask for sorting in advance,

The deleted will be 5.

FastArrayList, FasthashMap, and FastTreeMap classes can be operated in two modes, beyond the standards corresponding to them.

COLLECTION. The first mode is "slow mode", the class modification operation (added, deleted element) is synchronized. Relative to this, another mode

Is "fast mode", the access to these classes is defined as a read-only operation, so it is not necessary to synchronize, the speed is faster. In fast mode, structural changes

Complete by the following manner: First cloning the existing class, modify the cloned class, and finally replaced the original class with the cloned class.

FastArrayList, FasthashMap, and FastTreeMap classes are particularly suitable for most operations after initialization.

Multi-threaded environment.

The Iterator package provides a variety of collections and objects to provide an iterator provided by the standard Java Collection package. The sample application of this article is demonstrated.

Arrayiterator, access the contents of Array through iteration. The usage of various iterators in the ITERATORS package basically and standards

Java iterator is the same.

Finally, the Comparators package provides some practical comparison. The so-called comparators are actually a class, which defines how to compare

Two objects belonging to the same class determine their sorting order. For example, in the Buffer class mentioned earlier, we can define your own

The comparison is used to determine the order of the elements with a custom comparison. Rather than adopting the natural sort order of elements. Let's take a look at the specific

It has been achieved.

// ...

// 1 Create a BinaryHeap class, but this time

// Specify NullcomParetor. Nullcomparator

// null and other objects, according to Nullsarehigh tag

/ / Judgment NULL value is larger than other objects: if

// nullsarehigh's value is false, it is considered to be more than

// Other objects are small.

BinaryHeap Heap2 = New BinaryHeap

NEW NULLCOMPARATOR (FALSE);

// ...

// 2 Add some data (including several null values) to Heap: Heap2.Add (NULL);

Heap2.add (New Integer ("6"));

Heap2.Add (New Integer ("- 6"));

HEAP2.ADD (NULL);

// ...

// 3 finally delete an element, the NULL containing the BAG will decrease

//, because NULL is smaller than other objects.

Heap2.remove ();

The introduction of other class Commons components is ended here. If you want to know more details, please see the API document, the best

Take a look at the source code of these packages.

Third, Web class

The Web class components are used to perform tasks related to the web.

3.1 FileUpload

■ Overview: A file that can be used directly upload components.

■ Official Resources: Home. Since this component has not been officially released, there are many BUG released in February this year, so it is recommended

Download the latest version from Nightly Builds.

■ When applies: When you want to add an easy-to-use, high-performance file uploading components in the Java server environment.

■ Example App: FileUploadDemo.jsp, fileuploadDemo.htm, and msg.jsp. Require server-side application directory

Web-INF / LIB has commons-fileupload-1.0-devons-fileupload-1.0-dev.jar.

■ Description:

The FileUpload component solves the common file upload problem. It provides an easy-to-use interface to manage files uploaded to the server.

Can be used in JSP and servlets. FILEUPLOAD component complies with RFC1867, it analyzes input requests, providing a series of supplies to the application

Document to the server. Uploaded files can be retained in memory, or they can be placed in a temporary position (allowing configuring a representation of the file.

Small parameters, if the uploaded file exceeds the size specified by this parameter, write the file into a temporary location). There are also some parameters

Alternative, including acceptable maximum files, location of temporary files, etc.

Here is the steps to use the FileUpload component.

First create an HTML page. Note that all forms to upload files must set the encType property, and the value of the attribute must

Is Multipart / Form-Data, and the requesting method must be POST. The following form is in addition to the two files, there is another ordinary

Text input box:

Method = "post" encType = "multipart / form-data">

Enter your name:


Graphics:

Document:



Value = "Submit Your Files" /> Create a JSP page.

// ...

// 1 Check whether the input request is form data for Multipart.

Boolean ismultipart = fileupload.

IsmultipartContent (Request);

// ...

// 2 Create a handle for the request, parsing the request. carried out

// After analysis, all form items are saved in a list.

DiskfileUpload Upload ();

/ / Phattening request by handle, parsing the resulting item is saved in a list

List items = Upload.Parsequest (Request);

// ...

// 3 The file item inside List is obtained in turn through the loop. To distinguish

// Project and normal form input items, use isformfield ()

// method. According to the requirements of the processing request, we can save uploaded texts

// piece, or one byte one byte handles file content, or play

// Open the input stream.

Iterator itr = items.iterator ();

While (itr.hasnext ()) {

FILEITEM ITEM = (fileItem) ITR.NEXT ();

// Check the current project is a normal form element, or an uploaded file

IF (item.isformfield ()) {

/ / Get the name of the form field

String FieldName = item.getfieldname ();

// If the name of the form is Name ...

IF (FieldName.equals ("Name"))

Request.setattribute ("msg",

"Thank you:" item.getstring ());

} else {

/ / The project is an uploaded file and saves it to disk.

// Note item.getname ()

// will return the full path name of the upload file on the client, which seems to be a bug.

/ / To solve this problem, FullFile.getName () is used here.

FILE FULLFILE = New File (item.getname ());

File SavedFile = New File

(GetServletContext (). getRealPath ("/"),

Fullfile.getname ());

Item.write (SavedFile);

}

}

We can limit the size of upload files by uploading UPLoad.setsizemax. When the size of the uploaded file exceeds allowed

The program will encounter an exception when value. In the above example, the limit value of the file size is -1, indicating that the file allowed to be loaded with analogize.

There are other other forms of use, as indicated earlier, we can open an input stream on the uploaded file,

Or let them reside in memory until space occupies a certain limit value, or on the basis of judging the file type, in String or

The BYTE array obtains its content or deletes the file directly. All this can be convenient as long as the method provided by the FileItem class can be convenient

Decay (DefaultFileItem is an implementation of FileItem).

3.2 httpclient

■ Overview: This API extends the Java.net package, providing the function of analog browser.

■ Official resources: home page, binary, source code.

■ When applies: When you want to construct a web browser; when your application needs an efficient way to communicate with HTTP / HTTPS communication. ■ Example Application: httpclientDemo.java. Requires ClassPath to have commons-httpclient.jar,

Common-logging.jar. Requirements to use JDK 1.4 or higher.

■ Description:

HttpClient extension and enhances the standard java.net package, is a wide range of code libraries, which is extremely rich and can construct

Various distributed applications that use HTTP protocols, or can also be embedded to existing applications, and add the ability to access the HTTP protocol.

In the Commons Stabilization, the HTTPClient documentation seems to be more perfect than other packages, and there are several examples. Below we pass

A simple example to learn how to extract a web page, there is also a similar example in the HTTPClient document, we will expand

An example allows it to support SSL. Note this example requires JDK 1.4 support because it is to be used to use the Java Secure Socket Connection library.

This library is only available in JDK 1.4 and higher.

1 First determine a page that can be downloaded by HTTPS, this example is https://www.paypal.com/. At the same time

% Java_home% / jre / lib / security / java.security file contains the following line code:

Security.Provider.2 = com.sun.net.ssl.internal.ssl.provider.

In addition to these settings, the HTTPS connection has no other particular place - at least for this example. However, if

The root certificate used by the far site is not recognized by Java you use, first must import its certificate.

2 Create an instance of HTTPClient. The HTTPCLIENT class can be seen as the main drive of the application, all of all the work for the network.

It can depend on it. The HttpClient class requires a Connection Manager to manage connections.

HttpConnectionManager allows

We created your own connection manager, or we can also use built-in SimpleHttpConnectionManager or

MultithreadedhttpConnectionManager class. If you do not specify a connection manager when you create httpclient, httpclient

SimplehttpConnectionManager is used by default.

// Create an instance of httpclient

HTTPCLIENT Client = New httpclient ();

3 Create an instance of httpMethod, which is determined which transmission mode is used to communicate with the remote server, HTTP is allowed

Methods include: GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE. These transmission methods are respectively

Independent class implementation, but all of these classes implements HTTPMETHOD interfaces. In this example, we use GetMethod, create a getMethod

Specify the URL we want to get in the parameter when instances.

// Create an instance of HTTPMETHOD

HttpMethod method = New getMethod (URL);

4 Perform an extraction operation defined by HTTPMETHOD. After execution, the ExecuteMethod method will return the status of the remote server report.

Code. Note that ExecuteMethod is httpclient instead of httpmethod. // Perform an extraction operation defined by HTTPMETHOD

Statuscode = Client.executeMethod; Method;

5 Read the response returned by the server. If the previous connection fails, the program will encounter httpexception or ioException.

Where IOException generally means that the network is wrong, and continuing trial is not likely to succeed. The response returned by the server can be in a variety of

Read, for example, as an array of bytes, as an input stream, or as a String. After getting the response returned by the server,

We can set it with your needs.

Byte [] responsebody = method.getResponsebody ();

6 The last thing to do is to releasing the connection.

Method.releaseConnection ();

The above is only very simple to introduce the HTTPCLIENT library, and the actual functionality of httpclient is much more rich than this article.

Not only strong and efficient, please see the API documentation for details.

3.3 Net

■ Overview: A underlying API for operating the Internet underlying protocol.

■ Official resources: home page, binary, source code.

■ When you apply: When you want to access a variety of Internet underlying protocols (Finger, WHOIS, TFTP, Telnet, POP3, FTP, NNTP, and SMTP).

■ Sample application: NetDemo.java. The ClassPath is required to include Commons-Net-1.0.0.jar.

■ Description:

The NET package is a powerful, professional class library, and the class in the class library is originally a commercial product called NetComponents.

The NET package not only supports access to a variety of low-level protocols, but also provides a high-level abstraction. In most cases, NET package

Abstraction of an abstraction that has been met, which makes developers no longer need to directly face the low-level command of the Socket level of various protocols. High use

Layer abstraction does not reduce any function, NET API is well done in this regard, providing adequate features, not in terms of feature

Excessive compromise.

SocketClient is a fundamental class that supports all protocols, which is an abstract class that aggregates public functions required by various protocols. Various

The use of different protocols is actually very similar. First, use the Connect method to establish a connection to the remote server, execute the necessary

Operation, finally terminate the connection to the server. The specific use steps are described below by example.

// ...

// 1 Create a client. We will use NNTPCLIENT

// Download newsgroups from the news server.

Client = new nntpclient ();

// ...

// 2 Use the client created by the previously created to connect to the news server.

// This is a small server that is a small newsgroup.

Client.connect ("aurelia.deine.net");

// ...

// 3 Extract the list of newsgroups. The following command will return one

// NEWSGROUPINFO object array. If the specified service

/

// If an error is encountered, the return value is NULL.

List = client.listnewsgroups ();

// ...

// 4 Finally terminate the connection to the server.

Client.isconnected ())

Client.disconnect ();

It must be explained that the listnewsgroups command may take a long time to return, on the one hand, because the network speed is affected, and it may also be very large due to the list of newsgroups. The newsgroupinfo object contains detailed information about the newsgroup and provides

Some operational newsgroups, such as extracting the total number of articles, finally published articles, permission to publish articles, and so on.

Other clients, such as fingerclient, pop3client, telnetClient, etc., usage is similar.

Conclusion: The introduction to the web-related class and other classes is over. In the next article, we will explore the XML class and packaging classes.

The last article describes the tool class.

I hope the reader is interested in trying the program example provided in this paper. Many times Jakarta Commons give people a feeling of chaos, I hope this article

Make you deepen Jakarta Commons, or at least caught your commons sub-projects and the various practical APIs it offer.

Interest in the library.

Second part XML class and packaging

In the previous article, we divided the components of Jakarta Commons into five categories, and introduced the Web classes and other classes, this article

Introduce the XML class and packaging classes, the next last article will introduce the tool class. Note that Commons itself does not perform this classification, here

The classification 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 packs, one of which is implemented is a common Base64 and HEX encoding mechanism, and the other package is a language.

Speech 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 transmission specifies the base 64 encoding, thus making any binary

Data can be converted into a prinable ASCII character set securely transmitted. For example, suppose you want to transfer a graphic file via Email,

Email client software will use Base64 encoding to convert the binary data of the graphic file to the ASCII code. In Base64 encoding,

Each 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

The original 1.3 times, the end of the file is added "=" symbol. In addition to MIME documentation, Base64 encoding technology is also used for Basic certification mechanisms.

"User: Password" string of HTTP certification headers.

Base64 class is quite simple, the main two static methods are: base64.encodebase64 (byte [] byteArray,

Used to execute Base64 encoding in the contents specified in the byte array; base64.Decodebase64 (byte [] byteArray), for the byte

The content specified in the array performs base64 decoding. In addition, Base64 has a static method

Base64.isArrayBytebase64 (Byte []

BYTEARRAY, is used to detect if the specified byte array can be tested through the base64 (ie, whether the base64 encoded data is included.

As mentioned earlier, the result of Base64 encoding only contains printable ASCII characters). BYTE [] encodeBytes = Base64.encodebase64 ());

String decodedstring = new string (base64.decodebase64);

System.err.Println ("/ '^ /' Is a legitimate base64 character?"

Base64.isArrayBytebase64 (InvalidBytes);

HEX encoding / decoding is the conversion between hexadecimal representations of byte data and equivalent. HEX encoded code, decoding process

Similar to Base64, will not be described here.

1.2 Modeler

■ Overview: According to the definition of JMX (Java Management Extensions), support for Model MBean (Managed Bean)

Configuration and instantiation.

■ 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. Claim

Classpath contains commons-modeler-1.0.jar, commons-logging.jar,

Commons-digester.jar,

Commons-collections.jar, Commons-beanutils.jar, and Sun's JMX reference implementation 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 at the price.

The programmer needs to set a large amount of meta information to tell JMX how to create model mbean, which includes the properties, operations, and other components.

information. The purpose of Modeler is to reduce the workload of programmers to implement Model MBean, which provides a set of functions for processing metadata information.

It has brought convenience. 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 MBean, which is actually equivalent to one.

Create a factory of such beans.

Below we first create this XML file for a Managed Bean. Demomanagedbean has one

Name property, readable and written.

"- // Apache Software Foundation

// DTD MODEL MBeans Configuration File

"http://jakarta.apache.org/commons/dtds/mbeans-descriptors.dtd">" - JMX MBean Description ->

TYPE = "Managedbean">

TYPE = "java.lang.string" />

It can be seen that this XML file provides many ManageDbean information, including its properties, constructor, and it.

Operation (but this example is not displayed), this is the so-called metadata information. If you plan to extend the standard MBean with Modeler

(Known as BaseModelmbean), you can specify the class name of Model MBean in the form of an attribute in the MBean element:. in front of

In the example, the standard Model MBean simply passed 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 the grid through a static method.

Formulated registration information:

// Create a registry

Registry 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. This way, any

The 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.getserver ();

Managedbean management = registry.FindManagedbean ("managedbean");

Try {

Modelmbean modelmbean = management.creatembean (mbean);

String domain = mserver.getdefaultdom ();

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.getmbeadescriptor ());

System.err.println ("==== Test ====");

System.err.Println ("Name of the original value:"

Mserver.getattribute (name, "name"));

MServer.setttribute (Name, New Attribute ("Name", "Vikram");

System.err.Println ("Name of Name:"

Mserver.getattribute (name, "name"));

} catch (exception e) {

System.err.Println (e);

System.exit (0);

}

Although this example is relatively simple, it still clearly shows the convenience of using Modeler, may wish to use it without using Modeler

In the case of creating a similar Model MBean comparison. Describe ModelMbeanInfo is not only flexible, but

And it is also easy to expand, more improved than manually prepared this type of information.

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. Requires the classpath must be included

Commons-betwixt-1.0-alpha-1.jar, commons-logging.jar, commons-beanutils.jar,

Commons-Collections.jar, and Commons-Digester.jar.

■ Description:

If you have used Castor to bind data, you will definitely enjoy the flexibility of BetWixt. CASTOR is suitable in a predefined mode

(SCHEMA) is based on the conversion between beans and XML; but if you only want to perform data between data and XML, 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 a beanRead's instance, set its properties, then use Digester

Perform a conversion.

Convert BEAN to XML:

// convert the bean to XML with BETWixT must have instances of BeanWriter.

// Due to the requirements of BeanWriter, there is a writer object,

// So we start from creating a StringWriter

StringWriter OutputWriter = new stringwriter ();

// Note that the output is not a good format, so you need to start position.

// Write the following:

OutputWriter.write ("

// Create a beanwriter

BeanWriter Writer = New BeanWriter; OutputWriter;

/ / We can set the various properties of the write.

// The first line below prohibits writing ID,

// Second line allows formatting output

Writer.SetWriteIDS (FALSE);

Writer.enablePrettyPrint ();

// Create a bean and output it

Mortgage Mortgage = New Mortgage (6.5F, 25);

// Write the output result to the output device

Try {

Writer.write ("Mortgage", Mortgage;

System.err.println (OutputWriter.toString ());

} catch (exception e) {

System.err.Println (e);

}

Convert XML to bean:

// use BetWixt to read XML data and create this

// bean must use the BeanReader class. Note the Beanreader class extension

The Digester class of the // Digester package.

Beanreader Reader = new beanreader ();

// Registration class

Try {

Reader.RegisterBeanclass (Mortgage.Class);

/ / And parse it ...

Mortgage MortgageConverted =

(Mortgage) Reader.Parse (New File ("Mortgage.xml");

/ / Check if the converted MortGage contains the value in the file

System.err.println ("Rate:" MortgageConvertED.GETRATE ()

", Years:" MortGageConverted.getyears ());

} catch (exception EE) {

Ee.PrintStackTrace ();

}

Note that when you register with the BeanReader, if the name of the top element is different, you must register with another method and

Specify an accurate path, such as Reader.RegisterBeanclass ("ToplevelelementName", Mortgage.Class). 2.2 Digester

■ Overview: Provides a friendly, event-driven advanced XML document processing API.

■ Official resources: home page, binary, source code.

■ When applies: When you want to process XML documents, and hope to be able to trigger a set of rules that triggered in a specific mode in the XML document

To perform some operations.

■ Sample application: DigesterDemo.java, Employe.java, Company.java, Rules.xml, and Company.xml.

Requires ClassPath must include 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 opened for reading the struts profile.

When it was sent, it was then moved to the CommONS package.

Digester is a powerful mode matching tool that allows developers to process XML at a higher level than SAX or DOM API.

Documentation, a set of rules can be triggered when a specific mode (or cannot be found). Basic ideas using Digester are: first

Built an instance of Digester, then use it to register a series of modes and rules, and finally pass the XML document to it. Since then, Digester

The XML document will be analyzed, and the rules are triggered according to the registration order. If an element in the XML document matches one or more rules, all

The 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 pass through expansion

Exhibition Rule class defines its own rules.

When specified mode, the element must be given by absolute name. For example, the root element is specified directly, and the next layer element passes "/"

No. 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 matching mode, there are four callback methods that are associated with the matching mode, they are called: Begin, End, Body,

And Finish. These methods are called time, as indicated by their name, such as the time to call Begin and End, respectively, encounter an element

When the start mark and end tag, the body is called when the text is encountered within the match mode. Finish is all matching mode.

After the processing work is over, it is called.

Finally, the mode can be specified in an external rule XML document (using digester-rules.dtd), or within the code

Specifies that the first approach is used below because this method is more common.

Create two XML documents before using Digester. The first is data or configuration file, that is, we are ready to apply

The file is filed. Here is an example (Company.xml)

My company

China Zhejiang

Sun Wukong

10000

Pig Eight Rings

10001

The second file is the rule file rules.xml. Rules.xml tells Digester to find what to find in Company.xml, find

After the operation:

Paramcount = "0" />

MethodName = "setdress" paramcount = "0" />

Paramcount = "0" />

"setEmployeeno" paramcount = "0" />

What meanings do this file? First rules,

ClassName = "Company" /> tells Digester If you encounter mode companies, you must follow Object-Create-Rule,

That is to create an instance of a class! So what kind of instance is it to create? ClassName = "Company" attribute specifies a class

The name. Therefore, when analyzing Company.xml, when you encounter a top company element, wait until the Object-Create-Rule rule is executed, we have an instance of a COMPANY class created by Digester.

Now I have to understand that called-method-rule rules should be less difficult. The function of call-method-rule is encountered.

A method is called when COMPANY / NAME or COMPANY / Address mode (the name of the method is specified by the methodname property).

The last pattern match is worth noting that it is nested in the matching mode. The way two setting rules and patterns are

Digester accepts, we can choose anything according to your needs. In this example, the rules defined in the pattern are encountered

Create an object of an Employee class when COMPANY / EMPLOYEE mode, set its properties, and finally use set-next-rule to take this employee

Add to the top of Company.

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 this article

DiGesterDemo.java provided later.

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. There must be in classpath.

Commons-jelly-1.0-dev.jar, Dom4j.jar, Commons-Logging.jar, Commons-Beanutils.jar and

Commons-collections.jar.

■ Description:

To make it clear that Jelly is what role is it is very difficult. Jelly attempts to provide a universal

XML script engine, this script engine is a developer's element mapped by developers through custom action and tagging, an element in the XML documentation to

JavaBean, and the properties of the XML element are mapped to the properties of the JavaBean. In a sense, Jelly is a combination of betwixt

And Digester tools, but Jelly is more powerful and 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.

The parsed XML document element is bound to jelly tag dynamic processing. The second component is Jelly tag, it is an implementation JLLY

The javabean of the TAG interface, all Jelly tags can implement DOTAG methods, this dotag method is when the script engine encounters

The method of the specific element in the XML document is performed. Jelly is a dynamic script processing power through this mechanism, from a certain meaning

Look, it is a bit similar to the working mechanism of Digester.

Jelly has many predefined tags, some of which provide core Jelly support, other tags are used to provide resolution, loop,

Conditions of support for execution code. In addition, Jelly also provides a wide range of support for Ant tasks. To use Jelly in the Java application, first create an instance 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. JellyContext's output 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 method mentioned above (as shown in the example below), or provide an execution

Row method, such as invoke () or run ():

Public void dotag (xmloutput output) throws exception {

/ / Add to the action to be executed here,

// For example, set attributes, access file systems, etc. ...

THIS.INTPROP = 3;

}

The following is an example of an XML file for defining Jelly scripts:

XMLns: Tr = "TrivialTag">

Hello World

This example uses Jelly: Define and Jelly: Core tags, and a TRIVIALTAG tag. When you encounter TriVial tags

When an example, Jelly creates an instance of the corresponding JavaBean, execute the dotag method (or can be a RUN or INVOKE.

Calling method).

Jelly has many other features that can be run directly from the command line or Ant script, or can embed the code of the application.

For details, please see the Jelly documentation.

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. Require ClassPath must contain

Commons-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 objects, such as JavaBean.

Collection, Array, and Map, etc.

JXPathContext is the core class in JXPath, which uses a factory method to locate and create an instance of a context. due to

With this mechanism, it is necessary when the developer can insert a new JXPath implementation. 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.err.Println ("Author / AuthorId");

Context.SetValue ("Author / AuthorID", "1001");

Using JXPath can also find other types of objects, but the way to create a context object is the same, it is the static

Methods A new context, which is incoming to the object you want to query.

Conclusion: The introduction of the package and XML classes is over here. In the next article, we will understand the tools.

Class package. In this series of articles, we divide the components contained in the Commons project into five categories, introduced the Web class and other

class. The second article Theory and XML class and packaging classes. This is the last one to explore the components of the tool class. Note that Commons itself does not do this

Classification, classification here is purely to illustrate and organize convenience.

Part III, tool class

The tool class contains several components of BeanUtils, Logging, DBCP, Pool, and Validator.

First, beanutils

■ Overview: Tools for dynamic operation JavaBeans are provided.

■ Official resources: home page, binary, source code.

■ When applies: When you need to dynamically access Javabean, but for the compiled Accessor and

Modifier does not know anything. JavaBean, dynamically visited, must follow JavaBeans

Specification Defined Name Design Specification.

■ Sample application: beanutilsdemo.java, applayer1bean.java,

Applayer2bean.java, Subbean.java. It is required to contain commons-beanutils.jar in ClassPath.

Commons-logging.jar and Commons-Collects.jar.

■ Description:

In a dynamic Java application design environment, we do not necessarily understand the various sets, GET methods of JavaBean. Even

I know the name of these methods, and write the setXXX or getxxx method for each attribute of Bean. It is also a very troublesome thing. test

Considering this situation: Several almost identical beans are passed from a layer of the application to another, you will call every property

Bean1.setxxx (bean2.getxxx ())? Although you can do this, it is not necessarily to do, because you can let BeanUtils

Complete these cumbersome operations for you! Beanutils can help developers dynamically create, modify, and copy JavaBeans.

Beanutils can operate JavaBean that meets the following conditions:

(1) JavaBean must provide a constructor without parameters.

(2) JavaBean's properties must be able to access and modify through Getxxx and Setxxx methods. For the Boolean property, ISXXX is also allowed

And setxxx. JavaBean's properties can be read-only or only written, that is, allow only SET or GET methods for properties. (3) If there is no traditional naming method (ie, using get and set), you can name other ways to name JavaBean, and Modifier.

Then you must declare this by the BeanInfo class associated with JavaBean.

Let's take a simple example.

To get and set the simple properties of JavaBeans, use PropertyUtils.

GetSimpleProperty (Object Bean, String Name) and PropertyUtils.

SetsImpleProperty (Object Bean, String Name, Object Value) method. As shown in the example below,

Applayer1bean.java and Applayer2bean.java define two tests of JavaBean.

PropertyUtils.SetSimpleProperty (App1bean, "INTPROP1", New Integer (10));

System.err.Println ("App1Layerbean, Stringprop1:"

PropertyUtils.getsimpleProperty (App1bean, "StringProp1"));

Since we can call the bean method (App1Bean.getstringProp1 () or

App1bean.setintprop1 (10)) to get the properties of the bean, why do you have to use setsimpleproperty?

What about the GetSimpleProperty method? This is because we don't necessarily know the name of the JavaBean property, so it is not necessarily

Know which methods to call can get / set the corresponding properties. The names of these attributes may come from other processes or external applications.

Variables. Therefore, once you figure out the name of JavaBean's properties and save it to a variable, you can pass the variable to

PropertyUtils, no need to rely on other developers to pre-know the correct method name.

So, if the attribute of JavaBean is not a simple data type, what should I do? For example, JavaBean's properties may be one

Collection or a MAP. In this case, we have to use PropertyUtils.GetIndexedProperty or

PropertyUtils.getmappedProperty. For collection class attribute values, we must specify an index value, specify to be extracted or set

The value in the collection; for the MAP class properties, we must specify a key to indicate which value to extract. Here are two examples:

PropertyUtils.setIndexedProperty

App1bean, "ListProp1 [1]", "New Strings 1");

System.err.println ("App1Layerbean, ListProp1 [1]:"

PropertyUtils.GetIndexedProperty (app1bean,

"ListProp1 [1]"))));

Note that for the indexed properties, the index value is passed through square brackets. For example, in the above example, we put JavaBean

(App1bean) The value of the index is set to 1 "set" new string 1 ", and the back line of code is extracted from the location of the index 1.

A value. Another way can also achieve the same goal, that is, using PropertyUtils.SetIndexedProperty (Object)

Bean, string name, int index, object value), and PropertyUtils.GetIndexedProperty (Object Bean,

String name, int index method, the index value in these two methods is passed as the parameter of the method. There are also classes for MAP class properties.

Similar methods, as long as the key (rather than index) is changed, or set the specified value.

Finally, the property of the bean may be a bean. So how do you get or set those in the form of properties from belonging to the primary bean

What about the attribute bean? Just use PropertyUtils.GetnestedProperty (Object Bean, String Name) and

PropertyUtils.setnestedProperty (Object Bean, String Name, Object Value) is OK. Below

Of an example.

// Access and set the nested properties

PropertyUtils.setnestedProperty (App1bean, "Subbean.StringProp",

"Information from Subbean, setting with setnestedProperty.");

System.err.println

PropertyUtils.getnestedProperty (App1bean, "Subbean.StringProp")))));

As can be seen from the example above, the attribute of the slave bean is accessed through a period symbol.

The above ways described above can be used together, and the nesting depth is not limited. The two methods to be used are

PropertyUtils.getProperty (Object Bean, String Name) and PropertyUtils.SetProperty (Object Bean,

String name, Object value). For example: PropertyUtils.SetProperty (App1bean, "Subbean.listprop [0]",

"Value of attributes") ;.

This example is to access the nested bean objects and the canotic properties.

BeanUTILS is often used to dynamically access request parameters in web applications. In fact, it is BeanUtils triggered the Struts project.

Dynamically convert the request parameters into system javabean inspiration: Use the code to convert the user to a MAP, in which parameters

The name becomes the key in the MAP, the value of the parameters comes from the data entered in the form, then by a simple

The beanutils.populate call converts these values ​​into a system bean.

Finally, BeanUtils provides a step from a step to another bean from a bean to another.

/ / Copy the data of app1bean to App2Bean

Beanutils.copyProperties (App2bean, App1bean);

Beanutils also has a practical method that has not been mentioned here. But don't worry, beanutils is more perfect in the documentation in Commons.

One of the components, it is recommended that the reader refers to the Javadoc documentation of the beanutils package to understand the information about the rest of the method.

Second, Logging

■ Overview: A codebook that encapsulates many popular log tools and provides a unified log access interface.

■ Official resources: home page, binary, source code.

■ When applies: When your application requires more than one log tool, or when it is expected to have this requirement. ■ Example Application: LoggingDemo.java, Commons-logging.properties. Requires the classpath must be included

Commons-logging.jar, sometimes log4j.jar needs.

■ Description:

Logging enables us to debug and track the behavior and status of any time at any time. In any larger application,

Logging is an integral part of it, so there are now many third-party logging tools, they exempt developers themselves.

Write the Logging API. In fact, even if JDK has a structured Logging API. Since there are already so many options (log4j,

JDK, Logkit, etc.), usually we can always find the ready-made API that is best suited for your application.

However, there may be an exceptional situation, such as a familiar Logging API that cannot be compatible with the current application, or because of a certain

Reated stipulations, or due to the application of the architecture of the application. The way to logGing components in the Commons project is to record the log.

The function is packaged into a set of standard APIs, but its underlying implementation can be modified and transformed. Developers use this API to perform record logs

The command of the information is determined by the API to pass these commands to the appropriate underlying handle. Therefore, for developers, Logging components

It is neutral in any particular underlying implementation.

If you are familiar with Log4j, you should not have any problems with the logging API using your COMMONS. Even if you are not familiar with Log4j, just know

Using Logging must import two classes, create a log's static instance, the following shows the code of this section:

Import org.apache.commons.logging.log;

Import org.apache.commons.logging.logfactory;

Public class loggingdemo {

Private static log log = logfactory.getlog

LoggingdeMo.class;

// ...

}

It is necessary to explain what happened when you call logfactory.getlog (). Calling this function will start a discovery process, namely

Find out the implementation of the required underlying logging function, the specific discovery process is listed below. Note, regardless of the underlying log tool

It must be a class that implements the log interface, and must be in the classpath. Commons Loggingapi directly

Support for the following underlying logging tools: JDK14Logger, Log4jlogger, LogkitLogger, NOOPLOGGER (directly discard

All log information), there is a SimpleLog.

(1) Commons Logging first looks for a commons-logging.properties file in ClassPath. This property

The file must define the org.apache.commons.logging.log attribute, and its value should be the integrity of any of the above LOG interfaces.

Limited name.

(2) If the above steps fail, Commons' logging then checks the system properties.

Org.apache.commons.logging.log.

(3) If you can't find the org.apache.commons.logging.log system properties, Logging then looks for the Log4J class in ClassPath. If found, Logging assumes that the application is log4j. However, at this time, the property of the log4j itself is still passing.

Log4j.properties file is configured correctly.

⑷ If the above lookup can't find the appropriate Logging API, but the application is running on JRE 1.4 or higher, then

Use the JRE 1.4 logging feature by default.

⑸ Finally, if the above operation fails, the application will use the built-in SimpleLog. Simplelog directs all log information directly

Go to System.err.

After obtaining an appropriate underlying logging tool, you can start the log information. As a standard API, Commons

The main benefit of the Logging API is to establish an abstraction layer on the basis of the underlying log mechanism. Convert the call to specific

Implement the relevant logging command.

The sample program provided herein will output a prompt message telling you which underlying log tool is currently using. Please try it without

Run this program under the same environment, for example, run this program without specifying any properties, then use it by default

JDK14Logger; then specify system properties - jorg.apache.commons.logging.log = org.apache.commons.logging.Impl.simpland

Run the program, then the logging tool will be simplelog; finally put the log4j class into the class

ClassPath, you can get the log4jlogger output information as long as the log4j log4j.properties configuration file is set correctly.

Third, pool

■ Overview: Used to manage the code base of the object pool.

■ Official resources: home page, binary, source code.

■ When applies: When you need to manage an object instance pool.

■ Sample application: Poolomo.java and MyObjectFactory.java. Require ClassPath must have commons-pool.jar

And Commons-Collects.jar.

■ Description:

The POOL component defines a set of interfaces for the object pool, and also provides several universal object pool implementations, and

Some help developers create the basic class of the object pool.

For most developers, the object pool should not be a new concept. Maybe many readers have been accessing data

When the library is used, the database connection pool is used, and the concept of the object pool is actually similar. Object pool allows developers to create in buffers

Built a set of objects (creating the operation of the object can be done by the application's configuration file, or can also start the stage of the application

Completed), you can get a response when the application needs to use the object. If the application no longer needs an object,

It still returns the object to the buffer pool, and then extract from the buffer pool when you need to use the object next time.

The pool component allows us to create an object (instance) pool, but do not limit we must use a specific implementation.

The pool component itself provides several implementations, and we can also create your own implementation if necessary.

The Pool component contains three basic classes: ObjectPool, which is a definition and maintenance of the interface interface;

ObjectPoolFactory, responsible for creating an instance of ObjectPool; there is also a poolaableObjectFacotry, it

A set of lifecycle methods are defined for instances used within ObjectPool.

As indicated earlier, the Pool component contains several general implementations, one of which is genericObjectPool, below to see its usage by one instance.

1 Create a pooLableObjectFactory. This factory class definition object is created, dismantled, and verified.

Import org.apache.commons.pool.poolableObjectFactory;

Public Class MyObjectFactory Implements

POOLABLEOBJECTFACTORY {

Private static int counter

/ / Return a new string

Public Object makeObject () {

Return String.Valueof (Counter );

}

Public void destroyObject (Object obj) {}

Public Boolean ValidateObject (Object Obj)

{Return True;}

Public void ActivateObject (Object Obj) {}

Public void passivateObject (Object obj) {}

}

This example creates a sequence number of String objects, ValidateObject, always

Returns true.

2 Create a genericObjectPool, Maxactive, MaxIdle using PoolableObjectFactory

The options are used by default.

GenericObjectPool Pool = New GenericObjectPool

NEW myObjectFactory ());

3 A object from the object pool "Borrow".

System.err.println ("Borrowed:" pool.borrowObject ());

4 Return the object to the object pool.

POOL.ReturnObject ("0");

The status of the object pool can be known from a variety of methods, for example:

/ / How many objects have been activated (already borrowed)?

System.err.println ("The number of objects of the current activity:" pool.getnumactive ());

Poolo.java provided later in this article provides a complete source code.

Four, DBCP

■ Overview: Database connection pool. Based on the POOL component.

■ Official resources: home page, binary, source code.

■ When applies: When you need to access the relational database.

■ Sample application: dbcpdemo.java. There must be commons-dbcp.jar in ClassPath,

Commons-pool.jar and Commons-Collects.jar. Also be able to access the database, configure the appropriate

The database of JDBC drivers. The sample application test is a mysql database connection, the driver is mysql JDBC

Driver. Note that running this program requires the Nightly version of the binary file, and the current formal distribution lacks some essential classes.

Finally, when running this sample program, you should ensure that the system properties have been set for the JDBC driver (-djdbc.drivers = com.mysql.jdbc.driver).

■ Description:

Based on the Pool component, DBCP provides a database connection buffer pool mechanism. Compared to conventional connecting pools,

DBCP uses to be slightly complicated, because its idea provides a universal body in the form of a pseudo-JDBC driver

system. However, we have learned the basic knowledge of the Pool component, and now I understand that DBCP usage should be very simple. // ...

// 1 Create an instance of a GenericObjectPool class.

GenericObjectPool pool = new genericObjectPool (null);

// ...

// 2 Receive genericObjectPool when discussing the pool components in front

// Requirement There is a poolaableObjectFactory to create a need.

// The instance of the Object to buffer, for DBCP,

// This feature is now raised by PoolableConnectionFactory

// For supply, as shown in the following example:

DrivermanagerConnectionFactory CF =

New DriverManagerConnectionFactory (

"JDBC: MySQL: // Host / DB", "UserName", "Password");

PoolableConnectionFactory PCF = New PoolableConnectionFactory

CF, Pool, NULL, "Select * from mysql.db", false, true);

// ...

// 3 Now, we only need to create and register PoolingDriver:

New poolingDriver (). RegisterPool ("MyPool", Pool;

Next, you can get connected from this connection pool. Note Maxactive when creating this connection pool,

The default value of the MaxIdle and other options, if necessary, you can create the GenericObjectPool class in front of step 1

These values ​​are customized in the case. DBCPDemo.java provides a complete instance.

V. Validator

■ Overview: A API that collects common user input verification functions.

■ Official resources: home page, binary, source code.

■ When applies: When JavaBean performs a regular verification operation.

■ Sample application: ValidatorDemo.java, MyValidator.java, MyFORMBEAN.JAVA,

Validation.xml. It is required to have commons-validator.jar in ClassPath,

Commons-beanutils.jar, commons-collections.jar, commons-digester.jar, and

Commons-logging.jar.

■ Description:

If you have developed a web application with Struts, you should have used the Validator package. Validator

The package is greatly simplified by the user input data. However, Validator is not limited to web applications, it is also

It is used in other occasions that use JavaBean.

Validator allows the user input domain to define verification conditions, support error information internationalization, allowing to create custom

Verifier, in addition, the Validator package also provides some predefined verifiers that can be used directly.

Verify rules and verification methods are defined by XML files (you can define one or more XML files, but usually,

Separate them separately). The verification method file defines the validator to be used, specifying each actual implementation verifier

Java classes (do not require these classes to implement certain specific interfaces, nor require these classes to be derived from specific classes, only need to comply with the definitions in the method definition file).

Below we will construct a custom verifier, its function is to check if a String property of the bean is

Contains specific characters ("*").

Import org.apache.commons.validator. *;

Public class myvalidator {

Public Static Boolean ValidateContainSchar (

Object bean, field field) {

// First get the properties of the bean (ie a string value)

String Val = ValidatorUtil.getValueAsstring

Bean, Field.getProperty ());

/ / Returns true or false based on whether or not to contain "*" characters in the attribute.

Return ((Val.IndexOf ('*') == -1)? false: true);

}

}

The ValidatorUtil class provides many practical methods, such as validatorutil.getValueAsstring.

Extract the properties of the bean and return a string. Now we have to declare the MyValidator verifier in the XML file.

ClassName = "MyValidator"

Method = "ValidateContainschar"

Methodparams = "java.lang.object,

Org.apache.commons.validator.field "/>

It can be seen that the XML file details the feature of the verification method, including the input parameters of the method. Below

See the steps to use this verifier.

1 Join the verification rules we want to implement in the XML file above.

Containsstar Test ->

It can be seen that all verification rules are declared within the Formset element. First statement within the Formset element

The form of the certificate is listed in the form and the input domain to verify and its validation conditions. In this example, we hope to verify

MyFormBean's Name property checks if this property is able to verify through ContainStar (i.e., Name attribute)

The value contains "*" characters).

2 Based on the XML file, create a validator instance and initialize.

// Load the verifier XML file

InputStream in = getClass (). GetresourceAsStream

("Validator.xml");

// Create a ValidatorResources

ValidatorResources Resources = New ValidatorResources (); // Initialization Verifier Resources

ValidatorResourcesInitializer.Initialize (resources, in);

// Create Validator

Validator Validator = New Validator (Resources, "MyFormbean");

Validator.AddResource (Validator.Bean_Key, Bean);

3 verify the bean. The result of the verification is a ValidatorResults, which contains attributes of each required verification.

Perform verification results in accordance with their respective verification conditions.

// Perform verification

ValidatorResults Results = validator.validate ();

4 Processing ValidationResults.

// Verify the result Object ValidationResults may also contain the results of verifying other forms,

// We can extract their verification results separately for each property.

ValidatorResult Result = Results.getValidatorResult ("name");

// For each property, we can check the results of each verification condition separately.

//, for example, is the NAME attribute passed the Containsstar verification?

System.err.Println ("Name property contains" * "character test results:"

Result.issalid ("Containsstar");

For an instance of each ValidationResult, we can query whether it passes a specific check.

For example, in the above code, we check the NAME genus with Result.issalid ('containsstart') expression.

Sex ValidatorResult instances, see if it passes Containsstar verification.

For web applications, Validator is a quite useful component that provides a set of predefined verifiers.

Greatly, the user enters legality verification. A predefined verifier can be used (but not limited to) check the input value

Range, data type, length, and email address and geographic check. In addition, we can also define verification

The device and add it to the Validator framework.

Conclusion: The third article (also the last article) Introduction to Jakarta Commons will end here. although

This series of articles only involves the basics of each component, but I hope that they are already enough to start a deep study of the next step.

转载请注明原文地址:https://www.9cbs.com/read-16058.html

New Post(0)