Monday, December 29, 2014

New Prototype Source as a Servlet with Hibernate Transaction in NetBeans

Team. This will be a longer note. There have been a number of changes in the source since it was last posted. If you plan on rebuilding these files, getting the NetBeans Integrated Development Environment (IDE) would be wise. It can be found at www.netbeans.org and is "free-of-charge". The steps for building the CABOOSE project in its current state is as follows:

A. Creating Derby Database

0. All identifiers in quotes are case-sensitive.
1. Create a JDBC Derby database called "caboose" under the Services Navigator tab of NetBeans. This will serve asasourceof information which we can extract with Hibernate Object-Relational Mapping (ORM) modules.
2. The username and password for your database should be "root" and "root", respectively.
3. Create a table in your database called "CABOOSE".
4. Within this table create the fields "ID" of type Integer and "MESSAGE" of type VARCHAR with a maximum length of 256.
5. Run the an SQL Script which creates a record with an ID of 100 and the MESSAGE that "Hibernate is a friend of CABOOSE".

B. Creating the CABOOSE Web Application

0. Use the Netbeans IDE helper application to create a new web application called "CABOOSE"
1. Place directory.xml in the WEB-INF directory
2. Create a folder called "model" for holding the stencil models of each view.
3. Place exception.xhtml and xstencil.xhtml in the "model" directory of the "WEB-INF" folder
4. Replace the content of the "index.html" file generated by the inline source for index.html.
5. Create a servlet called "CAB.java" in the net.java.CABOOSE package. It URL pattern should be "/CAB"

C. Creating JAVA packages

0. Create the folowing packages
    0.1 [DEFAULT] Given
    0.2 net.java.CABOOSE
    0.3 net.java.CABOOSE.Hibernate
    0.4 org.sharpe.sample
1. Populate the packages with the appropriate source based upon the package statement at the beginning of each module.
2. Place hibernate.cfg.xml in the default package
3. Place hibernate.reveng.xml in the net.java.CABOOSE.Hibernate package
4. Place Caboose.hbm.xml in the net.java.CABOOSE.Hibernate package

Note: Much of the code for Hibernate processing was automatically generated by the Netbeans IDE. If you like you can repeat these steps. There are tutorials at Netbeans and other web sources on creating Hibernate transactions, plus it is almost self-explanatory.

This should be all of the instructions needed for recreating the project in NetBeans. The source is below. Once we complete the prototype with all of its sample extensions for common technologies, we will place it in the repository. La-La.

//BEGINNING OF SOURCE FILES
//exception.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>CABOOSE Exception</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>
    <body>
        <div>CABOOSE Exception</div>
        <!--
        I chose that my tile replacement identifiers would
        follow the pattern #ALL_CAPS_JAVA_IDENTIFIER#. This
        is only a convention and not strictly enforced by the
        cab. Obviously, the string used should not collide with
        any other one that might be found in a markup document.
        -->
        <p>#EXCEPTION_MESSAGE#</p>
    </body>
</html>
//xstencil.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>CABOOSE Standard Stencil</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>
    <body>
        <div>CABOOSE Standard Stencil</div>
        <!--
        I chose that my tile replacement identifiers would
        follow the pattern #ALL_CAPS_JAVA_IDENTIFIER#. This
        is only a convention and not strictly enforced by the
        cab. Obviously, the string used should not collide with
        any other one that might be found in a markup document.
        -->
        <p>#PROJECT#</p>
        <p>#MODULE#</p>
        <p>#CREATE_DATE#</p>
        <p>#HIBERNATE_MESSAGE#</p>
    </body>
</html>
//index.html
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>CABOOSE|Controller Application Bundles for Object-Oriented Software Engineering</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>CABOOSE Splash Page</div>
        <form action="/CABOOSE/CAB" method="POST">
            <input type="hidden" name="create_date" value="10.30.2014"/>
            <input type="hidden" name="module" value="StencilHandler"/>
            <input type="hidden" name="project" value="Caboose"/>
            <input type="submit" value="Run CABOOSE"/>
        </form>
    </body>
</html>
//directory.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<!-- the model is for the entire application. one view associates
with one page of markup. As attributes this element has an id and a stencil
which is a the filename of the markup. Each view has zero or more replacement
tile child elements associated with it. The tile id attribute appears in the
markup and will be replaced by the String content rendered by the method
uniquely described by the class and method attributes of the tile element.
-->
<model>   
 <view id="test_page" stencil="/WEB-INF/model/xstencil.xhtml">
            <tile id="#PROJECT#" class="org.sharpe.sample.StencilHandler" method="projectRenderer"/>
            <tile id="#MODULE#" class="org.sharpe.sample.StencilHandler" method="moduleRenderer"/>
            <tile id="#CREATE_DATE#" class="org.sharpe.sample.StencilHandler" method="createDateRenderer"/>  
            <tile id="#HIBERNATE_MESSAGE#" class="org.sharpe.sample.StencilHandler" method="hibernateMessageRenderer"/>
        </view>
        <view id="exception" stencil="/WEB-INF/model/exception.xhtml">
            <tile id="#EXCEPTION_MESSAGE#" class="org.sharpe.sample.StencilHandler" method="exceptionRenderer"/>
 </view>
</model>
//hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
    <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
    <property name="hibernate.connection.url">jdbc:derby://localhost:1527/caboose</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <mapping class="" file="" jar="" package="" resource="net/java/CABOOSE/Hibernate/Caboose.hbm.xml"/>
  </session-factory>
</hibernate-configuration>
//Caboose.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 28, 2014 1:19:10 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="net.java.CABOOSE.Hibernate.Caboose" table="CABOOSE" schema="ROOT" optimistic-lock="version">
        <id name="id" type="int">
            <column name="ID"/>
            <generator class="assigned" />
        </id>
        <property name="message" type="string">
            <column name="MESSAGE" length="256"/>
        </property>
    </class>
</hibernate-mapping>
//hibernate.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-schema="ROOT"/>
  <table-filter match-name="CABOOSE"/>
</hibernate-reverse-engineering>
//CAB.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net.java.CABOOSE;
/**
 *
 * @author Jody
 */
@javax.servlet.annotation.WebServlet(name = "CAB", urlPatterns = {"/CAB"})
public class CAB extends javax.servlet.http.HttpServlet implements SystemExceptions {
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
            throws javax.servlet.ServletException, java.io.IOException {
        response.setContentType("text/html;charset=UTF-8");
        java.io.PrintWriter out = response.getWriter();
        javax.servlet.ServletContext theServletContext = this.getServletContext();
        Kernel aCAB = new Kernel();       
        javax.servlet.http.HttpServletRequestWrapper aRequestWrapper = new javax.servlet.http.HttpServletRequestWrapper( request );
        javax.servlet.http.HttpServletResponseWrapper aResponseWrapper = new javax.servlet.http.HttpServletResponseWrapper( response );
        try {          
            aCAB.populatingTheDirectoryMap(theServletContext);
            //throw new Exception("Testing CABOOSE Exceptions");
            out.println(aCAB.preparingTheSuccessfulResponse("test_page",theServletContext, aRequestWrapper, aResponseWrapper));
        } catch (Exception e) {
           
            ((javax.servlet.http.HttpSession) aRequestWrapper.getSession()).setAttribute(EXCEPTION_KEY,e.getMessage());
            out.println(aCAB.preparingTheExceptionResponse(theServletContext, aRequestWrapper, aResponseWrapper));
            e.printStackTrace(out);
        }       
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
            throws javax.servlet.ServletException, java.io.IOException {
        processRequest(request, response);
    }
    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
            throws javax.servlet.ServletException, java.io.IOException {
        processRequest(request, response);
    }
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "CABOOSE General-Purpose Servlet";
    }// </editor-fold>
}
//Kernel.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net.java.CABOOSE;
/**
 * The CAB is the kernel of the CABOOSE general purpose servlet.
 * Implicit Contract Requirements and Guidelines: The CAB contracts with support
 * classes that have rendering methods which return String content. These
 * methods also must have the signature public String methodName(
 * java.util.HashMap<String,String> aMapParameter ) by implicit contract. If
 * they do not, the reflection activities which automatically invoke them will
 * fail since they cannot find the requested method. Class, method, tile
 * replacement, and stencil filename identifiers are all stored in a file called
 * directory.xml which contains a mapping between each item.
 * @author Jody
 */
public class Kernel implements SystemExceptions, SystemStandards {
   
    //Simulated URL String. We will eventually get all of our input from the
    //the servlet's Request object.
    String request = "?project=caboose&module=skeleton&create_date=10.30.2014";
   
    //A data structure for holding a description of the page, stencil, and tile
    //directory. It is keyed by the page name. Each value in the structure is a
    //ViewModel. See the description of this inner class for information on its
    //content and structure.
    java.util.HashMap<String, ViewModel> aDirectoryMap = null;
    //private inner class representing a model of a single view which the
    //controller can return.
    private class ViewModel {
        //The stencil filename.
        private String theStencilFileName = null;
        //A data structure which holds the tile identifier as a key and the name
        //of the class and method for rendering the the tile as a
        //comma seperated value
        private java.util.HashMap<String, String> theTileRendererMappings = null;
        //This method assigns the stencil filename
        void settingTheStencilFileName(String aStencilFileName) throws Exception {
            //Opening Contract
            //The stencil name is not a null or empty string.           
            if (aStencilFileName == null || aStencilFileName.length() == 0) {
                throw new Exception(STENCIL_FILE_NAME_ERROR);
            }
            theStencilFileName = aStencilFileName;
            //Closing Contract (Implicit)
            //The stencil name is a non-empty string.
        }
        //This method assigns the tile renderer mappings
        void settingTheTileRendererMappings(java.util.HashMap<String, String> aSetOfTileRendererMappings) throws Exception {
            //Opening Contract
            //The set of mappings between tiles and renderer methods is not null
            //It might be of size zero if there does not exist any replacment tiles
            //within the stencil.
            if (aSetOfTileRendererMappings == null) {
                throw new Exception(TILE_RENDERER_MAPPINGS_ERROR);
            }
            theTileRendererMappings = aSetOfTileRendererMappings;
            //Closing Contract (Implicit)
            //The tile renderer mappings is not null. They might be empty.
        }
        //This method returns the stencil file name
        String gettingTheStencilFileName() throws Exception {
            //Invariant Opening Contract
            //The stencil name is not a null or empty string.           
            if (theStencilFileName == null || theStencilFileName.length() == 0) {
                throw new Exception(STENCIL_FILE_NAME_ERROR);
            }
            return (theStencilFileName);
        }
        //This method retruns the tile renderer mappings data structure
        java.util.HashMap<String, String> gettingTheTileRendererMappings() throws Exception{
            //Invariant Opening Contract
            //The tile renderer mappings are not null. They might be empty.
            if (theTileRendererMappings == null ) {
                throw new Exception(TILE_RENDERER_MAPPINGS_ERROR);
            }           
            return (theTileRendererMappings);
        }
    }
    //This method extracts the content of a stencil from the file system based
    //upon a file name. In the future this method will need adapting so it
    //retrieves the proper file in a web server's file system using
    //the servlet context.
    private String gettingTheResponseStencil(javax.servlet.ServletContext theServletContext, String aStencilFileName) throws Exception {
        //Opening Contract
        //The file name of the view stencil is not a null or empty string.
        if (aStencilFileName == null || aStencilFileName.length() == 0) {
            throw new Exception(STENCIL_FILE_NAME_ERROR);
        }
        java.io.BufferedReader aStencilReader = new java.io.BufferedReader(new java.io.FileReader(theServletContext.getRealPath(aStencilFileName)));
        String theStencilContent = "", theNextLine = null;
        while ((theNextLine = aStencilReader.readLine()) != null) {
            theStencilContent += theNextLine;
        }
        //Closing Contract
        //The stencil content of the view in not its initial value of an empty string.
        if (theStencilContent.length() == 0) {
            throw new Exception(STENCIL_CONTENT_ERROR);
        }
        return (theStencilContent);
    }
    //This method extracts the name and value pairs from the input query string.
    //We assume that it is not url encoded. For the generic servlet edition of
    //the cab, this method will not be useful. But it might be of use for a
    //command-line based edition of the cab for report writing or rendering
    //windowing applications.
    java.util.HashMap<String, String> mappingTheRequestNameValuePairs(String aRequest) throws Exception {
        java.util.HashMap<String, String> aMap = new java.util.HashMap<String, String>();
        //Opening Contract
        //If the request query string is null or empty, return an empty aMap
        if (aRequest == null || aRequest.length() == 0) {
            return aMap;
        }
        aRequest = aRequest.replace("?", "");
        String[] theNameValuePairs = aRequest.split("&");
        for (String aNameValuePair : theNameValuePairs) {           
            String[] aTuple = aNameValuePair.split("=");
            aMap.put(aTuple[NAME_INDEX], aTuple[VALUE_INDEX]);
        }
        //Closing Contract
        //The Map cannot be empty on the input of a non-empty request query string
        if (aMap.size() == 0) {
            throw new Exception(QUERY_STRING_ERROR);
        }
        return aMap;
    }
    //When an exception has occurred, this method populates a view stencil with
    //the content generated by dynamically invoking rendering methods and
    //replacing their associated user-defined tile identifiers
    //( a.k.a stencil replacement variables ). Notice that this method does not
    //throw an exception upward.
    //See the contract guideline in the header comments of this document.
    String preparingTheExceptionResponse(javax.servlet.ServletContext theServletContext,javax.servlet.http.HttpServletRequest theHTTPServletRequest,javax.servlet.http.HttpServletResponse theHTTPServletResponse) {
        String aReplacementString = "";
        String aSupplementalExceptionMessage = "";
        String theStencilContent = VIEW_MODEL_ERROR;
        ViewModel aViewModel = null;
        String[] aTileClassAndMethod = null;
        //Opening Contract (Implicit)
        //The size of the request map is zero or larger
        aViewModel = (ViewModel) aDirectoryMap.get(EXCEPTION_VIEW);
        //Intermediate Contract
        //The view model cannot be null.
        if (aViewModel == null) {
            return (theStencilContent);
        }
        try {
            theStencilContent = gettingTheResponseStencil(theServletContext,aViewModel.gettingTheStencilFileName());
        } catch (Exception e) {
            return (theStencilContent);
        }
        //Intermediate Contract (Implicit)
        //The stencil content of the view in not an empty string.
        java.util.HashMap<String, String> someTileRenderMappings = null;
       
        try {
            someTileRenderMappings = aViewModel.gettingTheTileRendererMappings();
        }catch( Exception e ) {
            return (theStencilContent);
        }
       
        //Intermediate Contract (Implicit)
        //The tile renderer mappings are not null. They might be empty.
        for (String aTileId : someTileRenderMappings.keySet()) {
            //Intermediate Contract Within Evaluation (.get) (Implicit)
            //The tile class and method is a non-empty string which contains a single
            //comma as a CSV string.
            aTileClassAndMethod = ((String) someTileRenderMappings.get(aTileId)).split(",");                       
            //Intermediate Contract
            //The class and method names for the tile renderer cannot be null or empty.
            if (aTileClassAndMethod[CLASS_INDEX] == null || aTileClassAndMethod[METHOD_INDEX] == null || aTileClassAndMethod[CLASS_INDEX].length() == 0 || aTileClassAndMethod[METHOD_INDEX].length() == 0) {
                aSupplementalExceptionMessage += FORMATTED_CLASS_METHOD_ERROR;
            }
            try {
                //Start Reflection Activities
                Class aClass = Class.forName(aTileClassAndMethod[CLASS_INDEX]);
                Class[] theFullyQualifiedParameterTypeClasses = new Class[2];
                theFullyQualifiedParameterTypeClasses[0] = theHTTPServletRequest.getClass();
                theFullyQualifiedParameterTypeClasses[1] = theHTTPServletResponse.getClass();
                Object[] theParameterObjectList = new Object[2];
                theParameterObjectList[0] = theHTTPServletRequest;
                theParameterObjectList[1] = theHTTPServletResponse;
                aReplacementString = (String) (aClass.getMethod(aTileClassAndMethod[METHOD_INDEX], theFullyQualifiedParameterTypeClasses)).invoke((aClass.getConstructor()).newInstance(), theParameterObjectList);
                //End Reflection Activities                        
            } catch (Exception e) {
                aReplacementString = "<p>" + e.getMessage() + "</p>";
            }
            theStencilContent = theStencilContent.replace(aTileId, aReplacementString + aSupplementalExceptionMessage);
        }
        //Closing Contract (Implicit)
        //The class and method for the given name exist among the controller application bundle.     
        return (theStencilContent);
    }
    //This method populates a view stencil with the content generated by
    //dynamically invoking reendering methods and replacing their associated
    //user-defined tile identifiers ( a.k.a stencil replacement variables ).
    //See the contract guideline in the header comments of this document.
    String preparingTheSuccessfulResponse(String theViewId, javax.servlet.ServletContext theServletContext,javax.servlet.http.HttpServletRequest theHTTPServletRequest,javax.servlet.http.HttpServletResponse theHTTPServletResponse) throws Exception {
        //Opening Contract
        //The id of the view cannot be null or empty
        if (theViewId == null || theViewId.length() == 0) {
            throw new Exception(VIEW_IDENTIFIER_ERROR);
        }
        //Opening Contract (Implicit)
        //The size of the request map is zero or larger
        ViewModel aViewModel = (ViewModel) aDirectoryMap.get(theViewId);
        //Intermediate Contract
        //The view model cannot be null.
        if (aViewModel == null) {
            throw new Exception(VIEW_MODEL_MISSING_ERROR);
        }
        String[] aTileClassAndMethod = null;
        String theStencilContent = gettingTheResponseStencil(theServletContext,aViewModel.gettingTheStencilFileName());
        //Intermediate Contract (Implicit)
        //The stencil content of the view in not an empty string.
        java.util.HashMap<String, String> someTileRenderMappings = aViewModel.gettingTheTileRendererMappings();
        //Intermediate Contract (Implicit)
        //The tile renderer mappings are not null. They might be empty.
        for (String aTileId : someTileRenderMappings.keySet()) {
            //Intermediate Contract Within Evaluation (.get) (Implicit)
            //The tile class and method is a non-empty string which contains a single
            //comma as a CSV string.
            aTileClassAndMethod = ((String) someTileRenderMappings.get(aTileId)).split(",");
            //Intermediate Contract
            //The class and method names for the tile renderer cannot be null or empty.
            if (aTileClassAndMethod[CLASS_INDEX] == null || aTileClassAndMethod[METHOD_INDEX] == null || aTileClassAndMethod[CLASS_INDEX].length() == 0 || aTileClassAndMethod[METHOD_INDEX].length() == 0) {
                throw new Exception(CLASS_METHOD_ERROR);
            }
            //Start Reflection Activities
            Class aClass = Class.forName(aTileClassAndMethod[CLASS_INDEX]);
            Class[] theFullyQualifiedParameterTypeClasses = new Class[2];
                theFullyQualifiedParameterTypeClasses[0] = theHTTPServletRequest.getClass();
                theFullyQualifiedParameterTypeClasses[1] = theHTTPServletResponse.getClass();
                Object[] theParameterObjectList = new Object[2];
                theParameterObjectList[0] = theHTTPServletRequest;
                theParameterObjectList[1] = theHTTPServletResponse;
                theStencilContent = theStencilContent.replace(aTileId, (String) (aClass.getMethod(aTileClassAndMethod[METHOD_INDEX], theFullyQualifiedParameterTypeClasses)).invoke((aClass.getConstructor()).newInstance(), theParameterObjectList));
            //End Reflection Activities                        
        }
        //Closing Contract (Implicit)
        //The class and method for the given name exist among the controller application bundle.     
        return (theStencilContent);
    }
    private org.w3c.dom.Document gettingTheDirectoryXMLDocument(javax.servlet.ServletContext theServletContext) throws Exception {
       
        javax.xml.parsers.DocumentBuilderFactory theDocumentBuilderFactory =
        javax.xml.parsers.DocumentBuilderFactory.newInstance();
        javax.xml.parsers.DocumentBuilder theDocumentBuilder = theDocumentBuilderFactory.newDocumentBuilder();
        //Intermediate Contract (implicit)
        //The argument for the java.io.File constructor is the canonical name
        //for all CABOOSE bundles and is XML. (It will differ in the final version).
        java.io.File aFile = new java.io.File(theServletContext.getRealPath(STANDARD_DIRECTORY_SOURCE));
        org.w3c.dom.Document theDocument = theDocumentBuilder.parse(aFile);
        theDocument.getDocumentElement().normalize();
       
        return (theDocument);
    }
    //This module extracts the information from the directory.xml file using an
    //XML reader that creates a DOM from which the method creates a user-defined
    //map between view names and ViewModel objects. In the future, we might
    //utilize a SAX XML reader skipping the creation of the DOM and directly
    //create the ViewModel map data structure. This should result in a slight
    //processing speed up although we will only be doing it once during a servlet
    //session and storing the utlimate view model map in the servlet's session
    //object. Directory.xml represents a model mapping for the entire application.
    //Based upon the length of this method ( 50+ lines of code ) it should
    //likely be subdivided and invoke a few private utility methods for
    //completing its work.
    void populatingTheDirectoryMap(javax.servlet.ServletContext theServletContext) throws Exception {
        String aViewId = null;
        String aStencil = null;
        String aTileId = null;
        String aTileClass = null;
        String aTileMethod = null;
        aDirectoryMap = new java.util.HashMap<String, ViewModel>();
        org.w3c.dom.Document theDocument = gettingTheDirectoryXMLDocument(theServletContext);
       
        org.w3c.dom.NodeList theModelNodeList = theDocument.getElementsByTagName("model");
        for (int aModelNodeIndex = 0; aModelNodeIndex < theModelNodeList.getLength(); aModelNodeIndex++) {
            org.w3c.dom.Node aModelNode = theModelNodeList.item(aModelNodeIndex);
            if (aModelNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                org.w3c.dom.Element aModelElement = (org.w3c.dom.Element) aModelNode;
                org.w3c.dom.NodeList theViewNodeList =
                        aModelElement.getElementsByTagName("view");
                for (int aViewNodeIndex = 0; aViewNodeIndex < theViewNodeList.getLength(); aViewNodeIndex++) {
                    org.w3c.dom.Node aViewNode = (org.w3c.dom.Node) theViewNodeList.item(aViewNodeIndex);
                    if (aViewNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                        org.w3c.dom.Element aViewElement = (org.w3c.dom.Element) aViewNode;
                        ViewModel aViewModel = new ViewModel();
                        aViewId = aViewElement.getAttribute("id");
                        aStencil = aViewElement.getAttribute("stencil");
                        aViewModel.settingTheStencilFileName(aStencil);
                    
                        java.util.HashMap<String, String> someTileRendererMappings = new java.util.HashMap<String, String>();
                        org.w3c.dom.NodeList theTileNodeList = aViewElement.getElementsByTagName("tile");
                        for (int aTileNodeIndex = 0; aTileNodeIndex < theTileNodeList.getLength(); aTileNodeIndex++) {

                            org.w3c.dom.Node aTileNode = (org.w3c.dom.Node) theTileNodeList.item(aTileNodeIndex);
                            if (aTileNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                                org.w3c.dom.Element aTileElement = (org.w3c.dom.Element) aTileNode;
                                aTileId = aTileElement.getAttribute("id");
                                aTileClass = aTileElement.getAttribute("class");
                                aTileMethod = aTileElement.getAttribute("method");
                                someTileRendererMappings.put(aTileId, aTileClass + "," + aTileMethod);
                            }
                        }
                        aViewModel.settingTheTileRendererMappings(someTileRendererMappings);
                        aDirectoryMap.put(aViewId, aViewModel);
                    }
                }
            }
        }
        //Closing Contract
        //The directory map cannot be empty if the CAB returns a view
        if (aDirectoryMap.size() == 0) {
            throw new Exception(DIRECTORY_ERROR);
        }
    }
}
//SystemExceptions.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net.java.CABOOSE;
/**
 *
 * @author Jody
 */
public interface SystemExceptions {
     //Exception Handling Constants
    final String VIEW_MODEL_ERROR = "<html><head><title>CABOOSE ERROR</title><head><body>The exception view model, content, or tile mappings were not found.</body></html>";
    final String STENCIL_FILE_NAME_ERROR = "Stencil name is null or empty.";
    final String TILE_RENDERER_MAPPINGS_ERROR = "The mapping between tiles and render methods is null.";
    final String STENCIL_CONTENT_ERROR = "The stencil content of the view stencil is empty.";
    final String QUERY_STRING_ERROR = "The input key-value map is empty. Could not interpret the query string.";
    final String VIEW_IDENTIFIER_ERROR = "The view identifier is null or empty.";
    final String VIEW_MODEL_MISSING_ERROR = "The view model was not found.";
    final String CLASS_METHOD_ERROR = "The class or method name for the tile renderer was null or empty.";
    final String FORMATTED_CLASS_METHOD_ERROR = "<p>" + CLASS_METHOD_ERROR + "</p>"; ;   
    final String DIRECTORY_ERROR = "The application view directory map is empty.";
    final String EXCEPTION_VIEW = "exception";
    final String EXCEPTION_KEY = "exception_message";
}
//SystemStandards.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net.java.CABOOSE;
/**
 *
 * @author Jody
 */
public interface SystemStandards {
     //Standard Constants
    final int CLASS_INDEX = 0;
    final int METHOD_INDEX = 1;
    final int NAME_INDEX = 0;
    final int VALUE_INDEX = 1;
    final String STANDARD_DIRECTORY_SOURCE = "/WEB-INF/directory.xml";
   
}
//Caboose.java - Hibernate Auto-generated Class Through Reverse Engineering
package net.java.CABOOSE.Hibernate;
// Generated Dec 28, 2014 1:19:07 AM by Hibernate Tools 4.3.1

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
 * Caboose generated by hbm2java
 */
@Entity
@Table(name="CABOOSE"
    ,schema="ROOT"
)
public class Caboose  implements java.io.Serializable {

     private int id;
     private String message;
    public Caboose() {
    }

    public Caboose(int id) {
        this.id = id;
    }
    public Caboose(int id, String message) {
       this.id = id;
       this.message = message;
    }
  
     @Id
   
    @Column(name="ID", unique=true, nullable=false)
    public int getId() {
        return this.id;
    }
   
    public void setId(int id) {
        this.id = id;
    }
   
    @Column(name="MESSAGE", length=256)
    public String getMessage() {
        return this.message;
    }
   
    public void setMessage(String message) {
        this.message = message;
    }
}
//HibernatePort.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.sharpe.sample;
/**
 *
 * @author Jody
 */
class HibernatePort {
   
   
    private org.hibernate.SessionFactory aHibernateSessionFactory = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
   
    String listCABOOSEMessages () throws Exception{
        String theMessages = "";
        String anExceptionMessage = null;
        boolean anExceptionOccurred = false;
        org.hibernate.Session anHibernateSession = null;
        org.hibernate.Transaction anHibernateTransaction = null;
        try {
        anHibernateSession = aHibernateSessionFactory.openSession();
        anHibernateTransaction = anHibernateSession.beginTransaction();
        java.util.List<net.java.CABOOSE.Hibernate.Caboose> theCabooseMessages = anHibernateSession.createQuery("FROM Caboose").list();
        for ( net.java.CABOOSE.Hibernate.Caboose theMessage: theCabooseMessages ){
            theMessages += "MSG[" + theMessage.getId()+ "]: " + theMessage.getMessage() + "</br>";           
        }
        anHibernateTransaction.commit();
        }catch(org.hibernate.HibernateException anHibernateException){
            if( anHibernateTransaction != null ){
                anHibernateTransaction.rollback();
                anExceptionOccurred = true;
                anExceptionMessage = anHibernateException.getMessage();               
            }
        }finally{
            anHibernateSession.close();
        }
       
        if(anExceptionOccurred){
            throw new Exception(anExceptionMessage);
        }
        return theMessages;
    }
   
}
//StencilHandler.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.sharpe.sample;
/**
 * An example stencil handler class. For each unique instance of a CABOOSE
 * application, these will be user defined.
 * @author Jody
 */
public class StencilHandler implements net.java.CABOOSE.SystemExceptions{
     //Renderer for supplying content about the create date
    public String createDateRenderer( javax.servlet.http.HttpServletRequestWrapper theHTTPServletRequest, javax.servlet.http.HttpServletResponseWrapper theHTTPServletResponse ){
        return( theHTTPServletRequest.getParameter("create_date") ); 
    }
    //Renderer for supplying content about the module
    public String moduleRenderer(  javax.servlet.http.HttpServletRequestWrapper theHTTPServletRequest, javax.servlet.http.HttpServletResponseWrapper theHTTPServletResponse ){
        return( theHTTPServletRequest.getParameter("module") ); 
    }
    //Renderer for supplying content about the project
    public String projectRenderer(  javax.servlet.http.HttpServletRequestWrapper theHTTPServletRequest, javax.servlet.http.HttpServletResponseWrapper theHTTPServletResponse ){
        return( theHTTPServletRequest.getParameter("project") ); 
    }
    //Renderer for supplying exception content
    public String exceptionRenderer(  javax.servlet.http.HttpServletRequestWrapper theHTTPServletRequest, javax.servlet.http.HttpServletResponseWrapper theHTTPServletResponse ){
        return( (String) ((javax.servlet.http.HttpSession) theHTTPServletRequest.getSession()).getAttribute(EXCEPTION_KEY) ); 
    }
    public String hibernateMessageRenderer( javax.servlet.http.HttpServletRequestWrapper theHTTPServletRequest, javax.servlet.http.HttpServletResponseWrapper theHTTPServletResponse ) throws Exception{
        HibernatePort anHibernatePort = new HibernatePort();
        return( anHibernatePort.listCABOOSEMessages() ); 
    }
}
//END OF SOURCE FILES

No comments:

Post a Comment