Go About the Apache Commons toolset

Source: Internet
Author: User
Tags email string xpath

Apache Commons contains a lot of open source tools to solve the problems often encountered in programming, and reduce duplication of labor. I chose some of the more commonly used items to do a brief introduction. The text used a lot of online ready-made things, I just did a summary of the finishing.

First, Commons beanutils


Description: A toolset for beans. Since beans tend to have a bunch of get and set components, Beanutils also carries out some packaging on this basis.

Use example: There are a lot of features, detailed information on the website. A more common feature is bean copy, which is the properties of the copy bean. If you do a layered architecture development, you can use it, such as copying data from PO (persistent object) to Vo (Value object).

The traditional methods are as follows:

Get Teacherform

Teacherform teacherform= (teacherform) Form;

Constructing teacher Objects

Teacher teacher=new Teacher ();

Assign value
Teacher.setname (Teacherform.getname ());
Teacher.setage (Teacherform.getage ());
Teacher.setgender (Teacherform.getgender ());
Teacher.setmajor (Teacherform.getmajor ());
Teacher.setdepartment (Teacherform.getdepartment ());

Persisting teacher objects to a database
Hibernatedao.save (teacher);

With Beanutils, the code is greatly improved, as shown here:

Get Teacherform
Teacherform teacherform= (teacherform) Form;
Constructing teacher Objects
Teacher teacher=new Teacher ();

Assign value
Beanutils.copyproperties (Teacher,teacherform);

Persisting teacher objects to a database
Hibernatedao.save (teacher);

Second, Commons CLI


Description: This is a tool for handling commands. For example, the main method input string[] need to parse. You can pre-define the rules for parameters, and then you can invoke the CLI to parse them.

Examples of Use:

Create Options Object
Options options = new options ();
Add t option, option is the command parameter, False indicates that
This parameter was not required.

Options.addoption ("T", false, "display current Time");
Options.addoption ("C", True, "Country Code");

Commandlineparser parser = new Posixparser ();
CommandLine cmd = parser.parse (options, args);

if (Cmd.hasoption ("T")) {
Print the date and time
}else {
Print the date

Get C option value
String CountryCode = Cmd.getoptionvalue ("C");

if (CountryCode = = null) {
Print default Date
}else {
Print date for country specified by CountryCode

Third, Commons Codec


Description: This tool is used for encoding and decoding, including Base64,url,soundx and so on. The people who use this tool should be very clear about this, I will not introduce more.

Iv. Commons Collections


Description: You can think of this tool as an extension of java.util.

Use example: To give a simple example

Orderedmap map = new Linkedmap ();
Map.put ("FIVE", "5");
Map.put ("SIX", "6");
Map.put ("SEVEN", "7");
Map.firstkey (); Returns "FIVE"
Map.nextkey ("FIVE"); Returns "SIX"
Map.nextkey ("SIX"); Returns "SEVEN"

Five, Commons Configuration


Description: This tool is used to help with configuration files and supports a variety of storage methods

1. Properties files
2. XML Documents
3. Property list files (. plist)
5. JDBC Datasource
6. System Properties
7. Applet Parameters
8. Servlet Parameters

Examples of use: A simple example of a properties

# usergui.properties, definining the GUI,
Colors.background = #FFFFFF
Colors.foreground = #000080
Window.width = 500
Window.height = 300

propertiesconfiguration config = new Propertiesconfiguration ("Usergui.properties");
Config.setproperty ("Colors.background", "#000000);
Config.save ();

Config.save ("Usergui.backup.properties");//save a copy
Integer integer = Config.getinteger ("Window.width");

Commons DBCP


Description: Database Connection pool, Tomcat is the use of this, do not need me to say it, to use their own to the site to see the instructions.

Liu, Commons dbutils


Description: I used to write a database program, often the database operation to do a separate package. Dbutils is such a tool that it is not necessary to repeat the work after development. What is worth one is that this tool is not a popular or-mapping tool (like hibernate), but simplifies database operations, such as

Queryrunner run = new Queryrunner (DataSource);

Execute the query and get the results back from the handler
Object[] result = (object[]) run.query ("select * from person WHERE name=?", "John Doe");

Seven, Commons FileUpload


Description: JSP upload file function How to do it?

Examples of Use:

Create a factory for disk-based file items
Fileitemfactory factory = new Diskfileitemfactory ();
Create a new file upload handler
Servletfileupload upload = new Servletfileupload (factory);

Parse the request
List/* Fileitem */items = upload.parserequest (request);
Process the uploaded items
Iterator iter = Items.iterator ();
while (Iter.hasnext ()) {
Fileitem item = (Fileitem) iter.next ();
if (Item.isformfield ()) {
Processformfield (item);
} else {
Processuploadedfile (item);

Viii. Commons HttpClient


Description: This tool makes it easy to access the website programmatically.

Example of use: The simplest get operation

GetMethod get = new GetMethod ("http://jakarta.apache.org");

Execute method and handle any error responses.


InputStream in = Get.getresponsebodyasstream ();
Process the data from the input stream.
Get.releaseconnection ();

IX, Commons IO


Description: Can be seen as an extension of java.io, I think it is very convenient to use.

Examples of Use:

1. Read stream

Standard Code:

InputStream in = new URL ("http://jakarta.apache.org"). OpenStream ();
try {
InputStreamReader InR = new InputStreamReader (in);
BufferedReader buf = new BufferedReader (InR);
String Line;
while (line = Buf.readline ()) = null) {
System.out.println (line);
} finally {
In.close ();

Using Ioutils

InputStream in = new URL ("http://jakarta.apache.org"). OpenStream ();
try {
System.out.println (Ioutils.tostring (in));
} finally {
Ioutils.closequietly (in);

2. Read file

File File = new file ("/commons/io/project.properties");
List lines = fileutils.readlines (file, "UTF-8");

3. See the rest of the space
Long freeSpace = Filesystemutils.freespace ("c:/");

Ten, Commons Jxpath


Description: XPath you know, then Jxpath is an XPath based on a Java object, that is, querying a Java object with XPath. This thing is still very imaginative.

Examples of Use:
Address address = (address) jxpathcontext.newcontext (vendor).
GetValue ("locations[address/zipcode= ' 90210 ']/address");

The above code is equivalent to
Address address = null;
Collection locations = Vendor.getlocations ();
Iterator it = Locations.iterator ();
while (It.hasnext ()) {
Location location = (location) it.next ();
String ZipCode = location.getaddress (). Getzipcode ();
if (Zipcode.equals ("90210")) {
Address = location.getaddress ();

Xi. Commons Lang


Description: This toolkit can be seen as an extension to Java.lang. Tools such as StringUtils, Stringescapeutils, Randomstringutils, Tokenizer, wordutils are provided.

12, Commons Logging


Description: Do you know log4j?

13. Commons Math


Description: Look at your name and you should know what this bag is for. Some of the features offered by this package are duplicated with Commons Lang, but the package is more focused on doing math tools and more powerful.

14. Commons Net


Description: This package is still very useful, encapsulating a lot of network protocols.

1. FTP
4. POP3
5. Telnet
7. Finger
8. Whois
9. Rexec/rcmd/rlogin
Ten. Time (rdate) and daytime
One. Echo

Examples of Use:
telnetclient telnet = new Telnetclient ();
Telnet.connect ("", 23);
InputStream in = Telnet.getinputstream ();
PrintStream out = new PrintStream (Telnet.getoutputstream ());
Telnet.close ();

XV, Commons Validator


Description: A tool used to help with validation. such as verifying the email string, date string and so on is legitimate.

Examples of Use:

Get The Date Validator
Datevalidator validator = Datevalidator.getinstance ();
Validate/convert the date
Date foodate = validator.validate (foostring, "dd/mm/yyyy");
if (foodate = = null) {
Error...not a valid date

VI, Commons Virtual File System


Description: Provides access to a variety of resources. Supported resource types include

2. FTP
3. Local Files
6. Temporary Files
7. WebDAV
8. Zip, Jar and Tar (uncompressed, tgz or tbz2)
9. Gzip and BZIP2
Ten. Res
One. Ram

This package is powerful and greatly simplifies the program's access to resources.

Examples of Use:

To read a file from the jar

Locate the Jar file
Filesystemmanager Fsmanager = Vfs.getmanager ();
FileObject jarfile = Fsmanager.resolvefile ("Jar:lib/ajarfile.jar");

List the children of the Jar file
Fileobject[] Children = Jarfile.getchildren ();
System.out.println ("Children of" + jarfile.getname (). GetURI ());
for (int i = 0; i < children.length; i++) {
System.out.println (children[i].getname (). Getbasename ());

Reading files from SMB
Staticuserauthenticator auth = new Staticuserauthenticator ("username", "password", null);
Filesystemoptions opts = new Filesystemoptions ();
Defaultfilesystemconfigbuilder.getinstance (). Setuserauthenticator (opts, auth);
FileObject fo = Vfs.getmanager (). Resolvefile ("Smb://host/anyshare/dir", opts);

Go About the Apache Commons toolset

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.