Program Design: JAXB generate an XML document

  An XML schema (Schema) using XML syntax to express an XML document structure.    J2EE developers may need an XML schema XML documents.    Java XML binding framework (JAXB) provides a bundled compiler, xjc to XML mode from a generation Java class.    JAXB xjc generated by the Java class that represents a different XML schema elements and complex types (complexType).    (Through a complex type of attributes and elements within the specified elements to provide an element of the definition).    An XML schema with the XML documents from the Java class can be constructed out. 

  In this tutorial, the author from using JAXB to generate an XML schema in Java class.    These will generate a Java class examples of XML documents.    This article consists of the following: 

  1. Pre-installed 2. Overview 3. XMl model generated from the Java class 4. Generated in the Java class from an XML document pre-pre-installed in order to use JAXB from an XML generated in the Java class model, JAXB API class libraries and tools should be xjc There CLASSPATH environment variable.    Will be Java Web services development kit (JWSDP) 1.5 into an installation directory.    Will be the following. Jar document incorporated CLASSPATH environment variable. 

  <JWSDP> / Jaxb / lib / jaxb-api.jar 
  <JWSDP> / Jaxb / lib / jaxb-impl.jar 
  <JWSDP> / Jaxb / lib / jaxb-libs.jar 
  <JWSDP> / Jaxb / lib / jaxb-xjc.jar 
  <JWSDP> / Jwsdp-shared/lib/namespace.jar 
  <JWSDP> / Jwsdp-shared/lib/jax-qname.jar 
  <JWSDP> / Jwsdp-shared/lib/relaxngDatatype.jar 

  <JWSDP> Is Java Web services development kit 1.5 installation directory.    To <JWSDP> / jaxb / bin join the PATH environment variable.    <JWSDP> / Jaxb / bin directory contains xjc compiler.    To <JWSDP> / jwsdp-shared/bin directory into the PATH environment variable.    <JWSDP> / Jwsdp-shared/bin setenv directory contains the batch file, it set up a JAVA_HOME, ANT_HOME and JWSDP_HOME these environment variables. 

  JAXB outlined generation counterparts top of the XML elements and complex types of top-level elements of Java classes and interfaces.    In an XML model, the one element from <xs: element />, a complex type elements from <xs: complexType /> said.    This tutorial will give a scientific journal said in an article published on the model examples, examples of this model will be bundled JAXB compile.    XML schema, catalog.xsd, as follows: 

  <xsd:schema Xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
  <xsd:element Name="catalog" type="catalogType"/> 
  <xsd:complexType Name="catalogType"> 
<xsd:sequence>
  <Xsd: element ref = "journal" 
  MinOccurs = "0" maxOccurs = "unbounded" /> 
  </ Xsd: sequence> 
  <xsd:attribute Name="section" type="xsd:string"/> 
  <xsd:attribute Name="publisher" type="xsd:string"/> 
  </ Xsd: complexType> 
  <xsd:element Name="journal" type="journalType"/> 
  <xsd:complexType Name="journalType"> 
<xsd:sequence>
  <Xsd: element ref = "article" 
  MinOccurs = "0" maxOccurs = "unbounded" /> 
  </ Xsd: sequence> 
  </ Xsd: complexType> 
  <xsd:element Name="article" type="articleType"/> 
  <xsd:complexType Name="articleType"> 
<xsd:sequence>
  <xsd:element Name="title" type="xsd:string"/> 
  <xsd:element Name="author" type="xsd:string"/> 
  </ Xsd: sequence> 
  <xsd:attribute Name="level" type="xsd:string"/> 
  <xsd:attribute Name="date" type="xsd:string"/> 
  </ Xsd: complexType> </ xsd: schema> 

  Construction of some of the XML schema is not JAXB support.    If these are not included in the support structure of the model, then when you tried to use xjc to generate Java class will be the error.    The following models are not supported elements: xs: any, xs: anyAttribute, xs: notation, xs: redefine, xs: key, xs: keyref and xs: unique. Model of the following attributes are not supported: complexType.abstract, element. abstract, element.substitutionGroup, xsi: type, complexType.block, complexType.final, element.block, element.final, schema.blockDefault and schema.finalDefault. 

  Java class xjc generation tool based on this model to a model to bundle Java class.    Examples of this model against bind to the order is: 

  > Xjc catalog.xsd 

  Xjc command line interface options out in the table below: 

  - Nv for input mode does not enforce strict XML validation - b <file> designated external binding document - d <dir> designated generated documents stored path - p <pkg> targeted packages - classpath <arg> designated classpath 

  - Use packet-runtime <pkg> impl.runtime not be generated - xmlschema input mode is a W3C XML mode (the default) 

  For example model catalog.xsd, xjc will generate 45 categories, as follows xjc displayed in the output: 

  Parsing a schema … 
  Compiling a schema … 
  Generated \ impl \ runtime \ ErrorHandlerAdaptor.java 
  Generated \ impl \ runtime \ MSVValidator.java 
  Generated \ impl \ runtime \ NamespaceContext2.java 
  Generated \ impl \ runtime \ UnmarshallableObject.java 
  Generated \ impl \ runtime \ MarshallerImpl.java 
  Generated \ impl \ runtime \ ValidationContext.java 
  Generated \ impl \ runtime \ UnmarshallerImpl.java 
  Generated \ impl \ runtime \ DefaultJAXBContextImpl.java 
  Generated \ impl \ runtime \ ContentHandlerAdaptor.java 
  Generated \ impl \ runtime \ GrammarInfoFacade.java 
  Generated \ impl \ runtime \ UnmarshallingContext.java 
  Generated \ impl \ runtime \ UnmarshallingEventHandlerAdaptor.java 
  Generated \ impl \ runtime \ XMLSerializable.java 
  Generated \ impl \ runtime \ Discarder.java 
  Generated \ impl \ runtime \ PrefixCallback.java 
  Generated \ impl \ runtime \ SAXMarshaller.java 
  Generated \ impl \ runtime \ NamespaceContextImpl.java 
  Generated \ impl \ runtime \ UnmarshallingEventHandler.java 
  Generated \ impl \ runtime \ GrammarInfo.java 
  Generated \ impl \ runtime \ InterningUnmarshallerHandler.java 
  Generated \ impl \ runtime \ ValidatableObject.java 
  Generated \ impl \ runtime \ GrammarInfoImpl.java 
  Generated \ impl \ runtime \ ValidatingUnmarshaller.java 
  Generated \ impl \ runtime \ ValidatorImpl.java 
  Generated \ impl \ runtime \ SAXUnmarshallerHandlerImpl.java 
  Generated \ impl \ runtime \ XMLSerializer.java 
  Generated \ impl \ runtime \ Util.java 
  Generated \ impl \ runtime \ SAXUnmarshallerHandler.java 
  Generated \ impl \ runtime \ AbstractUnmarshallingEventHandlerImpl.java 
  Generated \ impl \ ArticleImpl.java 
  Generated \ impl \ ArticleTypeImpl.java 
  Generated \ impl \ CatalogImpl.java 
  Generated \ impl \ CatalogTypeImpl.java 
  Generated \ impl \ JAXBVersion.java 
  Generated \ impl \ JournalImpl.java 
  Generated \ impl \ JournalTypeImpl.java 
  Generated \ Article.java 
  Generated \ ArticleType.java 
  Generated \ Catalog.java 
  Generated \ CatalogType.java 
  Generated \ Journal.java 
  Generated \ JournalType.java 
  Generated \ ObjectFactory.java 
  Generated \ bgm.ser 
  Generated \ jaxb.properties 

  For example XML schema for each top-level xs: element and the top xs: complexType, corresponds to generate a Java interface and a Java class.    Also created a factory class (ObjectFactory.java), including the creation of interface object methods.    In articles in the sample code files jaxb-java-resources.zip find ObjectFactory.java category. 

  Catalog.java top of the corresponding elements catalog generation interface.    From the model generated by the elements of the interface extends javax.xml.bin.Elemnt category. 

  Catalog.java: 

  Package generated; public interface Catalog 
  Extends javax.xml.bind.Element, generated.CatalogType () 

  CatalogType.java top of the corresponding elements catalogType complex formation interface.    CatalogType corresponding catalog interface elements for each attribute designated setter and getter methods, and the corresponding catalog elements of the elements of a journal getter methods. 

  CatalogType.java: 

  Package generated; (public interface CatalogType 
  Java.lang.String getSection (); 
  Void setSection (java.lang.String value); 
  Java.util.List getJournal (); 
  Java.lang.String getPublisher (); 
  Void setPublisher (java.lang.String value);) 

  CatalogImpl.java and CatalogTypeImpl.java respectively corresponding Catalog.java CatalogType.java interface and the implementation class. 

  From the Java class to create an XML document in this section, the document will be an example XMl-Jin JAXB from Java class is created.    Examples of XML documents, catalog.xml as: 

  <? Xml version = "1.0" encoding = "UTF-8"> 
  <Catalog xmlns = "http://www.w3.org/2001/XMLSchema-Instance" 
  Section = "Java Technology" 
  Publisher = "IBM developerWorks"> 
<journal>
  <article Level="Intermediate" date="January-2004"> 
  <title> Service Oriented Architecture Frameworks </ titl 

EJB Design Patterns (5)

  EJB Design Patterns (5) 

  Just as we see in the design mode 4, the realization of Entity Bean was cut to size in the ejbCreate (), getData () 
  And setData () method in just a few lines, regardless of the number of CMP field. 
  The next step is modeling companies and employees Entity Beans, this somewhat cumbersome and advised readers on the first borland 
  Company <EJB programmer's guide> OR Mapping and the senior CMP understand. 
  Modeling of this relationship is no need to change the structure of the code, however Entity Beans need to achieve a little bit of revision to reflect the relationship between the two entities, in view of the Deployment Descriptor need for minor revisions. 
  , As before, the structure inherited from the Entity Bean, the company Entity Bean Below is the code fragment: 
  Public class CompanyBean extends CompanyStruct 
  (Implements EntityBean 
  EntityContext entityContext; 
  / / CMP for all fields in the CompanyStruct 
  Public Java. Util.Collection employees; / / one-to-many 
  / / Rest of the code including getData () and setData () 
  Public java.util.Collection getEmployees () ( 
  Return employees; 
  ) 
  ) 
  Below are the procedures employees Entity Bean fragment: 
  Public class EmployeeBean extends EmployeeStruct 
  (Implements EntityBean 
  EntityContext entityContext; 
  / / CMP for all fields in EmployeeStruct EXCEPT 
  / / The comId 
  Public Company company; / / remote reference to company 
  ) 
  In the above process in the region, employees Entity Bean structure inherited from the employee, the employee structure itself comId that there is a field between the employees and the foreign key in the design of all the previous model, 
  This field is the CMP. In the Design Mode 5 used in this field in the Deployment Descriptor 
  Un-checking method removed from the CMP. Entity Bean and the company is now remote quoted the CMP. 
  The question now is how the getData () and SetData () method of updating the application of the company Entity Bean, 
  When these methods only get and set comId (in the design mode was not in the context CMP) value. 
  Simply put, there is no change in the structure of the process and field comId (no longer CMP) was copied to the RPC 
  Entity Bean and copy out from the Entity Bean. Need is the company Entity Bean cited in the distance must be written into the database and read out from the database update. EjbLoad we need to use () and ejbStore () 
  Entity Bean method for the realization of this work we have completed. 
  Entity Bean employees in the ejbLoad () method code fragment below: 
  Public void ejbLoad () ( 
  Try ( 
  ComId = (company == 
  Null)? Null: (Integer) company.getPrimaryKey (); 
  ) Catch (Exception e) ( 
  / / Throw some runtime exception (eg EJBException) 
  ) 
  ) 
  Above code with virtually no explanation. When data is read from the database (at the beginning of the Panel), 
  ComId (not CMP) Entity Bean employees in the field was set. Therefore, when the getData () method is called, 
  Back to the structure will include the right to comId value. 
  Entity Bean employees in the ejbStore () method as follows: 
  Public void ejbStore () ( 
  Try ( 
  Company = (comId == 
  Null)? Null: beanGlossary.getCompanyHome (). FindByPrimary 
  Key (comId); 
  ) Catch (Exception e) ( 
  / / Throw some runtime exception (eg EJBException) 
  ) 
  ) 
  EjbStore () in the affairs ended when data was written into the database is invoked in such circumstances, the value of comId be changed (by calling setData methods), this must be written in the database. Above methods in the code to comId into the long-distance companies cited. (After all comId company Entity Bean is the main key). 
  Check the reasons for the use of space database is not kept empty value (Table between the weak invoked), and these also need modeling. 
  , Under any circumstances, use java on the basic types of packaging than the use of their own basic types, and because they can keep empty value and easy conversion into other forms. 
  BeanGlossary category of the above code fragment easily lead to some confusion. 
  This is actually a catch EJB lookup of the utility category (a stateless session bean), 
  In the state entity bean and session bean circumstances, the Home interface buffer lookup is. 
  Stateless session bean in the circumstances, the Remote Interface is a buffer (1.1 as a standard part of ejb, 
  In a SLSB Home interface called create () is not optimized). 
  In the above context through the buffer, we mean is the first request by the lookup. Subsequent call has been the object is initialized in the home use interface or remote interface. 
  BeanGlossarySB utility of the code fragment below: 
  Public class BeanGlossarySB implements SessionBean ( 
  Private Context context = null; 
  Public javax.naming.Context getContext () throws 
  NamingException ( 
  If (context == null) 
  Context = new javax.naming.InitialContext (); 
  Return context; 
  ) 
  / / Company 
  Private CompanyHome companyHome = null; 
  Public CompanyHome getCompanyHome () throws 
  NamingException ( 
  If (companyHome == null) 
  CompanyHome = ((CompanyHome) 
  Javax.rmi.PortableRemoteObject.narrow ( 
  GetContext (). Lookup ( "java: comp / env / ejb / Company") 
CompanyHome.class));
  Return companyHome; 
  ) 
  / / Rest of the EJBs 
  ) 
  5 in the design mode, we did not deal with the Home Entity Bean interface. 
  Entity Bean employees in the circumstances, there will be an element in the finder 
  FindEmployeesByCompany (Company pCompany) in a few lines, 
  This will be used to return a collection of remote employees. Entity Bean in the company in the Deployment 
  Descriptor map in the above elements of the definition of employee finder set. 
  Thus, in the company of the Entity Bean method getEmployees () in the remote interface in the call to return to the needs of the company and linked to remote employees cited the gathering (end). 

JUnit combat chapter

  JUnit combat chapter 

  Foreword 

  Because now companies Unit Test Case finishing stage, a time of Junit to understand, the following is a collection of all-director of the essence (as I consider is the idea of summing up, might not be entirely the author's expression of ideas, in Appendix I have all the reference articles address, we may wish to see the original). 

  First, the concept of testing 

  For a long time, I have come in contact with the software developer few people in the process of developing the testing work.    Most of the projects are in the final acceptance test of time to prepare documents, some of the projects did not even test the document.    Now the situation has changed.    We have always advocated UML, RUP, software engineering, CMM, the only one objective to enhance the quality of software development.    Cite an extreme example: If you are a super architect, a legendary figure (you can drink coffee side, while listening to the music, while the preparation of this operating system on the process of scheduling module, and within two days completed!).    I really have to admit that there are such people (that in the preparation of UNIX vi editor This is the guy).    However, It is very unfortunate that these gods were and did not leave any on how to thoroughly transform the README, so those of us mortals - at the same time can only focus on the number of points (according to the scientific statistics, I do not believe that the general At the same time the people can only consider a maximum of about seven, experts can achieve about 12), and the overall situation can not be both an overview and to understand the details - can only hope in other ways to ensure that we are prepared in software quality. 

  To illustrate those of us mortals how stupid.    A smart person entropy of the software (software entropy) of the concept: a good design process from beginning, with the new features added constantly, procedures gradually lose the original structure, and ultimately become a Yiqiuluanma .    You may argue that in this case, the design of the state is not very good, and if good, it would not have happened you said the situation.    Yes, it seems that you get smarter Unfortunately, you should also be noted that two issues: 1) We can not expect in the dinosaur era (about 10 years ago) to the design of the structure can now apply it; 2) The signature customer representatives can ignore whether or not to add a new function of the structure of the software will have any effect, the procedure is even influential designers need to consider the issue.    If you think that your refusal to accede to this deadly new features, then you may lose your housing loans, and bread (on the Chinese engineers, perhaps rice or noodles, it all depends on you southerners or northerners). 

  In addition, the need is that I have read some books on the test I have not written in such a human face (sorry ..    I would like to see the article brothers and sisters can be very easy to accept the concept of testing, and implementation.    Therefore, some local write some exaggeration, welcomed the test-depth understanding of our brothers and sisters to understand the public's sentiments, and spared Comments. 

  Well, we now get down to business again.    To test, it is necessary to understand the purpose of testing.    I think that the purpose of testing is very attractive is simple: high-quality software to write software entropy and resolve this issue.    Imagine, if you write software and Richard Stallman (GNU, FSF's head) is the same as the written standard, it is not great sense of accomplishment?    If you have maintained such high standards, I guarantee that your salary will vary. 

  Categories tested, white box testing, black-box testing, unit testing, integration testing, functional testing ….    No matter how many of us first classification to classify.    We look at those useful classifications, on the other tests, interested persons may refer to other information.    White box testing refers to the software being tested know how (How) completed and the completion of what function (What) function under the conditions of the test.    Is generally completed by the developer.    Because developers know their preparation software.    This paper is mainly white box testing.    Black-box testing is being tested in the software know what completed (What) function under the conditions of the test.    General staff from the testing is completed.    Black-box testing is not our focus.    This paper mainly concentrated in the unit testing, unit testing is a white box testing.    Purpose is to verify one or several categories according to whether the design work as normal.    Integrated testing is to verify whether all of a co-ordinated, collaborative completion of a specific task, we now not concerned about it.    Now I mentioned the testing, unless otherwise specified, are generally refers to unit testing. 

  Needs to be emphasized: testing is a continuous process.    That is the development and testing throughout the whole process, the unit test is especially suitable for incremental iteration (iterative and incremental) development process.    Martin Fowler (a bit like the words quoted Confucius) even said: "You do not know how to test the code before the procedure should not be prepared. Once you have completed the procedures to test code should also be completed. Unless tested successfully, you can not think you write a procedure can work. "I do not expect all developers will have such a high awareness of this level and it takes time.    But once we understand the purpose and benefits of testing will naturally insist on the introduction of test development process.    Because we are testing new, we do not disregard the complex test theory, first talk about the most simple: test is whether the expected results compare with the actual implementation of the results.    If the agreement is approved, it failed.    Look at the following example: 

  / / Will be tested in the category 

  Public class Car 

  ( 

  Public int getWheels () 

  ( 

  Return 4; 

  ) 

  ) 

  / / Test the implementation of the class 

  Public class testCar 

  ( 

  Public static void main (String [] args) 

  ( 

  TestCar myTest = new testCar (); 

  MyTest.testGetWheels (); 

  ) 

  Public void testGetWheels () 

  ( 

  Int expectedWheels = 5; 

  Car myCar = new Car (); 

  If (expectedWheels == myCar.getWheels ()) 

  System.out.println ( "test [Car]: getWheels works perfected!"); 

  Else 

  System.out.println ( "test [Car]: getWheels DOESN'T work!"); 

  ) 

  ) 

  If you write immediately hands the above code, you will find two questions: 

  First, if you want to test the implementation of the class testCar, you have to be manually Knock the following order: 

  [Windows] D: \> Java testCar 

  [Unix]% java testCar 

  Even if the tests show the cases as simple as that, you also may be reluctant to test each time knockin above orders, and hope that in a integrated environment (IDE) mouse click will be able to implement testing.    The following chapter will be introduced to these problems. 

  Secondly, if not certain norms, such as test preparation will be a need for another definition of the standard.    Nobody wants to see that others are testing the design category.    If everyone has a different design of the test methods, test-maintenance category was getting bored enough, who Gudeishang maintenance test-class?    In addition there is one point I do not want to mention, but this issue is too obvious that the test of the code being tested more than the class!    Does this mean that this double?    No! 

  1) Regardless of the test categories - Car getWheels method of the complex, testing categories - testCar testGetWheels the only way to maintain the same volume of code. 

  2) improve software quality and software entropy solve this problem is not price.    TestCar is price. 

  We can do is to reduce the costs of: We have prepared the test code maintenance personnel to be easily read, we have to prepare test code, there must be certain norms.    IDE tools that can best support these norms.    Well, you want to have a JUnit.    An Open Source projects.    On its home page with the words: "JUnit by Erich Gamma and Kent Beck prepared a regression testing framework (regression testing Framework). For Java developers to write unit testing purposes." Is the so-called framework Erich Gamma and Kent Beck set a number of rules, prepared by the test code you must follow this boxed: Inheriting a category to achieve a certain interface.    In fact, what we said earlier norms.    Fortunately, the current JUnit Most software engineers have been authorized.    We will follow JUnit got a lot of support.    Regression Testing is that you constantly prepared by the code of conduct test: prepare, test some, some debugging, and then cycle of the process, you will continue to repeat the previous test, even if you are preparing other categories, due to a software entropy there, you might type in the preparation of the fifth when found, the fifth such an action would lead to the second category of the test failed.    Through regression testing of us to seize this great Bug. 

  Second, why should JUnit profiles and the use of JUint 

  JUnit is the code to a Java unit testing framework.    Each modification procedures adopted after the test code, programmers can be assured that a small amount of code changes would not undermine the whole system.    Without such a Junit automated testing tools, the code will simply repeated tests were exhausted but also may be inaccurate.    Well now, the testing process can be frequent but also automatic, so you can make procedural mistakes to a minimum.    It is about testing unit (Unit Test): software engineering, the White-box Testing is a kind of a testing method functions.    XP respected in the test first design is based on the above technology. 

  If you write a section of code: 

  1. To use junit written test, and then write the code 

  2. Finished writing the code, testing, testing failure 

  3. Revised code, testing until the test successful 

  If after the revised procedures, and optimize (refactoring), as long as the re-testing code, if all the tests are successful, then the code revision completed. 

  The Java development team, the general cvs (version control) + ant (project management) + junit (integration testing) model: 

  1. Go to work every morning, every development from the cvs server access to a copy of the entire project work; 

  2. Get their own tasks, to use today junit write the mandate of the test code; 

  3. Tasks today and then write the code, testing until the test pass, the tasks have been completed; 

  4. In the 12 hours before the work, all of the developers submitted to the cvs server tasks; 

  5. Then in charge of the entire project running automatic testing, which tests mistakes, find relevant personnel changes until all test pass.    Work … 

  First written test, write code benefits: 

  Technically you first consider a mandatory class function, which is to provide this type of external interface, and not too early into the details of it.    This is an advocate of object-oriented design principles.    In fact, good test is a good document, this group of users can often see through this kind of test code for understanding its function.    In particular, if you get a procedure for others, he wrote test is the best understanding of the functions of the procedures.    Xp principle is make it simple, the writing is not recommended other documents, because the project in the development process of change is often, if the document written in the early days, after the code changes must file synchronization, one more work, and Because of the tight schedule projects are often incomplete or written documentation and code inconsistencies, instead of this, they would rather not write.    If the written document after the end of the project, developers often forget to write code at the various considerations, and since under the pressure of a project, managers are reluctant to re-write the project for the old documents, resulting in the issue of safeguarding the future .    No one can guarantee that demand does not change the past, projects are often significant changes in the demand for headaches, fear the changes will bring other parts of the error.    For this reason, in addition to design structures to separate good projects (loosely coupled), but if a test, and has already established a good testing framework to demand change, modify End code, as long as the re-testing code, if Test passed, the amendment will guarantee success, if the test errors will be found immediately Where goes wrong, and modify the corresponding part of further testing until the test entirely through. 

  Software companies often sector development and testing of the contradiction between the departments: Since the development and testing of two departments, more than a layer of cost and time to communicate, communicate often a wrong from occurring.    And easily form a vicious circle: developers rush to task, Black Black wrote the code, so it threw test, and then write other tasks, testing course is a failure, again took back the code rewrite, and in software companies often a domestic technology sector is the worst test departments (good people go to write code), and tests have become a very big headache problem.    The root of this vicious circle is unclear responsibility, in accordance with the provisions of xp: wrote this code must write code for their own testing, and only through testing, to be completed this task (including the test here all the testing, if the test As you found that the procedure leading to the failures other modules, you have the responsibility to inform the relevant until modified through the integration testing), so as to prevent the occurrence of such problems. 

Tomcat 5 clusters in the reproduction of a SESSION (AP)

  Tomcat 5 server clustering and replication SESSION provides integrated support.    The first in this series of articles will provide you with SESSION persistent and TOMCAT cluster SESSION copy of a summary of internal working mechanisms awareness.    I will discuss SESSION TOMCAT5 copy of what is in the cluster, as well as across multiple nodes SESSION persistent replication mechanism.    In Part 2, I will discuss in detail with a copy function TOMCAT SESSION cluster installation example, and compare different replication situation. 

  Cluster Server traditional independent (non-cluster) does not provide any failure seamless transfer and load balancing capability.    When a server failure, will not be able to access the entire site, unless the server is renewed.    The server failure, any stored in the server's memory SESSION will be lost, the user must re-enter all the landing and server failure due to the loss of data. 

  The difference is that, as part of the Cluster Server provides failure can be measured and seamless transfer of capacity.    A cluster is a group of synchronous operation and work together to provide high reliability, high stability and high predictability of the multi-server routines.    On the server cluster seems to be demonstrated by the client is a single server routines.    From the client's perspective, the client group and a separate server not much different, but their effectiveness by providing a seamless transfer and replication SESSION done SESSION uninterrupted services, as well as data persistence. 

  Cluster servers in the cluster communication server applications such as IP multicast (IP multicast) IP sockets and the other server technology and the sharing of information ● IP multicast: mainly used for more than one pair of communications servers through broadcasting services and heartbeats news server can be used to show that the effective ● IP sockets: mainly used in the cluster server routines in a P2P server communications using a one-to-many using IP multicast communications server TOMCAT use IP Multicast transmission in the cluster server routines between one-to-many communication, IP multicast is a multi-server allows the designated IP address and port, and a subscription to monitor news broadcasting technology (multicast IP address range from 224.0.0.0 to 239.255.255.255).    In each server in the cluster using multicast broadcasting heartbeat specific information by monitoring these heartbeat, in the cluster server routines decide when routines server failure.    Server communications using IP multicast of a drawback is that he can not guarantee that such information is being received by the.    For example, a continuous application of the local multicast cache full, it can not be written into the new multicast information, such as the information after the application procedures have not been notified to. 

  The use of IP Sockets for server communications IP sockets also adopted a set of servers in the cluster between news and data sent mechanism.    Server IP sockets in the routine use of cluster nodes between HTTP SESSION state replication.    SOKET correct preparation for the performance of clusters is essential, based on the efficiency of communication SOCKET SOCKET depends on the realization of categories (for example: the use of the local system or net realized JAVA SOCKET reader), if the use of server-JAVA SOCKET Reader depends on whether the registration server routine use sufficient SOCKET reader thread. 

  If you want to have the best SOCKET performance, the system should be registered to use local rather than pure SOCEKT JAVA Implementation.    This is because of the realization SOCKET based on JAVA, local SOCKET consume fewer system resources.    Although the reader SOCKET JAVA Implementation of P2P communication is a reliable way and can be mobile, but he was not in the cluster of heavy use SOCKET provide the best performance.    When judging whether data from SOCKET read when local SOCKET readers use more efficient methods.    SOCKET use of local readers realize, readers do not need to thread statistical static SOCKET: They only for the activities of the SOCKET services, and to set a start SOCKET active, they can immediately capture.    And the use of pure JAVA SOCKET readers, threads must be dynamic statistics all open SOCKET, see whether they contain can be read data.    In other words, the reader is always busy SOCKET SOCKET statistics, even if these SOCKET no data readable.    These systems should not reduce performance overhead. 

  TOMCAT 5 clusters TOMCAT5 While the earlier version also has the function of clusters, but in a later version (5. .19 Or higher), the cluster becomes more components of the module.    Server.xml elements in the cluster have been reconstructed so that we can replace some of the different clusters and will not affect other elements.    For example, the current configuration of the service members set to multicast found.    Here can easily be modified to serve the replacement for the use of TCP or Unicast, and will not change the collection of other parts of the logic. 

  Cluster some other elements, such as SESSION management, copy the sending end, copying the receiving end can also be replaced by the realization of the definition of cluster configuration without affecting other parts.    Similarly, in TOMCAT Cluster Server component of any set of API can be used to cluster in the information sent to all the members. 

  SESSION replication server clusters usually manipulated two SESSION: sticky sessions and replicated sessions.    Sticky sessions is that there is a single server in the network accepted the request SESSION, other members of the Cluster Server SESSION state entirely unclear if there SESSION server fails, users must once again landing site, to re-enter all stored in SESSION in the data. 

  Another SESSION type, in a state SESSION server to be copied in all other cluster server, whenever they SESSION was changed, the data must be re-SESSION being copied.    This is replicated session.    Sticky and replicated sessions have their advantages and disadvantages, Sticky sessions simple and easy to operate, because we do not have any SESSION copy data to other servers.    This system will reduce consumption and increase performance.    However, if the server fails, all stored in the server's memory SESSION data will also disappear.    SESSION If data has not been copied to other servers, these SESSION completely lost.    When we were conducting a search affairs when the loss of all data entry, will lead to a lot of problems. 

  To support JSP HTTP session of the state will expire automatically seamless transfer, TOMCAT server replication in memory of the state SESSION.    This is achieved through replication stored in a server on the cluster SESSION data to prevent other members of data loss and failure to allow a seamless transfer. 

  Object state management on the server through the preservation of state can be divided into four kinds of objects: 

  ● No state: a non-call in the state of the object in memory when not in the preservation of any state, because the client and server do not need to store any of the other information.    In such circumstances, each client will request the server will send data to the server.    SESSION state was in the client and server side sent back and forth.    This method is not always feasible and desirable, especially when transmission of data security or some more information we do not want to save the time in the client; 

  ● conversation: a session object in a SESSION only be used for a particular client.    In SESSION, for all he can from the client requests services, and this is only the client's request.    Through a SESSION, two requests the state information must be preserved.    Conversational services are normally stored in the memory of the short-term state, when the failure of the server may be lost.    SESSION state requests are usually kept in the server memory.    In order to empty the memory SESSION state can also be released from memory (as in an object CACHE).    In the object, performance and scalability are yet to be improved because the update was not a separate written on the disk, and the failure of the server when data there is no way the rescue. 

  ● Cache: Cache object in memory preservation status, and use this to deal with the multi-client to the request.    Cache services can be extended to the realization of their cache is stored in the back-end data backup memory (usually a relational database). 

  ● independent: an independent object in a time only active in a cluster of servers, from the processing of multi-client requests.    He usually by those private, long-lasting, in memory of the data to support relief inch.    He also has short-term memory to maintain the state, the server failure or loss of time to rebuild.    When failure, must be independent object in the same server or resumption of transplantation to another server. 

  (Source: "Using WebLogic Server Clusters") 

  SESSION copy of the design considerations of the network considerations Cluster multicast address and other applications isolation is essential.    We do not want cluster configurations or interfere with the distribution network to multicast communications server.    And other applications sharing cluster multicast address will force Cluster Server routines should not be dealt with the news consumption of system memory.    Sharing multicast addresses may also make IP multicast buffer overload, delayed messaging server heartbeat.    This delay may result in a server routines be marked for death simply because of his heartbeat was not timely receive information. 

  Programming considerations in addition to the above-mentioned factors related to the network, and we wrote some J2EE Web application design considerations relating to the procedure will affect SESSION reproduction.    Here is a list of some of the programming aspects to consider: 

  ● SESSION sequence of data must be: In order to support HTTP session state replication of memory, all the servlet and JSP session of the sequence data must be, the targets for each domain must be sequences, such objects are reliable serialization. 

  ● to applications such as the design of power: the power, and so is the meaning of a parade do not revise the state information, and the time of each operation to return to the same result (in other words: do so many times and the effect of a is the same), usually, WEB request, in particular HTML forms have been sent many times (when the user clicks the Send button twice Heavy pages many times), resulting in multiple HTTP requests.    WEB design SERVLET and other targets, such as power, I can tolerate repeated requests.    Detailed reference design model to be "Synchronized Token" and "Idempotent Receiver" on how to design such as power applications. 

  ● BUSINESS-tier storage in the state: the state should use a conversational state SESSION BEANS stored in the EJB layer, and not stored in the HttpSession WEB layer.    Because enterprise applications to support various client (WEB client, JAVA applications, other EJB), the data storage layer in the WEB client will result in double-data storage.    Therefore, it is the state SESSION BEAN in these circumstances to be used for storage SESSION state.    No state SESSION BEAN call for the re-structure of each session state.    These states may have to resume from the database-data compiler.    These shortcomings lost the use of non-state SESSION BEAN to enhance performance and scalability of the purpose of reducing serious performance. 

  ● Sequencing System consumption: in the sequence of data replication SESSION SESSION time to the state system will be more consumption.    With the sequence of the target size of the growth of consumption has more.    SE is to maintain the best 

Jdom Reading and Reading XML database generation insert XML database

  1. First revenue package is intended to http://jdom.org. Download, the latest version is the current jdom-1.0.zip. 

  2. Then its extract, and the build folder jdom.jar, its copy to your jdk installation directory lib Below, also copied to the installation directory jdk jre folder under the ext lib, This directory will be added to the classpath environment variables.    Such as: d: / jdk1.4/jre/lib/ext/jdom.jar and d: / jdk1.4/lib/jdom.jar. Addition to the attention of the problem is that you document storage java path to be added to the classpath As java environment variable settings, I do introduced here. 

  3. In this example I used in the database is mysql, I prefer because it is open-source and free things, so select it.    As for the specific version is as follows: 

  Mysqlcc-0.9.4-win32.zip / / graphical control interface 
  Mysql-5.0.0a-alpha-win.zip 
  Mysql-connector-java-3.0.17-ga.zip / / connect Driver In fact, the jar packets can be other versions.    I installed concrete here not say, If we do not understand, will be to find a goole relevant information can be:) 

  First I look at the design of the database table: for the sake of simplicity I only thoughtful a database containing two tables jdomdb, including a table of user information is stored userinfo table, and is used to store a demonstration of documents to read xml insert data inside the database table tmpinfo. 

  Below started to create a database table of information as below: 


  Table userinfo is part of the left field information.    At the same time table tmpinfo field information is the same.    I am also here to provide a database table structure jdomdb.sql document, as long as you establish a good name jdomdb database, and then can be introduced into the. 

  We must be prepared to demonstrate the basic data, here we have adopted a document testdb.jsp jsp to insert some data.    You can either direct hand in the table inserted several data. 

  4. Download package in the document: 

  Reading database and data export to XML documents in the document: ExtraXml.java guided by the document which called userinfo.xml; 
  Reading XML documents and data into the database file: ReadXml.java; 
  Packaging operations, such as the database connection JavaBean documents: DBConn.java; 
  There is a good example of this is ExtraXml3.java package, as long as the corresponding call javabean call on it. 
  I jdomdb.sql guided by the basic structure of the database tables can be imported directly. 
  There must be used by the jdom.jar package. 

  Download link: Attachments: javaXML.rar (150K) 

JBoss middleware 5 usher in the era completely configurable

  Object-oriented founder of Grady Booch said: The great thing about objects is they can be replaced. Object of the greatest of its can be replaced (this is also one of the main reasons to use OO). 

  Each object are alternative means that a high degree of flexibility, we have dreamed of "assembly-on-demand" era of the Ioc mode / rely on micro-injection of containers can help us to achieve the targets of irreplaceability. 

  Spring / HiveMind including Jdon Framework is composed of a micro-Ioc containers in the Java Enterprise System Architecture Choices consider a text, I have flexibility in the structure of several components were compared. 

  One of the important question: is POJO EJB3?    There are two concepts: whether to support the POJO EJB3?    Is POJO EJB3 itself?    The former answer is yes, but the latter was in the negative. 

  In response, we need to have a detailed understanding of POJO, initially proposed EJB POJO is relative, Martin Fowler on the POJO definition is: I found: People have forgotten the original Java Object normal, because these objects do not have a very special name ,…. so I named them POJO (Plain Old Java Object), a POJO domain model easy to put together, and rapid build in EJB containers outside running and testing, and do not rely on EJB.    Http://mindprod.com/jgloss/pojo.html 

  However, with EJB3 support POJO, POJO concepts from the original definition of relative EJB has been extended, and that the object of a rather flexible, that is, can be replaced at any time of the object, not because of any attachment framework can not be replaced. 

  Well, it is POJO EJB3 itself?    EJB container practical significance is whether POJO, that is to say: whether the EJB component itself can be replaced? 

  As I said in the Java Enterprise System Architecture Choices, a text written in consideration when we only need EJB3 clusters, and the Panel, and other basic functions are not necessary, we will support EJB server configuration and the arbitrary cut?    I would like to replace or one of the basic features of whether we can be arbitrary for the switch, which is Grady Booch the phrase: whether the object can be replaced? 

  Of course, this "EJB3 Is POJO" discussion, it was quoted saying foreigners: EJB3 itself is not discussed significance POJO Unfortunately, he said this concept of the foreigner did not meet their latest ideas. 

  Then, as a component structure, and whether the system can support both the application of any component object can be replaced, but also support for the framework is its own components can be replaced, whether the state can be achieved? 

  No question, at present, open-source software and HiveMind Jdon framework can support the complete replacement of the so-called complete framework that can replace some of its functions are also configurable, and can be embedded, not just the application can be replaced. 

  This realization of the component structure of the complete and thorough can be configured, or is a Embeddable Plug-in structure, the structure may allow developers to intervene in any level outreach and maintenance, which can be customized to create a powerful and to broaden and can use the metaphor of architecture, such Embeddable structure similar to the construction of reinforced structure, it's only a fixed number of frameworks and Banjin, what you like of the room entirely by you to decide.    The only limit is your imagination has. 

  Now, as the leading EJB3 container design JBoss open-source software version of the upcoming JBoss 5, in its version of the JBoss 5, the micro-core itself can be configured, and ultimately to achieve EJB3 thorough configurability. 

  Let us look at JBoss Blog (http://www.jboss.org/jbossBlog/blog/) this paragraph: 

  JBoss micro containers will be a complete inversion control, the injection dependent on light volume containers, it allows you through XML configuration POJO, POJO has its own life cycle, as a service to Service, it does not need the JBoss application server, .. Most of JBoss will provide the function will be to POJO, and can be configured … these will be in the 2006 version of the JBoss 5 fully realized. 

  This scene in the video (http://www.javalobby.org/av/javazone/69/aardal-jboss) Thomas Roka-Aardal introduced JBoss 5 - lightweight middleware with EJB3, who introduced the Java enterprise will be simplified and enhanced through a combination of new JBoss Microkernel, showed what a genuine lightweight application server, it is what the market will influence future development of the enterprises, middleware will be everywhere to be seen. 


  For now, most beginners, first of all, need to Jsp Java code embedded in the bad habit of changing, and your Java code using JavaBeans components to achieve, and then gradually going on for components (a component-oriented) Development , which rose to the components can be completely configured programming level. 

  JBoss 5 in the introduction, J2EE have been accused of In-House, that is to say, many functions bundled in J2EE server, based on the birth of many JBoss, based on Weblogic, Oracle-based, or even based on the J2EE JMX applications, When such a J2EE application system needs to transplantation, and because of those dependent containers / server viscous Talao, and unable to run with application systems. 

  So over the years, the industry has been urged to use Out-of-Box, Spring / HiveMind / Jdon framework should be such as respiratory and health, and Rod Johnson in the 2005 JavaOne conference on the prophetic speech: J2EE/Java EE will move toward a framework for the Centre the development of the new era.    In this way, applications rely on the many functions in the framework of, and the framework and applications can be everywhere transplant. 

  Obviously, such an Out-of-Box advocacy on JBoss line has posed a challenge to JBoss rose reaction, since you accused me of containers is a Box, then we Yibuzuoerbuxiu income, to break the Box, the forthcoming birth of JBoss 5 because JBoss itself can be dismembered 5 can be configured and, therefore, the use of the JBoss Java EE 5 applications need a transplant, you can rely on the system will be applied to those functions from JBoss five separate containers, with a run, so you Application System and the Java EE standards in the unique and can also containers as a framework with the run. 

  Of course, because the current standards including J2EE EJB also from the actual development section of the road, it did not put forward a programming model, as a sub-standard application server JBoss or in the practical application of the need to develop a framework of support, provide a powerful comprehensive Spring API library; HiveMind provide a flexible configuration, and a thorough Jdon framework can be configured based on the target application development in the investigation of these additions and deletions to achieve default functions, improve development efficiency, avoid large-scale development in these low-labor - level work. 

  On Out-of-box and break the box, the future components (components) will have a framework for the field, it was said, you forget about how Weblogic and Websphere?    There is one point I forget that, the fully configurable from the open source movement is stirring up the field, that is, the component architecture design, the open source movement has been at the front of the industrial sector, the industrial sector is running giants They spied on the strengths of money: Integration and the SOA. 

Use caching mechanisms fast data read XML documents

  Received a mandate, let me do the background of a company's Web site management system.    Request is simple, a press release and a recruitment module Information module.    But not the DB, can only be realized in the form of access to documents. 

  Certainly not consider using XML documents for data access, before doing a complete realization of the time had a similar function, so read on XML and there is no problem.    If the key is to consider the performance of the issue should be deliberated about, and I was new, before the design has not done anything, so to make things in some people's eyes there may be immature, and anything it does not matter, and take our own path for others to speak:) 

  If frequent analytical document, speed definitely be affected, in the document very large cases, even unbearable.    If the server is started when the first data in the document object arrays packaged as read to the cache, each visit to determine when the documents you want to visit entities have been updated, if not updated, directly from the cache will want to read out the data, of course, if the files are updated, but honestly that the analytical document to read out the data.    Managers number of changes to the document, after all, is one of the few, more visitors is the number of visits.    This will greatly increase access speeds, the cost to occupy certain memory space, but should be compared Xiaowu bar. 

  Below the simple realization of the few Class say. 

  Cache a realization of a first category, there are readers get the method of object (), if the documents are not modified, directly from the HashMap object inside will be removed, if the file is modified, calling readObject () method from the paper Douchushuju, and will be read out at the same time the data Add HashMap, will be the object of the original coverage.    This time next read data can be read directly from the cache, and that the latest data.    There is a judgement of whether the document was revised method getModified (); 

  Code as follows: 

  Import java.io.File; 
  Import java.util.HashMap; 

  (Public class Cache 

  HashMap mapLastModified = new HashMap (); 
  HashMap mapValues = new HashMap (); 
  Public Cache () ( 
  Super (); 
  ) 
  Public Object get (String name, String path, Class clsParser, Class clsInstantiator, Class clsObj) ( 
  Object obj = null; 
  String absPath = getClass (). GetResource (path). GetPath (); 
  Long modified = getModified (name, absPath); 
  If (modified! = Null) ( 
  Obj = readObject (absPath, clsParser, clsInstantiator, clsObj); 

  MapLastModified.put (name, modified); 
  MapValues.put (name, obj); 
  System.out.println ( "get object from file"); 
  Else () 
  Obj = mapValues.get (name); 
  System.out.println ( "get object from cache"); 
  ) 
  Return obj; 
  ) 

  Private Long getModified (String name, String path) ( 
  Long modified = new Long (new File (path). LastModified ()); 
  Long saveModified = (Long) mapLastModified.get (name); 
  If ((saveModified! = Null) & & (saveModified.longValue ()> = modified.longValue ())) ( 
  Modified = null; 
  ) 
  Return modified; 
  ) 

  Private Object readObject (String path, Class clsParser, Class clsInstantiator, Class clsObj) ( 
  Try ( 
  FileParser parser = (FileParser) clsParser.newInstance (); 
  Instantiator instantiator = (Instantiator) clsInstantiator.newInstance (); 

  Object config = parser.parse (path); 
  Return instantiator.instantiate (clsObj, config); 

  ) Catch (InstantiationException e) ( 
  E.printStackTrace (); 
  ) Catch (IllegalAccessException e) ( 
  E.printStackTrace (); 
  ) 
  Return null; 
  ) 
  ) 

  The analytic category XmlFileParser XML documents, 

  In order to facilitate the processing of documents of different analytical, where FileParser first definition of an interface, XmlFileParser achieve it, if there are other types of documents, such as the analytic can also reach it. 

  / / FileParser.java 
  (Public interface FileParser 
  Object parse (String path); 

  ) 

  / / XmlFileParser.java 
  / / The analytical methods used Jdom import java.io.FileInputStream; 
  Import java.io.IOException; 
  Import org.jdom.Document; 
  Import org.jdom.Element; 
  Import org.jdom.input.SAXBuilder; 

  Public class XmlFileParser implements FileParser ( 

  Public XmlFileParser () ( 
  Super (); 
  ) 

  Public Object parse (String path) ( 

  FileInputStream fi = null; 
  Try ( 
  Fi = new FileInputStream (path); 
  SAXBuilder sb = new SAXBuilder (); 
  Document doc = sb.build (fi); 
  Element root = doc.getRootElement (); 
  Return root.getChildren (); 
  ) Catch (Exception e) ( 
  E.printStackTrace (); 
  Finally () 
  Try ( 
  Fi.close (); 
  ) Catch (IOException e1) ( 
  ) 
  ) 
  ) 
  ) 

  Next is a three examples of the type ListTypeInstantiator deal with the same document in order to facilitate the processing of different examples, in the first definition of an interface here Instantiator, ListTypeInstantiator achieve it. 

  / / Instantiator.java 
  (Public interface Instantiator 
  Object instantiate (Class clazz, Object configuration); 
  ) 

  / / ListTypeInstantiator.java 
  Import java.util.ArrayList; 
  Import java.util.List; 

  Import org.apache.commons.beanutils.BeanUtils; 
  Import org.jdom.Element; 

  Public class ListTypeInstantiator implements Instantiator ( 

  Public ListTypeInstantiator () ( 
  Super (); 
  ) 

  Public Object instantiate (Class clazz, Object configuration) ( 
  List arr = new ArrayList (); 
  Object bean = null; 

  List children = (List) configuration; 
  Element child = null; 

  List attributes = null; 
  Element attribute = null; 

  Try ( 
  For (int i = 0; i <children.size (); i + +) ( 
  Child = (Element) children.get (i); 
  Clazz.newInstance bean = (); 
  Child.getChildren attributes = (); 
  For (int j = 0; j <attributes.size (); j + +) ( 
  Attribute = (Element) attributes.get (j); 
  BeanUtils.setProperty (bean, attribute.getName (), attribute.getText ()); 
  ) 
  Arr.add (bean); 
  ) 
  ) Catch (Exception e) ( 
  E.printStackTrace (); 
  ) 
  Return arr; 
  ) 
  ) 

  4 Also, I need a package to the JavaBean data format, here as a NewsBean (). 

  / / NewsBean.java 
  (Public class NewsBean 

  Private Long id; 
  Private String newsTitle; 
  Private String newsContent; 
  Private String newsType; 
  Private String deployDate; 
  Private String cancelDate; 

  Public Long getId () ( 
  Return id; 
  ) 
  Public void setId (Long id) ( 
  This.id = id; 
  ) 
  Public String getNewsTitle () ( 
  Return newsTitle; 
  ) 
  Public void setNewsTitle (String newsTitle) ( 
  This.newsTitle = newsTitle; 
  ) 
  Public String getNewsContent () ( 
  Return newsContent; 
  ) 
  Public void setNewsContent (String newsContent) ( 
  This.newsContent = newsContent; 
  ) 
  Public String getNewsType () ( 
  Return newsType; 
  ) 
  Public void setNewsType (String newsType) ( 
  This.newsType = newsType; 
  ) 
  Public String getDeployDate () ( 
  Return deployDate; 
  ) 
  Public void setDeployDate (String deployDate) ( 
  This.deployDate = deployDate; 
  ) 
  Public String getCancelDate () ( 
  Return cancelDate; 
  ) 
  Public void setCancelDate (String cancelDate) ( 
  This.cancelDate = cancelDate; 
  ) 
  ) 

  Five final step test results, the paper will be put news.xml classes directory. 

  / / MainClass.java 

  Import java.util.List; 
  (Public class MainClass 

  Public static void main (String [] args) throws Exception ( 

  List news1 = null; 
  List news2 = null; 
  NewsBean bean = null; 

  News1 = (List) Cache.get ( 
  "News", "/ news.xml" 
  XmlFileParser.class, ListTypeInstantiator.class, NewsBean.class); 
  For (int i = 0; i <news1.size (); i + +) ( 
  Bean = (NewsBean) news1.get (i); 
  System.out.println (bean.getId ()); 
  System.out.println (bean.getNewsTitle ()); 
  System.out.println (bean.getNewsContent ()); 
  System.out.println (bean.getNewsType ()); 
  System.out.println (bean.getDeployDate ()); 
  System.out.println (bean.getCancelDate ()); 
  ) 
  News2 = (List) Cache.get ( 
  "News", "/ news.xml" 
  XmlFileParser.class, ListTypeInstantiator.class, NewsBean.class); 
  For (int i = 0; i <news2.size (); i + +) ( 
  Bean = (NewsBean) news2.get (i); 
  System.out.println (bean.getId ()); 
  System.out.println (bean.getNewsTitle ()); 
  System.out.println (bean.getNewsContent ()); 
  System.out.println (bean.getNewsType ()); 
  System.out.println (bean.getDeployDate ()); 
  System.out.println (bean.getCancelDate ()); 
  ) 
  ) 

  From the first document Douchushuju, the second will read from the cache, and try to read a rate several times faster. 

Java socket programming (6)

  Java socket programming (6) 

  Multicast and MulticastSocket category 

  The previous examples show that the server send a single thread information (via socket or self-addressable socket) to the only client program, such acts as a single point of access (unicasting), the majority of cases not suited to a single point of delivery, such as rock singer for a concert will be broadcast through the Internet, the picture and sound quality depends on the transmission speed, the server process to transfer about 10 billion bytes of data to the client process, using a single point of delivery, then each client to be a copy of the data, if, the Internet has 10,000 clients to watch the concert, then the server process via the Internet to send 10000 G data, which will inevitably lead to network congestion reduce network transmission speed. 

  If the server to send the same message to more than one client, server and the client can use the multicast (multicasting) form of communication.    Multicast service program is dedicated to the multicast group of IP address and port sent a series of self-addressable data packets, IP addresses by adding operation was multicast Socket registration, the client can receive points sent to the group Since the addressable packets (the same client can also send to the group since the addressable packets), once the client to finish reading all the self-addressable data packets, then the operator can leave the group left the multicast group. 

  NOTE: IP address 224.0.0.1 to 239.255.255.255 (including) are retained multicast group address. 

  API through the network and MulticastSocket MulticastSocket category, as well as some supporting category (for example NetworkInterface) support multicast, when a client application to join the multicast group, to create a MulticastSocket object.    MulticastSocket (int port) constructor function allows applications to the specified port (through the port parameters) to receive the addressable packets, and the port must be procedures and services of the port matched to join the multicast group, clients call two joinGroup ( ) in a way, to leave the same transmission group, also called two leaveGroup () method in one. 

  As MulticastSocket expanded DatagramSocket category, a target has the right to visit MulticastSocket DatagramSocket methods. 

  List6 is MCClient source code, the code model of a client to join multicast group example. 

  Listing 6: MCClient.java 
  / / MCClient.java 

  Import java.io. *; 
  Import java.net .*; 

  Class MCClient 
  ( 
  Public static void main (String [] args) throws IOException 
  ( 
  / / Create a MulticastSocket bound to local port 10000. All 
  / / Multicast packets from the server program are received 
  / / On that port. 

  MulticastSocket s = new MulticastSocket (10000); 

  / / Obtain an InetAddress object that contains the multicast 
  / / Group address 231.0.0.1. The InetAddress object is used by 
  / / DatagramPacket. 

  InetAddress group = InetAddress.getByName ( "231.0.0.1"); 

  / / Join the multicast group so that datagram packets can be 
  / / Received. 

  S.joinGroup (group); 

  / / Read several datagram packets from the server program. 

  For (int i = 0; i <10; i + +) 
  ( 
  / / No line will exceed 256 bytes. 

  Byte [] = new byte buffer [256]; 

  / / The DatagramPacket object needs no addressing 
  / / Information because the socket contains the address. 

  DatagramPacket dgp = new DatagramPacket (buffer, 
  Buffer.length); 

  / / Receive a datagram packet. 

  S.receive (dgp); 

  / / Create a second byte array with a length that matches 
  / / The length of the sent data. 

  Byte [] buffer2 = new byte [dgp.getLength ()]; 

  / / Copy the sent data to the second byte array. 

  System.arraycopy (dgp.getData (), 
0,
  Buffer2, 
0,
  Dgp.getLength ()); 

  / / Print the contents of the second byte array. (Try 
  / / Printing the contents of buffer. You will soon see why 
  / / Buffer2 is used.) 

  System.out.println (new String (buffer2)); 
  ) 

  / / Leave the multicast group. 

  S.leaveGroup (group); 

  / / Close the socket. 

  S.close (); 
  ) 
  ) 
  MCClient creation of a bundled port of 10000 MulticastSocket target, the next he was a target InetAddress subclass, the type of target group includes multicast IP address 231.0.0.0, and then through joinGroup (InetAddress addr) method by adding more transmission points in the group receiving 10 next MCClient since addressable packets, and the content of their output, and then use leaveGroup (InetAddress addr) method from transmission group, the final closure of socket. 

  Perhaps you on the use of an array of two-byte buffer and buffer2 surprised when receiving packets to a self-addressed, getData () method returns a quote, since the length of the packet addressing 256 bytes, if we export all data, End actual output in the data will have a lot of space, which is obviously unreasonable, we must remove these spaces, so we created a small byte array buffer2, buffer2 the actual length is the actual length of data, by calling DatagramPacket''s getLength () method to get this length.    From the buffer to buffer2 rapid reproduction getLength () method is the length of the call System.arraycopy () method. 

  List7 MCServer the source code shows how the service program is working. 

  Listing 7: MCServer.java 
  / / MCServer.java 

  Import java.io. *; 
  Import java.net .*; 

  Class MCServer 
  ( 
  Public static void main (String [] args) throws IOException 
  ( 
  System.out.println ( "Server starting … \ n"); 

  / / Create a MulticastSocket not bound to any port. 

  MulticastSocket s = new MulticastSocket (); 

  / / Because MulticastSocket subclasses DatagramSocket, it is 
  / / Legal to replace MulticastSocket s = new MulticastSocket (); 
  / / With the following line. 

  / / DatagramSocket s = new DatagramSocket (); 

  / / Obtain an InetAddress object that contains the multicast 
  / / Group address 231.0.0.1. The InetAddress object is used by 
  / / DatagramPacket. 

  InetAddress group = InetAddress.getByName ( "231.0.0.1"); 

  / / Create a DatagramPacket object that encapsulates a reference 
  / / To a byte array (later) and destination address 
  / / Information. The destination address consists of the 
  / / Multicast group address (as stored in the InetAddress object) 
  / / And port number 10000 - the port to which multicast datagram 
  / / Packets are sent. (Note: The dummy array is used to prevent a 
  / / NullPointerException object being thrown from the 
  / / DatagramPacket constructor.) 

  Byte [] dummy = new byte [0]; 

  DatagramPacket dgp = new DatagramPacket (dummy, 
0,
  Group, 
10000);

  / / Send 30000 Strings to the port. 

  For (int i = 0; i <30000; i + +) 
  ( 
  / / Create an array of bytes from a String. The platform''s 
  / / Default character set is used to convert from Unicode 
  / / Characters to bytes. 

  Byte buffer [] = ( "Video line" + i). GetBytes (); 

  / / Establish the byte array as the datagram packet''s 
  / / Buffer. 

  Dgp.setData (buffer); 

  / / Establish the byte array''s length as the length of the 
  / / Datagram packet''s buffer. 

  Dgp.setLength (buffer.length); 

  / / Send the datagram to all members of the multicast group 
  / / That listen on port 10000. 

  S.send (dgp); 
  ) 

  / / Close the socket. 

  S.close (); 
  ) 
  ) 

  MCServer created a MulticastSocket, and since he is part of DatagramPacket object, so he did not bind ports, a multicast group DatagramPacket IP address (231.0.0.0), once created DatagramPacket object, entered a MCServer sent 30,000 The text of the cycle, the text of each row are required to create a byte array, and their use are stored in the front DatagramPacket object created through the send () method, since the addressable packets sent to all members of the group. 

  In the compiler and the MCServer MCClient, through the importation of java MCServer MCServer started running, and then run one or more MCClient. 

  Conclusion 

  This paper reveals the socket on the Java API for network applications, since we introduced the expense INTERLINKED read and socket components, as well as addressing the flow socket and the socket, and how to use InetAddress , Socket, ServerSocket, DatagramPacket, DatagramSocket and MulticastSocket category.    In this paper, after completion of the preparation can be the basic underlying communication procedures. 

  (End). 

Java language coding standards (1)

  Java language coding standards Original source http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html 
  2 document (File Names) 
  It lists some commonly used documents and a suffix. 
  2.1 extensions (File Suffixes) 
  Java programs use the following extensions: 
  Document type extensions 
  Java source files. Java 
  Java bytecode files. Class 
  2.2 commonly used document (Common File Names) 
  Common file name include: 
  Use the file name 
  GNUmakefile makefiles the preferred file name.    We used to create gnumake (build) software. 
  README outlined specific directory contents of the documents contained in the file name of choice 
  3 document (File Organization) 
  A document separate from a trip air from each of the paragraphs and paragraphs logo optional Notes common components.    More than 2,000 lines of difficult to read, it should be avoided as far as possible.    "Java source files example," provide a reasonable layout of the Java programming paradigm. 
  3.1 Java source files (Java Source Files) 
  Java source files each contain a single type of public or interface.    If private classes and a public interface and associated category, and they can be placed in a single category of public sources.    This must be a public document of the first of a class or interface. 
  Java source document also abide by the following rules: 
  — The beginning of the Notes (see "Notes beginning") 
  — Packet and the introduction of statements (see "package and the introduction of the words") 
  — Class and interface statement (see "category and interfaces statement") 
  3.1.1 beginning of the Notes (Beginning Comments) 
  All source files should be in the beginning of a C-language style of the Notes, which lists class name, version information, dates and copyright statement: 
  / * 
  * Classname 
*
  * Version information 
*
  * Date 
*
  * Copyright notice 
  * / 

  3.1.2 package and the introduction of statements (Package and Import Statements) 
  In most Java source files, the first visit is a non-Notes packet statement.    After it can be introduced with the statement.    For example: 
  Package java.awt; 

  Import java.awt.peer.CanvASPeer CanvASPeer; 

  3.1.3 category and interfaces statement (Class and Interface Declarations) 
  The following table describes the types and interfaces of the various parts of the statement as well as the priorities.    See "Java source files example," contains an annotated examples. 
  / Interface part of the statement notes 
  1 / Notes interface files (/ **…… * /) in the Notes for the information contained in, see "Notes documents" 
  Interface category 2 or statement 
  3 / interface Note (/ *…… * /) If necessary, any of the Notes should include the whole class or interface information, and such information is not suitable as a class / interface documentation Notes. 
  Class 4 (static) variables is the first of the public variables, followed by the protection of variables, then after a packet-level variables (No visit Xiuchifu, Access modifier), and finally a private variables. 
  5 instance variables is the first public level, then the protection level, then after a packet level (did not visit Xiuchifu), and finally a private level. 
  6 Constructors 
  7 methods These methods should be functional, rather than scope or access, packet.    For example, a proprietary method can be placed in two categories of public examples of ways between.    The purpose is to more ease of reading and understanding the code. 
  4 indentation typesetting (Indentation) 
  4 indented spaces often as a unit of typesetting.    Indentation did not explain in detail the precise designation (vs spaces. Tabs).    A tab equivalent to eight spaces (rather than four). 
  4.1 trip length (Line Length) 
  Try to avoid the length of his more than 80 characters, because many terminals and tools can not be treated. 
  Note: for example in the document should use a shorter president length generally not more than 70 characters. 
  4.2 newline (Wrapping Lines) 
  When an expression in his party, could not accommodate, can be based on the following general rules of the disconnect: 
  — Disconnect in a comma behind 
  — In front of a disconnect operators 
  — Prefer the higher levels (higher-level) disconnect, rather than lower-level (lower-level) Disconnect 
  — A new line should be on the same level expression of his entourage at the beginning of Alignment 
  — If the above rules lead to confusion or your code so that your code Doudui crowded on the right side, then replace it with indented eight spaces. 
  Following is the disconnect method invocation some examples: 
  SomeMethod (longExpression1, longExpression2, longExpression3, 
  LongExpression4, longExpression5); 

  Var = someMethod1 (longExpression1, 
  SomeMethod2 (longExpression2, 
  LongExpression3)); 

  Following are two examples of disconnect arithmetic expressions.    The former better because disconnect Office in brackets expression outside, it is a higher level of disconnect. 
  LongName1 = longName2 * (longName3 + longName4 - longName5) 
  + 4 * longname6; / / PREFFER 

  LongName1 = longName2 * (longName3 + longName4 
  — LongName5) + 4 * longname6; / / AVOID 

  Following are two examples of indentation method statement.    The former is the conventional situation.    If the latter use of conventional methods will be indented to the second line and the third line moved very right-hand lane, so replacing it with indented eight spaces 
  / / CONVENTIONAL INDENTATION 
  SomeMethod (int anArg, Object anotherArg, String yetAnotherArg, 
  Object andStillAnother) ( 

  ) 

  / / 8 INDENT SPACES TO AVOID VERY DEEP INDENTS 
  Private static synchronized horkingLongMethodName (int anArg, 
  Object anotherArg, String yetAnotherArg, 
  Object andStillAnother) ( 

  ) 

  If the phrase normally used for eight to the box rules, because conventional indentation (four spaces) of the statement would seem relatively hard.    For example: 
  / / DON'T USE THIS INDENTATION 
  If ((condition1 & condition2) 
  | | (Condition3 & condition4) 
  | |! (Condition5 & condition6)) (/ / BAD WRAPS 
  DoSomethingAboutIt (); / / MAKE THIS LINE EASY TO MISS 
  ) 

  / / USE THIS INDENTATION INSTEAD 
  If ((condition1 & condition2) 
  | | (Condition3 & condition4) 
  | |! (Condition5 & condition6)) ( 
  DoSomethingAboutIt (); 
  ) 

  / / OR USE THIS 
  If ((condition1 & condition2) | | (condition3 & condition4) 
  | |! (Condition5 & condition6)) ( 
  DoSomethingAboutIt (); 
  ) 

  There are three possible ways to deal with the ternary operator expression: 
  Alpha = (aLongBooleanExpression)? Beta: gamma; 

  Alpha = (aLongBooleanExpression)? Beta 
  : Gamma; 

  Alpha = (aLongBooleanExpression) 
  ? Beta 
  : Gamma; 
  Notes 5 (Comments) 

  There are two categories of Java programs Notes: The Note (implementation comments) and the Notes document (document comments).    Notes in the realization of those seen in C + +, and the use of /*…*/ / / define the Notes.    Notes documents (called "doc comments") is unique to Java by /**…*/ defined.    Notes documents can be converted into javadoc tool HTML file. 

  Implementation Notes for the Notes code or achieve details.    Notes from the documents of freedom (implementation-free) described the perspective of the code and standards.    It can be those who do not understand source developers. 

  Notes should be used to give the umbrella code, and provide their own code did not provide additional information.    Notes should only contain procedures to read and understand the information.    For example, the corresponding packet how to establish or directory in which such information should not be included in the Note. 

  In the Note, an important design decision-making or not obvious where this is possible, but should be avoided in the provision of the code has been clearly expressed in the duplication of information.    Notes of redundant easily outdated.    Should normally avoid those code updates to the Notes may be outdated. 

  NOTE: Notes frequent code reflects the sometimes low quality.    When you feel forced to increase the Notes, consider rewriting the code to make it more clear. 

  Notes should be written with an asterisk or other characters drawn large frame.    Notes should not be included, such as tabs and regression at such special characters. 

  Notes achieve the 5.1 format (Implementation Comment Formats) 

  There are four kinds of procedures can achieve the style Notes: block (block), single (single-line), tail (trailing) and at the end of line (end-of-line). 

  Notes 5.1.1 block (Block Comments) 

  Notes block normally used to provide the documents, methods, data structure and algorithm description.    Notes blocks were placed at the beginning of each document and each method before.    They also can be used elsewhere, for example, the internal method.    And the method of functional block within the Notes and they should be described by code indent with the same format. 

  Notes of the first block should have an empty trip for the Notes and to block separated from the code, for example: 

  / * 
  * Here is a block comment. 
  * / 

  Notes can block / *- beginning of this indent (1) can be identified as the beginning of a code block, and it will not rearrangement. 

  / *- 
  * Here is a block comment with some very special 
  * Formatting that I want indent (1) to ignore. 
*
  * One 
  * Two 
  * Three 
  * / 

  Note: If you do not use indent (1), would not have to use the code / *-, or others may run indent your code (1) concessions. 

  See "Notes documents" 

  5.1.2 single Note (Single-Line Comments) 

  Notes can be displayed on the short line, and after its code indent with the same level.    If a note in the party, not finished, the use of block Notes (see "block Notes").    Notes single before there should be an empty row.    Following is a single Java code in Notes examples: 

  If (condition) ( 

  / * Handle the condition * / 

  ) 

  5.1.3 end of the Notes (Trailing Comments) 

  Notes can be very short and they have to describe in the same line of code, but there should be sufficient gaps to separate code and the Notes.    If it has appeared in a number of short notes of the code, they should have the same indentation. 

  Following is a Java code in the end of the Notes examples: 

  If (a == 2) ( 
  Return TRUE; / * special case * / 
  Else () 
  Return isPrime (a); / * works only for odd a * / 
  ) 

  5.1.4 trip at the end of the Notes (End-Of-Line Comments) 

  Notes can be defined at "//", comment out of the whole trip or part of his entourage.    It generally not used for more than a footnote to the text; However, it can be used to comment out for a number of lines of code.    Following is the example of all three styles: 

  If (foo> 1) ( 

  / / Do a double-flip. 

  ) 
  Else ( 
  Return false; / / Explain why here. 
  ) 

  / / If (bar> 1) ( 
  / / 
  / / / / Do a triple-flip. 
  / / … 
  / /) 
  / / Else ( 
  / / Return false; 
  / /) 

  Notes 5.2 documents (Documentation Comments) 

  NOTE: Notes described herein format example, see "Java source files paradigm" 

  For more, see "How to Write Doc Comments for Javadoc", which contains the relevant information documents marked Notes (@ return, @ param, @ see): 

  Http://java.sun.com/javadoc/writingdoccomments/index.html 

  If you want to learn more about the document notes and javadoc detailed information, see the Home javadoc: 

  Http://java.sun.com/javadoc/index.html 

  Notes documents describe Java classes, interfaces, structures, methods, and the field (field).    Notes of each document will be placed delimiter /**…*/ Notes, the Notes of a corresponding category, interface or members.    Notes should be located in the statement before: 

  / ** 
  * The Example class provides … 
  * / 
  Public class Example (… 

  Attention to the top-level (top-level) class and interface is not indented, and its members are the indent.    Description of the Notes and the interface documentation (/**) not indent the first line; subsequent documents Notes 1 indent each row grid (vertical alignment of the stars).    Members, including structure, function, the document notes the first line indentation 4 grid, and then indent each row 5 grid. 

  If you want to give the category, interface, method or variable information, and such information is not suitable for writing in the document, can be used to achieve block Notes (see 5.1.1), or closely follow behind in the statement of a single Notes (see 5.1.2).    For example, the realization of the details of a class should be in the category Add to keep up with the statement after block the realization of the Notes, rather than on the document notes. 

  Notes documents can not be placed in a method or constructor block in the definition, because Java Notes documents will be located in a statement after its associated. 

  6 Statement (Declarations) 

  6.1 per line statement the number of variables (Number Per Line) 

  Recommended his statement, as it so writing notes.    That is to say, 

  Int level; / / indentation level 
  Int size; / / size of table 

  Is superior, 

  Int level, and size; 

  Not to the different types of variables statement on the same line, such as: 

  Int foo, fooarray []; / / WRONG! 

  Note: the above example, the types and identifiers in a space between the release and the other was allowed to use alternative means of tabs: 

  Int level; / / indentation level 
  Int size; / / size of table 
  Object currentEntry; / / currently selected table entry 

  6.2 initialization (Initialization) 

  In a statement to the local variable initialization at the same time.    The only reason not to do so is dependent on the initial values of variables in the calculation of certain previously occurred. 

JBPM BPEL achieve the wsdl extension

  1.1.1 wsdl extension of the structures 

  We know that in the standard WSDL namespace (xmlns = http://schemas.xmlsoap.org/wsdl/), types, message and portType, and other labels.    But in the BPEL standard wsdl part, there is a very important label, which is partnerLinkType.partnerLinkType wsdl itself is not part of the expansion, in part to expand that these jBPM BPEL is how to achieve the kind?    Let us first look at the following jBPM BPEL achieve the level structure of the WSDL: (I HongSoft this is the process of writing a work of a small flow in the draft. Map, not here, sorry. Less write here easy to understand, and and other parts more easily understood) 

  Javax.wsdl .* 

  (Sun-developed standardized interface) 

  Com.ibm.wsdl .* 

  (IBM's wsdl standards achieved) 

  Org.jbpm.bpel.wsdl .* 

  (JBPM bpel the expansion of the wsdl) 

  Javax.wsdl .* is the top is set out in the WSDL JSR standard interface expressed in jBPM BPEL code corresponding to wsdl4j.jar. Com.ibm.wsdl .* The second is that IBM right wsdl to achieve a standard, basically have not joined any expansion of their own in the jBPM BPEL code corresponding to wsdl4j.jar. jBPM is at the bottom of the BPEL WSDL part of the expansion to achieve, it uses wsdl4j.jar, and then joined the special part Analytical. 

  1.1.2 extension of the registration point 

  Expansion of the registration point (ExtensionRegistry) is the concept of WSDL itself, WSDL use it to register a new extension points.    Wsdl4j.jar in the WSDLFactoryImpl.java, and achieving the ExtensionRegistry function, and jBPM is to use IBM Implementation of this registration extended by adding three points, wsdl4j.jar the realization of the structure are as follows:: (this is being written, I HongSoft a work of a small flow in the draft. map, not here, sorry. written here is not easy to understand, and and other parts more easily understood) 

  1.1.3 expansion point 

  An extension of the registration point can register multiple expansion point.    Expansion point is the meaning of the need for new WSDL standards does not require new labels, such as BPEL is an extension of the partnerLinkType point. 

  Each registered an expansion points need to identify three areas of content: 

  1) In this process, the need to be able to translate into a corresponding sequence partnerLinkType object of XML documents, the XML file used in the network transmission, and then to each other in the process of anti-sequence.    For example, the expansion of partnerLinkType point for the realization of registry.registerSerializer (Definition.class, WsdlConstants.Q_PARTNER_LINK_TYPE, plinkTypeSerializer); plinkTypeSerializer here is an expansion of the category ExtensionSerializer interface.    ExtensionSerializer interface requirements and the need to achieve marshall () method. 

  2) As previously stated, other processes need to be able to XML documents into partnerLinkType anti-sequence objects.    For example, the expansion of partnerLinkType point for the realization of registry.registerDeserializer (Definition.class, WsdlConstants.Q_PARTNER_LINK_TYPE, plinkTypeSerializer); plinkTypeSerializer here is an expansion of the category ExtensionDeserializer interface.    ExtensionDeserializer interface requirements and the need to achieve unmarshall () method. 

  3) sequences and the methods of anti-sequence, only need to give the corresponding partnerLinkType Object interface can be, but the real need is the use of the specific category.    BPEL has extended the WSDL QName and specific category of mapping relations are as follows: registry.mapExtensionTypes (Definition.class, WsdlConstants.Q_PARTNER_LINK_TYPE, PartnerLinkTypeImpl.class); PartnerLinkTypeImpl here is the realization of a specific category PartnerLinkType interface.    And the interface is in PartnerLinkType marshall () method and unmarshall () method to be used. 

  1.1.4 BPEL point of WSDL expansion 

  JBPM of WSDL and the expansion of three points, respectively, to achieve PartnerLinkType functions, features and PropertyAlias Property function.    As follows chart below: 

QName

  Serialization 

  Anti-sequence of 

  Mapping category 

WsdlConstants.

Q_PARTNER_LINK_TYPE

PartnerLinkType

Serializer

PartnerLinkType

Serializer

PartnerLinkTypeImpl

WsdlConstants.

Q_PROPERTY

Property

Serializer

Property

Serializer

PropertyImpl

WsdlConstants.

Q_PROPERTY_ALIAS

PropertyAlias

Serializer

PropertyAlias

Serializer

PropertyAliasImpl

  QName that "qualified name", which was composed of two parts: 1) the name of the name space; 2) in the name of the XML element (element) name.    QName a corresponding expansion of a point, and extended the registration point (ExtensionRegistry) QName used as a key value of the map to preserve all of the expansion point. 

  JBPM sequence and the sequence of components-are at the same time the ExtensionDeserializer, ExtensionSerializer, Serializable interface three separate fact also can be realized. 

  Mapping of interface and implementation to achieve the separation, mapping each category corresponds to an interface, the interface is jBPM other parts of the large-scale use. 

keep looking »