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

Java tutorial

Introduction

Here is the source code for it.delli.mwebc.servlet.MWebCManager.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.annotations.WidgetAttribute;
import it.delli.mwebc.command.Command;
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.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

public class MWebCManager extends HttpServlet {

    private static final long serialVersionUID = 7097319851166755694L;

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

    public MWebCManager() {
        super();
    }

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

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            response.setContentType("text/xml");
            String action = request.getParameter("action");
            JsonObject data = new GsonBuilder()
                    .registerTypeAdapter(JsonObject.class, new JsonDeserializer<JsonObject>() {
                        public JsonObject deserialize(JsonElement json, Type arg1, JsonDeserializationContext arg2)
                                throws JsonParseException {
                            return json.getAsJsonObject();
                        }
                    }).create().fromJson(request.getParameter("data"), JsonObject.class);

            log.info("Begin managing client event request");

            log.debug("Client event request data: " + data.toString());

            Application application = (Application) request.getSession().getAttribute("application");
            application.setHttpServletRequest(request);
            application.setHttpServletResponse(response);

            Page page = application.getPage(data.get("pageName").getAsString());

            JsonElement widgets = data.get("widgets");
            if (widgets != null) {
                for (int i = 0; i < widgets.getAsJsonArray().size(); i++) {
                    updateServerWidget(page, widgets.getAsJsonArray().get(i).getAsJsonObject());
                }
            }

            Command command = application.getCommand(action);
            command.execute(page, data);

            PrintWriter out = response.getWriter();
            application.printJavaScriptStream(out);
            out.flush();
            out.close();

            cleanRemovedWidgets(page);

            log.info("End managing client event request");
        } catch (Exception e) {
            log.error("Exception in forwarding control to server", e);
            throw new ServletException(e);
        }
    }

    private void updateServerWidget(Page page, JsonObject widgetProp) {
        Widget widget = page.getWidget(widgetProp.get("id").getAsString());
        CastHelper castHelper = page.getApplication().getCastHelper(widget.getClass());
        JsonArray data = widgetProp.get("data").getAsJsonArray();
        for (int j = 0; j < data.size(); j++) {
            JsonObject itemData = data.get(j).getAsJsonObject();
            Field fieldAttribute = ReflectionUtils.getAnnotatedField(widget.getClass(),
                    itemData.get("attribute").getAsString(), WidgetAttribute.class);
            if (fieldAttribute != null) {
                fieldAttribute.setAccessible(true);
                Class<?> paramType = fieldAttribute.getType();
                try {
                    String value = null;
                    if (itemData.get("value") == null || itemData.get("value") instanceof JsonNull) {
                        value = null;
                    } else if (itemData.get("value") instanceof JsonArray) {
                        JsonArray valueArray = (JsonArray) itemData.get("value");
                        ArrayList<String> tmp = new ArrayList<String>();
                        for (JsonElement jsonElement : valueArray) {
                            tmp.add(jsonElement.getAsString());
                        }
                        if (tmp.size() > 0) {
                            value = StringUtils.join(tmp, ",");
                        } else {
                            value = null;
                        }
                    } else if (itemData.get("value") instanceof JsonObject) {
                        value = itemData.get("value").toString();
                    } else {
                        value = itemData.get("value").getAsString();
                    }
                    fieldAttribute.setAccessible(true);
                    fieldAttribute.set(widget, paramType.cast(castHelper.toType(value, paramType)));
                } catch (Exception e) {
                    log.warn("Warning in updating server widgets attribute '"
                            + itemData.get("attribute").getAsString() + "' for widget "
                            + widget.getClass().getName(), e);
                }
            } else {
                log.warn("Warning in updating server widgets attribute. The attribute '"
                        + itemData.get("attribute").getAsString() + "' doesn't exist for widget "
                        + widget.getClass().getName());
            }
        }
    }

    private void cleanRemovedWidgets(Page page) {
        for (Iterator<Widget> iterWidgets = page.getRegisteredWidgets().values().iterator(); iterWidgets
                .hasNext();) {
            Widget widget = iterWidgets.next();
            if (widget.isRemoveable()) {
                log.debug("Remove widget " + widget.getClass().getName() + "(" + widget.getId() + ")");
                widget.remove();
            }
        }
    }

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

    public void init() throws ServletException {

    }

}