Introduction to Apache commons

Source: Internet
Author: User
Tags email string


Apache commons contains many open-source tools to solve common programming problems and reduce repetitive work. I have selected some common projects for a brief introduction. I used a lot of online ready-made items in this article. I just made a summary.

Commons beanutils
Http://jakarta.apache.org/commons/beanutils/index.html
Description: A bean tool set. Beanutils also performs some packaging on the basis of a bunch of get and set beans.
Examples: There are many features and detailed descriptions on the website. A common function is bean copy, which is the property of copy bean. It will be used for hierarchical architecture development, such as copying data from Po (Persistent Object) to VO (value object ).
The traditional method is as follows:

  1. // Obtain the teacherform
  2. Teacherform = (teacherform) form;

  3. // Construct a teacher object
  4. Teacher = new teacher ();

  5. // Assign a value
  6. Teacher. setname (teacherform. getname ());

  7. Teacher. setage (teacherform. getage ());

  8. Teacher. setgender (teacherform. getgender ());

  9. Teacher. setmajor (teacherform. getmajor ());

  10. Teacher. setdepartment (teacherform. getdepartment ());
  11. // Persists the teacher object to the database
  12. Hibernatedao =;

  13. Hibernatedao. Save (teacher );

After using beanutils, the code is greatly improved, as shown below:
 

  1. // Obtain the teacherform
  2. Teacherform = (teacherform) form;

  3. // Construct a teacher object
  4. Teacher = new teacher ();

  5. // Assign a value
  6. Beanutils. copyproperties (teacher, teacherform );

  7. // Persists the teacher object to the database
  8. Hibernatedao =;

  9. Hibernatedao. Save (teacher );

Commons CLI
Http://jakarta.apache.org/commons/cli/index.html
Note: This is a tool for processing commands. For example, the string [] entered by the main method needs to be parsed. You can pre-define the parameter rules and then call CLI for parsing.
Example:

  1. // Create options object
  2. Options = new options ();
  3. // Add t option, option is the command parameter, false indicates that
  4. // This parameter is not required.
  5. Options. addoption ("T", false, "display current time ");
  6. Options. addoption ("C", true, "Country Code ");
  7. Commandlineparser parser = new posixparser ();
  8. CommandLine cmd = parser. parse (options, argS );
  9. If (CMD. hasoption ("T ")){
  10. // Print the date and time
  11. }
  12. Else {
  13. // Print the date
  14. }
  15. // Get C option value
  16. String countrycode = cmd. getoptionvalue ("C ");
  17. If (countrycode = NULL ){
  18. // Print default date
  19. }
  20. Else {
  21. // Print date for country specified by countrycode
  22. }

Commons Codec
Http://jakarta.apache.org/commons/codec/index.html
Note: This tool is used for encoding and decoding, including base64, URL, and soundx. People who use this tool should be clear about this and I will not introduce it much.

Commons collections
Http://jakarta.apache.org/commons/collections/
Note: You can regard this tool as an extension of Java. util.
Example: A simple example

  1. Orderedmap map = new linkedmap ();
  2. Map. Put ("five", "5 ");
  3. Map. Put ("six", "6 ");
  4. Map. Put ("seven", "7 ");
  5. Map. firstkey (); // returns "five"
  6. Map. nextkey ("five"); // returns "six"
  7. Map. nextkey ("six"); // returns "seven"

Commons Configuration
Http://jakarta.apache.org/commons/configuration/
Note: This tool is used to process configuration files and supports many storage methods.
1. properties files
2. XML documents
3. Property list files (. plist)
4. JNDI
5. JDBC datasource
6. System Properties
7. Applet Parameters
8. servlet Parameters
Example: A simple example of Properties
# Usergui. properties, definining the GUI,

  1. Colors. Background = # ffffff
  2. Colors. Foreground = #000080
  3. Window. width = 500
  4. Window. Height = 300
  5. Propertiesconfiguration Config = new propertiesconfiguration ("usergui. properties ");
  6. Config. setproperty ("Colors. Background", "#000000 );
  7. Config. Save ();
  8. Config. Save ("usergui. Backup. properties); // save a copy
  9. Integer integer = config. getinteger ("window. width ");

Commons DBCP
Http://jakarta.apache.org/commons/dbcp/
Note: This is the database connection pool, Tomcat is used. You can go to the website to view the instructions.

Commons dbutils
Http://jakarta.apache.org/commons/dbutils/
Note: When I was writing a database program, I often made a separate package for database operations. Dbutils is such a tool, and you do not need to repeat such work in future development. It is worth noting that this tool is not a popular or-mapping tool (such as Hibernate), but just to simplify database operations, such

  1. Queryrunner run = new queryrunner (datasource );
  2. // Execute the query and get the results back from the Handler
  3. Object [] result = (object []) Run. Query (
  4. "Select * From person where name =? "," John Doe ");

Commons fileupload
Http://jakarta.apache.org/commons/fileupload/
Note: How does the JSP file upload function work?
Example:

  1. // Create a factory for disk-based file items
  2. Fileitemfactory factory = new diskfileitemfactory ();
  3. // Create a new file upload Handler
  4. Servletfileupload upload = new servletfileupload (factory );
  5. // Parse the request
  6. List items = upload. parserequest (request );
  7. // Process the uploaded items
  8. Iterator iter = items. iterator ();
  9. While (ITER. hasnext ()){
  10. Fileitem item = (fileitem) ITER. Next ();
  11. If (item. isformfield ()){
  12. Processformfield (item );
  13. } Else {
  14. Processuploadedfile (item );
  15. }
  16. }

Commons httpclient
Http://jakarta.apache.org/commons/httpclient/
Note: This tool can be used to access the website through programming.
Example: The simplest get operation

  1. Getmethod get = new getmethod ("http://jakarta.apache.org ");
  2. // Execute method and handle any error responses.
  3. ...
  4. Inputstream in = Get. getresponsebodyasstream ();
  5. // Process the data from the input stream.
  6. Get. releaseconnection ();

Commons Io

Http://jakarta.apache.org/commons/io/

Note: It can be seen as an extension of Java. Io, which I think is very convenient to use.
Example:
1. Read stream
Standard Code:

  1. Inputstream in = new URL ("http://jakarta.apache.org"). openstream ();
  2. Try {
  3. Inputstreamreader INR = new inputstreamreader (in );
  4. Bufferedreader Buf = new bufferedreader (INR );
  5. String line;
  6. While (line = Buf. Readline ())! = NULL ){
  7. System. Out. println (line );
  8. }
  9. } Finally {
  10. In. Close ();
  11. }
  12. Use ioutils
  13. Inputstream in = new URL ("http://jakarta.apache.org"). openstream ();
  14. Try {
  15. System. Out. println (ioutils. tostring (in ));
  16. } Finally {
  17. Ioutils. closequietly (in );
  18. }

2. Read files

  1. File file = new file ("/commons/IO/Project. properties ");
  2. List lines = fileutils. readlines (file, "UTF-8 ");

3. view the remaining space

  1. Long freespace = filesystemutils. freespace ("C :/");

Commons jxpath

Http://jakarta.apache.org/commons/jxpath/

(XPath) You know, jxpath is an XPATH Based on Java objects, that is, it is used to query Java objects. This is still imaginative.
Example:

  1. Address = (Address) jxpathcontext. newcontext (vendor ).
  2. Getvalue ("locations [Address/zipcode = '000000']/address ");
  3. The above code is equivalent
  4. Address = NULL;
  5. Collection locations = vendor. getlocations ();
  6. Iterator it = locations. iterator ();
  7. While (it. hasnext ()){
  8. Location = (location) it. Next ();
  9. String zipcode = location. getaddress (). getzipcode ();
  10. If (zipcode. Equals ("90210 ")){
  11. Address = location. getaddress ();
  12. Break;
  13. }
  14. }

Commons Lang

Http://jakarta.apache.org/commons/lang/

Note: This Toolkit can be seen as an extension of Java. Lang. Provides tool classes such as stringutils, stringescapeutils, randomstringutils, tokenizer, and wordutils.

Commons Logging

Http://jakarta.apache.org/commons/logging/

Note: Do you know log4j?

Commons math
Http://jakarta.apache.org/commons/math/
Note: You should know what the package is for by name. The features provided by this package are somewhat different from those provided by commons Lang, but this package is more focused on mathematical tools and more powerful.

Commons net

Http://jakarta.apache.org/commons/net/

Note: This package is very practical and encapsulates many network protocols.
1. FTP
2. nntp
3. SMTP
4. POP3
5. Telnet
6. TFTP
7. Finger
8. Whois
9. rexec/RCMD/Rlogin
10. Time (rdate) and daytime
11. Echo
12. Discard
13. NTP/SNTP
Example:

  1. Telnetclient Telnet = new telnetclient ();
  2. Telnet. Connect ("192.168.1.99", 23 );
  3. Inputstream in = Telnet. getinputstream ();
  4. Printstream out = new printstream (Telnet. getoutputstream ());
  5. ...
  6. Telnet. Close ();

Commons validator
Http://jakarta.apache.org/commons/validator/
Note: This tool is used for verification. For example, verify whether the email string and date string are valid.
Example:

  1. // Get the date validator
  2. Datevalidator validator = datevalidator. getinstance ();
  3. // Validate/convert the date
  4. Date foodate = validator. Validate (foostring, "DD/MM/YYYY ");
  5. If (foodate = NULL ){
  6. // Error... not a valid date
  7. Return;
  8. }

Commons Virtual File System

Http://jakarta.apache.org/commons/vfs/

Description: Provides access interfaces for various resources. Supported resource types include
1. CIFS
2. FTP
3. Local files
4. HTTP and https
5. SFTP
6. Temporary Files
7. WebDAV
8. Zip, jar and tar (uncompressed, tgz or tbz2)
9. gzip and Bzip2
10. Res
11. Ram
This package is powerful and greatly simplifies the access to resources by programs.
Example:
Read files from jar

  1. // Locate the JAR File
  2. Filesystemmanager fsmanager = VFS. getmanager ();

  3. Fileobject jarfile = fsmanager. resolvefile ("jar: lib/ajarfile. Jar ");

  4. // List the children of the JAR File
  5. Fileobject [] children = jarfile. getchildren ();

  6. System. Out. println ("children of" + jarfile. getname (). geturi ());

  7. For (INT I = 0; I <children. length; I ++)
  8. {
  9. System. Out. println (Children [I]. getname (). getbasename ());
  10. }

Read files from SMB

  1. Staticuserauthenticator auth = new staticuserauthenticator ("username", "password", null );

  2. Filesystemoptions opts = new filesystemoptions ();

  3. Defaultfilesystemconfigbuilder. getinstance (). setuserauthenticator (OPTs, auth );

  4. Fileobject fo = VFS. getmanager (). resolvefile ("SMB: // host/anyshare/DIR", opts );


Some people say that Apache is like a helper, and there are many projects in it. Indeed, Apache project levels are uneven, and different projects often have overlapping functions or even crashes, such as Ant and Maven. However, there are still many outstanding Apache projects, such as Apache HTTP Server, tomcat, ant, And Geronimo. Apache commons is a toolkit that provides support for other projects. Many commons projects are extracted from other projects.

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.