it.delli.mwebc.servlet.MWebCRenderer.java Source code

Java tutorial

Introduction

Here is the source code for it.delli.mwebc.servlet.MWebCRenderer.java

Source

/*
 * (C) Copyright 2010, by Francesco Delli Paoli.
 * 
 * Project Info:  http://mwebc.sourceforge.net/
 * 
 * This file is part of mwebc - Model Web Controller.
 * 
 * mwebc is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * mwebc is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with mwebc; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

package it.delli.mwebc.servlet;

import it.delli.mwebc.MWebCConfig;
import it.delli.mwebc.annotations.WidgetAttribute;
import it.delli.mwebc.event.Event;
import it.delli.mwebc.event.listener.PageEventListener;
import it.delli.mwebc.ui.Application;
import it.delli.mwebc.ui.Page;
import it.delli.mwebc.ui.Widget;
import it.delli.mwebc.utils.CastHelper;
import it.delli.mwebc.utils.ReflectionUtils;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class MWebCRenderer extends HttpServlet {

    private static Log log = LogFactory.getLog(MWebCRenderer.class);

    private static final long serialVersionUID = 3252293321393433123L;

    public MWebCRenderer() {
        super();
    }

    public void destroy() {
        super.destroy();
    }

    public static void buildLayout(Element elem, Widget parent, Page page) throws Exception {
        Widget widget = null;
        if (elem.getNodeType() == Node.ELEMENT_NODE && elem.getNodeName().equals("Page")) {
            for (int j = 0; j < elem.getAttributes().getLength(); j++) {
                Node attribute = elem.getAttributes().item(j);
                if (!attribute.getNodeName().equals("id")) {
                    if (attribute.getNodeName().equals("eventListener")) {
                        log.debug("Setting PageEventListener");
                        try {
                            page.setEventListener(
                                    (PageEventListener) Class.forName(attribute.getNodeValue()).newInstance());
                        } catch (Exception e) {
                            log.error("Exception in setting PageEventListener");
                        }
                    }
                }
            }
            if (page.getEventListener() == null) {
                log.debug("Setting default PageEventListener");
                page.setEventListener(new PageEventListener() {

                    @Override
                    public void onLoad(Event event) {
                    }

                    @Override
                    public void onInit(Event event) {
                    }

                });
            }
            for (int i = 0; i < elem.getChildNodes().getLength(); i++) {
                Node node = elem.getChildNodes().item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    buildLayout((Element) node, widget, page);
                }
            }
        } else if (elem.getNodeType() == Node.ELEMENT_NODE && elem.getNodeName().equals("PageFragment")) {
            for (int i = 0; i < elem.getChildNodes().getLength(); i++) {
                Node node = elem.getChildNodes().item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    buildLayout((Element) node, parent, page);
                }
            }
        } else {
            Class<?> widgetClass = page.getApplication().getWidgetClass(elem.getNodeName());
            if (widgetClass == null) {
                log.fatal("Exception in getting widget class for widget " + elem.getNodeName());
                throw new Exception();
            } else if (widgetClass.getName().equals("com.dodifferent.applications.commander.widget.DataListItem")) {
                System.out.println();
            }
            CastHelper castHelper = page.getApplication().getCastHelper(widgetClass);

            String id = null;
            for (int j = 0; j < elem.getAttributes().getLength(); j++) {
                Node attribute = elem.getAttributes().item(j);
                if (attribute.getNodeName().equals("id")) {
                    id = attribute.getNodeValue();
                    break;
                }
            }

            HashMap<String, Object> initParams = new HashMap<String, Object>();
            for (int j = 0; j < elem.getAttributes().getLength(); j++) {
                Node attributeNode = elem.getAttributes().item(j);
                if (!attributeNode.getNodeName().equals("id") && !attributeNode.getNodeName().startsWith("on")) {
                    Field fieldAttribute = ReflectionUtils.getAnnotatedField(widgetClass,
                            attributeNode.getNodeName(), WidgetAttribute.class);
                    if (fieldAttribute != null) {
                        fieldAttribute.setAccessible(true);
                        Class<?> propertyType = fieldAttribute.getType();
                        //                  Type[] genericTypes = ((ParameterizedType)fieldAttribute.getGenericType()).getActualTypeArguments();
                        initParams.put(attributeNode.getNodeName(),
                                castHelper.toType(attributeNode.getNodeValue(), propertyType));
                    } else {
                        log.warn("Warning in updating server widgets attribute. The attribute '"
                                + attributeNode.getNodeName() + "' doesn't exist for widget "
                                + widgetClass.getName());
                    }
                }
            }

            try {
                if (id != null && initParams.keySet().size() == 0) {
                    Class[] constructorParams = { Page.class, String.class };
                    Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName())
                            .getConstructor(constructorParams);
                    widget = (Widget) widgetConstructor.newInstance(page, id);
                } else if (id != null && initParams.keySet().size() > 0) {
                    Class[] constructorParams = { Page.class, String.class, Map.class };
                    Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName())
                            .getConstructor(constructorParams);
                    widget = (Widget) widgetConstructor.newInstance(page, id, initParams);
                } else if (id == null && initParams.keySet().size() == 0) {
                    Class[] constructorParams = { Page.class };
                    Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName())
                            .getConstructor(constructorParams);
                    widget = (Widget) widgetConstructor.newInstance(page);
                } else if (id == null && initParams.keySet().size() > 0) {
                    Class[] constructorParams = { Page.class, Map.class };
                    Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName())
                            .getConstructor(constructorParams);
                    widget = (Widget) widgetConstructor.newInstance(page, initParams);
                }
            } catch (Exception e) {
                log.error("Exception in constructing widget " + widget.getClass().getName() + " (" + widget.getId()
                        + ")", e);
            }

            if (widget != null) {
                for (int j = 0; j < elem.getAttributes().getLength(); j++) {
                    Node attributeNode = elem.getAttributes().item(j);
                    if (!attributeNode.getNodeName().equals("id") && attributeNode.getNodeName().startsWith("on")) {
                        String event = attributeNode.getNodeName();
                        try {
                            widget.addEventListener(event, page.getEventListener(), attributeNode.getNodeValue());
                            //                     Method eventMethod = widget.getClass().getMethod("addEventListener", String.class, EventListener.class, String.class);
                            //                     eventMethod.invoke(widget, event, page.getEventListener(), attributeNode.getNodeValue());
                        } catch (Exception e) {
                            log.warn("Warning in registering EventListener for widget "
                                    + widget.getClass().getName() + " (" + widget.getId() + ")", e);
                        }
                    }
                }
                for (int i = 0; i < elem.getChildNodes().getLength(); i++) {
                    Node node = elem.getChildNodes().item(i);
                    if (node.getNodeType() == Node.CDATA_SECTION_NODE || node.getNodeType() == Node.TEXT_NODE) {
                        try {
                            String content = node.getNodeValue().replace("\t", "").replace("\n", "").replace("\"",
                                    "\\\"");
                            if (!content.equals("")) {
                                //                        Method attributeMethod = widget.getClass().getMethod("addTextContent", String.class);
                                //                        attributeMethod.invoke(widget, content);
                                widget.addTextContent(content);
                            }
                        } catch (Exception e) {
                            log.warn("Warning in setting content for widget " + widget.getClass().getName() + " ("
                                    + widget.getId() + ")", e);
                        }
                    } else if (node.getNodeType() == Node.ELEMENT_NODE) {
                        buildLayout((Element) node, widget, page);
                    }
                }
                widget.setParent(parent);
            }
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Application application = (Application) request.getSession().getAttribute("application");
        if (application == null) {
            log.info("Application not present in context. Creating new Application");
            application = MWebCConfig.init(request.getSession());
        }
        String pageName = request.getServletPath().substring(1, request.getServletPath().indexOf(".mwc"));
        String debugWidget = request.getParameter("debugWidget");
        Page page = application.createPage(pageName);
        application.addPage(page);
        try {
            Document pageDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(new File(getServletContext().getRealPath("/" + pageName + ".mwc")));
            buildLayout(pageDocument.getDocumentElement(), null, page);
        } catch (Exception e) {
            log.error("Exception in building widget tree", e);
        }

        ReflectionUtils.registerAnnotatedEventListenerMethods(page.getEventListener(), page);

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        out.println(
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//`EN\" \"http://www.w3.org/TR/html4/strict.dtd\">");
        out.println("<html xmlns:v=\"urn:schemas-microsoft-com:vml\">");
        out.println("<head>");
        out.println("<title>" + page.getTitle() + "</title>");
        out.println("<!-- mwebc by Francesco Delli Paoli -->");
        for (Iterator<String> iterator = application.getResources().getJavascriptUrl().iterator(); iterator
                .hasNext();) {
            out.println("<script type=\"text/javascript\" src=\"" + iterator.next() + "\"></script>");
        }
        for (Iterator<String> iterator = application.getResources().getCssUrl().iterator(); iterator.hasNext();) {
            out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + iterator.next() + "\" />");
        }
        for (Iterator<String> iterator = application.getResources().getJavascript().iterator(); iterator
                .hasNext();) {
            out.println("<script type=\"text/javascript\">" + iterator.next() + "</script>");
        }
        for (Iterator<String> iterator = application.getResources().getCss().iterator(); iterator.hasNext();) {
            out.println("<style type=\"text/css\">" + iterator.next() + "</style>");
        }
        if (debugWidget != null) {
            out.println("<script src=\"resources/" + debugWidget.replace(".", "/") + ".js\"></script>");
            out.println("<script>mwebc.debugWidget = \"" + debugWidget + "\";</script>");
        }
        out.println("</head>");
        out.println("<body class=\"claro\" >");
        out.println("</body>");
        out.println("<script type=\"text/javascript\">");
        out.println("mwebc.ready(function() {");
        out.println("   mwebc.delegate('event', {sessionId: '" + request.getSession().getId()
                + "', event: 'onInitPage', eventType: 'HtmlEvent', pageName: '" + page.getName()
                + "', forward: 'onInit', data: {} }, false);");
        out.println("   mwebc.delegate('event', {sessionId: '" + request.getSession().getId()
                + "', event: 'onLoadPage', eventType: 'HtmlEvent', pageName: '" + page.getName()
                + "', forward: 'onLoad', data: {} });");
        out.println("});");
        out.println("</script>");
        out.println("</html>");

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    public void init() throws ServletException {

    }
}