Jakarta-Common-on experience BeanUtils

  Abstract: Jakarta-Common-on experience BeanUtils 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> I. OVERVIEW 
  First saw BeanUtils package, in Struts projects, Struts as a tool to use, more functional, Lane estimated the stronger, moved to the Common projects on the bar. 
  <table Width="676" border="0"> <tr> <td width="397"> BeanUtils a total of four package: 
  Org.apache.commons.beanutils 
  Org.apache.commons.beanutils.converters 
  Org.apache.commons.beanutils.locale 
  Org.apache.commons.beanutils.locale.converters 

  After three packages are mainly used for data conversion, centering on a Converter interface There is only one way: 

  Java.lang.Object convert (java.lang.Class type, java.lang.Object value) 

  For a value will be converted into another type of type Object.    In some automation applications should be used. 

  Here is not to comment on future interest, or find it useful, and look again.    Here to talk about a package. 

  Second, the Bean test 
  At the beginning of all the tests before, I wrote a simple Bean to the test, the code below: 
  Package test.jakarta.commons.beanutils; </ td> <td width="269" align="right" valign="top"> </ td> </ tr> </ table> 
  (Public class Month 
  Private int value; 
  Private String name; 
  Private int [] days 11,22,33,44,55 = (); 

  Public Month (int v, String n) ( 
  Value = v; 
  Name = n; 
  ) 

  Public String getName () ( 
  Return name; 
  ) 

  Public int getValue () ( 
  Return value; 
  ) 

  Public void setName (String name) ( 
  This.name = name; 
  ) 

  Public void setValue (int value) ( 
  This.value = value; 
  ) 

  Public String toString () ( 
  Return value +"("+ name +")"; 
  ) 

  Public int [] getDays () ( 
  Return days; 
  ) 

  Public void setDays (int is []) ( 
  = Days is; 
  ) 

  ) 

  Third, BeanUtils 
  This is a major application of the Util Bean (Oh, this explanation is no bar), the following are a few examples of ways 

  / / Static java.util.Map describe (java.lang.Object bean) 
  / / This method returns an Object-readable all the attributes and attribute name / attribute values into a Map, another 
  / / Called a class attributes, the attribute value is the Object class name, the class is in fact an attribute java.lang.Object 
  New Month Month month = (1, "Jan"); 

  Try ( 
  Map map = BeanUtils.describe (month); 
  Set keySet = map.keySet (); 
  For (Iterator iter = keySet.iterator (); iter.hasNext ()) ( 
  Object element = (Object) iter.next (); 
  System.out.println ( "KeyClass:" + element.getClass (). GetName ()); 
  System.out.println ( "ValueClass:" + map.get (element). GetClass (). GetName ()); 
  System.out.print (element + "\ t"); 
  System.out.print (map.get (element)); 
  System.out.println (); 
  ) 
  ) Catch (IllegalAccessException e) ( 
  E.printStackTrace (); 
  ) Catch (InvocationTargetException e) ( 
  E.printStackTrace (); 
  ) Catch (NoSuchMethodException e) ( 
  E.printStackTrace (); 
  ) 
  Output: 

  C: \ java> java Month 
  KeyClass: java.lang.String 
  ValueClass: java.lang.String 
  11 days 
  KeyClass: java.lang.String 
  ValueClass: java.lang.String 
  Value 1 
  KeyClass: java.lang.String 
  ValueClass: java.lang.String 
  Class class Month 
  KeyClass: java.lang.String 
  ValueClass: java.lang.String 
  Name Jan 

  C: \ java> 
  Map noted that all the key / value are String, regardless of the actual object is the value of the number. 
  This also corresponds with static void populate (java.lang.Object bean, java.util.Map properties) will be used just to describe the Map to assemble into an object. 


  Look at this section of code 
  CAO Xiao Gang may recall that, in order to take an object property uncertain, indeed spent a lot of time, 
  Little difficulty, but to be 100% correct, and still need to pay a lot of energy. 
  / / Static java.lang.String getProperty (java.lang.Object bean, java.lang.String name) 
  New Month Month month = (1, "Jan"); 

  Try ( 
  System.out.println (BeanUtils.getProperty (month, "value")); 
  ) Catch (Exception e) ( 
  E.printStackTrace (); 
  ) 
  / / Output: 1. 

  And there are similar getProperty getIndexedProperty, getMappedProperty, 
  To getIndexedProperty example: 
  New Month Month month = (1, "Jan"); 

  Try ( 
  System.out.println (BeanUtils.getIndexedProperty (month, "days", 1)); 
  System.out.println (BeanUtils.getIndexedProperty (month, "days [1 ]")); 
  ) Catch (Exception e) ( 
  E.printStackTrace (); 
  ) 
  These two calls are the same. 


  BeanUtils also in a way: 
  Static void copyProperties (java.lang.Object dest, java.lang.Object orig) 
  It is really useful, but also remember that the struts are copyProperties flying in, I even wonder if the entire BeanUtils initially because this method is not only needs to write them. 
  It will target properties in the orig copied to the dest of work. 


  4. PropertyUtils 
  BeanUtils this category and class in many ways are the same parameters, but the return value different. 
  BeanUtils focus on the "Bean", the return value is usually String, and PropertyUtils focus on attributes, and its return value is usually Object. 


  5. ConstructorUtils 
  This category is divided into two main ways: one is by construction method is to create an object. 
  In fact most of the time by construction method is intended to create object, here only tell us about object creation. 
  / / Static java.lang.Object ConstructorUtils.invokeConstructor 
  / / (Java.lang.Class klass, java.lang.Object [] args) 
  / / According to a java.lang.Class construction method and the corresponding parameters to create an object. 
  Object obj = ConstructorUtils.invokeConstructor (Month.class, (new Integer (1), "Jan")); 
  Month month = (Month) obj; 
  Try ( 
  System.out.println (BeanUtils.getProperty (month, "value")); 
  ) Catch (Exception e) ( 
  E.printStackTrace (); 
  ) 
  Output that construction method call is a success. 
  If you need mandatory designated constructor parameter types, can call: 
  Object args [] = (new Integer (1), "Jan"); 
  Class [] = (int.class argsType, String.class); 
  Object obj; 
  Obj = ConstructorUtils.invokeExactConstructor (Month.class, args, argsType); 
  Month month = (Month) obj; 
  System.out.println (BeanUtils.getProperty (month, "value")); 
  ArgsType designated parameter type. 


  6. ConstructorUtils Create Object there is a residual method: invokeExactConstructor the method more stringent requirements on the parameters, transfer into must be in strict conformity with the parameters of the construction method of the list of parameters. 
  For example: 
  Object args [] = (new Integer (1), "Jan"); 
  Class [] = (int.class argsType, String.class); 
  Object obj; 
  / / Below this call will not succeed because args [0] types Integer, and not int 
  / / Obj = ConstructorUtils.invokeExactConstructor (Month.class, args); 

  / / This one can, because argsType designated types. 
  Obj = ConstructorUtils.invokeExactConstructor (Month.class, args, argsType); 
  Month month = (Month) obj; 
  System.out.println (BeanUtils.getProperty (month, "value")); 


  7. MethodUtils 
  And ConstructorUtils similar, but invoked, usually need to specify the parameters of a method name. 

  8. DynaClass / DynaBean 
  BeanUtils This seems to be the most interesting part of a very simple, simple to look at the interface of these two methods do not understand why these two interface to design.    But after that ResultSetDynaClass, understand.    Below are the java doc in the code: 
  ResultSet rs = …; 
  ResultSetDynaClass rsdc = new ResultSetDynaClass (rs); 
  Iterator rows = rsdc.iterator (); 
  While (rows.hasNext ()) ( 
  DynaBean row = (DynaBean) rows.next (); 
  … Process this row … 
  ) 
  Rs.close (); 
  This is a ResultSet original packaging, ResultSetDynaClass realized DynaClass its iterator method returns an ResultSetIterator, it is realized DynaBean interface. 
  Will receive a DynaBean, we can use 
  DynaBean row = (DynaBean) rows.next (); 
  System.out.println (row.get ( "field1")); / / field1 is one of the name of a field 

  Another category RowSetDynaClass look at the use, under the code n: 
  String driver = "com.mysql.jdbc.Driver"; 
  String url = "jdbc: mysql: / / localhost/2hu? UseUnicode = = true & characterEncoding GBK"; 
  String username = "root"; 
  String password = ""; 

  Java.sql.Connection con = null; 
  PreparedStatement ps = null; 
  ResultSet rs = null; 
  Try ( 
  Class.forName (driver). NewInstance (); 
  Con = DriverManager.getConnection (url); 
  Ps = con.prepareStatement ( "select * from forumlist"); 
  Rs = ps.executeQuery (); 
  / / Print to first for the results of testing behind. 
  While (rs.next ()) ( 
  System.out.println (rs.getString ( "name")); 
  ) 
  Rs.beforeFirst ();// beforeFirst here must be used, because the only RowSetDynaClass rolling forward from the current position 

  RowSetDynaClass rsdc = new RowSetDynaClass (rs); 
  Rs.close (); 
  Ps.close (); 
  List rows = rsdc.getRows ();// return to a standard List, storage is DynaBean 
  For (int i = 0; i    DynaBean b = (DynaBean) rows.get (i); 
  System.out.println (b.get ( "name")); 
  ) 
  ) Catch (Exception e) ( 
  E.printStackTrace (); 
  ) 
  Finally ( 
  Try ( 
  Con.close (); 
  ) Catch (Exception e) ( 
  ) 
  ) 

  Is not very interesting?    Packaging, a ResultSet data, the price of memory occupied.    If a table with 100,000 records, rsdc.getRows () will return 100,000 records.    @ @ 

  It must be noted that ResultSetDynaClass RowSetDynaClass and the difference between: 
  1, is based on the Iterator ResultSetDynaClass, only a return to a record, and is based on RowSetDynaClass List, a one-time return of all the records.    Direct impact on the comparison of data for a long time ResultSetDynaClass would be more rapid, and ResultSet RowSetDynaClass need to have all the data in read out (and stored in its internal), will take up too much memory, and speed will be slower. 
  2, ResultSetDynaClass a deal only with a record, in the complete processing before ResultSet not closed. 
  3, ResultSetIterator the next () method returns the DynaBean is at a fixed its internal 
  Object, in each next (), the internal value will be changed.    Their purpose in doing so is saving memory, if you need to preserve every 
  DynaBean, generated on the need to create another DynaBean, and data replication past, java doc Below is the code: 
  ArrayList results = new ArrayList (); / / To hold copied list 
  ResultSetDynaClass rsdc = …; 
  DynaProperty properties [] = rsdc.getDynaProperties (); 
  BasicDynaClass bdc = 
  New BasicDynaClass ( "foo", BasicDynaBean.class, rsdc.getDynaProperties ()); 
  Iterator rows = rsdc.iterator (); 
  While (rows.hasNext ()) ( 
  DynaBean oldRow = (DynaBean) rows.next (); 
  DynaBean newRow = bdc.newInstance (); 
  PropertyUtils.copyProperties (newRow, oldRow); 
  Results.add (newRow); 
  ) 

  In fact DynaClass / DynaBean can be used in many places, storage of various types of data.    Want to own it.    Hei hei. 


  9, since the definition of CustomRowSetDynaClass 
  RowSetDynaClass wrote two years ago with a goal of the same category, but more than one function, paging, data need only take, 
  This will reduce memory footprint. 

  Look at the section of code: 
  String driver = "com.mysql.jdbc.Driver"; 
  String url = "jdbc: mysql: / / localhost/2hu? UseUnicode = = true & characterEncoding GBK"; 
  String username = "root"; 
  String password = ""; 

  Java.sql.Connection con = null; 
  PreparedStatement ps = null; 
  ResultSet rs = null; 
  Try ( 
  Class.forName (driver). NewInstance (); 
  Con = DriverManager.getConnection (url); 
  Ps = con.prepareStatement ( "select * from forumlist order by name"); 
  Rs = ps.executeQuery (); 
  / * 
  While (rs.next ()) ( 
  System.out.println (rs.getString ( "name")); 
  ) 
  Rs.beforeFirst (); 
  * / 

  / / The second parameter that the first few pages, a third of the size of that page 
  CustomRowSetDynaClass rsdc = new CustomRowSetDynaClass (rs, 2, 5); 
  / / RowSetDynaClass rsdc = new RowSetDynaClass (rs); 
  Rs.close (); 
  Ps.close (); 
  List rows = rsdc.getRows (); 
  For (int i = 0; i    DynaBean b = (DynaBean) rows.get (i); 
  System.out.println (b.get ( "name")); 
  ) 
  ) Catch (Exception e) ( 
  E.printStackTrace (); 
  ) 
  Finally ( 
  Try ( 
  Con.close (); 
  ) Catch (Exception e) ( 
  ) 
  ) 
  Here used a CustomRowSetDynaClass category, construction method has been added to page and pageSize two parameters, so that regardless of the number of database records, most of the records from pageSize, if pageSize ==- 1, the same functions and RowSetDynaClass.    </ Td> </ tr> <tr> 

  ↑ Back 

Application of the use of the web log tool log4J

  Abstract: In the web application tools used in the log log4J 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> Log4J Jakarta is under an open source code component, with Log4J, we can use custom the format of the debug information and log information to the output of one or more areas in need.    Web applications in general use of a specialized Log4J Servlet to complete the configuration, and to ensure that the web.xml configuration, the other in the Servlet Servlet before, in order to call in the Servlet and jsp.    Below is the servlet, the code below: 
  <table Width="685" height="35" border="0"> <tr> <td width="399"> package example; 
  Import org.apache.log4j .*; 
  Import javax.servlet.http.HttpServlet; 
  Import javax.servlet.http.HttpServletRequest; 
  Import javax.servlet.http.HttpServletResponse; 

  Public class Log4jInit extends HttpServlet ( 
  Public void init () ( 
  String prefix = getServletContext (). GetRealPath ("/"); 
  String file = getInitParameter ( "log4j ");// configuration file location 
  If (file! = Null) ( 
  PropertyConfigurator.configure (prefix + file); 
  ) 
  ) 

  Public void doGet (HttpServletRequest req, HttpServletResponse res) 
  () 
  ) </ Td> <td width="275"> </ td> </ tr> </ table> 
  In this servlet configure web.xml: 

………..
  Servlet> 
  Log4j-init 
  Example.Log4jInit 

  Log4j 

WEB-INF/log4j.properties

  A 

………..


  Log4J used to configure the properties of documents: 
  Log4j.rootLogger = debug, A1, R 
  Log4j.appender.A1 = org.apache.log4j.ConsoleAppender 
  Log4j.appender.A1.layout = org.apache.log4j.PatternLayout 
  Log4j.appender.A1.layout.ConversionPattern =% d (-yyyy-MM-dd HH: mm: ss) [% c] - [% p]% m% n 
  Log4j.appender.R = org.apache.log4j.RollingFileAppender 
  Log4j.appender.R.File = cwblog4j.log 
  Log4j.appender.R.MaxFileSize = 100KB 
  Log4j.appender.R.MaxBackupIndex = 1 
  Log4j.appender.R.layout = org.apache.log4j.PatternLayout 
  Log4j.appender.R.layout.ConversionPattern t =% p% c% -% m% n 

  This configuration file specified two output sources A1 and R.    The former log information output to the console, which is a Web log files.    The largest file is 100 KB, when a log file reaches the maximum size, Log4J automatically example.log example.log.1 to rename, and then the rebuilding of a new example.log documents were rotate. 

  Test documents: 
  <% @ Page contentType = "text / html; charset = GB2312"%> 
  <% @ Page import = "org.apache.log4j .*"%> 
<%
  Logger logger = Logger.getLogger ( "test.jsp"); 
  Logger.debug ( "befor say hi"); 
%>

Hi


  <% Logger.info ( "after say hi ");%> 

  On the server, $ TOMCAT_HOME/log4j.log document that the following information: 
  DEBUG Thread-5 testlog4j.jsp - befor say hi 
  INFO Thread-5 testlog4j.jsp - after say hi 
  In the $ TOMCAT_HOME / logs / stdout.log the final document has the following output. 
  Information: Server startup in 5678 ms 
  2004-07-07 09:54:05 [testlog4j.jsp] - [DEBUG] befor say hi 
  2004-07-07 09:54:05 [testlog4j.jsp] - [INFO] after say hi </ td> </ tr> <tr> 

  ↑ Back 

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 

Validation powerful components apache Jakarta commons-validat

  Abstract: strong validation component apache Jakarta commons-validat 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="672" border="0"> <tr> <td width = " 392 "> 
  Validation powerful components apache Jakarta commons-validator 

  ↑ Back 

Lucene index page for examples

  Abstract: Lucene index page for examples 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="269" height="86" align="center" valign="top"> </ td> <td width="415" valign="top"> a key input word lucene.html 

<body>
  <form Name="form1" method="post" action="search.jsp"> 
  Enter keyword: <input type = "text" name = "keyword"> 
  <input Type="submit" name="Submit" value="提交"> 
  </ Form> 
  </ Body> 

  Drawings: 

  </ Td> </ tr> <tr> <td height="20" colspan="2"> 
  Second, the search and displays the results search.jsp <% @ page contentType = "text / html; gb2312 charset ="%> 
  <% @ Page import = "java.util .*"%> 
  <% @ Page import = "java.text.SimpleDateFormat"%> 
  <% @ Page import = "org.apache.lucene.analysis.standard.StandardAnalyzer"%> 
  <% @ Page import = "org.apache.lucene.index.IndexReader"%> 
  <% @ Page import = "org.apache.lucene.document.Document"%> 
  <% @ Page import = "org.apache.lucene.search.IndexSearcher"%> 
  <% @ Page import = "org.apache.lucene.search.Hits"%> 
  <% @ Page import = "org.apache.lucene.search.Query"%> 
  <% @ Page import = "page.Pagination"%> <% @ page import = "org.apache.lucene.queryParser.QueryParser"%> 
  <% @ Page import = "org.apache.lucene.analysis.Analyzer"%> 
<%

  String queryString = request.getParameter ( "keyword"); if (queryString == null | | queryString.length () == 0) (out.println ( "Search keywords can not be empty");) else (= new queryString String (queryString.getBytes ( "ISO8859_1")); String indexPath = getServletContext (). getRealPath ("/")+" index "; boolean error = false; Document doc; IndexSearcher searcher = null; Query query = null; Hits hits = null; try (searcher = new IndexSearcher (IndexReader.open (indexPath));) catch (Exception e) (out.print ( "did not find index files!"); out.print (e.getMessage ()); error = true;) if (error == false) (Analyzer analyzer = new StandardAnalyzer (); query try (= QueryParser.parse (queryString, "Article_name" analyzer);) catch (Exception e) (out.print (e. getMessage ()); error = true;)) if (error == false & searcher! = null) (hits = searcher.search (query) if (hits.length () == 0) (out.print ( " Sorry! did not find the resources you need. "); error = true;)) if (error == false & searcher! = null) (out.print (" Search keywords: "+ + queryString" "); / / Pagination is the downloading, and we need to pass along a vector, you can change, and this is not done two times Vector list = new Vector (); for (int i = 0; i <hits.length (); i + +) (doc = hits.doc (i); list.add (doc);) out.print ( "find resources"); Pagination pagination = null; String pageNumber = request.getParameter ( "pageNumber"); int showItemNumber = 10; if (pageNumber == null) (pageNumber = "1";) String HTML = ""; if (list! = null & list.size ()> 0) (pagination = new Pagination (); pagination.setPageNumber (Integer.parseInt (pageNumber)); pagination.setShowItemNumber (showItemNumber); pagination.setVisitPageURL ( "search.jsp? keyword =" + queryString); list = (Vector) pagination.interceptListByStarItemNumber (list) for (int i = 0; i <list . size (); i + +) (doc = (Document) list.get (i); String A_id = doc.get ( "Article_id"); String doctitle = doc.get ( "Article_name"); String url = doc.get ( "File_name ")+"? id =" + A_id; out.print ( "<a href = 'http://127.0.0.1:8080/cwbwebhome/" + url +"'>( ★) "+ + doctitle" " );) = pagination.buildHTML HTML ( "600"); out.print (HTML);))) 

  Figure effect: 

  Thirdly, a paging class Pagination.java (download) 

  </ Td> </ tr> </ table> </ td> </ tr> <tr> 

  ↑ Back 

How do you prepare a Shoubashoujiao Applet example of animation

  Abstract: How do you prepare a Shoubashoujiao Applet example of animation 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="665" border="0"> <tr> <td width = " 385 "> Applet is in the browser running small programs, Java Applet is from the start sweeping the world.    Applet through the preparation of this, we can learn knowledge as follows: 

  1, JApplet Applet and the main interface 

  2, the image loading and the use of MediaTracker 

  3, and the use of multiple threads threaded direct communication 

  4, Thread.join () method of use 

  5, the use of volatile keyword </ td> <td width="270"> 
  </ Td> </ tr> </ table>? 
  Animation is a major part of the Applet from codebase a group picture in the paper read, and then every one second rotation of a show.    Code as follows: 

  <table CellSpacing=0 borderColorDark=#ffffff cellPadding=2 width=400 align=center borderColorLight=black border=1> <tr> <td class=code style="FONT-SIZE: 9pt" bgColor=#e6e6e6> 

  Import javax.swing.JApplet; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; public class Animate extends JApplet (/ / photos private static final int NUM_OF_PIC = 4; int count; Image pics []; TimerThread timer; public void init () (count = 1; pics = new Image [NUM_OF_PIC]; MediaTracker tracker = new MediaTracker (this) for (int i = 0; i 

{

//将图片按照0,1,…,NUM_OF_PIC -1,

放置在目录中,格式为.jpg

pics[i] = getImage(getCodeBase(),

new Integer(i).toString()+”.jpg”);

tracker.addImage(pics[i], 0);

}

tracker.checkAll(true);

}

public void start()

{

timer = new TimerThread(this, 1000);

timer.start();

}

public void stop()

{

timer.shouldRun = false;

try {

timer.join();

//等待timer线程退出

} catch (InterruptedException e)

{

};

}

public void paint(Graphics g)

{

g.drawImage(pics[count++], 0, 0, null);

if(count == NUM_OF_PIC) count = 0;

}

}   </ Td> </ tr> </ table> 



  Animation control by a special thread TimerThread for processing. 

  <table CellSpacing=0 borderColorDark=#ffffff cellPadding=2 width=400 align=center borderColorLight=black border=1> <tr> <td class=code style="FONT-SIZE: 9pt" bgColor=#e6e6e6> 

  Import java.awt.Component; public class TimerThread extends Thread (Component comp; int timediff; / / shouldRun statement for the volatile volatile boolean shouldRun; public TimerThread (Component comp, int timediff) (super ( "TimerThread (" + + timediff "millseconds "); this.comp = comp; this.timediff = timediff; shouldRun = true;) public void run () (while (shouldRun) (try (comp.repaint (); sleep (timediff);) catch (Exception e) ())))    </ Td> </ tr> </ table> 



  The use of MediaTracker 

  Applet obtained in an image file can be called the Applet getImage () method.    But getImage method will be called immediately after the return, if at once using the Image getImage acquisition target, and then the Image object and not really loading or loading completed. 

  Therefore, we in the use of image files, the use of the MediaTracker java.awt package tracking an Image object loading, can guarantee that all pictures are finished loading.    MediaTracker need to use the following three steps: 

  1, an instance of MediaTracker, attention to the picture to show the object as a parameter Component imported. 

  <table CellSpacing=0 borderColorDark=#ffffff cellPadding=2 width=400 align=center borderColorLight=black border=1> <tr> <td class=code style="FONT-SIZE: 9pt" bgColor=#e6e6e6> 

  MediaTracker tracker = new MediaTracker (this);    </ Td> </ tr> </ table> 



  2, will be carrying the Image Object joined MediaTracker 

  <table CellSpacing=0 borderColorDark=#ffffff cellPadding=2 width=400 align=center borderColorLight=black border=1> <tr> <td class=code style="FONT-SIZE: 9pt" bgColor=#e6e6e6> 

  Pics [i] = getImage (getCodeBase (), new Integer (i). ToString ()+". jpg "); tracker.addImage (pics [i], 0);    </ Td> </ tr> </ table> 



  3, call the checkAll MediaTracker (), waiting for the loading process has ended. 

  <table CellSpacing=0 borderColorDark=#ffffff cellPadding=2 width=400 align=center borderColorLight=black border=1> <tr> <td class=code style="FONT-SIZE: 9pt" bgColor=#e6e6e6> 

  Tracker.checkAll (true);    </ Td> </ tr> </ table> 



  Thread.join () use 

  We stop in the Animate method join in the call timer () method will timer thread connection (join) to the current thread, the thread will wait for the timer will be consistent thread running after timer.join () method will return. 

  If the current thread waiting for the timer to return to the process of other thread was interrupted, then the current thread will be dished out InterruptedException.    If we do not use the Thread join method can be implemented only through polling timer thread state judge: 

  <table CellSpacing=0 borderColorDark=#ffffff cellPadding=2 width=400 align=center borderColorLight=black border=1> <tr> <td class=code style="FONT-SIZE: 9pt" bgColor=#e6e6e6> 

  While (timer.isAlive ()) (try (Thread.sleep (50);) catch (InterruptedException e) ())    </ Td> </ tr> </ table> 



  Clearly this approach and use join method, cpu resources will be wasted, but also a waste of time for some, because the current thread from time to time to make enquiries timer thread whether it is still viable, may timer thread has already ended. However, the current thread or to wait for some time before we can to monitor it. 

  On the volatile 

  We know that, in Java value of the variable settings operation, in addition to long and double types of variables, are atomic operation, that is, the variable value of the simple read and write operations without the need for synchronization.    This JVM 1.2, Java memory model of achieving always read from the main variable, is the need for special attention. 

  With JVM mature and optimization, and now in a multi-threaded environment the use of volatile keyword become very important.    In the current Java memory model, the thread can be stored in local memory variables (such as machines register), rather than directly in the main deposit and write. 

  This may result in the main thread of a revision in the value of a variable, and the other threads also continue to use it in the register in the value of the variable copy, causing data inconsistencies. 

  To solve this problem, just like in the proceedings of the case, the variable declaration for the volatile (instability) can be, which instructed JVM, this variable is unstable, it has to use each of the main to read.    Generally speaking, multi-tasking environment under the mandate of the signs should be shared and modified volatile. 

  Function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document . getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> </ tr> <tr> 

  ↑ Back 

Bitmap sort

  Abstract: Bitmap sort 

  </ Td> </ tr> <tr> <td width="504" height="35" valign="top" class="ArticleTeitle"> 

  1. Bitmap understanding we all understand that in the bitmap graphics format storage is actually a unit of a small box, a grid of vertical and horizontal grid an accumulation of every color represents a small box, of course, If the black-and-white color map of the two is even more simple, need only be a bit-that this is our computer data storage format is similar to the memory of the grid also like a bit of a crisscross grid from because it is inspired, we found that one bit of the same order as a line-up, and very strict order, if we can through a data conversion methods (logic) to orderly and bit mapping of the case, Then we follow the order of bit output it is not the sort of data collection? 

  2. Concept Index 
  Through the above description, it is easy to think of one thing - Index.    Index for the use of our database undoubtedly very important, so many huge volume of data on a single table in the performance of fully rely on it. Bitmap it and the similarity is: If we put each row of data as a unit of data, then the index can be seen as a transformation of the way through a data mapping to a storage space, if the data sequence and the sequence Index is the same, then when we orderly visit of the storage space, have been orderly data sets. course many cases, the data are part of index, however, Oracle function in the concept of indexing, it full expression to the way of such a transformation and mapping of the relationship. 

  3. Sort of a clever way 
  Bitmap inseparable from nature and sequencing, as it is the most orderly nature of the carrier. There is a question as follows: in a city of all existing seven-digit telephone numbers, we are required output accordingly. 

  Analysis: the goal - is to sort the problem of the digital -7-digit conditions, simple as 0000000-9999999 
  The environment - a city telephone number, a high number, most likely closer to 10 million, any sort of time method 
  And space costs are great. 
  Lenovo: Seize the significance of the issue, the telephone number on the issue in a realistic sense is that the telephone number in the telephone number on the set of seats, and a more feature is the telephone number itself response to such a position information and if we the establishment of 10 million bit of each one said that the position on the existence of telephone numbers (for the existence of a set, 0 - does not exist), in itself, is the phone number, then we traversal of all, the output of for - a telephone number, the telephone number is sort? clever of: because we use the meaning of the data itself! 

  Description: 
  1. Bit of the whole group initialized to 0 (000 billion …… 00000000) 

  2. Read all the numbers, the corresponding numbers in the home on a Bit 

  3. Circle: for (int i = 0; i <10000000; + + i) (/ / i is the telephone number if (bit [i] == 1) (print i;) 

  4. Extended bitmap itself needs some sort of environment, as described above in large quantities, and the number and location of the serial number and the significance of anastomosis. Course, we see the sort of bitmap efficient and ingenious of the best, we sort of data, can think about: our data analysis feature is very important, any problems are likely to find breakthrough features from the analysis, we consider the data or not there is a transformation approach allows him to this mapping kind of relationship of the figures. structure is the process of your creation. 

  5. Examples (abbreviated) to Cao, 2005, the method from <programming Abas> 

  This paper quoted a circular Address: http://blog.csdn.net/jiziba/services/trackbacks/348686.aspx 

  Function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document . getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> <td width="180" align="center" valign="top" class="ArticleTeitle"> 
  </ Td> </ tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle"> 

  ↑ Back 

LOG4J Quick Start and reference materials

  Abstract: LOG4J Quick Start and reference materials 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="282" height="86" align="center" valign="top"> </ td> <td width="402" valign="top"> 

  Original Source: http://www.vipan.com/ 
  Translator: White drunk ~ 

  The first part, the Quick Start 

  First, you will need to download the software and LOG4J to decompress them log4j.jar. In your application procedures contained in the classpath JAR file, you can simply copy this file to the JDK% java_home% \ lib \ ext directory. 
  End in for more work, you can save it to the following code named TestLogging.java: 
##############################
  Import org.apache.log4j .*; 

  / / How to use log4j 
  (Public class TestLogging 

  / / Initialize a logging category. Here, we get THE ROOT CATEGORY 

  </ Td> </ tr> </ table> 

  / / Static Category cat = Category.getRoot (); 
  / / Or, get a custom category 
  Static Category cat = Category.getInstance (TestLogging.class.getName ()); 

  / / From here on, log away! Methods are: cat.debug (your_message_string) 
  / / Cat.info (…), cat.warn (…), cat.error (…), cat.fatal Sort 

  Public static void main (String args []) ( 
  / / Try a few logging methods 
  Cat.debug ( "Start of main ()"); 
  Cat.info ( "Just testing a log message with priority set to INFO"); 
  Cat.warn ( "Just testing a log message with priority set to WARN"); 
  Cat.error ( "Just testing a log message with priority set to ERROR"); 
  Cat.fatal ( "Just testing a log message with priority set to FATAL"); 

  / / Alternate but INCONVENIENT form 
  Cat.log (Priority.DEBUG, "Calling init ()"); 

  New TestLogging (). Init (); 
  ) 

  Public void init () ( 
  Java.util.Properties prop = System.getProperties (); 
  Java.util.Enumeration enum = prop.propertyNames (); 

  Cat.info ("*** System Environment As Seen By Java ***"); 
  Cat.debug ("*** Format: PROPERTY VALUE = ***"); 

  While (enum.hasMoreElements ()) ( 
  String key = (String) enum.nextElement (); 
  Cat.info (key + "=" + System.getProperty (key)); 
  ) 
  ) 

  ) 

  ################################################## ########## 
  Log4J default can be recorded under five levels (from low to high) to log messages. 
  1) debug 
  2) info 
  3) warn 
  4) error 
  5) fatal 

  TestLoggin.class directory in the preservation of a name for log4j.properties file, as follows.    By default, when you use code getRoot () or getInstance ( "category_name"), Log4j applications will be in the classpath View of the document: 
############################################
  Log4j.rootCategory = DEBUG, dest1 
  Log4j.appender.dest1 = org.apache.log4j.ConsoleAppender 
  Log4j.appender.dest1.layout = org.apache.log4j.PatternLayout 
############################################
  ConsoleAppender designated console is attached, which log messages will be output to the console, and the news PatternLayout is designated output format, the default format for% m% n,% m is the designated news content, designated% n is the operating system platform on the newline, it's more similar to the C language output control sentence. 
  Now you can compile and run TestLogging.java, you will receive the following output: 

  Start of main () 
  Just testing a log message with priority set to INFO 
  Just testing a log message with priority set to WARN 
  Just testing a log message with priority set to ERROR 
  Just testing a log message with priority set to FATAL 
  Calling init () 
  *** System Environment As Seen By Java *** 
  *** Format: PROPERTY VALUE = *** 
  Java.runtime.name = Java (TM) 2 Runtime Environment, Standard Edition 
  Sun.boot.library.path = c: \ jdk1.3 \ jre \ bin 
  Java.vm.version = 1.3.0_02 
  Java.vm.vendor = Sun Microsystems Inc. 
  … And so on 

  If you want to print news such as the level of debug, info, error, it can log4j.properties file on the last line to add the following line: 
  Log4j.appender.dest1.layout.ConversionPattern =%-5p:% m% n 

  This will cover the default output format information% m% n,% p is the designated print news levels (info, and debug …, which is designated -5 five characters width - is the designated left-justified ),% m is the designated news content, designated% n is the newline operating system platform. 
  End as these work, the need to re-compile TestLogging.java again use TestLogg will not be the output of the following: 

  DEBUG: Start of main () 
  INFO: Just testing a log message with priority set to INFO 
  WARN: Just testing a log message with priority set to WARN 
  ERROR: Just testing a log message with priority set to ERROR 
  FATAL: Just testing a log message with priority set to FATAL 
  DEBUG: Calling init () 
  INFO: *** System Environment As Seen By Java *** 
  DEBUG: *** Format: PROPERTY VALUE = *** 
  INFO: java.runtime.name = Java (TM) 2 Runtime Environment, Standard Edition 
  INFO: sun.boot.library.path = c: \ jdk1.3 \ jre \ bin 
  INFO: java.vm.version = 1.3.0_02 
  INFO: java.vm.vendor = Sun Microsystems Inc. 
  … And so on 

  If you do not want the output log DEBUG and INFO message, can be amended "log4j.rotCategory = DEBUG, dest1": 
  Log4j.rootCategory = WARN, dest1 
  The document will tell Log4j Skip levels below WARN news output, that is to say if DEBUG, INFO-level information will not produce output, TestLogging.class running again by the following findings: 
####################
  WARN: Just testing a log message with priority set to WARN 
  ERROR: Just testing a log message with priority set to ERROR 
  FATAL: Just testing a log message with priority set to FATAL 
####################

  The second part Log4j explain 
  Log4j has three main components: category, and the layout of the annex. 
  In the proceedings, you can initialize a category called it and the various ways to log information will be recorded to the log string. 
  A category can be configured to output to multiple targets, and these targets log in Log4j framework known as Annex, the annex could include the console, text files, HTML files, XML documents-or even the Windows event log system , and can even be used as e-mail is sent.    These are all goals through log4j.properties file to configure the framework for the use Log4j terms of the procedures simply call similar to the info (), debug () method. 
  Annex-type can be ConsoleAppender, FileAppender, SMTPAppender, SocketAppender, NTEventLogAppender, SyslogAppender, JMSAppender, such as AsyncAppender and NullAppender.    Annex-type layout can be used (layout) to send a message to the target format before.    For example, the information will be formatted HTMLLayout as HTML. 
  Apart from the string can be recorded to the log file information, but also can record the date, time, message-level, class name, the source code line number, and method name, the name and other information thread, and the output of the specific needs of the Annex The layout manager to configure. 
  Category name is to distinguish between upper and lower case "." The separation of a string.    Under normal circumstances we normally use your_class_name.class.getName () to obtain a JAVA class name as a category name, for example testproj.util.test. 
  Each word in the category name is said to be an ancestor of the subsequent words and a parent of the immediately following word. This is important because Log4j has this concept of inheriting priorities and appenders from ancestors until overridden in a particular category. 
  One category is not the name of the root, it is like xml element of the document is that all category ancestors. 
  Use the following code to a root of the initial category or designated category. 
################
  Category cat = Category.getRoot (); 
  Category cat2 = Category.getInstance ( "your.category.name"); 
###################
  Representatives from the constant high-level meeting is to FATAL, ERROR, WARN, INFO and DEBUG can log4j.properties category specified in the respective levels, such as designated log4j.rootCategory = WARN, simple signifies that the root of this category called the procedure only WARN WARN record and more than news.    If there is no category for a specified default category, then the category will be from the category to succeed his father. 
  Category common type of log method: 
  Public void log (Priority p, Object message); 

  / / Convenient shortcuts to the generic logging method 
  Public void debug (Object message); 
  Public void info (Object message); 
  Public void warn (Object message); 
  Public void error (Object message); 
  Public void fatal (Object message); 

  Log4j only record levels and default levels equal to or higher level of information, such as the following code: 
  Category cat = Category.getRoot (); 
  Cat.setPriority (Priority.ERROR) / / set default levels for ERROR - 
  / / Later … 
  / / Cat.info ( "Started processing …"); / / this news will not be output, ERROR 
  Cat.error ( "User input is erroneous!"); / / News output, the same level 
  Cat.fatal ( "Cannot process user input. Program terminated!"); / / News output levels higher than the default level 

  The third part Log4j configuration 
  All configuration should be completed in log4j.properties file, and the document on the general application of the same directory. 
  In the log system, we must first configure log4j. Log4j means an increase in the allocation for the annex to Category 1 and Category for each provision of a Layout. 
  Category is between inheritance, but they log4j.properties document to the order is not fixed. 

  Example 1: 
  ################################################## ########### 
  # Log4j set up by the roots category is the default level DEBUG, A1 and use only for the Annex. 
  Log4j.rootCategory = DEBUG, A1 
  # A1 of the annex is set to annex for the console. 
  Log4j.appender.A1 = org.apache.log4j.ConsoleAppender 
  # Annex for the use of the layout is PatternLayout, that is the layout mode 
  Log4j.appender.A1.layout = org.apache.log4j.PatternLayout 
  # Annex A1-model is r% -4 [% t]%-5p% c% x -% m% n,% m string representatives news, the representative of newline% n,% by the beginning of the other representatives of characters meaning of the following text. 
  4r-log4j.appender.A1.layout.ConversionPattern =% [% t]%-5p% c% x -% m% n 
  ################################################## ############### 
  Example 2: 
  ################################################## ####### 
  # # # # Use two appenders, one to log to console, and another to log to a file 
  Log4j.rootCategory = debug, stdout, R 
  # Print only messages of priority WARN or higher for your category 
  Log4j.category.your.category.name = WARN 
  # Specifically inherit the priority level 
  # = INHERITED log4j.category.your.category.name 
  # # # # First appender writes to console 
  Log4j.appender.stdout = org.apache.log4j.ConsoleAppender 

  Log4j.appender.stdout.layout = org.apache.log4j.PatternLayout 
  # Pattern to output the caller's file name and line number. 
  Log4j.appender.stdout.layout.ConversionPattern =% 5p [% t] (% F: L%) -% m% n 
  # # # # Second appender writes to a file 
  Log4j.appender.R = org.apache.log4j.RollingFileAppender 
  Log4j.appender.R.File = example.log 
  # Control the maximum log file size 
  Log4j.appender.R.MaxFileSize = 100KB 
  # Archive log files (one backup file here) 
  Log4j.appender.R.MaxBackupIndex = 1 
  Log4j.appender.R.layout = org.apache.log4j.PatternLayout 
  Log4j.appender.R.layout.ConversionPattern t =% p% c% -% m% n 
  ################################################## ###### 

  Part IV Log4j useful Layout 
  The layout has some useful TTCCLayout, HTMLLayout, PatternLayout, SimpleLayout and XMLLayout. 
  PatternLayout overlooked and which SimpleLayout JAVA throwable interface derived from errors and Exceptions.HTMLLayout and XMLLayout deal with these anomalies. 
  SimpleLayout log contained in the output of the level of information, followed by "-" after a string of log messages.    For example: 
  DEBUG - Hello World Message 
  Patternlayout can output string to determine the mode of news output, string pattern similar to the model in the C language string.    For example, if usage patterns in the PatternLayout string "% r [% t]-5p% c% -% m% n" will output the following message: 
  176 [main] INFO org.foo.Bar-Located nearest gas station 
  Following the domain of the explanation for this: 
  1)% r output beginning of the process after the implementation of several microseconds 
  2)% t output the name of the current thread 
  3)%-5p news output level. 
  4)% c output category name 
  5) -% m s and is log information itself,% n is the newline. 
  In the current model can be embedded in the string you want to output any of the characters. 
  Patterns in the model are as follows: 
  % M: news itself 
  % P: the level of information 
  % R: From the beginning of the process to the current implementation of a log time at the interval (microsecond) 
  % C: output current log the movements of the category name.    For example: If the category is the name "abc", "% c (2)" will be exporting "bc." (2) means that the output "to the point of separating the name of the category after two components." If (n ) not, will be output as a whole category name. 
  % T: the name of the output current thread 
  % X: output associated with the current thread and the NDC (see detailed explanation below), especially as java servlets used such multi-client multi-threaded applications. 
  % N: output platform related newline. 
  %: Output a "%" characters 
  % D: log output produced when the date, of course, can be customized to fit the format of the date.    For example:% d (HH: mm: ss, SSSS% d) or (dd MMM yyyy HH: mm: ss, SSSS), if there is no designated behind the format will be the format of the output ISO8601. 
  % L: output location information, the equivalent% C.% M (% F:% L) combination. 
  % C: log messages generated at the output of the class name, if the category were "test.page.Class1"% C (1) said output category of "Class1"% C (2) exporting "page.Class1" and % C output is "test.page.Class1." 
  % M: output log messages generated when the method name 
  % F: output of log messages generated when the file name 
  % L: output lines of code 
  In the mode% and characters with Xiuchifu to control the minimum width, maximum width, and text alignment manner.    Such as: 
  1)% 20c: the name of the designated export category, the smallest width is 20, if the category's name is less than 20, then the default alignment right circumstances. 
  2)%-20c: the name of the designated export category, the smallest width is 20, if the category of the names of less than 20, "-" designated left-justified. 
  3)% .30 c: the name of the designated export category, the largest width is 30, if the names of more than 30 category, it would be more of the characters in the left Jiediao, but less than 30 so there will be no space. 
  4)% 20.30c: If the category is less than 20 names on the meeting spaces, and the right alignment, if their names longer than 30 characters, from the left cross Jiediao sold out of the characters. 
  4)% 20.30c: 

  Log4j in Annex V of the keys and related parameters 
  1.ConsoleAppender options 
  Threshold = WARN: log information specified minimum level of output. 
  ImmediateFlush = true: The default value is true, means that all information will be immediately output. 
  Target = System.err: The default circumstances: System.out designated console output 
  2.FileAppender options 
  Threshold = WARN: log information specified minimum level of output. 
  ImmediateFlush = true: The default value is true, means that all information will be immediately output. 
  File = mylog.txt: news output to a designated mylog.txt document. 
  Append = false: The default value is true, will be designated to document information, false designation refers to news coverage of the contents of the documents. 
  3.RollingFileAppender options 
  Threshold = WARN: log information specified minimum level of output. 
  ImmediateFlush = true: The default value is true, means that all information will be immediately output. 
  File = mylog.txt: news output to a designated mylog.txt document. 
  Append = false: The default value is true, will be designated to document information, false designation refers to news coverage of the contents of the documents. 
  MaxFileSize = 100KB: suffix can be KB, MB or GB. Arrived in the log file size, it will automatically scroll, will be moved to mylog.log.1 the contents of the original document. 
  MaxBackupIndex = 2: Designated rolling paper can produce the greatest number. 
  4.DailyRollingFileAppender options 
  Threshold = WARN: log information specified minimum level of output. 
  ImmediateFlush = true: The default value is true, means that all information will be immediately output. 
  File = mylog.txt: news output to a designated mylog.txt document. 
  Append = false: The default value is true, will be designated to document information, false designation refers to news coverage of the contents of the documents. 
  DatePattern = '.' Yyyy-ww: rolling a weekly paper, a new weekly produce the documents.    Of course, but you can also specify month, week, day, time and points.    That is the corresponding format are as follows: 
  1) '.' Yyyy-MM: Monthly 
  2) '.' Yyyy-ww: weekly 
  3) '.' Yyyy-MM-dd: daily 
  4) '.' Yyyy-MM-dd-a: twice a day 
  5) '.' Yyyy-MM-dd-HH: Hourly 
  6) '.' Yyyy-MM-dd-mm-HH: every minute 
  5.PatternLayout options 
  ConversionPattern =% m% n: specified format specified how the news. 
  6.HTMLLayout options 
  LocationInfo = true: The default value is false, the output file name and line java, 
  Title = my app file: The default value is Log4J Log Messages. 
  7.XMLLayout options 
  LocationInfo = true: The default value is false, the output of java to documents and 

  Part VI Log4j configuration Case 

  Part VI Log4j configuration Case 
  # = True log4j.debug 
  # = Fatal log4j.disable 
  # = False log4j.additivity.TestLogging 

  Log4j.rootCategory =, dest1 
  Log4j.category.TestLogging = DEBUG, dest1 
  Log4j.appender.dest1 = org.apache.log4j.ConsoleAppender 
  # Log4j.appender.dest1.layout = org.apache.log4j.SimpleLayout 
  Log4j.appender.dest1.layout = org.apache.log4j.PatternLayout 
  # Log4j.appender.dest1.layout.ConversionPattern =%-5p% l% x:% m% n 

  !———————-####### END OF PROPERTIES #######———- ————! 

  ################################################## ############################# 
  # Below I document in more detail how to write a log4j configuration file. # 
  # SELECTIVELY copy lines beginning with #, paste and uncomment them above. # 
  ################################################## ############################# 

  !————————————————- —————————-! 
  ! PLACE THIS FILE ANYWHERE IN CLASSPATH! 
  ! Appenders are additive by default.! 
  ! Priorities are inherited until overridden in a category.! 
  ! In, the value of the key can be defined as a system! 
  ! Property or in this file itself. System properties are searched first and! 
  ! Then this file.! 
  !————————————————- —————————-! 

  !————————————————- —————————-! 
  ! Configure log4j's operation at the meta level! 
  !————————————————- —————————-! 
  ! Observe log4j parsing this file 
  # = True log4j.debug 
  ! Set this to false for log4j to actually obey the log4j.disable property (next) 
  # = False log4j.disableOverride 
  ! Disable all logging in all categories for messages with priority equal to 
  ! Or lower than the one given here 
  # = INFO log4j.disable 

  !————————————————- —————————-! 
  ! Configure categories (loggers)! 
  !————————————————- —————————-! 

  ! ROOT CATEGORY (Usually sufficient to set this one only) 
  ! Here, logs messages with priority DEBUG (default) or higher 
  # = Log4j.rootCategory, dest1 
  ! Or, 
  # Log4j.rootCategory = debug, dest1, dest2 

  ! YOUR CATEGORIES (to customize logging per class / pkg / project / etc) 
  ! Here, overrides ancestor's priority and makes it WARN or higher for this cat. 
  # = WARN log4j.category.TestLogging, dest3 
  ! Or, 
  # Log4j.category.TestLogging = DEBUG, dest3 

  !——– DON'T DO THIS! APPENDERS ARE ADDITIVE BY DEFAULT !!!—————! 
  ! It will write the same log message TWICE to dest1. Once for root, then for! 
  ! This category.! 
  ! Log4j.category.TestLogging # = DEBUG, dest1, dest3! 
  ! If you DO NOT want additivity for this category, say so! 
  ! Log4j.additivity.TestLogging # = false! 
  !————————————————- —————————-! 

  !————————————————- —————————-! 
  ! Configure appenders (log destinations / targets) and their options! 
  !————————————————- —————————-! 

  ! WRITE TO CONSOLE (stdout or stderr) 
  # Log4j.appender.dest1 = org.apache.log4j.ConsoleAppender 
  # = True log4j.appender.dest1.ImmediateFlush 

  ! WRITE LOG TO A FILE, ROLL THE FILE AFTER SOME SIZE 
  # Log4j.appender.dest2 = org.apache.log4j.RollingFileAppender 
  ! This appender will only log messages with priority equal to or higher than 
  ! The one specified here 
  # = ERROR log4j.appender.dest2.Threshold 
  ! Specify the file name (gets substituted with its value) 
  # Log4j.appender.dest2.File = / log4j.log 
  ! Don't append, overwrite 
  # = False log4j.appender.dest2.Append 
  ! Control the maximum log file size 
  # Log4j.appender.dest2.MaxFileSize = 100KB 
  ! Keep backup file (s) (backups will be in filename.1, .2 etc.) 
  # Log4j.appender.dest2.MaxBackupIndex = 2 

  ! WRITE LOG TO A FILE, ROLL THE FILE EVERY WEEK 
  # Log4j.appender.dest3 = org.apache.log4j.DailyRollingFileAppender 
  ! Specify the file name 
  # Log4j.appender.dest3.File = log4TestLogging2.html 
  ! Control the maximum log file size 
  # Log4j.appender.dest3.MaxFileSize = 300KB 
  ! Rollover log file at the start of each week 
  # Log4j.appender.dest3.DatePattern = '.' Yyyy-ww 

  !————————————————- —————————-! 
  ! Configure appender layouts (log formats) and their options! 
  !————————————————- —————————-! 

  ! USE SIMPLE LOG FORMAT (eg INFO - your log message) 
  # Log4j.appender.dest1.layout = org.apache.log4j.SimpleLayout 

  ! USE AC PRINTF STYLE PATTERN TO FORMAT LOG MESSAGE 
  # Log4j.appender.dest1.layout = org.apache.log4j.PatternLayout 
  ! For a pattern layout, specify the pattern (Default is% m% n which is fastest) 
  # Log4j.appender.dest1.layout.ConversionPattern =%-5p:% m% n 
  ! Or, 
  Log4j.appender.dest1.layout.ConversionPattern =% #% 6.10r-5p [% t]% x (% F: L%) -% m% n 

  # Log4j.appender.dest2.layout = org.apache.log4j.PatternLayout 
  # Log4j.appender.dest2.layout.ConversionPattern = [ISO8601) (% d]% 6.6r% 5p [% t]% x (% F: L%) -% m% n 
  ! Or, (the pattern below will slow down your app) 
  # Log4j.appender.dest2.layout.ConversionPattern = [% d (yyyy-mm-dd hh: mm), 6.6r%]%-5p [% t]% x (% F: L%) -% m% n 

  ! FORMAT LOG MESSAGES IN THE FORM OF AN HTML TABLE 
  # Log4j.appender.dest3.layout = org.apache.log4j.HTMLLayout 
  ! Include Java file name and line number (Default is false) 
  # = True log4j.appender.dest3.layout.LocationInfo 
  ! Set 

  </ Td> </ tr> <tr> 

  ↑ Back 

A watermark to the picture

  Abstract: a watermark to the picture 

  </ Td> </ tr> <tr> <td width="543" height="35" valign="top" class="ArticleTeitle"> 
  Larger an image Figure 2 results: 

  Import java.awt .*; 
  Import java.io. *; 
  Import java.awt.image .*; 
  Import com.sun.image.codec.jpeg .*; 
  Import javax.imageio .*; 

  (Public class ImgBean_i 
  Public void ImgBean_i () ( 

  ) 

  Public void ImgYin (String Imagename_biao, String ImgName) ( 
  Try ( 
  File _file = new File (ImgName); 
  Image src = ImageIO.read (_file); 
  Int wideth src.getWidth = (null); 
  Int height = src.getHeight (null); 
  BufferedImage image = new BufferedImage (wideth, height, BufferedImage.TYPE_INT_RGB); 
  Graphics g = image.createGraphics (); 
  G.drawImage (src, 0,0, wideth, height, null); 

  / / Watermark document 
  File _filebiao = new File (Imagename_biao); 
  Image src_biao = ImageIO.read (_filebiao); 
  Int wideth_biao src_biao.getWidth = (null); 
  Int height_biao src_biao.getHeight = (null); 
  G.drawImage (src_biao, wideth-110, height-110, wideth_biao, height_biao, null); 
  / / Watermark documents in the original picture file, and the original picture file in the lower right corner for wideth-0, height-0 
  G.dispose (); 
  FileOutputStream out = new FileOutputStream (ImgName); 
  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder (out); 
  Encoder.encode (image); 
  Out.close (); 
  ) Catch (Exception e) ( 
  System.out.println (e); 
  ) 
  ) 

  Public static void main (String args []) ( 
  ImgBean_i ib = new ImgBean_i (); 
  Ib.ImgYin ( "logo.gif", "pic1339.gif"); 
  ) 
  ) 
  </ Td> <td width="169" valign="top" class="ArticleTeitle"> 
  </ Td> </ tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle"> 

  ↑ Back 

"Chinese actor problem," the Chinese Ant problem

  Abstract: "Chinese actor problem," the Chinese Ant problem 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="415" height="86" align="left" valign="top"> 

  In the software system, because there are all sorts of character encoding issues, such as our very headache Chinese issues.    Therefore, we tend to use as UTF-8 encoding software through encoding formats, thereby avoiding most character encoding problem.    In inadequacies of the criticism we welcome comments. 

  In the Java development, we often use Ant to compile and package the project.    The default is to call an Ant will be named build.xml documents, in the definition of the relevant units and tasks, users can order the implementation of the mandate of the corresponding unit. 

  For example, in many open-source projects such as Spring, webwork, EasyJWeb, EasyDBO, with its root directory has a build.xml file.    The open-source projects abroad, build.xml file of the contents of all English characters, use common build.xml ANSI or GBK UTF-8 or not, nor will he encounter a character encoding problem.    As for China-made open-source projects EasyJWeb, EasyDBO, for the convenience of domestic users, affirmed in the document that will include some Chinese.    The default circumstances, including Chinese characters, the build.xml ANSI format for the document is not properly run. 

  </ Td> <td width="269" valign="top"> </ td> </ tr> </ table> 


  At this point, we need to change build.xml file UTF-8 format, and designated xml document format utf-8.    Below are EasyJWeb such as open-source projects build.xml part of the contents of documents: 
  <? Xml version = "1.0" encoding = "UTF-8"> 
















….
  The question here is how to build a UTF-8 format build.xml file. 
  Wrong habits: 
  Under normal circumstances, we have been accustomed to the use of the notepad windows tools such as direct coding xml content of the document, and save for the UTF-8 format, as shown below: 


  This established by the build.xml file is not correct, and the most disturbing is a very unstable.    This instability in the performance of some systems to the proper use, and there will be some system similar to the following error: 

  D: \ EasyJF \ wlhy \ bin> build.bat 
  Buildfile: .. \ build.xml 
  BUILD FAILED 
  D: \ EasyJF \ wlhy \ build.xml: 1: the lack of paper root components 
  Total time: 0 seconds 
  Press any button to continue.. 

  This is wrong in the williamRaym EasyJF team in the build script writing EasyJWeb found, and later many netizens reflect similar mistakes, such as under the current EasyJF iula item on the existence of this problem: 
  Http://www.easyjf.com/html/bbs/20060814/1208824819851986.htm 
  (Perhaps my fault-tolerant machines, and the error will not, huh!). 

  The correct way: 
  Said earlier, with a notepad to establish UTF-8 format xml document is not correct, we have on several occasions after practice, and correct one of the ways is to use Eclipse to build this xml documents in the time needed to establish the project as a whole works Character Set a UTF-8 set, and then the establishment of a direct build.xml document, by default under the document to UTF-8 format. 
  This set up a script file, the use of Ant time, no matter what build.xml contains Chinese characters, can operate normally.    Of course, we should also can use other development tools to build UTF-8 format document and also requested everyone to trial.    Also JAVA can be used to write a small program to the ANSI file format conversion UTF-8 document, which would also be no problem. 

  Summary: 
  The reason why many of the open source projects build process will not exist, because he was not in the script file contains Chinese characters or other characters.    In the face of domestic open-source projects, because of Chinese notes, notes, etc., in the establishment of build.xml file when the need for some special handling, use UTF-8 format.    Of course, the paper also highlighted the establishment of two UTF-8 document, which is unstable with a notepad, wrong, and with professional development tools or Java JDK established script is the correct and stable. 

  (Note: The author of this article, the Gap team EasyJF open source, reproduced statement retained author!) 

  </ Td> </ tr> <tr> 

  ↑ Back 

keep looking »