Lucene explain examples of a variety of ways to search

  Import java.io.StringReader; 
  Import java.util.Date; 

  Import org.apache.lucene.analysis.Analyzer; 
  Import org.apache.lucene.analysis.SimpleAnalyzer; 
  Import org.apache.lucene.analysis.TokenStream; 
  Import org.apache.lucene.analysis.cjk.CJKAnalyzer; 
  Import org.apache.lucene.analysis.cn.ChineseAnalyzer; 
  Import org.apache.lucene.analysis.standard.StandardAnalyzer; 
  Import org.apache.lucene.document.DateField; 
  Import org.apache.lucene.document.DateTools; 
  Import org.apache.lucene.document.Document; 
  Import org.apache.lucene.document.Field; 
  Import org.apache.lucene.index.IndexReader; 
  Import org.apache.lucene.index.Term; 
  Import org.apache.lucene.queryParser.MultiFieldQueryParser; 
  Import org.apache.lucene.queryParser.QueryParser; 
  Import org.apache.lucene.search.BooleanClause; 
  Import org.apache.lucene.search.BooleanQuery; 
  Import org.apache.lucene.search.FuzzyQuery; 
  Import org.apache.lucene.search.Hits; 
  Import org.apache.lucene.search.IndexSearcher; 
  Import org.apache.lucene.search.Query; 
  Import org.apache.lucene.search.QueryFilter; 
  Import org.apache.lucene.search.RangeQuery; 
  Import org.apache.lucene.search.Sort; 
  Import org.apache.lucene.search.SortField; 

  Import java.util.Date; 

  Import org.apache.lucene.analysis.standard.StandardAnalyzer; 
  Import org.apache.lucene.document.Document; 
  Import org.apache.lucene.index.IndexReader; 
  Import org.apache.lucene.queryParser.QueryParser; 
  Import org.apache.lucene.search.Hits; 
  Import org.apache.lucene.search.IndexSearcher; 
  Import org.apache.lucene.search.Query; 
  Import org.apache.lucene.search.highlight.Highlighter; 
  Import org.apache.lucene.search.highlight.QueryScorer; 
  Import org.apache.lucene.search.highlight.SimpleFragmenter; 
  Import org.apache.lucene.search.highlight.SimpleHTMLFormatter; 

  (Public class LuceneSearch 
  Public static void main (String [] args) throws Exception ( 
  LuceneSearch test = new LuceneSearch (); 
  / / 
  Hits h = null; 
  H = test.search ( "Show"); 
  Test.printResult (h); 

  H = test.search ( "jy"); 
  Test.printResult (h); 

  H = test.search ( "djy"); 
  Test.printResult (h); 

  H = test.search ( "not material"); 
  Test.printResult (h); 

  H = test.search ( ""); 
  Test.printResult (h); 
  ) 
  Public LuceneSearch () ( 
  Try ( 
  Searcher = new IndexSearcher (IndexReader.open ( "E: \ \ lucene \ \ test4 \ \ index")); 
  ) Catch (Exception e) ( 
  E.printStackTrace (); 
  ) 
  ) 
  / / Declare a IndexSearcher object 
  Private IndexSearcher searcher = null; 
  / / Query object of a statement 
  Private Query query = null; 
  ChineseAnalyzer analyzer = new ChineseAnalyzer (); 
  Highlighter highlighter = null; 
  Public final Hits search (String keyword) ( 
  System.out.println ( "Search keywords are:" + keyword); 
  Try ( 
  Date start = new Date (); 

  /***** A keyword query to a field *****/ 
  QueryParser qp = new QueryParser ( "content" analyzer); 
  Qp.parse query = (keyword); 
  / / = Searcher.search Hits hits (query); 

  /***** Fuzzy query *****/ 
  / / Term term = new Term ( "content" keyword); 
  / / FuzzyQuery fq = new FuzzyQuery (term); 
  / / = Searcher.search Hits hits (fq); 

  /***** A keyword in the field for two *****/ 
  / * 
  [] * 1.BooleanClause.Occur of three types: 
  * MUST: + and 
  * MUST_NOT: - not 
  * SHOULD: or 
  * 2. Enquiries following means: the content must be included in the keyword, and there is indifferent title 
  * 3. Below this query, the length of Occur [] [] must Fields and the length of the same.    Each column corresponds restrictions 
  * / 
  / / BooleanClause.Occur flags [] [] = (new BooleanClause.Occur BooleanClause.Occur.SHOULD, BooleanClause.Occur.MUST); 
  / / = MultiFieldQueryParser.parse query (keyword, new String [] ( "title", "content"), flags, analyzer); 

  /***** Two (more) of the two keyword (s) to field enquiries, the default matching rules *****/ 
  / * 
  * 1. Keyword and the number must be equal to the number of fields 
  * 2. Match because there was no specific provisions for default, "SHOULD" 
  * Thus, the following query was: "title" contains keyword1 or "content" contains keyword2. 
  * In this case, the same keyword1 and keyword2 
  * / 
  / / Query = MultiFieldQueryParser.parse (new String [] (keyword, keyword), new String [] ( "title", "content"), analyzer); 

  /***** Two (more) of the two keyword (s) to field enquiries, manual matching rules specified *****/ 
  / * 
  * 1. Keyword must be the number == == fields of the number of the number of matching rules 
  * 2. Enquiries following means: "title" must not contain keyword1, and "content" must contain keyword2 
  * / 
  / / BooleanClause.Occur flags [] [] = (new BooleanClause.Occur BooleanClause.Occur.MUST_NOT, BooleanClause.Occur.MUST); 
  / / Query = MultiFieldQueryParser.parse (new String [] (keyword, keyword), new String [] ( "title", "content"), flags, analyzer); 

  /***** Date of the field inquiries *****/ 

  /***** Scope for the digital *****/ 
  / * 
  * 1. Two conditions must be the same field 
  * 2. Front of a condition than to be behind a small conditions, otherwise no data 
  * 3.new RangeQuery the third parameter that contains the "=" 
  * True:> = or <= 
  * False:> or < 
  * 4. Identify 55> = id> = 53 or 60> = id> = 57: 
  * / 
  / / Term lowerTerm1 = new Term ( "id", "53"); 
  / / Term upperTerm1 = new Term ( "id", "55"); 
  / / RangeQuery rq1 = new RangeQuery (lowerTerm1, upperTerm1, true); 
  / / 
  / / Term lowerTerm2 = new Term ( "id", "57"); 
  / / Term upperTerm2 = new Term ( "id", "60"); 
  / / RangeQuery rq2 = new RangeQuery (lowerTerm2, upperTerm2, true); 
  / / 
  / / BooleanQuery bq = new BooleanQuery (); 
  / / Bq.add (rq1, BooleanClause.Occur.SHOULD); 
  / / Bq.add (rq2, BooleanClause.Occur.SHOULD); 

  / / = Searcher.search Hits hits (bq); 

  /***** Sort *****/ 
  / * 
  * 1. Was sort of a field must be indexed (Indexecd), in the index can not be used when Field.Index.TOKENIZED 
  * (Use normal UN_TOKENIZED can achieve. NO time for normal use, but not the normal sort settings or descending) 
  * 2.SortField type 
  * SCORE, DOC, AUTO, STRING, INT, FLOAT, CUSTOM 
  * This type fields are mainly based on the type of choice 
  * The third parameter 3.SortField representatives is descending 
  * True: descending false: ascending 
  * / 
  / / Sort sort = new Sort (new SortField [] (new SortField ( "id", SortField.INT, true))); 
  / / = Searcher.search Hits hits (query, sort); 

  / * 
  * Sort by Date 
  * / 
  / / Sort sort = new Sort (new SortField [] (new SortField ( "createTime" SortField.INT, false))); 

  /***** Filters ******/ 
  / / QueryParser qp1 = new QueryParser ( "content" analyzer); 
  / / Query fquery = qp1.parse ( "I"); 
  / / 
  / / BooleanQuery bqf = new BooleanQuery (); 
  / / Bqf.add (fquery, BooleanClause.Occur.SHOULD); 
  / / 
  / / QueryFilter qf = new QueryFilter (bqf); 

  Hits hits = searcher.search (query); 

  Date end = new Date (); 
  System.out.println ( "Search completed, at the" + (end.getTime ()-start.getTime ())+" ms "); 
  Return hits; 
  ) Catch (Exception e) ( 
  E.printStackTrace (); 
  Return null; 
  ) 

  ) 

  Public void printResult (Hits h) ( 
  If (h.length () == 0) ( 
  System.out.println ( "Sorry, did not find the results you want."); 
  Else () 
  For (int i = 0; i <h.length (); i + +) ( 
  Try ( 
  Document doc = h.doc (i); 

  System.out.println ( "results" + (i +1 )+":"+ doc.get ( "id") + "createTime:" + doc.get ( "createTime") + "title:" + doc. get (the "title") + "content:" + doc.get ( "content")); 

  / / System.out.println (doc.get ( "path")); 
  ) Catch (Exception e) ( 
  E.printStackTrace (); 
  ) 
  ) 
  ) 
  System.out.println ("————————————–"); 
  ) 
  ) 

IBM Rational use of the test concepts build successful test team

  Class: Junior 

  IBM, 

  June 1, 2004 

  Text on the IBM Rational in the software testing and Ratioanl the concept of the product testing programme, you can understand how to use IBM Rational testing concepts build successful test team. 

  Back to top 

  Back to top 

  Back to top 

  Back to top 

  Back to top 




  Back to top 

  About the author 

  IBM has authored this article 

JAVA interception for writing

  Package test; 
  Import javax.servlet .*; 
  Import javax.servlet.http .*; 
  Import java.io. *; 
  Import java.util .*; 
  Public class Listener1 extends HttpServlet implements ServletContextListener, 
  ServletContextAttributeListener, HttpSessionListener, 
  HttpSessionAttributeListener, ServletRequestListener, 
  ServletRequestAttributeListener ( 
  / / Notification that the web module is ready to process requests 
  Public void contextInitialized (ServletContextEvent sce) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method contextInitialized () not yet implemented."); 
  ) 
  / / Notification that the servlet context is about to be shut down 
  Public void contextDestroyed (ServletContextEvent sce) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method contextDestroyed () not yet implemented."); 
  ) 
  / / Notification that a new attribute has been added to the servlet context 
  Public void attributeAdded (ServletContextAttributeEvent scab) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method attributeAdded () not yet implemented."); 
  ) 
  / / Notification that an attribute has been removed from the servlet context 
  Public void attributeRemoved (ServletContextAttributeEvent scab) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method attributeRemoved () not yet implemented."); 
  ) 
  / / Notification that an attribute of the servlet context has been replaced 
  Public void attributeReplaced (ServletContextAttributeEvent scab) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method attributeReplaced () not yet implemented."); 
  ) 
  / / Notification that a session was created 
  Public void sessionCreated (HttpSessionEvent se) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method sessionCreated () not yet implemented."); 
  ) 
  / / Notification that a session was invalidated 
  Public void sessionDestroyed (HttpSessionEvent se) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method sessionDestroyed () not yet implemented."); 
  ) 
  / / Notification that a new attribute has been added to a session 
  Public void attributeAdded (HttpSessionBindingEvent se) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method attributeAdded () not yet implemented."); 
  ) 
  / / Notification that an attribute has been removed from a session 
  Public void attributeRemoved (HttpSessionBindingEvent se) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method attributeRemoved () not yet implemented."); 
  ) 
  / / Notification that an attribute of a session has been replaced 
  Public void attributeReplaced (HttpSessionBindingEvent se) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method attributeReplaced () not yet implemented."); 
  ) 
  / / Notification that a request was created 
  Public void requestInitialized (ServletRequestEvent sre) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method requestInitialized () not yet implemented."); 
  ) 
  / / Notification that a request was invalidated 
  Public void requestDestroyed (ServletRequestEvent sre) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method requestDestroyed () not yet implemented."); 
  ) 
  / / Notification that a new attribute has been added to a request 
  Public void attributeAdded (ServletRequestAttributeEvent srae) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method attributeAdded () not yet implemented."); 
  ) 
  / / Notification that an attribute has been removed from a request 
  Public void attributeRemoved (ServletRequestAttributeEvent srae) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method attributeRemoved () not yet implemented."); 
  ) 
  / / Notification that an attribute of a request has been replaced 
  Public void attributeReplaced (ServletRequestAttributeEvent srae) ( 
  Throw new java.lang.UnsupportedOperationException ( 
  "Method attributeReplaced () not yet implemented."); 
  ) 
  ) 

3 hibernate wanted a special enterprise development

  Want to do a third of the enterprise development hibernate feature, the current hibernate 3 has the following characteristics: 

  1, based on java1.5, particularly the use of some java1.5 new features, such as generics, making the original hibernate2 code into hibernate 3 on, it is wrong.    Need to use <E> formats; 

  2, are now on the books hibernate hibernate2 presentation, but hibernate3 and hibernate2 many places is entirely different, it is necessary to make a presentation hibernate3, of course, first introduced starting from java1.5; 

  3, hibernate3 and EJB3 has been integrated, so the future is contained hibernate3 the j2ee 

  4, many of the documents only one side of the hibernate, but in the development of enterprises in the end what to do, be the best, are not involved; 

  In sum, I intend to hibernate3 enterprises in the development process to be a practical presentation, of course, is from the perspective of the development of enterprise-class to make a comprehensive presentation, with some time to write it down. 

Flash and Java development tools combined _ "Java for Flash dynamic web development Letters" _ serial sections (1)

  Section â…  chapter Java for Flash based entry 

  Learn any technology has a basic knowledge of Java for Flash is no exception.    This contains several chapters on Java for Flash basic knowledge. 

  In the first chapter, we have information on how to install and configure Java for Flash development and runtime environment, so that users can develop Flash Web applications in order to achieve and Java application interaction. 

  In the ensuing chapters, we introduced the use of the Java language, and how to use JDBC database with Java and object-oriented development. 

  In Chapter V, we began to use the traditional method of middleware as a JSP page Flash Web application development, and exchange of data between servers, understanding how to set up the network environment the most general principles, with the creation of a basic interactive network Application of Flash videos of the basic knowledge, this is the realization of a Flash movie applications as the main network applications a "leap." 

String objects

  String object yqj2065 (Yan Qian-Jun) → 

  CSDN recent forum to look at some of the questions users paste, which on the issue of String often mentioned.    I have always thought he is very clear this thing, but in fact get to the bottom, find themselves not so clear, will make some mistakes it has also produced a number of Lenovo.    Summary of this. 

  1, "abc" and the new String ( "abc"); 

  Often ask questions to the surface: String s = new String ( "abc"); created several String Object? [Such as the number of objects created here? And a small face questions: 

  This problem is relatively simple, involving a knowledge include: 

  •   Use variables and object distinction; 
  •   Text string "abc" is a String object; 
  •   [Pool [pool of literal strings] and stack [heap] String object. 

  1, cited variables and objects: In addition to some of the early books and now the Java garbage books, people can see more clearly and to learn the difference between the two.    A aa; sentence of the statement cited a class A variable aa [I often call handle], and the general adoption of new objects created.    Therefore, the title is a quote s only variable, it is not a target.    [Ref handle, and use objects] 

  Second, all of the Java string [[string constants] is a String objects.    Some people [in particular C programmers] in a number of occasions like the string "as / as" an array of characters, there is no way, because of the string and an array of characters, there are some intrinsically linked.    In fact, it is an array of characters and two entirely different audiences. 

  System.out.println ( "Hello." Length ()); 
  Char [] (cc = 'H', 'i'); 
  System.out.println (cc. length); 

  Third, the creation of a string object: string object because the use of large quantities [it is a target, in general object in the heap always allocate memory], Java in order to save memory space and run-time [such as string comparison, == than equals () Express], when they compile all the text into a text string pool [pool of literal strings], and [running Chi Chi part of a constant.    [Pool the benefits of the pool is all the same string constants are merged, only occupying a space.    We know that the use of the two variables, the use == judge their value is equal to [use] that point to the same object: 

  String s1 = "abc"; 
  String s2 = "abc"; 
  If (s1 == s2) 
  System.out.println ( "s1, s2 refer to the same object"); 
  Else System.out.println ( "trouble"); 

  Here shows that the output of two text strings for the preservation of an object.    That is to say, only in the above code in the creation of a pool String object. 

  Looking at the present String s = new String ( "abc"); statement here "abc" in the pool itself is an object, and in run-time implementation of new String (), will be in the pool put a copy of the object in the heap , and the heap of this object to the application of s holders.    Ok, this statement would create two String objects. 

  String s1 = new String ( "abc"); 
  String s2 = new String ( "abc"); 
  If (s1 == s2) (/ / will not enforce the sentences) 

  Then use == judgement on, we can see that while the two targets of the "content" of the same [equals () judgement], but the two variables used by some quoted different, 

  BTW: The above code to create a number of String Object? [3, in a pool, two in the heap.  ]
  [Java2 certification exam study guides (No. 4) (English) p197-199 are illustrated.  ]


  2, strings and string operations + 

  String conversion and connected in series is the basis of content, I thought that the problem simply send sub-themes.    In fact, I had to explanations of the errors. 

  String str = new String ( "jf"); / / jf transfer points 
  Str = 1 +2 + str +3 +4; 
  Create a total of the number of String objects?    [I began to answer: five.    Jf, new, 3jf, 3jf3, 3jf34] 

  JLS first look at the exposition: 

  A string environment [JLS 5.4 String Conversion] 

  String environment merely means the use of dual + operator of one operand is a String object.    In this particular case, several operations into another String, in the expression of these two is the result of the rods String. 

  Second, rods operator [JLS 15.18.1 String Concatenation Operator +] 

  If an operator / String is the type of expression, in another operation of running into a String object, and the two connected in series.    At this time, any type can be converted into String.    [Here, I missed the "3" and "4"] 

  •   If the basic data types, as its packaging converted into first class objects, such as int x convert as Integer (x). 
  •   Now quoted unify all types of conversion to the String.    As such conversion [as if] call the object's toString method without parameters.    [If it is null then converted into "null"].    ToString method as defined in the Object, it has all the categories, and Boolean, Character, Integer, Long, Float, Double, and String rewrite of the method. 
  •   About + is connected in series or additive, by the operator of a decision.    1 +2 + str +3 +4 is very easy to know "jf34."    [BTW: 15.18.1.3 in the JLS cited in a jocular little example, it is really boring.  ]

  The following example test rewrite toString method situation.. 

  Class A ( 
  Int i = 10; 
  Public static void main (String [] args) ( 
  String str = new String ( "jf"); 
  Str + = new A (); 
  System.out.print (str); 
  ) 

  Public String toString () ( 
  Return "ai =" + i + "\ n"; 
  ) 
  ) 

  3, string conversion optimization 

  According to the above argument, str = 1 +2 + str +3 +4; statement should seem to be generating five String object: 

  1.   1 +2 = 3, then 3 → Integer (3) → "3" in pool? [Hypothetical case] 
  2.   "3" + str (in heap) = "3jf" (in heap) 
  3.   "3jf" +3, first 3 → Integer (3) → "3" in pool? [Not create] then "3jf3" 
  4.   "3jf3" +4 create "4" in pool 
  5.   Then "3jf34" 

  3,4 here it is not clear whether the string conversion in the pool, so the result is still speculation. 

  In order to reduce the creation of the intermediate string object, connected in series and repeatedly enhance the performance of computing, a Java compiler can use StringBuffer or similar technology, or to convert into step with the rods.    For example: For a + b + c, Java compiler can be regarded it as [as if] 

  New StringBuffer (). Append (a). Append (b). Append (c). ToString (); 

  Note that the basic types and invoke types, in the append (a) will be first in the course of conversion parameters, from this point of view, str = 1 +2 + str +3 +4; create a string may be a "3", "4" and "3 jf34" [as well as a StringBuffer object]. 

  Now, I still do not know how to answer str = 1 +2 + str +3 +4 has built a number of String objects,.    Perhaps, on this issue does not have to be at least SCJP not test it. 

  3, which is different: str = "3" + "jf" + "" + "4"; 

  If it is a text string composed entirely by the expression, in the compiler, has been optimized and not at run-time creation of the middle string.    Test code as follows: 

  String str1 = "3jf34"; 
  String str2 = "3" + "jf" + "" + "4"; 
  If (str1 == str2) ( 
  System.out.println ( "str1 == str2"); 
  Else () 
  System.out.println ( "think again"); 
  ) 
  If (str2.equals (str1)) 
  System.out.println ( "yet str2.equals (str1)"); 

  Clearly, str1 and str2 point to the same object, and this object in the pool.    All follow the Java Language Spec compiler must be compiled with the constant expressions can be simplified.    JLS: Strings computed by constant expressions (ý15.28) are computed at compile time and then treated as if they were literals. 

  The String str2 = "3" + "jf" + "" + "4"; we say that only the creation of a target.    Attention, "the number of objects created," said the discussion is the creation of run-time object. 

  BTW: Compiler Optimization 

  String x = "aaa" + "bbb"; 
  If (false) ( 
  X = x + "ccc"; 
  ) 
  X + = "ddd"; 

  Equivalent to: 

  String x = "aaa bbb"; 
  X = x + "ddd"; 

  4, the same category 

  String object is immutable (immutable).    Some of str = 1 +2 + str +3 +4; statement questioned how the content can be changed str?    In fact remains unclear because: invoke the distinction between variables and objects.    Str variable is only invoked, the value of it - it can change the application of holders.    You constantly create new objects, I constantly changing direction.    [Reference TIJ the Read-only classes.  ]

  The same type, the key is to target all the operations are unlikely to change the original object [if necessary, on return to a change of the new object].    This object irrevocable guarantee.    Why should a class designed the same category?    A OOD design principles: Law of Demeter.    Its broad interpretation is: 

  Use the same category.    Wherever possible, the category to be the same type design. 

EasyMock extended to the use of Class provide Mock objects

  EasyMock extended to the use of Class provide Mock objects 

  Author: kongxx 

  I usually Mody some kind of testing time to rely on some other type or interface, and this may be the only possible type or interface method signatures is not really realized.    At this time we will be able to use some third-party libraries to solve this problem, for example, commonly used EasyMock, such as JMock.    But these two libraries default under any circumstances, can only Mock interface, and not Mock category, then how should we solve this problem?    In fact, two JMock EasyMock and also provides a framework for Mock of the solution, but this function need to provide them with an expanded class library can be achieved.    We can they download on the official website of the two expansion.    For EasyMock download EasyMock Class Extension 2.0_Pre-Release, JMock download jMock / CGLIB extension binary JAR. 
  Below is a small example: 
  Worker.java a need to test the business category, which depends on an abstract Configuration object. 

  Class package easymock; 

  (Public class Worker 

  Private Configuration configuration; 

  Public Configuration getConfiguration () ( 
  Return configuration; 
  ) 

  Public void setConfiguration (Configuration configuration) ( 
  This.configuration = configuration; 
  ) 

  Public boolean execute () ( 
  String name = configuration.getName (); 
  String type = configuration.getType (); 

  If (name.equals ( "System") & & type.equals ( "Snapshot")) ( 
  / / TODO 

  Return true; 
  ) 
  Return false; 
  ) 
  ) 

  ( 
  Public static void main (String [] args) 
  ( 
  System.out.println ( "Hello World!"); 
  ) 
  ) 

  Configuration.java an abstract category, there will be a number of sub-categories to achieve its abstract way. 

  Package easymock; 

  Import java.io.File; 

  (Public abstract class Configuration 

  Protected String name; 
  Protected String type; 

  Public abstract Configuration configurate (File file); 

  Public abstract String getName (); 

  Public abstract String getType (); 
  ) 

  WorkerTest.java a test category, are required Configuration instance, here Mock Configuration object of a method used to execute provide support. 

  Package easymock; 

  Import junit.framework.TestCase; 
  Import org.easymock.classextension .*; 

  Public class WorkerTest extends TestCase ( 
  Private Worker worker; 
  Protected void setUp () throws Exception ( 
  Super.setUp (); 

  Worker = new Worker (); 
  ) 

  Protected void tearDown () throws Exception ( 
  Super.tearDown (); 
  ) 

  / * 
  * Test method for 'easymock.Worker.execute ()' 
  * / 
  Public void testExecute () ( 
  Configuration conf = (Configuration) EasyMock.createMock (Configuration.class); 
  EasyMock.expect (conf.getName ()). AndReturn ( "System"); 
  EasyMock.expect (conf.getType ()). AndReturn ( "Snapshot"); 

  EasyMock.replay (conf); 

  Worker.setConfiguration (conf); 

  / / With the implementation of the test method 
  AssertTrue (worker.execute ()); 
  ) 

  ) 

  Running JUnit tests GreenBar.    OK! 

Java learning Notes (5) - super usage, final usage, abstract class, interface

  Subclass father will not inherit the constructor method, in the category of construction method can be used in the super (the list of parameters) call the constructor method father. 
  Class Person 
  (String name; 
  Int age; 
  Public Person (); 
  Public Person (String name, int age) 
  (This.name = name; 
  This.age = age; 
  ) 
  Public void getInfo () 
  (System.out.println ( "name =" + name + "age =" + age);) 
  ) 
  Class Student extends Person 
  (Public String school = "unknow" 
  Public Student () 
  (Super ();) 
  Public Student (String name, int age) 
  (Super (name, age)) 
  Public Student (String name, int age, String school) 
  (This (name, age); / / call here with this other constructor public Student (String name, int age) 
  / / Super (name, age); super here with no meaning 
  This.school = school; 
  Super.getInfo () / / Call Father of the getInfo () 
  ) 
  Public void getInfo () / / rewrite father of the method 
  (System.out.println ( "school =" + school + ", name =" + name + "age =" + age)) 
  Public void study () 
  () 
  ) 
  / / 1.super () and this () call in a statement at the same time can not be constructed in a function 
  / / 2.super () and this () call only as a constructor function statement in the first sentence of a 

  Class TestStudent 
  (Public static void main (String [] args) 
  Student st = (new Student ( "zhangshan", 20, "Qinghua University") 
  St.getInfo () 
  ) 
  ) 

  ———————– 
  French final 
  1.final increase in the Class of this class were not allowed to inherit 
  2.final increase in the members of variables, constants, variables members, was not allowed to re-assignment (1) final String x = "abc"; (2) final String x; 
  X = "abc" / / x = "abc" must be on the constructor function, and overloaded constructor function had to write x = "abc"; 
  3. Method is defined as final, in the sub-category method is not covered only inheritance 

  Static role: the definition of static variables can be directly used not object creation of a category called Abc.x 
  (Class Abc 
  Public static String x = "abc" 
  ) 

  (Class Abc 
  Public static final String x = "abc" 
  Public Abc () (x = "abc") / / wrong, because x has been defined as static, so the final definition of constants in the structure can not be assigned a letter, must be in the definition of early. 
  ) 

  System.out.println (Float.MAX_VALUE); print out the largest floating point decimals 

  ————————— 

  Abstract class (abtract) 
  Java in some non-method can be defined in the method, which means to the realization of such sub-categories according to their own circumstances to achieve this is by means of abstract methods, including methods of the abstract type called abstract classes. 
  — An abstract class must be abstract keywords to modification; abstract method must be modified to abstract.    Abstract class in all categories must be abstract approach - abstract class can not be instantiated, which is not used to produce new keyword targets. 
  — Abstract method only statement, without realizing. 
  — Containing abstract methods of the statement must be abstract class, the abstract class must cover all categories of the abstract methods can be examples of this sub-class or otherwise abstract category. 
  Abstract class A 
  (Private int i = 1; / / abstract class can be defined variables 
  Abstract int aa (int x, int y); 
  Abstract void bb (); 
  Public void cc () / / abstract class can be defined in a general way 
  (System.out.println (i);) 
  ) 
  Class B extends A 
  (Int aa (int x, int y) (return 1;) / / there must be a method to value - 
  Void bb () () 

  Public static void main (String [] args) 
  (B b = new B (); 
  System.out.println (b.aa (1,2)); 
  B.cc (); 
  ) 
  ) 

  Interface (interface) 
  If an abstract class methods are all abstract, we can use this class will be another way to define, that is, interface definitions.    Interface is often abstract methods and the definition of money collection, essentially speaking, the interface is a special kind of abstract class, this abstract class only constants, and methods include the definition, but not the realization of variables and methods. 
  — Interfaces are the members of the public access type.    The default interface is in constant use public static final logo, interface variables are global static constants. 
  — We can define a new interface with the keyword extends to inherit an existing interface - we can also define a category by keyword implements an interface to achieve in all *** *** (including This interface Father interface methods) 
  — We also can be to define an abstract class implements used to achieve a keyword in the definition of the interface method *** *** part. 
  — A class can inherit a kind of father at the same time, to achieve one or more interfaces, extends keyword must be situated implements keyword. 

  Interface Runner 
  (Public static final int ID = 1; or int ID = 1 / / definition of constants can be public static final Thus, the definition is constant, because only in the interface definition constants. 
  Void run (); 
  ) 
  Interface Animal extends Runner / / succession Runner interface (void breathe (); 
  ) 

  Class Fish implements Animal 
  (Public void run (); / / Interface, the statement because the public is the default category, and in need of a succession of the father than the kind of access to high, it is not directly write void run (), if we do not write for public Yi will be wrong. 
  (System.out.println ( "fish is swimming"); 
  ) 
  Public void breathe () 
  (System.out.println ( "fish is bubbling"); 
  ) 
  Public static void main (String [] args) 
  (Fish f = new Fish (); 
  Int j = 0; 
  J = Runner.ID; / / Runner to use the constants id, id because of the default is static, with a direct call Runner. 
  J = f.ID; 
  J = Fish.ID; / / Fish category because, the father of succession, so this can be invoked 
  F.iD = 2; / / this wrong, because id is constant, not assignment 

  ) 
  ) 
  Abstract class LandAnimal implements Animal / / Animal succession because LandAnimal not all, it must be in the former category statement for abstract classes. 
  (Public void breathe (){}; //????? there is a problem, since this definition of a class because it is an abstract class can not be defined object, but for a succession after this class, the compiler errors, and the abstract Classes why Canada (), the original procedure in my documents, Aaa.java 
  ) / / Problem solving, abstract class does not object creation, this right, and if this type of succession, in front of all the successor have to be rewritten, and the point is () must be added to the inside, an abstract category inherit an interface, abstract class must be added in the (), following a succession of written procedures for it, but if it re-defined as an abstract method can be written, abstract public void breathe (); 
  Class LAL extends LandAnimal 
  (Public void breathe () ( 
  System.out.println ( "hhhhhhhhhhhhhhhhh"); 
  ) 
  Public voic run (){}; / / subclass inheritance of the father is an abstract class or interface is necessary to inherit the father of all the ways 
  ) / / No such problem 

  Class Student extends Person implements Runner / / previous assumptions there is a Person class that is that this type of succession Person, but also realized implements this interface, but extends to the front in the implements. 
  (Public void run (); 
  ) 

  Interface Flyer 
  (Void fly ();) 
  Class Bird implements Runner, Flyer / / a class can inherit multiple interfaces 
  (Public void run () () 
  Public void fly () () 
  ) 

Java learning experience abnormal welcome Bozhuan

  Java abnormal learning experience 

  This paper重在abnormal mechanisms in Java some of the concepts.    The purpose of this paper is to write for a long time after I forgot If these things can be quickly recalled this article together. 

  1. Abnormal mechanism 
  1.1 abnormal mechanism is that when an error procedures, procedures for how to deal with.    Specifically, the procedure provides a mechanism for abnormal withdrawal of safe passage.    When errors, the process of implementation procedures changed, the process to transfer control of the abnormal processor. 
  1.2 abnormal traditional treatment approaches, a special function to return to the results of that unusual (usually this is the result of all special agreement called), the function call the procedures for inspection and analysis functions return results.    This will be the following drawbacks: for example, the function returns -1 representative unusual, but if function is to return to the correct value of -1 when there will be confusion; reduce readability, and the code will be dealt with very mixed father in the code together; by calling the function of the wrong procedure, which requires programmers to library functions, has a very deep understanding. 
  1.3 Process Exception Handling 
  1.3.1 encountered errors, and methods to put an immediate end does not return a value at the same time, dished out an unusual object 
  1.3.2 call the method will not continue to implement the procedures continue, but the search can be dealt with a very abnormal processor, and the implementation of the code 

  Abnormal Category 2 
  2.1 abnormal Category 
  2.1.1 inherited abnormal structure: base class for Throwable, and Exception Error succession Throwable, RuntimeException such as inheritance and IOException Exception, the specific RuntimeException succession RuntimeException. 
  2.1.2 Error and RuntimeException and did not check a subclass abnormalities (unchecked), and the other checks have become abnormal anomalies (checked). 
  2.2 Each type of unusual characteristics 
  2.2.1 System Error 
  Error category of the Java runtime system described in the internal system error and resource depletion in the case.    Applications should not be thrown out of this type of object (usually dished out by the virtual machine).    If such a mistake, in addition to withdraw from the security procedures, in addition to other aspects of the powerless.    Therefore, during the design process, it should be more concerned about Exception system. 
  2.2.2 Exception system 
  Exception system includes RuntimeException system and other non-RuntimeException system 
  2.2.2.1 RuntimeException 
  RuntimeException system includes the wrong type of conversion, and an array of cross-border visit to visit null pointer, and so on.    Handling RuntimeException principle is: if RuntimeException, then necessarily the programmer errors.    For example, you can check through the array and array subscript border to avoid abnormal array cross-border visits. 
  2.2.2.2 Other (IOException, etc.) 
  Such external abnormalities is generally wrong, for example, to read from the document after the end of data, this process itself is not wrong, but in the application of the external environment wrong. 
  C + + 2.3 and classification of different anomalies 
  2.3.1 In fact, the Java class name from RuntimeException this is not appropriate, because any abnormal operation are emerging.    (Compile-time error is not the abnormal, in other words, abnormal operating procedure is to solve the wrong time). 
  2.3.2 C + + and Java logic_error in RuntimeException is equivalent, and Java and Central Africa RuntimeException runtime_error type of anomaly is equivalent. 

  3 the use of the unusual 
  Abnormal methods statement dished out 3.1 
  3.1.1 Syntax: throws (abbreviated) 
  3.1.2 Method statement dished out why abnormal? 
  Approach dished out anomalies and the type of return value method as important.    Dished out the assumption method is not unusual statement this method will throw abnormal, then, programmers can not call this method and the preparation of the code dealing with the anomalies.    Then, once unusual, then there is no suitable abnormal abnormal controller to solve. 
  3.1.3 dished out why abnormal certain checks have been abnormal? 
  Error RuntimeException and can be produced in any code, they do not need to display dished out by the programmer, once an error, then the corresponding anomaly will be automatically thrown out.    Just check abnormal dished out by the programmer, which is divided into two situations: customer programmers call will be dished out the abnormal function (the abnormal function dished out by the programmer); customer programmers to use the phrase throw parabolic abnormalities.    Error encountered, programmers are generally powerless; encountered RuntimeException, then a certain logic there is a procedural error, it is necessary to modify the program (equivalent to a method of debugging); anomaly has inspected only concern is the programmer, procedures should be thrown out and only deal with checks or abnormal. 
  3.1.4 Note: Father coverage of a subclass method methods should not be dished out more than Father of the abnormal way, and sometimes the father of the design methods will be dished out unusual statement, but the actual implementation of the code, however, do not throw an error, it is intended to facilitate coverage of methods of the father of method can throw an error. 
  How unusual dished out 3.2 
  3.2.1 Syntax: throw (abbreviated) 
  3.2.2 dished out what abnormal? 
  For an unusual object, truly useful information, the target of abnormal types, and abnormal object itself is meaningless.    For example, an exception is the type of object ClassCastException, then this is the only category of useful information.    Therefore, the choice of what dished out anomalies, the most critical is to choose the type of abnormality can be clearly stated exceptions classes. 
  3.2.3 There are two abnormal structures normally functions: One is the non-parametric structural function, the other is with a string of constructor function, the string will serve as a target in addition to this type of anomaly in addition note. 
  3.2.4 create their own anomaly: When the built-in Java are not abnormal anomalies clear that the time needed to create their own anomaly.    It must be noted that the only useful is this type of information, so do not abnormal in the category spent on the design of energy. 
  If caught a 3.3 anomaly has not been dealt with, then, a non-graphical interface for the procedure, the program will be suspended and output anomaly; procedures for a graphical interface, the output will be abnormal information, but does not stay proceedings, but returned to the user interface processing cycle. 
  3.3.1 Syntax: try, and finally catch (abbreviated) 
  Controller Module try block must be immediately behind.    If an abnormal rolled abnormal control mechanisms will search parameters and the very consistent with the type of a controller then it will enter a clause that catch, and that has been abnormal control.    Once the catch clause for the end of the search controller will stop. 
  3.3.1.1 capture multiple anomalies (Grammar and capture the attention of the order) (Omitted) 
  3.3.1.2 finally with the use of exception handling process (abbreviated) 
  3.3.2 Exception Handling for what? 
  For Java, as a refuse collection, exception handling does not require recovery of memory.    But there are still some resources programmers need to collect, such as documents, photographs, and other network connections and resources. 
  3.3.3 Method statement should be thrown out or abnormal caught in the methodology? 
  Principles: to catch and deal with the know how to deal with the anomalies, and transmission do not know how to deal with the anomalies 
  3.3.4 once again trotted out anomalies 
  3.3.4.1 again dished out why abnormal? 
  In this class, can only deal with part of some deal with a higher level of need in the completion of the environment, so it should be once again trotted out anomalies.    This would enable each level of abnormal processor with it will be able to handle anomalies. 
  3.3.4.2 abnormal processes corresponding try block and catch the same block will be ignored by tossing out the anomaly will enter a higher level. 

  4 anomaly on the other issues 
  4.1 excessive use of abnormal First, the use of anomaly is convenient, programmers in general are no longer willing to deal with the preparation of the wrong code, but only the simple throw an anomaly.    This is wrong, completely wrong known, it should be prepared to deal with such wrong code, increasing the robustness of the procedures.    In addition, the mechanism of abnormal poor efficiency. 
  4.2 will be extraordinarily wrong with the ordinary distinction between the ordinary exactly the same mistake, it should be prepared to deal with such wrong code, increasing the robustness of the procedures.    Only external unable to identify and predict runtime error only need to use the anomaly. 
  4.3 unusual object in the information contained in normal circumstances, the only unusual object type of information is useful information.    However, the use of string with abnormal function of the structure, this string can be as additional information.    Call Anomaly object getMessage (), toString () or printStackTrace () method can be anomalies were targeted additional information, like name and call stack information.    And the information contained in the latter is a superset of the former. 

Appfuse in common ant instructions

  Appfuse is a mainstream structure in the framework of the basic development platform, J2EE developers can help quickly J2EE project development.    It is divided into several portfolio framework, the default is spring struts + + hibernate, and the forefront of the use of a lot or mainstream technology, high gold content.    Author    Matt Raible is an ant cows, the project contains a large number of complex ant instructions, it can effectively improve your J2EE developers work efficiency, persistent object can be configured automatically created in the corresponding database table, and automatically generated persistence layer , service layer, layer shows that the basic categories and the corresponding unit testing categories, automatic configuration file configuration, and so on.    It is also worth learning Java developers, particularly those who use the framework and new technologies.    The latest version is 1.8.2, the official Web site: http://raibledesigns.com/wiki/Wiki.jsp?page=AppFuse 

  There can be used in various manuals and technical information.    A nation called rocksun network, the use of manual and done a lot of technical information Han, also released at the top. 

  This is the process I used in the use of a number of ant instructions, do a summarized, and convenience in Show. 

  A, the project generated Appfuse 
  1, ant new 
  Appfuse project started generating configuration interface (using the root directory build.xml file) 
  2, ant setup (or ant setup-db setup-tomcat deploy) 
  The establishment of a database structure, configuration tomcat configuration file, the deployment of the content of the tomcat (build.xml use of the root directory) 
  3, ant test-all 
  Start tomcat and all the tests (using the root directory build.xml file) 
  4, ant test-reports 
  Test results will be generated test report (using the root directory build.xml file) 
  5, ant gen-forms 
  Showing the form of generating object. 
  B, the creation of lasting 
  1, ant setup-db 
  Configure the persistent object in the hibernate marker, generate database table structure.    (Build.xml use of the root directory) 
  2, (optional) ant db-export 
  IDE has been created from the use of the data in the database export data to a document.    Contents of this document by adding metadata / sql / sample-data.xml, can be used as the test data.    (Build.xml use of the root directory) 
  3, ant compile-dao 
  Compiler lasting layer of paper.    (Build.xml use of the root directory) 
  4, ant test-dao-Dtestcase = PersonDAO 
  Test persistence layer.    PersonDAO testing can be changed to the DAO object names.    (Build.xml use of the root directory) 
  C, create a service layer 
  1, ant compile-service 
  Compiler of the type of document services.    (Build.xml use of the root directory) 
  2, ant test-service-Dtestcase = PersonManager 
  Testing services layer.    PersonManager testing to be replaced by the Manager object names.    (Build.xml use of the root directory) 
  D, the creation of the show 
  1, ant-Dmodel.name = = Person-person Dmodel.name.lowercase 
  Against persistent object to generate DAO including services that all floors of the necessary elements.    (Use extras / appgen build.xml file in the catalog) 
  Generate documents in extras / appgen / build / gen directory. 
  2, ant test-web-Dtestcase = PersonAction 
  Test indicates that layer Action.    PersonAction should be replaced by tests conducted Action object names.    (Build.xml use of the root directory) 
  3, ant db-load deploy 
  Inclusion in the database table structures and procedures to the deployment of the tomcat.    (Build.xml use of the root directory) 
  4, deploy web - 
  Deploy Web directory content to the server.    (Build.xml use of the root directory) 
  5, ant test-canoo-Dtestcase = PersonTests 
  Tomcat start in the circumstances test pages.    (Build.xml use of the root directory) 
  6, ant test-jsp-Dtestcase = PersonTests 
  Tomcat stop in the circumstances test pages.    (Build.xml use of the root directory) 
  E, the creation and validation of the list 
  1, ant clean webdoclet 
  By persistent object in the allocation of struts validation conditions validation.xml generated content.    (Build.xml use of the root directory) 
  Generated content will be located in the build / Project Name / WEB-INF / directory. 

keep looking »