Search in sources :

Example 51 with Interceptor

use of com.opensymphony.xwork2.interceptor.Interceptor in project struts by apache.

the class JSONInterceptor method intercept.

@SuppressWarnings("unchecked")
public String intercept(ActionInvocation invocation) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    String requestContentType = readContentType(request);
    String requestContentTypeEncoding = readContentTypeEncoding(request);
    Object rootObject = null;
    final ValueStack stack = invocation.getStack();
    if (this.root != null) {
        rootObject = stack.findValue(this.root);
        if (rootObject == null) {
            throw new RuntimeException("Invalid root expression: '" + this.root + "'.");
        }
    }
    if (jsonContentType.equalsIgnoreCase(requestContentType)) {
        // load JSON object
        Object obj = JSONUtil.deserialize(request.getReader());
        // JSON array (this.root cannot be null in this case)
        if (obj instanceof List && this.root != null) {
            String mapKey = this.root;
            rootObject = null;
            if (this.root.indexOf('.') != -1) {
                mapKey = this.root.substring(this.root.lastIndexOf('.') + 1);
                rootObject = stack.findValue(this.root.substring(0, this.root.lastIndexOf('.')));
                if (rootObject == null) {
                    throw new RuntimeException("JSON array: Invalid root expression: '" + this.root + "'.");
                }
            }
            // create a map with a list inside
            Map m = new HashMap();
            m.put(mapKey, new ArrayList((List) obj));
            obj = m;
        }
        if (obj instanceof Map) {
            Map json = (Map) obj;
            // clean up the values
            if (dataCleaner != null)
                dataCleaner.clean("", json);
            if (// model overrides action
            rootObject == null)
                rootObject = invocation.getStack().peek();
            // populate fields
            populator.populateObject(rootObject, json);
        } else {
            LOG.error("Unable to deserialize JSON object from request");
            throw new JSONException("Unable to deserialize JSON object from request");
        }
    } else if (jsonRpcContentType.equalsIgnoreCase(requestContentType)) {
        Object result;
        if (this.enableSMD) {
            // load JSON object
            Object obj = JSONUtil.deserialize(request.getReader());
            if (obj instanceof Map) {
                Map smd = (Map) obj;
                if (rootObject == null) {
                    // model makes no sense when using RPC
                    rootObject = invocation.getAction();
                }
                // invoke method
                try {
                    result = this.invoke(rootObject, smd);
                } catch (Exception e) {
                    RPCResponse rpcResponse = new RPCResponse();
                    rpcResponse.setId(smd.get("id").toString());
                    rpcResponse.setError(new RPCError(e, RPCErrorCode.EXCEPTION, getDebug()));
                    result = rpcResponse;
                }
            } else {
                String message = "SMD request was not in the right format. See http://json-rpc.org";
                RPCResponse rpcResponse = new RPCResponse();
                rpcResponse.setError(new RPCError(message, RPCErrorCode.INVALID_PROCEDURE_CALL));
                result = rpcResponse;
            }
        } else {
            String message = "Request with content type of 'application/json-rpc' was received but SMD is " + "not enabled for this interceptor. Set 'enableSMD' to true to enable it";
            RPCResponse rpcResponse = new RPCResponse();
            rpcResponse.setError(new RPCError(message, RPCErrorCode.SMD_DISABLED));
            result = rpcResponse;
        }
        JSONUtil jsonUtil = invocation.getInvocationContext().getContainer().getInstance(JSONUtil.class);
        String json = jsonUtil.serialize(result, excludeProperties, getIncludeProperties(), ignoreHierarchy, excludeNullProperties);
        json = addCallbackIfApplicable(request, json);
        boolean writeGzip = enableGZIP && JSONUtil.isGzipInRequest(request);
        JSONUtil.writeJSONToResponse(new SerializationParams(response, requestContentTypeEncoding, this.wrapWithComments, json, true, writeGzip, noCache, -1, -1, prefix, "application/json"));
        return Action.NONE;
    } else {
        LOG.debug("Accept header parameter must be '{}' or '{}'. Ignoring request with Content Type '{}'", jsonContentType, jsonRpcContentType, requestContentType);
    }
    return invocation.invoke();
}
Also used : ValueStack(com.opensymphony.xwork2.util.ValueStack) HttpServletResponse(javax.servlet.http.HttpServletResponse) RPCResponse(org.apache.struts2.json.rpc.RPCResponse) RPCError(org.apache.struts2.json.rpc.RPCError) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) HttpServletRequest(javax.servlet.http.HttpServletRequest)

Example 52 with Interceptor

use of com.opensymphony.xwork2.interceptor.Interceptor in project struts by apache.

the class SpringObjectFactoryTest method testFallsBackToDefaultObjectFactoryInterceptorBuilding.

public void testFallsBackToDefaultObjectFactoryInterceptorBuilding() throws Exception {
    InterceptorConfig iConfig = new InterceptorConfig.Builder("timer", ModelDrivenInterceptor.class.getName()).build();
    Interceptor interceptor = objectFactory.buildInterceptor(iConfig, new HashMap<String, String>());
    assertEquals(ModelDrivenInterceptor.class, interceptor.getClass());
}
Also used : InterceptorConfig(com.opensymphony.xwork2.config.entities.InterceptorConfig) DebugInterceptor(org.springframework.aop.interceptor.DebugInterceptor) Interceptor(com.opensymphony.xwork2.interceptor.Interceptor) NoOpInterceptor(org.apache.struts2.interceptor.NoOpInterceptor) ModelDrivenInterceptor(com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor)

Example 53 with Interceptor

use of com.opensymphony.xwork2.interceptor.Interceptor in project struts by apache.

the class ActionAutowiringInterceptorTest method testLoadsApplicationContextUsingWebApplicationContextUtils.

public void testLoadsApplicationContextUsingWebApplicationContextUtils() throws Exception {
    StaticWebApplicationContext appContext = new StaticWebApplicationContext();
    loadSpringApplicationContextIntoApplication(appContext);
    ActionAutowiringInterceptor interceptor = new ActionAutowiringInterceptor();
    interceptor.init();
    SimpleAction action = new SimpleAction();
    ActionInvocation invocation = new TestActionInvocation(action);
    interceptor.intercept(invocation);
    ApplicationContext loadedContext = interceptor.getApplicationContext();
    assertEquals(appContext, loadedContext);
}
Also used : WebApplicationContext(org.springframework.web.context.WebApplicationContext) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) ActionInvocation(com.opensymphony.xwork2.ActionInvocation) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) SimpleAction(com.opensymphony.xwork2.SimpleAction)

Example 54 with Interceptor

use of com.opensymphony.xwork2.interceptor.Interceptor in project struts by apache.

the class ActionAutowiringInterceptorTest method testSetAutowireType.

public void testSetAutowireType() throws Exception {
    XmlConfigurationProvider prov = new StrutsXmlConfigurationProvider("xwork-default.xml");
    container.inject(prov);
    prov.setThrowExceptionOnDuplicateBeans(false);
    XmlConfigurationProvider c = new StrutsXmlConfigurationProvider("com/opensymphony/xwork2/spring/xwork-autowire.xml");
    container.inject(c);
    loadConfigurationProviders(c, prov);
    StaticWebApplicationContext appContext = new StaticWebApplicationContext();
    loadSpringApplicationContextIntoApplication(appContext);
    ActionAutowiringInterceptor interceptor = new ActionAutowiringInterceptor();
    interceptor.init();
    SimpleAction action = new SimpleAction();
    ActionInvocation invocation = new TestActionInvocation(action);
    interceptor.intercept(invocation);
    ApplicationContext loadedContext = interceptor.getApplicationContext();
    assertEquals(appContext, loadedContext);
}
Also used : StrutsXmlConfigurationProvider(org.apache.struts2.config.StrutsXmlConfigurationProvider) WebApplicationContext(org.springframework.web.context.WebApplicationContext) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) XmlConfigurationProvider(com.opensymphony.xwork2.config.providers.XmlConfigurationProvider) StrutsXmlConfigurationProvider(org.apache.struts2.config.StrutsXmlConfigurationProvider) ActionInvocation(com.opensymphony.xwork2.ActionInvocation) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) SimpleAction(com.opensymphony.xwork2.SimpleAction)

Example 55 with Interceptor

use of com.opensymphony.xwork2.interceptor.Interceptor in project struts by apache.

the class ActionAutowiringInterceptorTest method testIfApplicationContextIsNullThenBeanWillNotBeWiredUp.

public void testIfApplicationContextIsNullThenBeanWillNotBeWiredUp() throws Exception {
    ActionContext.of(new HashMap<>()).withApplication(new HashMap<>()).bind();
    ActionAutowiringInterceptor interceptor = new ActionAutowiringInterceptor();
    interceptor.init();
    SimpleAction action = new SimpleAction();
    ActionInvocation invocation = new TestActionInvocation(action);
    TestBean bean = action.getBean();
    // If an exception is thrown here, things are going to go wrong in
    // production
    interceptor.intercept(invocation);
    assertEquals(bean, action.getBean());
}
Also used : HashMap(java.util.HashMap) TestBean(com.opensymphony.xwork2.TestBean) ActionInvocation(com.opensymphony.xwork2.ActionInvocation) SimpleAction(com.opensymphony.xwork2.SimpleAction)

Aggregations

ActionInvocation (com.opensymphony.xwork2.ActionInvocation)32 HashMap (java.util.HashMap)28 ActionContext (com.opensymphony.xwork2.ActionContext)20 InterceptorMapping (com.opensymphony.xwork2.config.entities.InterceptorMapping)19 MockActionInvocation (com.opensymphony.xwork2.mock.MockActionInvocation)19 ServletActionContext (org.apache.struts2.ServletActionContext)14 InterceptorStackConfig (com.opensymphony.xwork2.config.entities.InterceptorStackConfig)13 PackageConfig (com.opensymphony.xwork2.config.entities.PackageConfig)12 LinkedHashMap (java.util.LinkedHashMap)12 Map (java.util.Map)11 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 ActionConfig (com.opensymphony.xwork2.config.entities.ActionConfig)10 InterceptorConfig (com.opensymphony.xwork2.config.entities.InterceptorConfig)10 DefaultAcceptedPatternsChecker (com.opensymphony.xwork2.security.DefaultAcceptedPatternsChecker)10 DefaultExcludedPatternsChecker (com.opensymphony.xwork2.security.DefaultExcludedPatternsChecker)10 Cookie (javax.servlet.http.Cookie)10 ArrayList (java.util.ArrayList)9 List (java.util.List)9 Mock (com.mockobjects.dynamic.Mock)8 ActionSupport (com.opensymphony.xwork2.ActionSupport)8