Using Jakarta commons Lang to simplify Java (zz)

Source: Internet
Author: User
Tags key string

Summary
As an Enterprise Java developer, we always need to implement various functions, such as parsing XML, using HTTP, verifying input and processing dates. The objective of using the Jakarta Commons project is to create components responsible for processing all such common tasks, saving time and allowing you to focus on core business solutions. In this article, we will briefly introduce the Jakarta Commons project, and then demonstrate how to use the Lang component in Jakarta commons to process and simplify daily Java tasks, such as string operations, date and calendar, comparison data objects, and object sorting. For all examples in this article, we will use the latest Lang version (2.1 ).
Editor's note: the code in this article is based on RC1 Of Commons Lang. The final version will be released soon.

Commons and Lang Components
The Jakarta Commons project is designed to implement reusable Java components. This project contains dozens of components to simplify Java development. Each component is responsible for meeting a specific requirement. A large number of components are available, and they are not limited to specific types of Java applications.

The project is classified into two parts:

  1. Commons proper: projects in commons proper can be put into practical use.
  2. Commons sandbox: The project in sandbox is still in the experimental stage.

Currently, commons proper has 33 projects and commons sandbox has 22 projects. Therefore, any type of Java project has its own meaning.
The Lang component is one of the more popular components in Jakarta commons. Lang is a group of classes to be presented in j2se itself.
In this article, we will understand some of the most useful functions of Lang. Note that you can use only the basic Java class to complete each function of Lang, but it is much easier to use Lang than to learn, understand, and write code. Even if you can write the best code, using the tested and tested Lang functions will be faster, saving a lot of time for checking and testing. Along with Lang's unique JUnit test cases, Lang is widely used and has been tested by its creators and the real world.
An important feature of Lang is its simplicity. In general, new Java components are very complex. You need to know several technologies before using them. It is usually difficult to understand the purpose of a component, let alone the actual use of the component. But for most commons components, this is not a problem. Lang is a type of component that is easy to use and is useful to beginners and advanced Java users.
If you need full assurance before using the technology, search for commons-lang *. jar in the directory where your Java software is saved. The results will surprise you. Common Java projects such as Tomcat, struts, hibernate, spring, and webwork all use Lang.
First, let's take a look at the string operation that most developers must perform almost every day using Lang.

Processing string
No matter whether the application is based on Swing, J2EE, or J2EE, it must use strings. Therefore, although it is quite simple to use strings in Java, it is not easy to modify and process strings according to certain conditions. You have to find a variety of uncommon methods in various string-related classes, and then try to make them work together to get the desired results. Although some Lang Methods overlap some methods in j2se, in most cases, a Lang method can provide the functions of multiple j2se methods in various types, to help you obtain the required output.
The Lang component has many classes specifically used for string operations. Now we will use a simple Java application to demonstrate some useful classes and methods.
When the application accepts user input, because the user may have incorrect input, or the user may input data in various formats, you want to process and store data in only one format, operations on strings are usually involved.
For example, you have a form with an input box in which you enter the license key. You want to allow a 1111-Java key. You must perform the following operations:

  1. Check whether it is a null string.
  2. Ignore spaces.
  3. The key is case sensitive.
  4. Use the "-" mark to separate the key string and then check whether all the first part is a number, the second part contains only valid character sets "J", "A", "V", and "".
  5. Both parts should contain four characters.
  6. The fourth digit in the first part should be "0 ".

The application queries the database only when the key meets all these conditions and checks whether the key is valid.
If you do not spend a lot of time browsing the string, stringtokenizer, and other API documents, can you complete the above tasks? I cannot, so now I will try to use the Lang component to manage the verification.
Listing 1. checklicensekey () method

/** * Check if the key is valid * @param key license key value * @return true if key is valid, false otherwise. */public static boolean checkLicenseKey(String key){    //checks if empty or null    if(StringUtils.isBlank(key)){        return false;    }    //delete all white space    key= StringUtils.deleteWhitespace(key);    //Split String using the - separator    String[] keySplit = StringUtils.split(key, "-");    //check lengths of whole and parts    if(keySplit.length != 2        || keySplit[0].length() != 4        || keySplit[1].length() != 4) {        return false;    }    //Check if first part is numeric    if(!StringUtils.isNumeric(keySplit[0])){        return false;    }    //Check if second part contains only    //the four characters 'J', 'A', 'V' and 'A'    if(! StringUtils.containsOnly(keySplit[1]            ,new char[]{'J', 'A', 'V', 'A'})){        return false;    }    //Check if the fourth character  //in the first part is a '0'    if(StringUtils.indexOf(keySplit[0], '0') != 3){        return false;    }    //If all conditions are fulfilled, key is valid.    return true;}

In listing 1, we use the methods provided in the org. Apache. commons. Lang. stringutils class to verify the strings according to all the rules we previously defined. The isblank () method checks whether the string is null. The deletewhitespace () method ensures that the string does not contain spaces. Then we use the split () method to separate strings and use the isnumeric (), containsonly (), and indexof () methods to verify the two parts of the key.
Note that although the indexof () method is already available in j2se, it is best to use indexof () in stringutils (). Unlike j2se indexof (), you do not need to worry about null pointers when using stringutils indexof. Triggering nullpointerexception is considered the most common mistake of Java programmers. Lang ensures that you do not make the same mistake. Nullpointerexception is not thrown even if a null value is passed to indexof () or other such methods. Indexof () will return-1 directly.
In this way, only a few lines of simple code can be used to implement the corresponding functions, while using other methods requires many lines of code, which is very troublesome. If the checklicensekey () method is executed using the main method shown in Listing 2, the result is shown in listing 3.

Listing 2. Main () method

public static void main(String[] args) {    String []key= {"1210-JVAJ","1211-JVAJ", "210-JVAJ", "1210-ZVAJ"};    for (int i=0; i < key.length; i++){        if(checkLicenseKey(key[i])){            System.out.println(key[i]+ " >> Is Valid");        }        else{            System.out.println(key[i]+ " >> Is InValid");        }    }}

Listing 3. Output

1210-JVAJ >> Is Valid1211-JVAJ >> Is InValid210-JVAJ >> Is InValid1210-ZVAJ >> Is InValid

Most of the methods used for string operations belong to org. Apache. commons. Lang. stringutils, but other classes can be used. Charutils and charsetutils provide practical methods to use character sets and character sets, respectively. Wordutils is the first class that appears in version 2.0. It is used to hold a practical method dedicated to word processing. However, as there are a large number of overlapping operations on strings and words, such operations seem unnecessary. The randomstringutils class can generate random strings according to various rules.
Now let's take a look at another useful aspect of Lang: Date and time processing capabilities.

Time Technology
Processing Date and Time in Java is quite tricky. If you want to use Java. text. simpledateformat, Java. util. calendar, Java. util. date and other classes require a certain amount of time to adapt. You also need to have a good understanding of each of the classes and interfaces involved in order to smoothly process the date and time.
The Lang component completely simplifies Date Processing and can be formatted. You can easily format dates for display, comparison, rounding, or truncation, or even getting all dates in a specific range.

Listing 4. Processing Date and Time

public static void main(String[] args) throws InterruptedException, ParseException {    //date1 created    Date date1= new Date();    //Print the date and time at this instant    System.out.println("The time right now is >>"+date1);    //Thread sleep for 1000 ms    Thread.currentThread().sleep(DateUtils.MILLIS_IN_SECOND);    //date2 created.    Date date2= new Date();    //Check if date1 and date2 have the same day    System.out.println("Is Same Day >> "        + DateUtils.isSameDay(date1, date2));    //Check if date1 and date2 have the same instance    System.out.println("Is Same Instant >> "        +DateUtils.isSameInstant(date1, date2));    //Round the hour    System.out.println("Date after rounding >>"        +DateUtils.round(date1, Calendar.HOUR));    //Truncate the hour    System.out.println("Date after truncation >>"        +DateUtils.truncate(date1, Calendar.HOUR));    //Three dates in three different formats    String [] dates={"2005.03.24 11:03:26", "2005-03-24 11:03", "2005/03/24"};    //Iterate over dates and parse strings to java.util.Date objects    for(int i=0; i < dates.length; i++){        Date parsedDate= DateUtils.parseDate(dates[i],        new String []{"yyyy/MM/dd", "yyyy.MM.dd HH:mm:ss", "yyyy-MM-dd HH:mm"});        System.out.println("Parsed Date is >>"+parsedDate);    }    //Display date in HH:mm:ss format    System.out.println("Now >>"        +DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(System.currentTimeMillis()));}

Listing 4 demonstrates some functions of the org. Apache. commons. Lang. dateutils and org. Apache. commons. Lang. dateformatstringutils classes. There are many other ways to perform the same operation, but the input format is different. Therefore, if you have to analyze and format a date value, you only need to use one of the provided methods and one line of code.
The input after executing the code in Listing 4 is shown in listing 5.

Listing 5. Output

The time right now is >>Sat Apr 09 14:40:41 GMT+05:30 2005Is Same Day >> trueIs Same Instant >> falseDate after rounding >>Sat Apr 09 15:00:00 GMT+05:30 2005Date after truncation >>Sat Apr 09 14:00:00 GMT+05:30 2005Parsed Date is >>Thu Mar 24 11:03:26 GMT+05:30 2005Parsed Date is >>Thu Mar 24 11:03:00 GMT+05:30 2005Parsed Date is >>Thu Mar 24 00:00:00 GMT+05:30 2005Now >>14:40:43

In Listing 4, we created two dates, which have only one second difference. Then, use the issameinstant () and issameday () methods to check whether the two dates are the same. Next, round and truncate the date, and then parse the special date case using the formats specified in the array.
When you integrate your application into a third-party application, the input format cannot be fully determined. I used to integrate an old application. For every question, this application always has three answers. Therefore, if you must parse the dates provided by such applications, you need to provide three and four different date formats. In Listing 4, The parsedate () method is used to complete this task. In this way, the date can be parsed even if the input changes. Note that the order of the in-array mode is different from that of the input mode, but the method still finds the appropriate mode and parses it accordingly.
Finally, we format the date in iso_time_no_t_format (HH: mm: SS) and print the input. Now we will understand how to use Lang to generate common methods tostring ().

Generate tostring () method
The equals (), tostring (), and hashcode () methods are often used. However, when talking about the implementation of these methods, not only do most of us not want to do this, but we cannot determine how to write these methods accurately and simply. The generator package provides some helper classes to help you easily create implementation of these methods. In most cases, you only need a line of code. Next we will understand the tostring function of Lang.

Tostring () method
You may not notice that in Listing 4. out. println () transmits a java. util. date object. The output is still displayed as the correct date and time. When the object reference is passed, the tostring () method is automatically called, so this can be implemented. In our example, Java. util. in the tostring () method of the date class, we can get the correct output because someone overwrites Java. util. java. lang. the tostring () method of the object class.
If the tostring () method is not overwritten, the output is only the name of the Class Name and hashcode. No data in the class is displayed. Therefore, if you write a new class and want to get the correct print output, you need to override the tostring () method in the class.

Listing 6. tostring () method

public class Computer {    String processor;    String color;    int cost;    /** Creates a new instance of Computer */    public Computer(String processor, String color, int cost) {        this.processor=processor;        this.color=color;        this.cost=cost;    }    public static void main(String[] args) {        Computer myComp=new Computer("Pentium","black",1000);        System.out.println(myComp);    }        public String toString(){        return ToStringBuilder.reflectionToString(this);        /*        return ToStringBuilder.reflectionToString(this            , ToStringStyle.SHORT_PREFIX_STYLE);        return ToStringBuilder.reflectionToString(this            , ToStringStyle.MULTI_LINE_STYLE);        return new ToStringBuilder(this)            .append("processor", processor).toString();         */    }}

Listing 6 demonstrates the computer class with three fields. The tostring () method is worth noting. Call the reflectiontostring () method to determine which fields are in the class and print the names and values. In the main () method, we only create an instance of this class and print it out. The output of this class is dev2dev. Computer @ f6a746 [processor = Pentium, color = Black, cost = 1000].
Therefore, if you do not want to spend too much energy, but you need tostring () Implementation for your class, the simplest way is to copy and paste the two lines of code into all your classes. If you want to better control the generated results, see the options mentioned in the notes. By creating a new instance of tostringbuilder, you can apply various styles to the output, or even generate all the outputs. If all four return statements are executed in the order listed, the output is shown in listing 7.

Listing 7. Four possible outputs based on the tostringbuilder Method

1) dev2dev.Computer@f6a746[processor=Pentium,color=black,cost=1000]2) Computer[processor=Pentium,color=black,cost=1000]3) dev2dev.Computer@f6a746[   processor=Pentium   color=black   cost=1000   ]4) dev2dev.Computer@192d342[processor=Pentium]

Object comparison and sorting
Data Objects are often compared and sorted accordingly. So how can we compare and sort the computer class objects in Listing 6?
Guess! Let's use Lang to sort computer objects based on computer costs. To compare objects, you must implement the java. Lang. Comparable interface. This interface has the unique method compareto (object ). This method compares the current object with the object passed to this method. If the object is smaller than, equal to, or greater than the specified object, this method returns negative, zero, or positive numbers respectively.
To compare computer objects, implement the compareto () method in the computer class, as shown in listing 8.

Listing 8. compareto () method

public int compareTo(Object obj) {    Computer anotherComputer = (Computer)obj;    //return new CompareToBuilder().reflectionCompare(this, anotherComputer);    return new CompareToBuilder().append(this.cost, anotherComputer.cost).toComparison();}

Then, for actual comparison, we compile a simple class named computersor, as shown in listing 9. We only add three objects to the arraylist and sort them.

Listing 9. computersort class

public class ComputerSort  {    public static void main(String[] args) {        ArrayList computerList = new ArrayList();        computerList.add(new Computer("Pentium","black", 1000));        computerList.add(new Computer("Pentium","chocolate", 334));        computerList.add(new Computer("Pentium","darkgray", 2234));        Collections.sort(computerList);        System.out.println(computerList);    }}

When computersort is executed, the object is sorted according to the value of the cost field. Similar to tostringbuilder, comparetobuilder also has a reflection-based usage option. We have commented on the bitwise element in the compareto () method in listing 8, because in this case, the reflection option compares all fields and finally gets incorrect results. If you do not want to compare fields in the current class, or compare fields in its super class, comparetobuilder also provides methods that can be used for this purpose. The output of the computersort class is shown in listing 10.

Listing 10. Computer objects after sorting

[dev2dev.Computer@cf2c80[processor=Pentium,color=chocolate,cost=334], dev2dev.Computer@12dacd1[processor=Pentium,color=black,cost=1000], dev2dev.Computer@1ad086a[processor=Pentium,color=darkgray,cost=2234]]

Conclusion
In this article, we understand some of the main functions of the Jakarta commons Lang component. In general, the Commons project is a very useful project, but it is not fully utilized. Although open-source projects use many commons components, they are not widely used outside the open-source world. Now that you know something about Lang, you should consider applying it to your application immediately. In addition, you can find various useful components in the Commons project to simplify XML parsing, enable HTTP sessions for applications, implement systematic verification, and execute many other functions.

Download
Download the code used in this article: examples.zip (3kb)

References

  • Jakarta commons
  • Jakarta commons Lang

Harshad oak is the founder of the Java J2EE portal website indicthreads.com. He compiled pro Jakarta commons and Oracle jdeveloper 10g: Empowering J2EE development, and co-authored Java 2 Enterprise Edition 1.4 bible. He is also the founder of rightrix solutions.

Source
Http://dev2dev.bea.com/pub/a/2005/04/commons_lang.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.