defaultremoter.java

来自「反向的AJAX。最大的特性是我们成为反向的Ajax。DWR1.x允许你用java」· Java 代码 · 共 562 行 · 第 1/2 页

JAVA
562
字号
/* * Copyright 2005 Joe Walker * * 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 org.directwebremoting.impl;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.lang.reflect.Modifier;import java.util.Collection;import java.util.Collections;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import org.directwebremoting.AjaxFilter;import org.directwebremoting.AjaxFilterChain;import org.directwebremoting.WebContext;import org.directwebremoting.WebContextFactory;import org.directwebremoting.extend.AccessControl;import org.directwebremoting.extend.AjaxFilterManager;import org.directwebremoting.extend.Call;import org.directwebremoting.extend.Calls;import org.directwebremoting.extend.Converter;import org.directwebremoting.extend.ConverterManager;import org.directwebremoting.extend.Creator;import org.directwebremoting.extend.CreatorManager;import org.directwebremoting.extend.NamedConverter;import org.directwebremoting.extend.Property;import org.directwebremoting.extend.EnginePrivate;import org.directwebremoting.extend.Remoter;import org.directwebremoting.extend.Replies;import org.directwebremoting.extend.Reply;import org.directwebremoting.util.Continuation;import org.directwebremoting.util.JavascriptUtil;import org.directwebremoting.util.LocalUtil;import org.directwebremoting.util.Logger;/** * In implementation of Remoter that delegates requests to a set of Modules * @author Joe Walker [joe at getahead dot ltd dot uk] * @author Mike Wilson */public class DefaultRemoter implements Remoter{    /* (non-Javadoc)     * @see org.directwebremoting.Remoter#generateInterfaceScript(java.lang.String, java.lang.String)     */    public String generateInterfaceScript(String scriptName, String path) throws SecurityException    {        String actualPath = path;        if (overridePath != null)        {            actualPath = overridePath;        }        StringBuffer buffer = new StringBuffer();        // Output the class definitions for the converted objects        Collection converterMatches = converterManager.getConverterMatchStrings();        Iterator it = converterMatches.iterator();        while (it.hasNext())        {            String match = (String) it.next();            try            {                StringBuffer paramBuffer = new StringBuffer();                Converter conv = converterManager.getConverterByMatchString(match);                // We will only generate JavaScript classes for compound objects/beans                if (conv instanceof NamedConverter)                {                    NamedConverter boConv = (NamedConverter) conv;                    String jsClassName = boConv.getJavascript();                    // We need a configured JavaScript class name                    if (jsClassName != null && !jsClassName.equals(""))                    {                        // Wildcard match strings are currently not supported                        if (match.indexOf("*") == -1)                        {                            paramBuffer.append('\n');                            // output: if (typeof <class> != "function") { var <class> = function() {                            paramBuffer.append("if (typeof " + jsClassName + " != \"function\") {\n");                            paramBuffer.append("  function " + jsClassName + "() {\n");                            // output: this.<property> = <init-value>;                            Class mappedType;                            try                            {                                mappedType = LocalUtil.classForName(match);                            }                            catch (ClassNotFoundException ex)                            {                                throw new IllegalArgumentException(ex.getMessage());                            }                            Map properties = boConv.getPropertyMapFromClass(mappedType, true, true);                            for (Iterator pit = properties.entrySet().iterator(); pit.hasNext();)                            {                                Map.Entry entry = (Map.Entry) pit.next();                                String name = (String) entry.getKey();                                Property property = (Property) entry.getValue();                                Class propType = property.getPropertyType();                                // Property name                                paramBuffer.append("    this." + name + " = ");                                // Default property values                                if (propType.isArray())                                {                                    paramBuffer.append("[]");                                }                                else if (propType == boolean.class)                                {                                    paramBuffer.append("false");                                }                                else if (propType.isPrimitive())                                {                                    paramBuffer.append("0");                                }                                else                                {                                    paramBuffer.append("null");                                }                                paramBuffer.append(";\n");                            }                            paramBuffer.append("  }\n");                            paramBuffer.append("}\n");                        }                    }                }                buffer.append(paramBuffer.toString());            }            catch (Exception ex)            {                log.warn("Failed to create parameter declaration for " + match, ex);                buffer.append("// Missing parameter declaration for " + match + ". See the server logs for details.");            }        }        Creator creator = creatorManager.getCreator(scriptName);        buffer.append('\n');        String init = EnginePrivate.getEngineInitScript();        buffer.append(init);        buffer.append("if (" + scriptName + " == null) var " + scriptName + " = {};\n");        buffer.append(scriptName + "._path = '" + actualPath + "';\n");        Method[] methods = creator.getType().getMethods();        for (int i = 0; i < methods.length; i++)        {            Method method = methods[i];            String methodName = method.getName();            // We don't need to check accessControl.getReasonToNotExecute()            // because the checks are made by the execute() method, but we do            // check if we can display it            try            {                accessControl.assertIsDisplayable(creator, scriptName, method);            }            catch (SecurityException ex)            {                if (!allowImpossibleTests)                {                    continue;                }            }            // Is it on the list of banned names            if (JavascriptUtil.isReservedWord(methodName))            {                continue;            }            // Check to see if the creator is reloadable            // If it is, then do not cache the generated Javascript            String script;            if (!creator.isCacheable())            {                script = getMethodJS(scriptName, method);            }            else            {                String key = scriptName + "." + method.getName();                // For optimal performance we might use the Memoizer pattern                // JCiP#108 however performance isn't a big issue and we are                // prepared to cope with getMethodJS() being run more than once.                script = (String) methodCache.get(key);                if (script == null)                {                    script = getMethodJS(scriptName, method);                    methodCache.put(key, script);                }            }            buffer.append(script);        }        return buffer.toString();    }    /**     * Generates Javascript for a given Java method     * @param scriptName  Name of the Javascript file, sans ".js" suffix     * @param method Target method     * @return Javascript implementing the DWR call for the target method     */    private String getMethodJS(String scriptName, Method method)    {        StringBuffer buffer = new StringBuffer();        String methodName = method.getName();        buffer.append(scriptName + '.' + methodName + " = function(");        Class[] paramTypes = method.getParameterTypes();        for (int j = 0; j < paramTypes.length; j++)        {            if (!LocalUtil.isServletClass(paramTypes[j]))            {                buffer.append("p" + j + ", ");            }        }        buffer.append("callback) {\n");        String executeFunctionName = EnginePrivate.getExecuteFunctionName();        buffer.append("  " + executeFunctionName + "(" + scriptName + "._path, '" + scriptName + "', '" + methodName + "\', ");        for (int j = 0; j < paramTypes.length; j++)        {            if (LocalUtil.isServletClass(paramTypes[j]))            {                buffer.append("false, ");            }            else            {                buffer.append("p" + j + ", ");            }        }        buffer.append("callback);\n");        buffer.append("}\n");        return buffer.toString();    }    /* (non-Javadoc)     * @see org.directwebremoting.Remoter#execute(org.directwebremoting.Calls)     */    public Replies execute(Calls calls)    {        Replies replies = new Replies(calls.getBatchId());        int callCount = calls.getCallCount();        if (callCount > maxCallCount)        {            log.error("Call count for batch exceeds maxCallCount. Add an init-param of maxCallCount to increase this limit");            throw new SecurityException("Call count for batch is too high");        }        for (int callNum = 0; callNum < callCount; callNum++)        {

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?