JAKARTA COMMONS: Use class and components

xiaoxiao2021-03-06  37

Jakarta Commons is a child project of Jakarta. It creates and maintains many independent packages, which are generally independent of other frameworks or products, where a large number of small, practical components are collected, and most of the server-side programming.

The package of Commons is divided into two parts: Sandbox, the Commons Code Base. Sandbox is a test platform for verifying various ideas, planning. The components introduced herein belong to the Commons Code Base. The article will show the functions of each component, applicable, and introduce the usage by a simple example.

I. Overview

Reusability is the soul of the Jakarta Commons project. These packages have considered a reusability problem in the design phase. Some of these packages, such as the logging package used to record the logs, which is originally designed for other projects, such as Jakarta Struts projects, and it is very useful for other projects to greatly help other projects. Decide to construct a "public" storage location for these packages, 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 is basically independent, not only independent of other projects, but also independent of most of the other packages inside Commons. Although there are some exceptions, such as the BetwixT package is used to use the XML API, but most of them use the most basic API, the main purpose is to be able to easily call through simple interfaces.

However, due to the brilliance, 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.

Description: Jakarta Commons and

Apache Commons is different, the latter is a top project of Apache Software Foundation, the former is a sub-project for the Jakarta project, and the protagonist to be discussed herein. Behind this article refers to 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 a 5 class, 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, and the boundaries of these categories sometimes have a certain overlap.

This article first introduces the components of the Web related category and other classes. The next article will involve XML-related, packaging these two categories, and the last article specializes in the tool class.

Second, other classes

CLI, Discovery, Lang and Collections are incorporated into other classes, because they are all desirable for a clear, practical small goal.

2.1 CLI

■ Overview: CLI, Command Line Interface, is also "command line interface", which provides a unified interface for Java program access and parsing command line parameters.

■ Official resources:

Homepage,

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 unify only a single interface, unify the input parameters (whether it is forced parameter, value or string, etc.), according to a range of rule analysis parameters, determine the path to the path to use, then it is 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, add each Option object to the Options object, and then use the method provided by the CLI to resolve the user's input parameters. Option objects may require a user to enter a parameter, such as the file name must be provided on the command line. If a parameter is a must, it is necessary to explicitly specify when creating an Option object.

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, but basic use ideas are still consistent. See the sample program provided in this article.

2.2 Discovery

■ Overview: Discovery Components is an implementation of Discovery Pattern, and its goal is to locate and instantiate classes and other resources in a unified manner.

■ Official resources:

Homepage,

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. In the case of the service, the Discovery component is especially useful when we want to find all known providers of a service.

Consider this situation: We have written an interface for a particularly complex task. All the implementations of the interface are done in different ways to complete this complex task, and end users can choose 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 a specific implementation. 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, such as images or other files. 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. Readers Refer to the interface MyInterface.java and two implementation class MyImpl1.java, MyIMple2.java, in this article. When using Discovery, you should put it in the meta-inf / service directory, pay attention to the full qualified name of the file corresponding to the interface, if the interface belongs to a package, the name of the file is also It must be changed 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 that if your implementation is in the package, the name registered here should also be modified accordingly. If the file is not placed in the correct location, or the implementation class of the specified name cannot be found or instantiated, the program will Throw discoverexception, indicating that the implementation of the eligible condition is not found. Below is an example of the content of MyInterface file: 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, according to the class finding mechanism within Discovery, the class registered according to this method will be the Class finally found by Discovery. Another commonly used registration method is to pass the name of the implementation class through the system attribute or user-defined attribute, for example, abandon the file in the meta-inf / services directory, change the java -dmyinterface = myImpl1 discoveryDemo command to run the sample program The system attribute here 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 situations are related to operating this code and what service provider has been registered in the operating environment, running in different environments, the actual service provider may vary. 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:

Homepage,

Binary,

Source code.

■ When applies: When the method provided by the java.lang package is not met, you want more features to handle String, value, and system properties; and if you want to use C style enumerations.

■ 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 to change a word's first character to uppercase, simply call: StringUtils.capitalise ("name"), the output result called the call is Name. Please browse the StringUtils API document to learn other static methods, maybe you will find some code that can be used directly. The sample program provided herein 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 password is too convenient.

The NumberUtils class provides methods for processing numerical data. Many methods are worthwhile, such as finding the maximum, minimum method, converts String to a numerical method, and so on. The NumberRange and the Charrange class provide a way to create and operate numerical ranges, and character ranges.

The class in the Builder package provides some special methods, which can be used to construct the Tostring, Hashcode, Compareto and Equals methods. Its basic ideas is to construct high quality Tostring, Hashcode, Compareto, and Equals methods, The user defines these methods, as long as the method in the Builder package is called. For example, we can use toStringBuilder to construct a class of TSTRING description, 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 BUILDER methods are 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 returns IDOL from the enumeration data type created in front. This example is relatively simple. In fact, the ENUM class also provides a number of useful methods, see the complete instances provided later in this article.

2.4 Collectes

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

■ Official resources:

Homepage,

Binary,

Source code.

■ When applies: Almost all important Java development projects that need to operate data structures can use the Collections API. Compared to Java standard implementation, 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 in a limited article space, but here will still cover most of the most important classes, hoping to cause your interest, and carefully understand the rest of the class. The documentation of Collectes itself also provides many data and explains usage of each class.

The BAG interface extension standard Java Collection allows the generator to track all elements in BAG. BAG is very useful when you want to track the total number of elements of a collection. Since the BAG itself is an interface, the actual use should be a class that implements the interface, such as Hashbag or Treebag - from these classes, it can also be seen that Hashbag implements a HashMap's BAG, and Treebag is implemented. Treemap Bag. The two most important ways in the BAG interface are: getCount (Object O), used to return the number of times of specific objects in BAG; uniqueSet (), returns all unique elements. The buffer interface allows the object in the collection in the predefined order, the delete order can be LIFO (Last In First Out, the first out), or FIFO (First In First Out, advanced first out), and it can also be customized. order. Let's take a look at how to implement a buffer, delete the element according to 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 pass a FALSE to tell HEAP to adopt a 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 reverse sequence, it will be 5.

FastArrayList, FasthashMap, and FastTreeMap classes can be operated in two modes, beyond the standard Collection corresponding to them. The first mode is "slow mode", the class modification operation (added, deleted element) is synchronized. On the other hand, another mode is "fast mode", and 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 are completed in the following manner: First cloning the existing class, modify the cloned class, and finally replaced the original class with the cloning class. FastArrayList, FasthashMap, and FastTreeMap classes are particularly suitable for the most operations after initialization. Multi-threaded environments for read-only operations.

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 demonstrates ArrayItemrator, and accesses the contents of Array through iteration. The usage of various iterators in the ITERATORS package is basically the same as the standard Java iterator.

Finally, the Comparators package provides some practical comparison. The so-called comparison is 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 comparison, with a custom comparison to determine the ordering order of the elements, rather than adopting the natural sort order of elements. Let's take a look at the specific implementation.

// ...

// 1 Create a BinaryHeap class, but this time

// Specify NullcomParetor. Nullcomparator

// null and other objects, according to NULLSAREHIGH tags // Judgment NULL value is larger or small 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, see the API document, it is best to look at the source code for 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 page. Since this component has not yet been officially released, there are many BUG released in February this year, so it is recommended from

Nightly Builds Download the latest version.

■ 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 a 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, which can be used in JSP and servlets. FileUpload Components Follow the RFC1867, which analyzes the input request, and provides a series of files uploaded to the server to the application. Uploaded files can be retained in memory, or they can be placed in a temporary location (allowing parameters that represent file size, if the uploaded file exceeds the size specified by this parameter, write a temporary position). There are also some parameters to be configured, including acceptable maximum files, location of temporary files, and more.

Here is the steps to use the FileUpload component.

First create an HTML page. Note that all forms to upload files must set an encType property, and the value of the attribute must be Multipart / Form-Data, and the requesting method must be POST. The following form except for both files, there is another normal text input box:

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

Enter your name:


Graphics:

File:


Value = "Submit your file" />

Next, 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 file exceeds the allowable value, the program will encounter an exception. 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 a input stream on the uploaded file, or let them reside in memory until the space occupies a certain limit value, or in judging files On the basis of the type, the content is obtained in the form of a string or byte array, or the file is deleted directly. All this can be easily achieved using the method provided by the FileItem class (DefaultFileItem is an implementation of FileItem). 3.2 HTTPCLIENT ■ Overview: This API extends the Java.net package, providing the function of the 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. It is required to have commons-httpclient.jar in ClassPath, 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 a variety of distributed applications that use HTTP protocols, or embedded to existing applications. Increase 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 understand how to extract a web page through a simple example, there is also a similar example in the HTTPClient document, and we will expand that example to support SSL. Note This example requires JDK 1.4 support because it uses the Java Secure Socket Connection library, and 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/. Make sure that the% 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 remote website is not recognized by the Java you use, you must first import its certificate. 2 Create an instance of HTTPClient. The HTTPCLIENT class can be seen as the main drive of the application, and all the functions of the network relies on it. The HttpClient class requires a Connection Manager to manage connections. HTTPConnectionManager allows us to create its 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 uses SimplehttpConnectionManager by default.

// Create an instance of httpclient

HTTPCLIENT Client = New httpclient ();

3 Create an instance of httpMethod, which is determined which transmission method for communication with the remote server, HTTP allows the transmission methods including: GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE. These transmission methods are implemented as an independent class, but all of these classes implements HTTPMETHOD interfaces. In this example, we use getMethod to specify the URL we want GET in the parameter when you create a getMethod instance. // Create an instance of HTTPMETHOD

HttpMethod method = New getMethod (URL);

4 Perform an extraction operation defined by HTTPMETHOD. After the execution is completed, the ExecuteMethod method will return the status code of the remote server report. 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 operation fails, the program will encounter HTTPEXCEPTION or IOException, where IOException generally means that the network is wrong, and continues to try is not likely to succeed. The response returned by the server can be read according to a variety of ways, such as an array, as an input stream, or as a string. After getting the response returned by the server, we can dispose of it according to 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 robust and efficient, please refer to the API documentation.

3.3 Net

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

■ Official resources:

Homepage,

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, the abstraction provided by the NET package can meet the general needs, which makes developers no longer need to directly face the low-level commands of the Socket level of the various protocols. Using high-level abstraction does not reduce any feature, NET API is well done in this regard, providing adequate features, not too much compromise in feature.

SocketClient is a fundamental class that supports all protocols, which is an abstract class that aggregates public functions required by various protocols. The use of various agreements is actually very similar. First, use the Connect method to establish a connection to the remote server, perform the necessary operation, and finally terminate the connection with 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 a command of the operation newsgroup, such as extracting the total number of articles, the last published article, the permission to publish the article.

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 classes and packaging classes, and 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 confusion, I hope this article has deepened you to learn from Jakarta Commons, or at least in your interest in the Commons sub-project and it provides the various practical APIs and libraries.

Please download this article from here:

JAKARTACMMONS1_CODE.ZIP

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

New Post(0)