com.sinosoft.one.mvc.web.impl.thread.RootEngine.java Source code

Java tutorial

Introduction

Here is the source code for com.sinosoft.one.mvc.web.impl.thread.RootEngine.java

Source

/*
 * Copyright 2007-2010 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sinosoft.one.mvc.web.impl.thread;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import com.sinosoft.one.mvc.web.Invocation;
import com.sinosoft.one.mvc.web.RequestPath;
import com.sinosoft.one.mvc.web.instruction.InstructionExecutor;
import com.sinosoft.one.mvc.web.instruction.InstructionExecutorImpl;
import com.sinosoft.one.mvc.web.var.FlashImpl;

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

/**
 * {@link RootEngine}{@link com.sinosoft.one.mvc.MvcFilter}webMvc?.
 * <p>
 * {@link RootEngine}web?{@link RootEngine}
 * ????match(InvocationBean)false.
 * <p>
 * 
 *
 */
public class RootEngine implements Engine {

    // ------------------------------------------------------------

    protected final Log logger = LogFactory.getLog(getClass());

    /** ?Mvc? */
    protected InstructionExecutor instructionExecutor = new InstructionExecutorImpl();

    // ------------------------------------------------------------

    /**
     * ?modules {@link RootEngine}.
     * <p>
     * ? initMappings(List)??????
     * 
     * @throws Exception
     * @throws NullPointerException ??null
     */
    public RootEngine(InstructionExecutor instructionExecutor) {
        if (instructionExecutor != null) {
            this.instructionExecutor = instructionExecutor;
        }
    }

    // ------------------------------------------------------------

    public int isAccepted(HttpServletRequest mvc) {
        return 1;
    }

    /**
     * {@link RootEngine} ?.?.??
     * ?;
     * 
     * @return
     * @throws ServletException
     */

    public Object execute(Mvc mvc) throws Throwable {

        InvocationBean inv = mvc.getInvocation();
        ServletRequest request = inv.getRequest();
        //
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
            if (logger.isDebugEnabled()) {
                logger.debug("set request.characterEncoding by default:" + request.getCharacterEncoding());
            }
        }

        //
        final RequestPath requestPath = inv.getRequestPath();

        // save before include
        if (requestPath.isIncludeRequest()) {
            saveAttributesBeforeInclude(inv);
            // ??include???(Model)
            mvc.addAfterCompletion(new AfterCompletion() {

                public void afterCompletion(Invocation inv, Throwable ex) throws Exception {
                    restoreRequestAttributesAfterInclude(inv);
                }
            });
        }

        // ?
        inv.addModel("invocation", inv);
        inv.addModel("ctxpath", requestPath.getCtxpath());

        // instructionactionInstruction(???)
        Object instruction = mvc.doNext();

        if (Thread.currentThread().isInterrupted()) {
            logger.info("stop to render: thread is interrupted");
        } else {
            // flash?Cookie (include?)
            if (!requestPath.isIncludeRequest()) {
                FlashImpl flash = (FlashImpl) inv.getFlash(false);
                if (flash != null) {
                    flash.writeNewMessages();
                }
            }

            // ?
            instructionExecutor.render(inv, instruction);
        }
        return instruction;
    }

    public void destroy() {
    }

    /**
     * Keep a snapshot of the request attributes in case of an include, to
     * be able to restore the original attributes after the include.
     * 
     * @param inv
     */
    private void saveAttributesBeforeInclude(final Invocation inv) {
        ServletRequest request = inv.getRequest();
        logger.debug("Taking snapshot of request attributes before include");
        Map<String, Object> attributesSnapshot = new HashMap<String, Object>();
        Enumeration<?> attrNames = request.getAttributeNames();
        while (attrNames.hasMoreElements()) {
            String attrName = (String) attrNames.nextElement();
            attributesSnapshot.put(attrName, request.getAttribute(attrName));
        }
        inv.setAttribute("$$one-mvc.attributesBeforeInclude", attributesSnapshot);
    }

    /**
     * Restore the request attributes after an include.
     * 
     *        before the include
     */
    private void restoreRequestAttributesAfterInclude(Invocation inv) {
        logger.debug("Restoring snapshot of request attributes after include");
        HttpServletRequest request = inv.getRequest();

        @SuppressWarnings("unchecked")
        Map<String, Object> attributesSnapshot = (Map<String, Object>) inv
                .getAttribute("$$one-mvc.attributesBeforeInclude");

        // Need to copy into separate Collection here, to avoid side effects
        // on the Enumeration when removing attributes.
        Set<String> attrsToCheck = new HashSet<String>();
        Enumeration<?> attrNames = request.getAttributeNames();
        while (attrNames.hasMoreElements()) {
            String attrName = (String) attrNames.nextElement();
            attrsToCheck.add(attrName);
        }

        // Iterate over the attributes to check, restoring the original value
        // or removing the attribute, respectively, if appropriate.
        for (String attrName : attrsToCheck) {
            Object attrValue = attributesSnapshot.get(attrName);
            if (attrValue != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Restoring original value of attribute [" + attrName + "] after include");
                }
                request.setAttribute(attrName, attrValue);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Removing attribute [" + attrName + "] after include");
                }
                request.removeAttribute(attrName);
            }
        }

    }

    @Override
    public String toString() {
        return "root";
    }
}