Jakarta Commons is a subpredal of Jakarta with aims to create and maintain packages that are independent of other frameworks and products. These packages are some collection of a small range of valid components, usually suitable for server-side programming. The Commons project is divided into two parts: Sandbox and Commons libraries. SANDBOX is used to test. This article pays attention to the library components, including when used, where, and use examples how to use it. Brief introduction The Jakarta Commons project originated from reuse, where the package must be ensured. There are some packages from other items, such as a general log package, is part of Jakarta Struts. When the developer finds that a package is useful for other projects, it can shorten the development cycle, and they decide to make these packages into generic components. This is the Jakarta Commons project. To truly reuse, each package must be independent of other larger frameworks and projects. Therefore, each package in the Commons project is largely independent, not only relative to other items, but also even for other packages. The situation in violation of this principle is present, but most of the case is the use of mature APIs. For example, the BetWiXT package is based on the XML APIS. Although this project is intended to establish a package that does not rely on other components. Most packages are very simple to lack the necessary documents, maintenance and help. Some packages even have only wrong connections and very little documents. In most cases, you can only explore how to use them, why use them. I hope this article is helpful to you. Note: Jakarta Commons is different from apache commit. The latter is the top programs of Apache Software Foundation (ASF). The former is a subproject of another top project Jakarta in ASF, which is an object introduced in this article. Moreover, Jakarta Commons only uses Java. In this article, Commons refers to Jakarta Commons. The components are convenient for organization, and I will divide 18 (including EL, LATKA and JEXL) Commons components into five categories. As shown in the following table: Component Category Components Web Related Fileupload, HttpClient, and Net XML Related Betwixt, Digester, Jelly and JxPath Tools BeanUtils, Logging, DBCP, Pool and Validator Package Codec and Modeler Appions CLI, Discovery, Lang and Collectes should pay attention to this Classification is only in this paper, and it does not exist in the Commons project. Classification is overlapping in some extent. This article will introduce the Web related and applet, the next article, including XML related and packaging classes, tool classes in the last article. Small procedures class CLI, Discovery, Lang, and Collectes are written because they are written for a small and practical purpose. 1.Cli Summary: CLI (Command Line Interface) Provides a universal interface for your Java program to read and parse command line parameters. At that result: Home, Program, Source Code. When to use: When you need a unified manipulation command line parameter. Example: Clidemo.java, you need to add Commons-CLI-1.0.jarCommons to ClassPath. Description: The processing section of the application input parameters must be rewritten when a Java program is not completed.
If there is a unique interface to define, resolve and read the input parameters, do you decide whether the program's mode is not very good? CLI is the answer. For the CLI, each parameter to be processed in the command line is an Option. Create an OPTIONS object, add the Option object, and then resolve the user's input parameters with the function provided by the CLI. A Option may also need a user to enter a value, such as a file name. At this time, Option must be created at the specified office. The CLI use steps are as follows: 1. Create options: options options = new options (); options.addoption ("t", false, "current time"); 2. Create a parser resolution user input: CommandLineParser Parser = New BasicParser () CommandLine cmd; try {cmd = parser.parse (options, args);} catch (optionption pE) {usage (options); Return;} 3. Perform appropriate operations according to user input: IF (cmd.hasoption ("n" )) {System.err.println ("Nice to meet you:" cmd.getoptionValue ('n'));} The above basics is the entire process of using the CLI. Of course, the CLI provides other advanced options to control various formats and parsers, but the basic operations are the same. A complete example can see Demo. 2.Discovery Summary: DISCOVERY mode implementation, providing generic methods for positioning and instantiation or other resources. At that result: Home, Program, Source Code. This package is in the pre-release state. When used: When you need to quickly find the implementation of the Java interface in your code. Example: DiscoveryDemo.java, MyInterface.java, MyImpl1.java, MyImpl2.java, MyInterface. Need to add Commons-Discovery.jar and Commons-Logging.jar to ClassPath. Description: The purpose of discovery is to use the best algorithm to get all the implementations of the interface. This will be particularly useful when users want to find all providers who provide a service. Suppose you write an interface for a certain problem. All implementations of this interface will solve this problem in a unique encoding method. The real user will have a variety of options when actually solving this problem. How can he know that the implementation of the interface is feasible in his system? This is the SERVICE and Service Provider structure. Service is the interface you defined. Service Providers offers service implementation. Users need to select Service Providers. The Discovery component helps in a variety of ways. Note that Discovery is not only used to discover implementation classes, but also find resources, such as images or other files. It follows Sun's Service Provider Architecture specification. Similarly, Discovery is also very simple.
In the example program, MyImpl1 and MyImpl2 are the implementation of the MyInterface interface. MyInterface file must be in the meta-inf / service directory. Note that this file must correspond to the full path to the interface. If the interface is in the package, the file name should also be changed accordingly. 1. Get ClassLoaders: ClassLoaders Loaders = ClassLoaders.GetApploaders (MyInterface.class, getClass (), FALSE; 2. Create discoverclass to find implementation classes: discoverclass discover = new discoverclass (loadingers); 3. Find Implementation Class: Class Implclass = Discover.Find (MyInterface.class); System.err.Println ("Implementing Provider:" Implclass.getName ()); Run the above code (discoveryDemo.java) will get registered in MyInterface files Class, as shown below. Remind again that if the implementation is included in a package structure, the file name must be modified. If this file is not in the specified directory, or the class cannot instantiate or locate, the discoveryException will throw the discoveryException, indicating that the implementation of MyInterface cannot be found. MyImpl2 # Implementation 2 Of course, this is not the only way to register implementation, otherwise Discovery uses! In fact, this is the last step of the internal mechanism of discovery discovery. Other methods include defining the name of the implementation class in the system properties or user properties. For example, delete files in meta-inf / services directory, run DEMO as follows, and the result is the same. Here the system attribute is an interface name, and the value is an interface implementation provider. Java -dmyinterface = MyImpl1 DiscoveryDemo Discovery can also be used to create an instance of the service provider and call their functions. As follows: (MyInterface) discover.newinstance (MyInterface.class)). MyMethod (); note that we don't know that service provider implements myMethod function, we don't care. The implementation of this function depends on what manages the above code and the registered service provider. 3.LANG Summary: The extension of java.lang package increases many of the String operations. Provide an enumeration of class C language. At that result: Home, Program, Source Code. What is introduced here is LANG1.0, and the LANG2.0 has been released when translated this article. When used: When the default implementation provided by Java.lang is bored, it is better to control the String operation, numerical functions, and system properties, and if you want to use a C language style. Example: langdemo.java, Mortgage.java, Ontv.java. Need to add Commons-Lang.jar to the ClassPath.
Description: Many tool functions provided in this package can simplify the work of Java programmers. These functions can reduce programming of daily functions. Especially the Stringutils class, it provides the function of stronger operation strings than standard java.lang.string packages. They are very simple, as long as the correct parameter calls a static function. For example, you have to turn a sentence to the beginning of your uppercase: StringUtils.capitalise ("name"); the output of this function is like "Name" we need. Browse the other static functions of the StringUtils API, you may find it is useful. Some of the examples are used in the example. Another interesting class is RandomStringUtils. The functions in this class generate a random string, which is useful when generating a random password. Class NumberUtils provides functions for data operations, including maximum minimum functions, and transform strings into numbers. NumberRange and Charrange handle numbers and characters respectively. The class in the Builder package is provided to add TOSTRING, Hashcode, CompareTo, and equals functions to the class. That is, you can add a high quality Tostring, HashCode, CompareTo, and equals functions you can add in the class, as long as the function in the Builder package is available. For example, add a TSTRING method to the class with the TOSTRINGBUILDER function: public class mortgage {private float rate; private int years; .... public string toString () {Return New TostringBuilder (this) .append ("rat", this.rate) .append ("years", this.year). TOSTRING ();}} Why is this function? Because it uses a generic method to handle all data types, proper return NULL, while controlling the details of the object and aggregation. This is valid for all functions in all Builders, and the syntax is similar to the same. As a Java programmer, if you miss the enumeration of C language style, the type of secure ENUM data type in this package will fill this gap. The ENUM class is an abstract class, so to create your own enumeration, you must extend this class.
As shown in the following example: 1. Definition and extended enumeration class: import org.Apache.commons.lang.enum.enum; import java.util.map; import java.util.list; import java.util.itrator; public final class office, {public static Final ONTV IDOL = New ONTV ("idol"); public static final office odate; public static final office office {"SEINFELD"); private office (SHOW) {super );} public static OnTV getEnum (String show) {return (OnTV) getEnum (OnTV.class, show);} public static Map getEnumMap () {return getEnumMap (OnTV.class);} public static List getEnumList () {return GetENUMLIST (ONTV.CLASS);} public static iterator itrator () {r ETURN ITV.CLASS;}} 2. You can now use the enumeration in your method: ONTV.GETENUM ("IDOL"); the line code returns the IDOL item from the enumeration data type we created. The Enum class has other useful functions. 4.Collections Summary: Extension to the Java Collection Frame, add new data structure, Iterators, and comparators. At that result: Home, Program, Source Code. Time to use: It is highly recommended to use the Collections API as needed in the Java project that needs to handle the data structure, and you will get a lot of benefits than Java default. Example: CollectsDemo.java. Need to add Commons-Collections.jar to ClassPath. Description: There are many classes in the Collections API, which is difficult to introduce in a section. So I am focused on the most important classes, I hope you can be interested in carefully studying other classes. The document comes with the API has a detailed description of each class. The BAG interface extends Java Collections, adds a count for all members, which is useful when you want to enter the input element.
Because the BAG is an interface, it actually uses its implementation class, such as Hashbag or Treebag. As the name suggests, hashbag is an implementation of HashMap-based BAG, while Treebag is treems based on TreeMap. Two important methods in the Bag interface are getCount (Object O) and UniqueSet (). The former returns a number of special elements in the BAG, the latter returns the unique element in the BAG (the translator is understood as: element type, original: The unique elements). The buffer interface allows you to delete an object from the aggregation in a predetermined order, which can be first out, advanced first, or custom order. The following example demonstrates how to delete elements in the order of nature. The BinaryHeap class implements the buffer interface and deletes elements according to nature. If you want to delete the reverse nature, you can be parameters with false: binaryheap heap = new binaryHeap (); 2. Add element: 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)); 3. Call the REMOVE method. According to natural sorting, -10 will be deleted, and the reverse 5 is deleted: Heap.Remove (); FastArrayList, FasthashMap, and FastTreeMap class use two modes to operate the corresponding Collection class. The first is slow mode, which is the default mode after these classes initialized. In slow mode, the structural changes of these classes are synchronous. In fast mode, access to these classes is considered to be read-only, so faster, and no synchronization occurs. To change the structure of the class in fast mode, you should first clone the class, modify it on the clone class, and then override the class. These classes are very useful in most access to read-only multi-threaded environments. The Iterator package provides the Iterator of the aggregation and objects that are not available in many regular Java Collections packages. The arrayiterator of the Iterator array is demonstrated in the example program. These Iterator are the same as ordinary Java Iterators. Finally, some useful comparators are provided in the Comparator package that define the comparison and the order of the two objects that determine the same class. For example, in the buffer mentioned earlier, you can define your own comparator and use it to replace the natural sort decision order. As follows: 1. Use nullcomparator to create binaryheap this time. Nullcomparator determines the size of NULL and other objects based on the value of the flag NullareHigh. If the value is false, NULL is smaller than other objects: binaryheap heap2 = new binaryheap (new nullcomparator (false)); 2. Add objects, including some null heap2.add (null); Heap2.Add (New Integer ("6")); Heap2.Add (New Integer ("- 6")); Heap2.Add (NULL); 3. Finally, the delete operation is performed.
Because NULL is less than other objects, the last thing of BAG is null Heap2.remove (); here, the small program class is over. For more details, please see the API document, or the source code for these packages. The component helps the Java programmer complete the web-related task in the Web Related Class Web Related Class. 1.FileUpload Summary: Home-up Upload Components. At that get: Home. When used: When you need easy to use and efficient documentation upload components in the Java server environment. Example: FileUploadDemo.jsp, fileuploaddemo.htm, msg.jsp. Need to add Commons-fileUpload-1.0-dev.jar to the web-inf / lib directory of the program. Description: FILEUPLOAD solves the common problem of the server-up server, providing an easy-to-use interface uploaded by control files, available in the JSP page and servlet. It conforms to the RFC1867 protocol standard, parsing the input request, and handles the subunit of a series of files uploaded to the server to the application. Uploaded files are saved in the memory or temporary directory (this is determined by a parameter indicating the size of the file, if the uploaded file size exceeds the parameter value, the file will be written to the temporary directory). You can also set additional parameters, such as the maximum size of the received file, and a temporary file directory. FILEUPLOAD is divided into a few steps, and I will use an example of two different files to simultaneously upload two pages. 1. Create an HTML page. Note To ensure that the type of upload file is allowed, the EncTyPE parameter must be Multipart / Form-Data, requesting the parameter Method must be POST. Another point to note is that this page not only has two file controls and a general text control.