Tuesday, November 18, 2014

Hocus Pocus Invoke Us - Reflection Time

Team. Below is the source the first stage of this week's coding activity. When compiling and running, be certain that your source is in a package called cab. If not, adjust the class names in the "directory" XML file and remove the package statements. The portion of the source which uses reflection has been clearly marked. This is probably the most "advanced" portion of the development. If you understand it, you will not have a problem with any of the other portions. Basically you are invoking a method dynamically after being given its name and class location. There is an implicit contract between the CAB and the rendering methods which states that their only parameter will be a HashMap. In the future, it will support the HTTPRequest and HTTPResponse objects as parameters. This likely is enough for now. During the next stage this week, we will remove the redundant source code for reading the XML file. Talk with you later. La-La.

// BEGIN CAB JAVA Source
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cab;
/**
 * The CAB will eventually for the kernel of the CABOOSE general purpose servlet
 *
 * @author Jody Sharpe
 */
public class CAB {
    //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";
    String gettingTheResponseStencil(String aViewFileName) throws Exception {
        java.io.BufferedReader aStencilReader = new java.io.BufferedReader(new java.io.FileReader(aViewFileName));
        String theStencilContent = "", theNextLine = null;
        while ((theNextLine = aStencilReader.readLine()) != null) {
            theStencilContent += theNextLine;
        }
        return (theStencilContent);
    }
    java.util.HashMap<String, String> mappingTheRequestNameValuePairs(String aRequest) {
        java.util.HashMap<String, String> aMap = new java.util.HashMap<String, String>();
        aRequest = aRequest.replace("?", "");
        String[] theNameValuePairs = aRequest.split("&");
        for (String aNameValuePair : theNameValuePairs) {
            final int theName = 0, theValue = 1;
            String[] aTuple = aNameValuePair.split("=");
            aMap.put(aTuple[theName], aTuple[theValue]);
        }
        return aMap;
    }
   
    String preparingTheResponse(String theViewId, String theStencilName, java.util.HashMap<String, String> aRequestMap) throws Exception {
        String aViewId = null;      
        String aTileId = null;
        String aTileClass = null;
        String aTileMethod = null;
        String theStencilContent = gettingTheResponseStencil( theStencilName );
        javax.xml.parsers.DocumentBuilderFactory theDocumentBuilderFactory =
                javax.xml.parsers.DocumentBuilderFactory.newInstance();
        javax.xml.parsers.DocumentBuilder theDocumentBuilder = theDocumentBuilderFactory.newDocumentBuilder();
        java.io.File aFile = new java.io.File("./src/cab/directory.xml");
        org.w3c.dom.Document theDocument = theDocumentBuilder.parse(aFile);
        theDocument.getDocumentElement().normalize();
        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;
                        aViewId = aViewElement.getAttribute("id");
                        if (aViewId.equalsIgnoreCase(theViewId)) {
                            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");
                                   
                                    //Start Reflection Activities
                                    Class aClass = Class.forName( aTileClass );
                                    Class [] theFullyQualifiedParameterTypeClasses = new Class[1];
                                    theFullyQualifiedParameterTypeClasses[0] = (new java.util.HashMap<String,String>()).getClass();
                                    Object [] theParameterObjectList= new Object [1];                                   
                                    theParameterObjectList[0] = aRequestMap;
                                    theStencilContent = theStencilContent.replace( aTileId , (String) ( aClass.getMethod(aTileMethod,theFullyQualifiedParameterTypeClasses) ).invoke((aClass.getConstructor()).newInstance(), theParameterObjectList));  
                                    //End Reflection Activities
                                }
                            }
                        }
                    }
                }
            }
        }
        return (theStencilContent);
    }
    String readingTheDirectoryXMLFile(String theViewId) throws Exception {
        String aViewId = null;
        String aStencil = null;
        javax.xml.parsers.DocumentBuilderFactory theDocumentBuilderFactory =
                javax.xml.parsers.DocumentBuilderFactory.newInstance();
        javax.xml.parsers.DocumentBuilder theDocumentBuilder = theDocumentBuilderFactory.newDocumentBuilder();
        java.io.File aFile = new java.io.File("./src/cab/directory.xml");
        org.w3c.dom.Document theDocument = theDocumentBuilder.parse(aFile);
        theDocument.getDocumentElement().normalize();
        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;
                        aViewId = aViewElement.getAttribute("id");
                        if (aViewId.equalsIgnoreCase(theViewId)) {
                            aStencil = aViewElement.getAttribute("stencil");
                        }
                    }
                }
            }
        }
        return (aStencil);
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        CAB aCAB = new CAB();
        java.util.HashMap<String, String> aRequestMap = aCAB.mappingTheRequestNameValuePairs(aCAB.request);
        try {
            System.out.println(aCAB.preparingTheResponse("test_page", aCAB.readingTheDirectoryXMLFile("test_page"), aRequestMap));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
//END CAB JAVA Source

//BEGIN StencilHandler JAVA Source
*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cab;
/**
 *
 * @author Jody Sharpe
 */
public class StencilHandler {
    public String createDateRenderer( java.util.HashMap<String,String> aRequestMap){
        return( aRequestMap.get("create_date") ); 
    }
    public String moduleRenderer( java.util.HashMap<String,String> aRequestMap){
        return( aRequestMap.get("module") ); 
    }
    public String projectRenderer( java.util.HashMap<String,String> aRequestMap){
        return( aRequestMap.get("project") ); 
    }
}
//END StencilHandler JAVA Source

//BEGIN directory.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<model>
 <view id="test_page" stencil="./src/cab/xstencil.xhtml">
            <tile id="#PROJECT#" class="cab.StencilHandler" method="projectRenderer"/>
            <tile id="#MODULE#" class="cab.StencilHandler" method="moduleRenderer"/>
            <tile id="#CREATE_DATE#" class="cab.StencilHandler" method="createDateRenderer"/>
 </view>
</model>
//END directory.xml

No comments:

Post a Comment