Apache Commons contains many open source tools to solve problems that are often encountered in programming and reduce repetitive labor. Below is a brief introduction to the tools I have used during the development process in the past few years.
| Components | Functional introduction |
| BeanUtils | Provides various operations, cloning objects, properties, etc. for JavaBeans. |
| Betwixt | Convert XML and Java objects to each other. |
| Codec | Tools that deal with commonly used coding methods such as DES, SHA1, MD5, Base64, etc. |
| Collections | Java collection framework operation. |
| Compress | Java provides file packaging compression class library. |
| Configuration | A configuration management class library for java applications. |
| DBCP | Provide database connection pooling services. |
| DbUtils | Provides operation encapsulation of jdbc to simplify data query and record read operations. |
| Java sends mail to encapsulation of javamail. | |
| FileUpload | Provides file upload function. |
| HttpClient | Provides various communication operations between HTTP clients and servers. It has now been changed to HttpComponents |
| IO | Encapsulation of io tools. |
| Lang | Tool class packages for Java basic object methods such as: StringUtils, ArrayUtils, etc. |
| Logging | It provides a Java logging interface. |
| Validator | Provides a data verification framework for client and server side. |
1. BeanUtils provides various operations for JavaBeans, such as object, attribute copying, etc.
//1. Cloning object// Create a new normal Java Bean to be used as the cloned object public class Person {private String name = "";private String email = "";private int age;//Omit set,get method}// Create a Test class, where the code in the main method is as follows: import java.lang.reflect.InvocationTargetException;import java.util.HashMap;import java.util.Map;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.beanutils.ConvertUtils;public class Test {/** * @param args */public static void main(String[] args) {Person person = new Person();person.setName("tom");person.setAge(21);try {//Clone Person person2 = (Person)BeanUtils.cloneBean(person);System.out.println(person2.getName()+">>"+person2.getAge());}catch (IllegalAccessException e) {e.printStackTrace();}catch (InstantiationException e) {e.printStackTrace();}catch (InvocationTargetException e) {e.printStackTrace();}catch (NoSuchMethodException e) {e.printStackTrace();}}}// The principle is also done through the Java reflection mechanism. // 2. Convert a Map object into a Bean // The key of this Map object must correspond to the Bean's properties. Map map = new HashMap();map.put("name","tom");map.put("email","tom@");map.put("age","21");//Convert map into a Person object Person person = new Person();BeanUtils.populate(person,map);// Through the above line of code, the person's attribute already has the value assigned above. // Convert a Bean into a Map object, as follows: Map map = BeanUtils.describe(person)2. Betwixt XML and Java objects are converted.
//1. Convert JavaBean to XML content// Create a new Person class public class Person{private String name;private int age;/** Need to allow bean to be created via reflection */public PersonBean() {}public PersonBean(String name, int age) {this.name = name;this.age = age;}//Omit set, get method public String toString() {return "PersonBean[name='" + name + "',age='" + age + "']";}}//Create a WriteApp class: import java.io.StringWriter;import org.apache.commons.betwixt.io.BeanWriter;public class WriteApp {/** * Create an example bean and convert it into XML. */public static final void main(String [] args) throws Exception {// Create a StringWriter first, we will write it as a string StringWriter outputWriter = new StringWriter();// Betwixt here just writes the bean as a fragment// So if we want to complete XML content, we should write to the header format outputWriter.write("<?xml version='1.0' encoding='UTF-8' ?>/n");// Create a BeanWriter, which will be written to the stream we prepared. BeanWriter beanWriter = new BeanWriter(outputWriter);// Configure betwixt // For more details, please refer to java docs or the latest document beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);beanWriter.getBindingConfiguration().setMapIDs(false);beanWriter.enablePrettyPrint();// If this place does not pass in the root node name of the XML, Betwixt will guess what it is// But let's use the example Bean name as the root node beanWriter.write("person", new PersonBean("John Smith", 21));//Output result System.out.println(outputWriter.toString());// Betwixt writes fragments rather than a document, so don't automatically close writers or streams, // But here is just an example and won't do more, so you can turn off outputWriter.close();}}//2. Convert XML to JavaBean import java.io.StringReader;import org.apache.commons.betwixt.io.BeanReader;public class ReadApp {public static final void main(String args[]) throws Exception{// Create an XML first. Since this is only an example, we hardcoded a piece of XML content StringReader xmlReader = new StringReader( "<?xml version='1.0' encoding='UTF-8' ?> <person><age>25</age><name>James Smith</name></person>");//Create BeanReader BeanReader beanReader = new BeanReader();//Configure reader beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);beanReader.getBindingConfiguration().setMapIDs(false);//Register beans so that betwixt knows what bean XML will be converted into beanReader.registerBeanClass("person", PersonBean.class);//Now we parse XML PersonBean person = (PersonBean) beanReader.parse(xmlReader);//Output result System.out.println(person);}}3. Codec provides some public codec implementations, such as Base64, Hex, MD5, Phonetic and URLs, etc.
//Base64 codec private static String encodeTest(String str){Base64 base64 = new Base64();try {str = base64.encodeToString(str.getBytes("UTF-8"));}catch (UnsupportedEncodingException e) {e.printStackTrace();}System.out.println("Base64 Encoded: "+str);return str;}private static void decodeTest(String str){Base64 base64 = new Base64();//str = Arrays.toString(Base64.decodeBase64(str)); str = new String(Base64.decodeBase64(str)); System.out.println("Base64 Decoded: "+str);}4. Collections extends java.util and processes data quite flexible.
org.apache.commons.collections Commons Collections Customized set of common interfaces and tool classes
org.apache.commons.collections.bag A set of classes that implement the Bag interface
org.apache.commons.collections.bidimap A set of classes that implement BidiMap series interfaces
org.apache.commons.collections.buffer A set of classes that implement the Buffer interface
org.apache.commons.collections.collection A set of classes that implement the java.util.Collection interface
org.apache.commons.collections.comparators A set of classes that implement the java.util.Comparator interface
org.apache.commons.collections.functors Commons Collections Customized set of functional classes
org.apache.commons.collections.iterators A set of classes that implement the java.util.Iterator interface
org.apache.commons.collections.keyvalue implements a set of classes related to collection and key/value mapping
org.apache.commons.collections.list A set of classes that implement the java.util.List interface
org.apache.commons.collections.map A set of classes that implement Map series interfaces
org.apache.commons.collections.set A set of classes that implement Set series interfaces
/** * Get a certain key after the key stored in the set */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" /** * Get value through key * Get key through value * Switch key and value in map */BidiMap bidi = new TreeBidiMap();bidi.put("SIX", "6");bidi.get("SIX");// returns "6" bidi.getKey("6");// returns "SIX" // bidi.removeValue("6"); // removes the mapping BidiMap inverse = bidi.inverseBidiMap();// returns a map with keys and values swapped System.out.println(inverse);/** * Get the same element in the two sets*/List<String> list1 = new ArrayList<String>();list1.add("1");list1.add("2");list1.add("3");List<String> list2 = new ArrayList<String>();list2.add("2");list2.add("3");list2.add("5");Collection c = CollectionUtils.retainAll(list1, list2);System.out.println(c);5. Compress commons packaged and compressed class libraries.
//Create a compressed object ZipArchiveEntry entry = new ZipArchiveEntry("CompressTest");//The file to be compressed f=new File("e://test.pdf");FileInputStream fis=new FileInputStream(f);//The file compressed by the output object ZipArchiveOutputStream zipOutput=new ZipArchiveOutputStream(new File("e://test.zip"));zipOutput.putArchiveEntry(entry);int i=0,j;while((j=fis.read()) != -1) {zipOutput.write(j);i++;System.out.println(i);}zipOutput.closeArchiveEntry();zipOutput.close();fis.close();6. Configuration is used to help 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
//Give a simple example of Properties# usergui.properties colors.background = #FFFFF 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");7. DBCP (Database Connection Pool) is a database connection pool that relies on the Jakarta commons-pool object pool mechanism. Tomcat's data source uses DBCP.
import javax.sql.DataSource;import java.sql.Connection;import java.sql.Statement;import java.sql.ResultSet;import java.sql.SQLException;import org.apache.commons.pool.ObjectPool;import org.apache.commons.pool.impl.GenericObjectPool;import org.apache.commons.dbcp.ConnectionFactory;import org.apache.commons.dbcp.PoolingDataSource;import org.apache.commons.dbcp.PoolableConnectionFactory;import org.apache.commons.dbcp.DriverManagerConnectionFactory;//Official Example public class PoolingDataSources {public static void main(String[] args) {System.out.println("Load jdbc driver");try {Class.forName("oracle.jdbc.driver.OracleDriver");}catch (ClassNotFoundException e) {e.printStackTrace();}System.out.println("Done.");// System.out.println("Set data source");DataSource dataSource = setupDataSource("jdbc:oracle:thin:@localhost:1521:test");System.out.println("Done.");// Connection conn = null;Statement stmt = null;ResultSet rset = null;try {System.out.println("Creating connection.");conn = dataSource.getConnection();System.out.println("Creating statement.");stmt = conn.createStatement();System.out.println("Executing statement.");rset = stmt.executeQuery("select * from person");System.out.println("Results:");int numcols = rset.getMetaData().getColumnCount();while(rset.next()) {for (int i=0;i<=numcols;i++) {System.out.print("/t" + rset.getString(i));}System.out.println("");}}catch(SQLException e) {e.printStackTrace();} finally {try {if (rset != null) rset.close();}catch(Exception e) {}try {if (stmt != null) stmt.close();}catch(Exception e) {}try {if (conn != null) conn.close();}catch(Exception e) {}}}public static DataSource setupDataSource(String connectURI) {//Set the connection address ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, null);// Create the connection factory PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory);// Get the instance of GenericObjectPool connectionPool connectionPool = new GenericObjectPool( poolableConnectionFactory);// Create PoolingDriver PoolingDataSource dataSource = new PoolingDataSource(connectionPool);return dataSource;}}8. A resource JDBC tool class library provided by DbUtilsApache organization. It is a simple encapsulation of JDBC, secondary encapsulation of traditional operating database classes, and can convert the result set into a List. , and it does not affect the performance of the program.
DbUtils class: Startup class
ResultSetHandler interface: conversion type interface
MapListHandler class: Implementation class, convert records into List
BeanListHandler class: implements the class, converts records into List, and makes records into JavaBean type object
QreryRunner class: class that executes SQL statements
import org.apache.commons.dbutils.DbUtils;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanListHandler;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.List;//Convert to list public class BeanLists {public static void main(String[] args) {Connection conn = null;String url = "jdbc:mysql://localhost:3306/ptest";String jdbcDriver = "com.mysql.jdbc.Driver";String user = "root";String password = "ptest";DbUtils.loadDriver(jdbcDriver);try {conn = DriverManager.getConnection(url, user, password);QueryRunner qr = new QueryRunner();List results = (List) qr.query(conn, "select id,name from person", new BeanListHandler(Person.class));for (int i = 0; i < results.size(); i++) {Person p = (Person) results.get(i);System.out.println("id:" + p.getId() + ",name:" + p.getName());}}catch (SQLException e) {e.printStackTrace();} finally {DbUtils.closeQuietly(conn);}}}public class Person{private Integer id;private String name;//Omit set, get method}import org.apache.commons.dbutils.DbUtils;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.MapListHandler;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.List;import java.util.Map;//Convert to map public class MapLists {public static void main(String[] args) {Connection conn = null;String url = "jdbc:mysql://localhost:3306/ptest";String jdbcDriver = "com.mysql.jdbc.Driver";String user = "root";String password = "ptest";DbUtils.loadDriver(jdbcDriver);try {conn = DriverManager.getConnection(url, user, password);QueryRunner qr = new QueryRunner();List results = (List) qr.query(conn, "select id,name from person", new MapListHandler()); for (int i = 0; i < results.size(); i++) {Map map = (Map) results.get(i);System.out.println("id:" + map.get("id") + ",name:" + map.get("name"));}}catch (SQLException e) {e.printStackTrace();} finally {DbUtils.closeQuietly(conn);}}}9. An open source API provided by Email is an encapsulation of javamail.
//Send emails using commons email public static void main(String args[]){Email email = new SimpleEmail();email.setHostName("smtp.googlemail.com");email.setSmtpPort(465);email.setAuthenticator(new DefaultAuthenticator("username", "password"));email.setSSLOnConnect(true);email.setFrom("[email protected]");email.setSubject("TestMail");email.setMsg("This is a test mail... :-)");email.addTo("[email protected]");email.send();}10. FileUpload java web file upload function.
//Official example: //* Check that we have a file upload request Boolean isMultipart = ServletFileUpload.isMultipartContent(request);//Now we have a list of items//If your application is close to the simplest case, the above processing is enough. But sometimes we still need more control. //The following are several control options: // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory();// Set factory constraints factory.setSizeThreshold(yourMaxMemorySize);factory.setRepository(yourTempDirectory);// Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory);// Set the maximum upload size upload.setSizeMax(yourMaxRequestSize);// parse all requests List /* FileItem */items = upload.parseRequest(request);// Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(yourMaxMemorySize, yourTempDirectory);// Once the parsing is completed, you need to further process the list of items. // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) {FileItem item = (FileItem) iter.next(); if (item.isFormField()) {processFormField(item);} else {processUploadedFile(item);}}//Distinguish whether the data is simple form data, if it is simple data: // processFormField if (item.isFormField()) {String name = item.getFieldName();String value = item.getString();//...Omit steps}//If it is a submitted file: // processUploadedFile if (!item.isFormField()) {String fieldName = item.getFieldName();String fileName = item.getName();String contentType = item.getContentType();Boolean isInMemory = item.isInMemory();long sizeInBytes = item.getSize();//...Omit steps}//For these items, we usually write them to a file, or convert them into a stream// Process a file upload if (writeToFile) {File uploadedFile = new File(...);item.write(uploadedFile);} else {InputStream uploadedStream = item.getInputStream();//...Omitted steps uploadedStream.close();}// or convert it into a byte array to save in memory: // Process a file upload in memory byte[] data = item.get();//...Omitted steps// If this file is really large, you may want to report to the user how much it has been transmitted to the server, so that the user can understand the upload process//Create a progress listener ProgressListener progressListener = new ProgressListener(){public void update(long pBytesRead, long pContentLength, int pItems) {System.out.println("We are currently reading item " + pItems);if (pContentLength == -1) {System.out.println("So far, " + pBytesRead + " bytes have been read.");} else {System.out.println("So far, " + pBytesRead + " of " + pContentLength + " bytes have have read.");}}};upload.setProgressListener(progressListener);11. HttpClien is an HTTP/1.1-compatible HTTP client implemented based on HttpCore. It provides a series of reusable client authentication, HTTP status maintenance, and HTTP connection management modules.
//GET method import java.io.IOException;import org.apache.commons.httpclient.*;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.params.HttpMethodParams;public class GetSample{public static void main(String[] args) {// Construct an instance of HttpClient HttpClient httpClient = new HttpClient();// Create an instance of GET method GetMethod getMethod = new GetMethod("http://www.ibm.com");// Use the default recovery policy provided by the system to getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());try {// Execute getMethod int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) {System.err.println("Method failed: " + getMethod.getStatusLine());}// Read content byte[] responseBody = getMethod.getResponseBody();// Handle content System.out.println(new String(responseBody));}catch (HttpException e) {// A fatal exception occurred, which may be that the protocol is incorrect or the returned content is problematic System.out.println("Please check your provided http address!");e.printStackTrace();}catch (IOException e) {// A network exception occurred e.printStackTrace();} finally {// Release the connection getMethod.releaseConnection();}}}}//POST method import java.io.IOException;import org.apache.commons.httpclient.*;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.params.HttpMethodParams;public class PostSample{public static void main(String[] args) {// Construct an instance of HttpClient HttpClient httpClient = new HttpClient();// Create an instance of the POST method String url = "http://www.oracle.com/";PostMethod postMethod = new PostMethod(url);// Fill in the values of each form field NameValuePair[] data = { new NameValuePair("id", "youUserName"), new NameValuePair("passwd", "yourPwd")};// Put the value of the form into postMethod postMethod.setRequestBody(data);// Execute postMethod int statusCode = httpClient.executeMethod(postMethod);// HttpClient cannot automatically handle forwarding for requests that require subsequent services such as POST and PUT // 301 or 302 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {// Take out the address of the steering from the beginning Header locationHeader = postMethod.getResponseHeader("location");String location = null;if (locationHeader != null) {location = locationHeader.getValue();System.out.println("The page was redirected to:" + location);} else {System.err.println("Location field value is null.");}return;}}}12. IO is very convenient for java.io to extend the operation file.
//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 file File file = new File("/commons/io/project.properties");List lines = FileUtils.readLines(file, "UTF-8");//3. View the remaining space long freeSpace = FileSystemUtils.freeSpace("C:/");13. Lang is mainly a collection of public tools, such as operations on characters, arrays, etc.
// 1 Merge two arrays: org.apache.commons.lang. ArrayUtils // Sometimes we need to combine two arrays into an array, and it is very convenient to use ArrayUtils. The example is as follows: private static void testArr() {String[] s1 = new String[] { "1", "2", "3" };String[] s2 = new String[] { "a", "b", "c" };String[] s = (String[]) ArrayUtils.addAll(s1, s2);for (int i = 0; i < s.length; i++) {System.out.println(s[i]);}String str = ArrayUtils.toString(s);str = str.substring(1, str.length() - 1);System.out.println(str + ">>" + str.length());}//2 Intercept the string starting from StringUtils.substringAfter("SELECT * FROM PERSON ", "from");//3 Determine whether the string is composed of numbers (0~9). If so, return true, but this method does not recognize decimal points and please note that StringUtils.isNumeric("454534");//Return true //4. Get the class name System.out.println(ClassUtils.getShortClassName(Test.class)); // Get its package name System.out.println(ClassUtils.getPackageName(Test.class)); //5.NumberUtils System.out.println(NumberUtils.stringToint("6")); //6. Five-digit random letters and numbers System.out.println(RandomStringUtils.randomAlphanumeric(5)); //7.StringEscapeUtils System.out.println(StringEscapeUtils.escapeHtml("<html>"));//The output result is <html> System.out.println(StringEscapeUtils.escapeJava("String"));//8.StringUtils, determine whether it is a space character System.out.println(StringUtils.isBlank(" "));//Separate the contents in the array by System.out.println(StringUtils.join(test,","));//Add characters to the right to make the total length of 6 System.out.println(StringUtils.rightPad("abc", 6, 'T'));//The first letter is capitalized System.out.println(StringUtils.capitalize("abc"));//Deletes all whitespaces from a String Delete all spaces System.out.println( StringUtils.deleteWhitespace("abc"));//Deletes all whitespaces from a String Delete all spaces System.out.println( StringUtils.contains("abc", "ba"));//Denotes the two characters on the left System.out.println( StringUtils.left("abc", 2));System.out.println(NumberUtils.stringToint("33"));14. Logging provides a Java logging interface, which takes into account both lightweight and does not rely on specific log implementation tools.
import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class CommonLogTest {private static Log log = LogFactory.getLog(CommonLogTest.class);//log print public static void main(String[] args) {log.error("ERROR");log.debug("DEBUG");log.warn("WARN");log.info("INFO");log.trace("TRACE");System.out.println(log.getClass());}} 15. Validator is a general verification system, which provides a data verification framework for client and server side.
Verification date
// Get date verification DateValidator validator = DateValidator.getInstance();// Verify/Convert date Date fooDate = validator.validate(fooString, "dd/MM/yyyy");if (fooDate == null) {// The error is not a date return;}Expression verification
// Set the parameter Boolean caseSensitive = false;String regex1 = "^([AZ]*)(?://-)([AZ]*)*$" String regex2 = "^([AZ]*)$";String[] regexs = new String[] {regex1, regex1};// Create a validator RegexValidator validator = new RegexValidator(regexs, caseSensitive);// Verify returns boolean Boolean valid = validator.isValid("abc-def");// Verify returns the string String result = validator.validate("abc-def");// Verify returns the array String[] groups = validator.match("abc-def");Use verification in configuration files
<form-validation> <global> <validator name="required" classname="org.apache.commons.validator.TestValidator" method="validateRequired" methodParams="java.lang.Object, org.apache.commons.validator.Field"/> </global> <formset> </formset> </form-validation> Add name verification. <form-validation> <global> <validator name="required" classname="org.apache.commons.validator.TestValidator" method="validateRequired" methodParams="java.lang.Object, org.apache.commons.validator.Field"/> </global> <formset> <form name="nameForm"> <field property="firstName" depends="required"> <arg0 key="nameForm.firstname.displayname"/> </field> <field property="lastName" depends="required"> <arg0 key="nameForm.lastname.displayname"/> </formset> </form-validation>
Verification Class
Excelpts from org.apache.commons.validator.RequiredNameTest //Load the verification configuration file InputStream in = this.getClass().getResourceAsStream("validator-name-required.xml");ValidatorResources resources = new ValidatorResources(in);//This is a bean created by myself. I omitted Name name = new Name();Validator validator = new Validator(resources, "nameForm");//Set the parameter validator.setParameter(Validator.BEAN_PARAM, name);Map results = null;//Verify results = validator.validate();if (results.get("firstName") == null) {//Verify successfully} else {//There is an error int errors = ((Integer)results.get("firstName")).intValue();}Summarize
The above is all the detailed explanation of the apache commons tool set code in this article, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!