About Apache Commons Toolkit
Abstract: Introduction Apache Commons Toolkit
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td height="50" align="left" valign="top"> </ td> </ tr> </ table>
Apache Commons contains many open-source tools to solve programming often peacetime problems, reduce duplication of effort. I have chosen some of the more common items so brief. Wen spent a lot of things online ready, I just made a aggregate basis.
First, Commons BeanUtils
Http://jakarta.apache.org/commons/beanutils/index.html
Description: Bean for a tool set. As Bean is often set and get a lot of, in this BeanUtils is on the basis of some packaging.
Examples of use: There are many functions, as detailed on the Web site. A more commonly used functions Bean Copy, which is copy bean properties. If the development of a layered architecture to do so will be used, for example, from the PO (Persistent Object) copy data to VO (Value Object).
Traditional methods are as follows:
/ / Get TeacherForm
TeacherForm teacherForm = (TeacherForm) form;
/ / Object structure Teacher
Teacher teacher = new Teacher ();
/ / Assignment
Teacher.setName (teacherForm.getName ());
Teacher.setAge (teacherForm.getAge ());
Teacher.setGender (teacherForm.getGender ());
Teacher.setMajor (teacherForm.getMajor ());
Teacher.setDepartment (teacherForm.getDepartment ());
/ / Persistent object to the database Teacher
HibernateDAO =;
HibernateDAO.save (teacher);
BeanUtils use, the code will be greatly improved, as follows:
/ / Get TeacherForm
TeacherForm teacherForm = (TeacherForm) form;
/ / Object structure Teacher
Teacher teacher = new Teacher ();
/ / Assignment
BeanUtils.copyProperties (teacher, teacherForm);
/ / Persistent object to the database Teacher
HibernateDAO =;
HibernateDAO.save (teacher);
Second, the Commons CLI
Http://jakarta.apache.org/commons/cli/index.html
Note: This is a tool for handling orders. For example, the main method of input string [] needs analysis. You can pre-defined parameters of the rules, and then we can call CLI to the analysis.
Examples of use:
/ / Create Options object
Options options = new Options ();
/ / Add t option, the option is the command parameter, false indicates that
/ / This parameter is 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
)
3. Commons Codec
Http://jakarta.apache.org/commons/codec/index.html
Description: This tool is used for encoding and decoding, including Base64, URL, Soundx and so on. Use this tool should be very aware of these people, I do not multi-introduced.
4. Commons Collections
Http://jakarta.apache.org/commons/collections/
Note: You can use that tool as java.util expansion.
Examples of use: Take 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"
5. Commons Configuration
Http://jakarta.apache.org/commons/configuration/
Description: This tool is used to help deal with configuration files, and support a variety storage
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
Examples of use: Take a simple example 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
Http://jakarta.apache.org/commons/dbcp/
Description: Database Connection pool, the Tomcat is to use this, I do not have to say much of the bar, use their own perspective to the site.
6. Commons DbUtils
Http://jakarta.apache.org/commons/dbutils/
Note: I write database programs in the past, they often do to a single database operation package. DbUtils This is a tool, not to repeat the future development of this work. Worth one is that this tool is not now popular OR-Mapping tools (such as Hibernate), but to simplify 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");
7. Commons FileUpload
Http://jakarta.apache.org/commons/fileupload/
Description: jsp file upload function of how do?
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 * / upload.parseRequest items = (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);
)
)
8. Commons HttpClient
Http://jakarta.apache.org/commons/httpclient/
Description: This tool can be easily programmed approach to visit the Web site.
Examples of use: Get the most simple 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 ();
9. Commons IO
Http://jakarta.apache.org/commons/io/
Description: can be regarded as a java.io expansion, I think that is very convenient for them 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 ();
)
Use IOUtils
InputStream in = new URL ( "http://jakarta.apache.org"). OpenStream ();
Try (
System.out.println (IOUtils.toString (in));
Finally ()
IOUtils.closeQuietly (in);
)
2. Read documents
File file = new File ( "/ commons / io / project.properties");
List lines = FileUtils.readLines (file, "UTF-8");
3. Look at the remaining space
FileSystemUtils.freeSpace long freeSpace = ( "C :/");
10. Commons JXPath
Http://jakarta.apache.org/commons/jxpath/
Description: Xpath you know it, it is based on Java JXpath Xpath object, which is used on Java objects Xpath inquiries. This stuff was very imaginative.
Examples of use:
Address address = (Address) JXPathContext.newContext (vendor).
GetValue ( "locations [address / zipCode ='90210 '] / address");
Equivalent to the above code
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")) (
Location.getAddress address = ();
Break;
)
)
11. Commons Lang
Http://jakarta.apache.org/commons/lang/
Description: This kit can be viewed as the expansion of the java.lang. Provided such as StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils tools category.
12. Commons Logging
Http://jakarta.apache.org/commons/logging/
Description: Did you know Log4j?
13. Commons Math
Http://jakarta.apache.org/commons/math/
Description: name you should see that this package is used to doing in a bar. This package provides some of the functions of Commons Lang and repeat, but this package more focus on doing mathematical tool and more powerful.
14. Commons Net
Http://jakarta.apache.org/commons/net/
Description: This package is very practical, Packaging, a lot of 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
Examples of use:
TelnetClient telnet = new TelnetClient ();
Telnet.connect ( "192.168.1.99", 23);
InputStream in telnet.getInputStream = ();
PrintStream out = new PrintStream (telnet.getOutputStream ());
…
Telnet.close ();
15. Commons Validator
Http://jakarta.apache.org/commons/validator/
Description: to help verification tool. Email authentication string for example, whether legitimate date string.
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
Return;
)
16. Commons Virtual File System
Http://jakarta.apache.org/commons/vfs/
Description: provide access to various resources. Interface. The types of support, including resources
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 features very powerful, greatly simplified the procedures of resources visit.
Examples of use:
Read documents 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 the" + jarFile.getName (). GetURI ());
For (int i = 0; i <children.length; i + +) (
System.out.println (children [i]. GetName (). GetBaseName ());
)
Read documents 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);
Some people say that Apache is like Gaibang inside of a lot of miscellaneous items. Indeed, the level of the Apache project uneven, but also between different projects often have overlapping functions, and even a crash, such as Ant and Maven. However, the Apache there are still many outstanding projects, such as Apache Http Server, Tomcat, Ant, Geronimo, and so on. Apache Commons is a tool kits, provide support for other projects, many in the Commons project is taken from other projects out. I hope that my introduction to your help, I mentioned some of the projects in the Commons I have not used, but now is sold in, it is inevitable errors and omissions that understanding.
</ Td> </ tr> <tr>
↑ Back
Tags: java apache, java commons






