lovegigi 发表于 2017-1-2 06:08:12

apache-commons 工具包学习

  Commons是apache下属的开源子项目,专门提供一些通用的工具类。
  这些方法用起来后,程序看起来更加简单,专业。
  Commons的主要类结构:



Attributes



Runtime API to metadata attributes such as doclet tags.




BeanUtils



Easy-to-use wrappers around the Java reflection and introspection APIs.




Betwixt



Services for mapping JavaBeans to XML documents, and vice versa.




Chain



Chain of Responsibility pattern implemention.





CLI



Command Line arguments parser.




Codec



General encoding/decoding algorithms (for example phonetic, base64, URL).




Collections



Extends or augments the Java Collections Framework.




Compress



Defines an API for working with tar, zip and bzip2 files.




Configuration



Reading of configuration/preferences files in various formats.




Daemon



Alternative invocation mechanism for unix-daemon-like java code.




DBCP



Database connection pooling services.




DbUtils



JDBC helper library.




Digester



XML-to-Java-object mapping utility.




Discovery



Tools for locating resources by mapping service/reference names to resource names.




EL



Interpreter for the Expression Language defined by the JSP 2.0 specification.




Email



Library for sending e-mail from Java.




Exec



API for dealing with external process execution and environment management in Java.




FileUpload



File upload capability for your servlets and web applications.




IO



Collection of I/O utilities.




JCI



Java Compiler Interface




Jelly



XML based scripting and processing engine.




Jexl



Expression language which extends the Expression Language of the JSTL.




JXPath



Utilities for manipulating Java Beans using the XPath syntax.




Lang



Provides extra functionality for classes in java.lang.




Launcher



Cross platform Java application launcher.




Logging



Wrapper around a variety of logging API implementations.




Math



Lightweight, self-contained mathematics and statistics components.




Modeler



Mechanisms to create Model MBeans compatible with JMX specification.




Net



Collection of network utilities and protocol implementations.




Pool



Generic object pooling component.




Primitives



Smaller, faster and easier to work with types supporting Java primitive types.




Proxy



Library for creating dynamic proxies.




Sanselan



A pure-Java image library.




SCXML



An implementation of the State Chart XML specification aimed at creating and maintaining a Java SCXML engine. It is capable of executing a state machine defined using a SCXML document, and abstracts out the environment interfaces.




Transaction



Implementations for multi level locks, transactional collections and transactional file access.




Validator



Framework to define validators and validation rules in an xml file.




VFS



Virtual File System component for treating files, FTP, SMB, ZIP and such like as a single logical file system.

  



  Lang


  Lang
Provides extra functionality for classes in java.lang.
  org.apache.commons.lang.builder.
ToStringBuilder:

  提供object重写toString()的工具类.
  ApplicationToStringStyle.APP_TO_STRING_STYLE提供toString的style。
  Fruit中重写了toString方法。

public abstract class ApplicationToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
public static final ApplicationToStringStyle APP_TO_STRING_STYLE = new CustomToStringStyle();
/**
* Constructor
*
* Use the static constant rather than instantiating
*/
private static final class CustomToStringStyle extends ApplicationToStringStyle {
private static final long serialVersionUID = -4289672936337739486L;
public CustomToStringStyle() {
super();
this.setUseClassName(true);
this.setUseIdentityHashCode(false);
this.setContentStart(SystemUtils.LINE_SEPARATOR + "[");
this.setFieldSeparator(SystemUtils.LINE_SEPARATOR + "");
this.setFieldSeparatorAtStart(true);
this.setContentEnd(SystemUtils.LINE_SEPARATOR + "]");
this.setUseShortClassName(true);
}
/**
* Override the append() method to skip fields that start with "_".In this
* application, Axis generates some fields using this prefix that we don't want to include
* in the log files.
*/
@Override
public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {
if (fieldName != null && !fieldName.startsWith("_")) {
super.append(buffer, fieldName, value, fullDetail);
}
}
/**
* Ensure Singleton after serialization
*
* @return the singleton
*/
private Object readResolve() {
return ApplicationToStringStyle.APP_TO_STRING_STYLE;
}
}   
}
 
public class Fruit {
private String name = "apple";
private String size = "3";
private String price = "$40";
public String toString() {
return ReflectionToStringBuilder.toString(this, ApplicationToStringStyle.APP_TO_STRING_STYLE);
}
}
  
 



  HttpClient


  The Commons HttpClient project used to be a part of Commons, but is now part of
Apache HttpComponents
-
see Jakarta Commons
HttpClient

  用于http有关的连接,包括ssl等。
  Notice that we go
through the entire process regardless of whether the server returned an error or
not. This is important because HTTP 1.1 allows multiple requests
to use the same
connection by simply sending the requests one after the other.
Obviously, if we
don't read the entire response to the first request, the left over data will get
in the way of the second response. HttpClient
tries to handle this but
to avoid problems it is important to always release the connection.
  基本http get访问


package commons.httpclient;
import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class Test {
public static void main(String[] args) throws HttpException, IOException {
//1. Create an instance of HttpClient.
HttpClient client = new HttpClient();
//2.
//Create an instance of one of the methods (GetMethod in this case).
//The URL to connect to is passed in to the the method constructor.
GetMethod method = new GetMethod("http://www.baidu.com/");
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
//3.Tell HttpClient to execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
//4.Read the response.
String reponse = method.getResponseBodyAsString();
//5.Release the connection.
method.releaseConnection();
//6.Deal with the response.
System.out.println(reponse);
}
}
页: [1]
查看完整版本: apache-commons 工具包学习