JAKARTA Commons Project Group introduces Jakarta Commons: Class and Components Jakarta Commons are Jakarta subprojects, which creates and maintains many independent software packages, which are generally independent of other frameworks or products, which collect a large number of small, practical components. 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. 1. 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. Note: Jakarta Commons and Apache Commons are different, the latter is a top project of Apache Software Foundation, the former is Jakarta
A sub-project of the project is also 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, can be described as decentralized. 2.1 CLI ■ Overview: CLI is Command Line Interface, which is the "command line interface", which provides a unified interface for Java program access and parsing command line parameters. ■ Official resources: home page, binary, source code ■ When you apply: When you need to access 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 an options: options options = new options (); Options.addoption ("t", false, "current time"); // ... // 2 Create a parser, analyze input: CommandLineParser Parser = New BasicParser (); CommandLine CMD; Try {cmd = parser.parse (options, args);} catch (optionption pE) {usage (options); Return;} // ... // 3 Finally, according to user 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, which is to locate and instantiate classes and other resources in a unified manner. ■ 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. 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. Please read the reader to see the interface in the sample program in this article. MYINTERFACE.JAVA
And two implementation class MyImpl1.java, MyIMple2.java, learn about the details of the following examples. 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 loader. ClassLoaders Loaders = ClassLoaders.GetApploaders (MyInterface.class, getClass (), false); // ... // 2 Use discoverclass instance to find the implementation class. DiscoverClass discover = new DiscoverClass (loaders); // ... // ③ lookup implements the specified interface class: 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 operations of String, and also supports C-style enumerations.
. ■ Official resources: home page, 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 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 ();}} Is there any benefit to use 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.itrator; public final class office 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 office (String Show) {super (show);} public static ONTV Getenum (OnTv.class, show);} public static map genummap () {return genummap (ontv.class);} public static list getenumlist () {return genumlist (ontv.class); } public static iterator itrator () {return iterator;} After 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 Collections ■ Overview: Extension 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. Compared to Java standard implementation, Collections API has many advantages. ■ Sample application: CollectionsDemo.java. Require ClassPath contains commons-collections.jar. ■ Description: To introduce the Collections API in detail within a limited article level, it 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 (); // ... // adds the element to the HeapHeap.Add (new integer (-1)); Heap.Add (New Integer (10)); Heap.Add (0) HEAP.ADD (New Integer (-3)); Heap.Add (New Integer (5)); // ... // Delete an element Heap.Remove (); call the HEAP Remove, according to the natural order, element The -10 in the collection 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 this way, another model
The formula is "fast mode", which is a read-only operation for these types of access, 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 the parameter / / specifies NullcomParetor. NullComparator compare // null and other objects, according to NullsareHigh tags // Judgment NULL value is large or small than other objects: If // nullsarehigh is false, it is considered that NULL is smaller than // other objects. 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 more than other objects small. Heap2.remove (); Introduction to other COMMONS components is over here. If you want to know more details, see the API document, it is best to look at the source code of these packages. Third, the components of the Web class web class 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 yet been officially released, there are many BUGs released in February this year, so it is recommended to 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 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 the uploading two files, there is another normal text input box: