Are You Recruiter/Hiring Manager?
Cloud-based Candidate Screening | Online Tests
PMP 1600 Questions
PMP 1600 Questions
1600 PMP mock questions 1400 CAPM mock questions 800 SCJP 6 mock questions 600 OCAJP 7 mock questions 590 OCPJP 7 mock questions 556 SCWCD 5 mock questions 500 OCEJWCD 6 mock questions pdfDownload (java,struts, hibernet etc)

Tutorial Home

Hibernate

  • Advantage of Hibernate over JDBC
  • Hibernate Setup with an web Application
  • First Hibernate Application
  • Hibernate mapping with Database TABLE
  • Hibernate Data Type-Java Data Type - SQL Data Type mapping
  • One to Many Relation in Hibernate
  • One to Many Relation in Hibernate bi-directional
  • Many to Many Relation in Hibernate
  • HQL: The Hibernate Query Language
  • Criteria Queries
  • Criteria Queries : Equal (eq), Not Equal(ne), Less than (le), greater than (gt),greater than or equal(ge) and Ordering the results
  • Criteria Queries: And OR conditions
  • Hibernate generator to generate id (primary key)
  • prevent concurrent update in Hibernate,slate object updatation in Hibernate,version checking in Hibernate

    Struts


  • Model View Controller (MVC)
  • Model View Controller (MVC)
  • Struts Flow-How Struts Works?
  • Struts Tutorial - Struts Setup- First Struts Action class setup
  • Message Resources
  • Validation Framework
  • Validation Framework-client side
  • ForwardAction
  • IncludeAction
  • DispatchAction
  • LookupDispatchAction
  • DynaActionForm
  • DynaActionForm
  • Struts Tutorial - Mutli-click prevention using struts tokens-Prevent Duplicate Submission
  • Logic Iterate Map and List

    JSP


  • JSP Tutorial
  • Introduction to JSP
  • JSP Comments
  • JSP Syntax
  • JSP Scripting Elements :Scriptlet, expression, declaration
  • JSP Directives
  • implicit objects in JSP
  • JSP Actions
  • Introduction to JSP
  • jsp:useBean
  • The jsp:setProperty Action
  • The jsp:getProperty Action
  • Introduction to JSP

    Spring


  • Spring Tutorial
  • Introduction to Spring
  • Benefits of Using Spring Framework
  • Inversion of Control in Spring
  • Introduction to BeanFactory
  • Dependency Injection in Spring
  • Collections Setter Injection
  • Bean Scopes in Spring
  • Spring IOC Setup Step by Step
  • Bean Lifecycle in Spring
  • ApplicationContext
  • MessageSources in Spring
  • Web Spring MVC framework
  • Developing Your First Spring Web Application
  • Developing Your Second Spring Web Application with Spring Form
  • Developing Your First Spring Web Application with Spring Validation Framework with Code Example
  • Spring integration with Hibernate
  • Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ)

    Describe the functions and capabilities of the APIs included within JAXP.

    SAX

    SAX allows you to process a document as it's being read, which avoids the need to wait for all of it to be stored before taking action.

    Consider the following XML code snippet:

    
    <?xml version="1.0"?>
    <samples>
    	<server>UNIX</server>
    	<monitor>color</monitor>
    </samples>
    					
    					
    A SAX processor analyzing this code snippet would generate, in general, the following events:
    Start document
    Start element (samples)
    Characters (white space)
    Start element (server)
    Characters (UNIX)
    End element (server)
    Characters (white space)
    Start element (monitor)
    Characters (color)
    End element (monitor)
    Characters (white space)
    End element (samples)
    End document
    					
    The SAX API allows a developer to capture these events and act on them.

    SAX processing involves the following steps:

    1. Create an event handler.

    2. Create the SAX parser.

    3. Assign the event handler to the parser.

    4. Parse the document, sending each event to the handler.

    Create the parser

    This example uses a pair of classes, SAXParserFactory and SAXParser, to create the parser, so you don't have to know the name of the driver itself. First declare the XMLReader, xmlReader, and then use SAXParserFactory to create a SAXParser. It's the SAXParser that gives you the XMLReader:

    import org.xml.sax.helpers.DefaultHandler;					
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.XMLReader;
    
    public class SurveyReader extends DefaultHandler {
    	public static void main (String args[]) {
    		XMLReader xmlReader = null;
    		try {
    			SAXParserFactory spfactory = SAXParserFactory.newInstance();
    			SAXParser saxParser = spfactory.newSAXParser();
    			xmlReader = saxParser.getXMLReader();
    		} catch (Exception e) {
    			System.err.println(e);			
    		}
    	}
    }					
    					

    Set validation options

    Turn off validation for any parser the SAXParserFactory creates by setting the validating property:

    ...
    public static void main (String args[]) {
    	XMLReader xmlReader = null;
    	try {
    		SAXParserFactory spfactory = SAXParserFactory.newInstance();
    		spfactory.setValidating(false);
    		SAXParser saxParser = spfactory.newSAXParser();
    		xmlReader = saxParser.getXMLReader();
    	} catch (Exception e) {
    		System.err.println(e);
    	}
    }
    ...					
    					

    Set the content handler

    The parser has to send its events to a ContentHandler:

    package org.xml.sax;
    
    public interface ContentHandler {
    
        public void setDocumentLocator (Locator locator);
    
    
        /**
         * Receive notification of the beginning of a document.
         */
        public void startDocument () throws SAXException;
    
        /**
         * Receive notification of the end of a document.
         */
        public void endDocument() throws SAXException;
    
        /**
         * Begin the scope of a prefix-URI Namespace mapping.
         */
        public void startPrefixMapping (String prefix, String uri) throws SAXException;
    
        /**
         * End the scope of a prefix-URI mapping.
         */
        public void endPrefixMapping (String prefix) throws SAXException;
    
    
        /**
         * Receive notification of the beginning of an element.
         */
        public void startElement (String namespaceURI, String localName,
    			      String qName, Attributes atts) throws SAXException;
    
        /**
         * Receive notification of the end of an element.
         */
        public void endElement (String namespaceURI, String localName,
    			    String qName) throws SAXException;
    
        /**
         * Receive notification of character data.
         */
        public void characters (char ch[], int start, int length) throws SAXException;
    
    
        /**
         * Receive notification of ignorable whitespace in element content.
         */
        public void ignorableWhitespace (char ch[], int start, int length) throws SAXException;
    
    
        /**
         * Receive notification of a processing instruction.
         */
        public void processingInstruction (String target, String data) throws SAXException;
    
    
        /**
         * Receive notification of a skipped entity.
         */
        public void skippedEntity (String name) throws SAXException;
    }
    					
    To keep things simple, SurveyReader is both the main application and the content handler, so create a new instance of it and set it as the ContentHandler using the XMLReader.setContentHandler() method:
    	...
    	xmlReader = saxParser.getXMLReader();
    	xmlReader.setContentHandler(new SurveyReader());
    } catch (Exception e) {
    	...					
    					

    Parse the InputSource

    To actually parse a file you need an InputSource:

    package org.xml.sax;
    
    import java.io.Reader;
    import java.io.InputStream;
    
    /**
     * A single input source for an XML entity.
     */
    public class InputSource {
        
        public InputSource ()  { }
        
        /**
         * Create a new input source with a system identifier.
        public InputSource (String systemId)  {
    		setSystemId(systemId);
        }
        
        /**
         * Create a new input source with a byte stream.
         */
        public InputSource (InputStream byteStream) {
    		setByteStream(byteStream);
        }
        
        
        /**
         * Create a new input source with a character stream.
         */
        public InputSource (Reader characterStream) {
    		setCharacterStream(characterStream);
        }
        ...
    }					
    This SAX class wraps whatever data you're going to process. Now you're ready to actually parse the file. The parse() method takes the file, wrapped in the InputSource, and processes it, sending each event to the ContentHander:
    ...
    import org.xml.sax.InputSource;
    	...
    	xmlReader = saxParser.getXMLReader();
    	xmlReader.setContentHandler(new SurveyReader());
    	InputSource source = new InputSource("surveys.xml");
    	xmlReader.parse(source);
    } catch (Exception e) {
    	...					
    					

    Set an ErrorHandler

    You can create an error handler just as you created a content handler. Normally, you would create this as a separate instance of ErrorHandler, but to simplify the example, you'll include error handling right in SurveyResults. This dual-usage is possible because the class extends DefaultHandler, which includes implementations of both the ContentHandler methods and the ErrorHandler methods. Set a new ErrorHandler just as you set the ContentHandler:

    ...
    xmlReader.setContentHandler(new SurveyReader());
    xmlReader.setErrorHandler(new SurveyReader());
    InputSource source = new InputSource("surveys.xml");
    ...					
    					

    Event handlers and the SAX events

    • startDocument()

      Start by noting the beginning of the document using the startDocument() event. This event, like the other SAX events, throws a SAXException:

      ...
      import org.xml.sax.SAXException;
      
      public class SurveyReader extends DefaultHandler {
      
      	public void startDocument() throws SAXException {
      		System.out.println("Tallying survey results...");
      	}
      
      	public static void main (String args[]) {
      		XMLReader xmlReader = null;
      		...								
      								

    • startElement()

      For each element, the example echoes back the name that is passed to the startElement() event. The parser actually passes several pieces of information for each element:

      • The qualified name, or qName. This is actually a combination of namespace information, if any, and the actual name of the element. The qName also includes the colon (:) if there is one - for example, revised:question.

      • The namespace URI. An actual namespace is a URI of some sort and not the alias that gets added to an element or attribute name. For example, http://www.example.com as opposed to simply revised:.

      • The local name. This is the actual name of the element, such as question. If the document doesn't provide namespace information, the parser may not be able to determine which part of the qName is the localName.

      • Any attributes. The attributes for an element are actually passed as a collection of objects.

      Start by listing the name of each element:

      ...
      import org.xml.sax.Attributes;
      
      public class SurveyReader extends DefaultHandler {
      	...
      	public void startDocument() throws SAXException {
      		System.out.println("Tallying survey results...");
      	}
      
      	public void startElement(String namespaceURI, String localName, 
      				String qName, Attributes atts) throws SAXException {
      		System.out.print("Start element: ");
      		System.out.println(qName);
      	}
      
      	public static void main (String args[]) {
      		...								
      								

      The startElement() event also provides access to the attributes for an element. They are passed in within an Attributes data structure. You can retrieve an attribute value based on its position in the array, or based on the name of the attribute:

      								
      ...
      public void startElement(String namespaceURI, String localName,
      		String qName, Attributes atts) throws SAXException {
      	System.out.print("Start element: ");
      	System.out.println(qName);
      	for (int att = 0; att < atts.getLength(); att++) {
      		String attName = atts.getQName(att);
      		System.out.println(" " + attName + ": " + atts.getValue(attName));
      	}
      }
      ...							
      
      								

    • endElement()

      You'll find plenty of good reasons to note the end of an element. For example, it might be a signal to process the contents of an element. Here you'll use it to pretty print the document to some extent, indenting each level of elements. The idea is to increase the value of the indent when a new element starts, decreasing it again when the element ends:

      								
      ...
      int indent = 0;
      
      public void startDocument() throws SAXException {
      	System.out.println("Tallying survey results...");
      	indent = -4;
      }								
      
      public void printIndent(int indentSize) {
      	for (int s = 0; s < indentSize; s++) {
      		System.out.print(" ");
      	}
      }
      
      public void startElement(String namespaceURI, String localName,
      			String qName, Attributes atts) throws SAXException {
      	indent = indent + 4;
      	printIndent(indent);
      	System.out.print("Start element: ");
      	System.out.println(qName);
      	for (int att = 0; att < atts.getLength(); att++) {
      		printIndent(indent + 4);
      		String attName = atts.getLocalName(att);
      		System.out.println(" " + attName + ": " + atts.getValue(attName));
      	}
      }
      
      public void endElement(String namespaceURI, String localName, String qName) 
      		throws SAXException {
      	printIndent(indent);
      	System.out.println("End Element: "+localName);
      	indent = indent - 4;
      }
      ...
      
      								

    • characters()

      Now that you've got the elements, go ahead and retrieve the actual data using characters(). Take a look at the signature of this method for a moment:

      public void characters(char[] ch, int start, int length) throws SAXException								
      								
      Notice that nowhere in this method is there any information whatsoever as to what element these characters are part of. If you need this information, you're going to have to store it. This example adds variables to store the current element and question information. (It also removes a lot of extraneous information that was displayed.)

      Note two important things here:

      • Range: The characters() event includes more than just a string of characters. It also includes start and length information. In actuality, the ch character array includes the entire document. The application must not attempt to read characters outside the range the event feeds to the characters() event.

      • Frequency: Nothing in the SAX specification requires a processor to return characters in any particular way, so it's possible for a single chunk of text to be returned in several pieces. Always make sure that the endElement() event has occurred before assuming you have all the content of an element. Also, processors may use ignorableWhitespace() to return whitespace within an element. This is always the case for a validating parser.

      								
      ...
      public void printIndent(int indentSize) {
      	for (int s = 0; s < indentSize; s++) {
      		System.out.print(" ");
      	}
      }
      
      String thisQuestion = "";
      String thisElement = "";
      
      public void startElement(String namespaceURI, String localName,
      			String qName, Attributes atts) throws SAXException {
      	if (qName == "response") {
      		System.out.println("User: " + atts.getValue("username"));
      	} else if (qName == "question") {
      		thisQuestion = atts.getValue("subject");
      	}
      	thisElement = qName;
      }
      
      public void endElement(String namespaceURI, String localName, String qName)
      		throws SAXException {
      	thisQuestion = "";
      	thisElement = "";
      }
      
      public void characters(char[] ch, int start, int length)
      		throws SAXException {
      	if (thisElement == "question") {
      		printIndent(4);
      		System.out.print(thisQuestion + ": ");
      		System.out.println(new String(ch, start, length));
      	}
      }
      ...		
      						
      								

    • endDocument()

      Once the document is completely parsed, you'll want to print out the final tally as shown below. This is also a good place to tie up any loose ends that may have come up during processing:

      public void endDocument() {
      	System.out.println("Appearance of the aliens:");
      	System.out.println("A: " + getInstances(appearance, "A"));
      	System.out.println("B: " + getInstances(appearance, "B"));
      	...
      }
      	
      public static void main (String args[]) {
      	...								
      								

    ErrorHandler events

    Just as the ContentHandler has predefined events for handling content, the ErrorHandler has predefined events for handling errors. Because you specified SurveyReader as the error handler as well as the content handler, you need to override the default implementations of those methods. You need to be concerned with three events: warning, error, and fatalError:

    ...
    import org.xml.sax.SAXParseException;
    
    public class SurveyReader extends DefaultHandler {
    
    	public void error (SAXParseException e) {
    		System.out.println("Error parsing the file: "+e.getMessage());
    	}
    
    	public void warning (SAXParseException e) {
    		System.out.println("Problem parsing the file: "+e.getMessage());
    	}
    
    	public void fatalError (SAXParseException e) {
    		System.out.println("Error parsing the file: "+e.getMessage());
    		System.out.println("Cannot continue.");
    		System.exit(1);
    	}
    	
    	...					
    					

    Resolving Entities. org.xml.sax.EntityResolver interface

    An XML document is made up of entities. Each entity is identified by public identifiers and/or system identifiers. The system IDs tend to be URLs. The public IDs generally require some sort of catalog system that can convert them into URLs. An XML parser reads each entity using an InputSource connected to the right URL. Most of the time you just give the parser a system ID or an InputSource pointing to the document entity, and let the parser figure out where to find any further entities referenced from the document entity. However, sometimes you want the parser to read from different URLs than the ones the document specifies. For example, the parser might ask for the XHTML DTD from the W3C web site. However, you might choose to replace that with a cached copy stored locally.

    The EntityResolver API lets you convert a public ID (URN) into a system ID (URL). Your application may need to do that, for example, to convert something like href="urn:/someName" into "http://someURL".

    The org.xml.sax.EntityResolver interface allows you to filter the parser's requests for external parsed entities so you can replace the files it requests with your own copies, either faithful or modified. You might even use this interface to provide some form of custom proxy server support, though chances are that would be better implemented at the socket level rather than in the parsing API.

    org.xml.sax.EntityResolver is a callback interface much like ContentHandler. It is attached to an org.xml.sax.XMLReader interface with set and get methods:

    package org.xml.sax;
    
    public interface XMLReader {
    	...
    	public void setEntityResolver(EntityResolver resolver);
    	public EntityResolver getEntityResolver();
    	...
    }
    					

    The EntityResolver interface contains just a single method, resolveEntity(...). If you register an EntityResolver with an XMLReader, then every time that XMLReader needs to load an external parsed entity, it will pass the entity's public ID and system ID to resolveEntity(...) first. The external entities can be: external DTD subset, external parameter entities, etc.

    The EntityResolver allows you to substitute your own URI lookup scheme for external entities. Especially useful for entities that use URL and URI schemes not supported by Java's protocol handlers; e.g. jdbc:/ or isbn:/.

    The resolveEntity(...) can either return an InputSource or null. If it returns an InputSource, then this InputSource provides the entity's replacement text. If it returns null, then the parser reads the entity in the same way it would have if there wasn't an EntityResolver - by using the system ID and the java.net.URL class.

    You could replace the host in the system ID to load the DTDs from a mirror site. You could bundle the DTDs into your application's JAR file and load them from there. You could even hardwire the DTDs in the EntityResolver as string literals and load them with a StringReader.

    package org.xml.sax;
    
    public interface EntityResolver {
    	public InputSource resolveEntity(String publicId,
    		String systemId) throws SAXException, IOException;
    }
    					

    The following resolver will redirect system identifier to local URI:

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import org.xml.sax.EntityResolver;
    import org.xml.sax.InputSource;
    
    public class UseLocal implements EntityResolver {
    	public InputSource resolveEntity(String publicId, String systemId)
    		throws FileNotFoundException {
    			
    		if (systemId.equals("http://server.com/DTD/quiz.dtd")) {
    			// use local version
    			return new InputSource(new FileInputStream("local/DTD/quiz.dtd"));
    		} else {
    			// use the default behaviour
    			return null;
    		}
    	}
    }
    					

    DOM

    A DOM Document is a collection of nodes, or pieces of information, organized in a hierarchy. This hierarchy allows a developer to navigate around the tree looking for specific information. Analyzing the structure normally requires the entire document to be loaded and the hierarchy to be built before any work is done. Because it is based on a hierarchy of information, the DOM is said to be tree-based, or object-based.

    For exceptionally large documents, parsing and loading the entire document can be slow and resource-intensive. DOM provides an API that allows a developer to add, edit, move, or remove nodes at any point on the tree in order to create an application, while event-based models like SAX do not allow a developer to actually change the data in the original document.

    The basic node types

    1. Elements

      Elements are the basic building blocks of XML. Typically, elements have children that are other elements, text nodes, or a combination of both. Element nodes are also the only type of node that can have attributes.

    2. Attributes

      Attribute nodes contain information about an element node, but are not actually considered to be children of the element, as in:

      								
      <customerid limit="1000">12341</customerid>
      
      								

    3. Text

      A text node is exactly that - text. It can consist of more information or just white space.

    4. Document

      The document node is the overall parent for all of the other nodes in the document.

    Parsing a file into a document

    To work with the information in an XML file, the file must be parsed to create a Document object.

    The Document object is an interface, so it can't be instantiated directly; generally, the application uses a factory instead. In the example Java environment, parsing the file is a three-step process:

    1. Create the DocumentBuilderFactory. This object creates the DocumentBuilder.

    2. Create the DocumentBuilder. The DocumentBuilder does the actual parsing to create the Document object.

    3. Parse the file to create the Document object.

    Start by creating the basic application, a class called OrderProcessor:

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import java.io.File;
    import org.w3c.dom.Document;
    
    public class OrderProcessor {
    	public static void main (String args[]) {
    		File docFile = new File("orders.xml");
    		Document doc = null;
    		try {
    			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    			DocumentBuilder db = dbf.newDocumentBuilder();
    			doc = db.parse(docFile);
    		} catch (Exception e) {
    			System.out.print("Problem parsing the file: "+e.getMessage());
    		}
    	}
    }					
    					
    First, the Java code imports the necessary classes, and then it creates the OrderProcessor application. Within the try-catch block, the application creates the DocumentBuilderFactory, which it then uses to create the DocumentBuilder. Finally, the DocumentBuilder parses the file to create the Document.

    One of the advantages of creating parsers with a DocumentBuilder lies in the control over various settings on the parsers created by the DocumentBuilderFactory. For example, the parser can be set to validate the document:

    ...
    try {
    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    	dbf.setValidating(true);
    	DocumentBuilder db = dbf.newDocumentBuilder();
    	doc = db.parse(docFile);
    } catch (Exception e) {
    ...
    					

    Get the root element

    Once the document is parsed and a Document is created, an application can step through the structure to review, find, or display information. This navigation is the basis for many operations that will be performed on a Document. Stepping through the document begins with the root element. A well-formed document has only one root element, also known as the DocumentElement. First the application retrieves this element:

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import java.io.File;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    
    public class OrderProcessor {
    	...
    		//STEP 1: Get the root element
    		Element root = doc.getDocumentElement();
    		System.out.println("The root element is " + root.getNodeName());
    	...
    }					
    					

    Get the children of a node

    Once the application determines the root element, it retrieves a list of the root element's children as a NodeList. The NodeList class is a series of items through which the application can iterate. In this example, for brevity, the application gets the child nodes and verifies the retrieval by showing only how many elements appear in the resulting NodeList:

    ...
    import org.w3c.dom.NodeList;
    	...
    		//STEP 1: Get the root element
    		Element root = doc.getDocumentElement();
    		System.out.println("The root element is "+root.getNodeName());
    		
    		//STEP 2: Get the children
    		NodeList children = root.getChildNodes();
    		System.out.println("There are "+children.getLength()+" nodes in this document.");
    	}
    }					
    					

    Using getFirstChild() and getNextSibling()

    The parent-child and sibling relationships offer an alternative means for iterating through all of the children of a node that may be more appropriate in some situations, such as when these relationships and the order in which children appear is crucial to understanding the data. In Step 3, a for-loop starts with the first child of the root. The application iterates through each of the siblings of the first child until they have all been evaluated. Each time the application executes the loop, it retrieves a Node object, outputting its name and value. Notice also that the elements carry a value of null, rather than the expected text. It is the text nodes that are children of the elements that carry the actual content as their values:

    ...
    import org.w3c.dom.Node;
    	...
    		//STEP 3: Step through the children
    		for (Node child = root.getFirstChild(); child != null; child = child.getNextSibling()) {
    			System.out.println(child.getNodeName() + " = " + child.getNodeValue());
    		}
    	}
    }
    				
    					

    A Node object carries member constants that represent each type of node, such as ELEMENT_NODE or ATTRIBUTE_NODE. If the nodeType matches ELEMENT_NODE, it is an element. For every element it finds, the application creates a NamedNodeMap that contains all of the attributes for the element. The application can iterate through a NamedNodeMap, printing each attribute's name and value, just as it iterated through the NodeList:

    					
    ...
    import org.w3c.dom.NamedNodeMap;
    	...
    	private static void stepThroughAll (Node start) {
    		System.out.println(start.getNodeName()+" = "+start.getNodeValue());
    		if (start.getNodeType() == start.ELEMENT_NODE) {
    			NamedNodeMap startAttr = start.getAttributes();
    			for (int i = 0; i < startAttr.getLength(); i++) {
    				Node attr = startAttr.item(i);
    				System.out.println(" Attribute: "+ attr.getNodeName() +" = "+attr.getNodeValue());
    			}
    		}
    		
    		for (Node child = start.getFirstChild();child != null;child = child.getNextSibling()) {
    			stepThroughAll(child);
    		}
    	}					
    
    					

    TrAX (Transformation API for XML)

    TrAX is an API for transforming XML documents using XSLT style sheets. TrAX is a Java API and has been defined to provide common access to different XSLT Processors. TrAX is part of the JAXP API, which combines a number of Java APIs.

    The TrAX API extends the original JAXP mission to include XML transformations: provide a vendor and implementation agnostic standard Java API for specifying and executing XML transformations. This is important to note, because TrAX is more than just a standard interface for XSLT engines - it is designed to be used as a general-purpose transformation interface for XML documents.

    TrAX isn't a competitor to the existing DOM and SAX APIs used to represent and process XML, but a common Java API to bridge the various XML transformation methods (a la JDBC, JNDI, etc.) including SAX Events and XSLT Templates. In fact, TrAX relies upon a SAX2- and DOM-level-2-compliant XML parser/XSLT engine. JAXP 1.0 allows the developer to change XML parsers by setting a property, and TrAX provides the same functionality for XSLT engines.

    Here is a sample of how to apply an XSLT stylesheet to an XML document and write the results out to a file. In this example, both the stylesheet and the XML document exist as files, but they could just as easily have come from any Java InputStream or Reader class. The same follows for the results of the transformation; I could've just as easily written the results out to any Java OutputStream or Writer class.

    // 1. create the XML content input source:
    //    can be a DOM node, SAX stream, or any Java input stream/reader
    String xmlInputFile = "myXMLinput.xml";
    Source xmlSource = new StreamSource(new FileInputStream(xmlInputFile));
    
    // 2. create the XSLT Stylesheet input source
    //    can be a DOM node, SAX stream, or a java input stream/reader
    String xsltInputFile = "myXsltStylesheet.xsl";
    Source xsltSource = new StreamSource(new FileInputStream(xsltInputFile));
    
    // 3. create the result target of the transformation
    //    can be a DOM node, SAX stream, or a java out stream/reader
    String xmlOutputFile = "result.html";
    Result transResult = new StreamResult(new FileOutputStream(xmlOutputFile));
    
    // 4. create the transformerfactory and transformer instance
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer(xsltSource);
    
    // 5. execute transformation and fill result target object
    t.transform(xmlSource, transResult);					
    					
    The first three stanzas simply establish our inputs and result targets, and aren't that interesting, with one exception. Notice that the XSLT stylesheet isn't handled via a different class in TrAX. It's treated just like any other XML source document, because that's exactly what it is. We use the stream implementations of the Source and Result interfaces from the javax.xml.transform.stream package to handle reading the data from our file streams.

    In the fourth stanza, we use the TransformerFactory to get an instance of a Transformer, and then use the Source instance for the XSLT stylesheet we created in the second stanza to define the transformation that this transformer will perform. A Transformer actually executes the transformation and assembles the result. A single Transformer instance can be reused, but it is not thread-safe.

    In this example, the XSLT stylesheet is reprocessed for each successive transformation. A very common case is that the same transformation is applied multiple times to different Sources, perhaps in different threads. A more efficient approach in this case is to process the transformation stylesheet once, and save this object for successive transformations. This is achieved through the use of the TrAX Templates interface:

    // we've already set up our content Source instance, 
    // XSLT Source instance, TransformerFactory, and 
    // Result target from the previous example
    
    // process the XSLT stylesheet into a Templates instance
    // with our TransformerFactory instance
    Templates t = tf.newTemplates(xsltSource);
    
    // whenever you need to execute this transformation, create 
    // a new Transformer instance from the Templates instace
    Transformer trans = t.newTransformer();
    
    // execute transformation and fill result target object
    trans.transform(xmlSource, transResult);					
    					

    While the Transformer performs the transformation, a Templates instance is the actual run-time representation of the processed transformation instructions. Templates instances may be reused to increase performance, and they are thread-safe. It might seem odd that an interface has a plural name, but it stems from the fact that an XSLT stylesheet consists of a collection of one or more xsl:template elements. Each template element defines a transformation in that stylesheet, so it follows that the simplest name for a representation of a collection of template elements is Templates.

    One of the main reasons the TrAX API is so clean and simple is the Interface-driven approach to design. The highest-level interfaces define the essential entities that are being modeled, and the interactions are left to the implementations. The interfaces themselves aren't very interesting. They are essentially marker interfaces.

    Source

    The Source interface is a generic container for existing XML documents that will be used in a transformation as either the input document or the stylesheet. Serve as a single vendor-neutral object for multiple types of input. Implementations of the Source interface provide access to the XML document to be processed. TrAX defines Source implementations for DOM trees (DOMSource); SAX 2.0 InputSources (SAXSource); and Java InputStreams, Readers and any of their derived classes (StreamSource).

    package javax.xml.transform;
    					
    public interface Source {
        public void setSystemId(String systemId);
        public String getSystemId();
    }										
    					

    Result

    The Result interface is a generic container for an XML document that will be produced by a transformation. Serve as a single object for multiple types of output, so there can be simple process method signatures. Implementations of the Result interface provide access to the transformed XML document. TrAX defines Result implementations for DOM trees (DOMResult); SAX 2.0 ContentHandlers (SAXResult); and Java OutputStreams, Writers and any of their derived classes (StreamResult).

    package javax.xml.transform;
    
    public interface Result  {
    
      public static final String PI_DISABLE_OUTPUT_ESCAPING;
      public static final String PI_ENABLE_OUTPUT_ESCAPING;
    
      public void   setSystemId(String url);
      public String getSystemId();
    
    }				
    					

    Templates

    Templates is a thread-safe interface that represents a compiled stylesheet. It can quickly create new Transformer objects without having to reread and reparse the original stylesheet. It’s particularly useful when you want to use the same stylesheet in multiple threads. The runtime representation of the transformation instructions. A template implementation is the optimized, in-memory representation of an XML transformation that is processed and ready to be executed. Templates objects are safe to use in concurrent threads. To reuse a single Template instance in multiple concurrent threads, multiple Transformer instances would have to be created via the Templates.newTransformer() factory method. Each Transformer instance may be used completely independently in concurrent threads, and both the Templates and the Transformer instances can be reused for subsequent transformations.

    package javax.xml.transform;
    
    public interface Templates  {
     
      public Transformer newTransformer() throws TransformerConfigurationException;   
      public Properties  getOutputProperties();
    
    }
    					

    Transformer

    Transformer is the abstract class that represents a compiled stylesheet. It transforms Source objects into Result objects. A single Transformer can transform multiple input documents in sequence but not in parallel. Act as a per-thread execution context for transformations, act as an interface for performing the transformation. A Transformer is the object that actually applies the transformation to the source document and creates the result document. However, it is not responsible for outputting, or serializing, the result of the transformation. This is the responsibility of the transformation engine's serializer and this behavior can be modified via the setOutputProperty(java.lang.String name, java.lang.String value) method. The configurable OutputProperties are defined in the OutputKeys class, and are described in the XSLT 1.0 Specification. Transformers are immutable, they cannot change which Templates instance gets applied to the Source.

    package javax.xml.transform;
    
    public abstract class Transformer  {
    
      protected Transformer();
      public void transform(Source input, Result output) throws TransformerException;
      
      public void setParameter(String name, Object value);
      public Object getParameter(String name);
      public void clearParameters();
      public void setURIResolver(URIResolver resolver);
      public URIResolver getURIResolver();
      public void setOutputProperties(Properties serialization) throws IllegalArgumentException;
      public Properties getOutputProperties();
      public void setOutputProperty(String name, String value) throws IllegalArgumentException;
      public String getOutputProperty(String name) throws IllegalArgumentException;
      public void setErrorListener(ErrorListener listener) throws IllegalArgumentException;
      public ErrorListener getErrorListener();
    
    }
    					

    TransformerFactory

    TransformerFactory is an abstract factory that creates new Transformer and Templates objects. The concrete subclass that newInstance() instantiates is specified by the javax.xml.transform.TransformerFactory Java system property. If this class is not set, a platform dependent default class is chosen. Serve as a vendor-neutral Processor interface for XSLT and similar processors. The TransformerFactory is primarily responsible for creating new Transformers and Templates objects. New instances of Transformer are created via the static newTransformer() method. Processing Source instances into Templates objects is handled by the newTemplates(Source source) method.

    package javax.xml.transform;
    
    public abstract class TransformerFactory  {
    
      protected TransformerFactory();
      public static TransformerFactory newInstance() throws TransformerFactoryConfigurationError;
    
      public Transformer newTransformer(Source source) throws TransformerConfigurationException;
      public Transformer newTransformer() throws TransformerConfigurationException;
      public Templates   newTemplates(Source source) throws TransformerConfigurationException;
     
      public Source getAssociatedStylesheet(Source source, String media, String title, String charset) 
         throws TransformerConfigurationException;
      public void setURIResolver(URIResolver resolver);
      public URIResolver getURIResolver();
      public boolean getFeature(String name);
      public void setAttribute(String name, Object value) throws IllegalArgumentException;
      public Object getAttribute(String name) throws IllegalArgumentException;
      public void setErrorListener(ErrorListener listener) throws IllegalArgumentException;
      public ErrorListener getErrorListener();
    
    }
    					

    The information you are posting should be related to java and ORACLE technology. Not political.