Search in sources :

Example 1 with PreResultListener

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

the class MockActionInvocation method invoke.

public String invoke() throws Exception {
    for (Object preResultListener : preResultListeners) {
        PreResultListener listener = (PreResultListener) preResultListener;
        listener.beforeResult(this, resultCode);
    }
    return resultCode;
}
Also used : PreResultListener(com.opensymphony.xwork2.interceptor.PreResultListener)

Example 2 with PreResultListener

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

the class DefaultActionInvocation method invoke.

/**
 * @throws ConfigurationException If no result can be found with the returned code
 */
public String invoke() throws Exception {
    if (executed) {
        throw new IllegalStateException("Action has already executed");
    }
    if (asyncManager == null || !asyncManager.hasAsyncActionResult()) {
        if (interceptors.hasNext()) {
            final InterceptorMapping interceptorMapping = interceptors.next();
            Interceptor interceptor = interceptorMapping.getInterceptor();
            if (interceptor instanceof WithLazyParams) {
                interceptor = lazyParamInjector.injectParams(interceptor, interceptorMapping.getParams(), invocationContext);
            }
            resultCode = interceptor.intercept(DefaultActionInvocation.this);
        } else {
            resultCode = invokeActionOnly();
        }
    } else {
        Object asyncActionResult = asyncManager.getAsyncActionResult();
        if (asyncActionResult instanceof Throwable) {
            throw new Exception((Throwable) asyncActionResult);
        }
        asyncAction = null;
        resultCode = saveResult(proxy.getConfig(), asyncActionResult);
    }
    if (asyncManager == null || asyncAction == null) {
        // return above and flow through again
        if (!executed) {
            if (preResultListeners != null) {
                LOG.trace("Executing PreResultListeners for result [{}]", result);
                for (Object preResultListener : preResultListeners) {
                    PreResultListener listener = (PreResultListener) preResultListener;
                    listener.beforeResult(this, resultCode);
                }
            }
            // now execute the result, if we're supposed to
            if (proxy.getExecuteResult()) {
                executeResult();
            }
            executed = true;
        }
    } else {
        asyncManager.invokeAsyncAction(asyncAction);
    }
    return resultCode;
}
Also used : WithLazyParams(com.opensymphony.xwork2.interceptor.WithLazyParams) InterceptorMapping(com.opensymphony.xwork2.config.entities.InterceptorMapping) PreResultListener(com.opensymphony.xwork2.interceptor.PreResultListener) Interceptor(com.opensymphony.xwork2.interceptor.Interceptor) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException) NoSuchPropertyException(ognl.NoSuchPropertyException) StrutsException(org.apache.struts2.StrutsException) MethodFailedException(ognl.MethodFailedException)

Example 3 with PreResultListener

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

the class DefaultActionInvocationTester method testInvokeWithAsyncManager.

public void testInvokeWithAsyncManager() throws Exception {
    DefaultActionInvocation dai = new DefaultActionInvocation(new HashMap<String, Object>(), false);
    dai.stack = container.getInstance(ValueStackFactory.class).createValueStack();
    final Semaphore lock = new Semaphore(1);
    lock.acquire();
    dai.setAsyncManager(new AsyncManager() {

        Object asyncActionResult;

        @Override
        public boolean hasAsyncActionResult() {
            return asyncActionResult != null;
        }

        @Override
        public Object getAsyncActionResult() {
            return asyncActionResult;
        }

        @Override
        public void invokeAsyncAction(Callable asyncAction) {
            try {
                asyncActionResult = asyncAction.call();
            } catch (Exception e) {
                asyncActionResult = e;
            }
            lock.release();
        }
    });
    dai.action = new Callable<Callable<String>>() {

        @Override
        public Callable<String> call() throws Exception {
            return new Callable<String>() {

                @Override
                public String call() throws Exception {
                    return "success";
                }
            };
        }
    };
    MockActionProxy actionProxy = new MockActionProxy();
    actionProxy.setMethod("call");
    dai.proxy = actionProxy;
    final boolean[] preResultExecuted = new boolean[1];
    dai.addPreResultListener(new PreResultListener() {

        @Override
        public void beforeResult(ActionInvocation invocation, String resultCode) {
            preResultExecuted[0] = true;
        }
    });
    List<InterceptorMapping> interceptorMappings = new ArrayList<>();
    MockInterceptor mockInterceptor1 = new MockInterceptor();
    mockInterceptor1.setFoo("test1");
    mockInterceptor1.setExpectedFoo("test1");
    interceptorMappings.add(new InterceptorMapping("test1", mockInterceptor1));
    dai.interceptors = interceptorMappings.iterator();
    dai.ognlUtil = new OgnlUtil();
    dai.invoke();
    assertTrue("interceptor1 should be executed", mockInterceptor1.isExecuted());
    assertFalse("preResultListener should no be executed", preResultExecuted[0]);
    assertNotNull("an async action should be saved", dai.asyncAction);
    assertFalse("invocation should not be executed", dai.executed);
    assertNull("a null result should be passed to upper and wait for the async result", dai.resultCode);
    if (lock.tryAcquire(1500L, TimeUnit.MILLISECONDS)) {
        try {
            dai.invoke();
            assertTrue("preResultListener should be executed", preResultExecuted[0]);
            assertNull("async action should be cleared", dai.asyncAction);
            assertTrue("invocation should be executed", dai.executed);
            assertEquals("success", dai.resultCode);
        } finally {
            lock.release();
        }
    } else {
        lock.release();
        fail("async result did not received on timeout!");
    }
}
Also used : ArrayList(java.util.ArrayList) Semaphore(java.util.concurrent.Semaphore) PreResultListener(com.opensymphony.xwork2.interceptor.PreResultListener) Callable(java.util.concurrent.Callable) MockInterceptor(com.opensymphony.xwork2.mock.MockInterceptor) OgnlUtil(com.opensymphony.xwork2.ognl.OgnlUtil) InterceptorMapping(com.opensymphony.xwork2.config.entities.InterceptorMapping) MockActionProxy(com.opensymphony.xwork2.mock.MockActionProxy)

Example 4 with PreResultListener

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

the class DebuggingInterceptor method intercept.

/*
     * (non-Javadoc)
     *
     * @see com.opensymphony.xwork2.interceptor.Interceptor#invoke(com.opensymphony.xwork2.ActionInvocation)
     */
public String intercept(ActionInvocation inv) throws Exception {
    boolean actionOnly = false;
    boolean cont = true;
    Boolean devModeOverride = PrepareOperations.getDevModeOverride();
    boolean devMode = devModeOverride != null ? devModeOverride : this.devMode;
    if (devMode) {
        final ActionContext ctx = ActionContext.getContext();
        String type = getParameter(DEBUG_PARAM);
        ctx.getParameters().remove(DEBUG_PARAM);
        if (XML_MODE.equals(type)) {
            inv.addPreResultListener(new PreResultListener() {

                public void beforeResult(ActionInvocation inv, String result) {
                    printContext();
                }
            });
        } else if (CONSOLE_MODE.equals(type)) {
            consoleEnabled = true;
            inv.addPreResultListener(new PreResultListener() {

                public void beforeResult(ActionInvocation inv, String actionResult) {
                    String xml = "";
                    if (enableXmlWithConsole) {
                        StringWriter writer = new StringWriter();
                        printContext(new PrettyPrintWriter(writer));
                        xml = writer.toString();
                        xml = xml.replaceAll("&", "&amp;");
                        xml = xml.replaceAll(">", "&gt;");
                        xml = xml.replaceAll("<", "&lt;");
                    }
                    ActionContext.getContext().put("debugXML", xml);
                    FreemarkerResult result = new FreemarkerResult();
                    result.setFreemarkerManager(freemarkerManager);
                    result.setContentType("text/html");
                    result.setLocation("/org/apache/struts2/interceptor/debugging/console.ftl");
                    result.setParse(false);
                    try {
                        result.execute(inv);
                    } catch (Exception ex) {
                        LOG.error("Unable to create debugging console", ex);
                    }
                }
            });
        } else if (COMMAND_MODE.equals(type)) {
            ValueStack stack = (ValueStack) ctx.getSession().get(SESSION_KEY);
            if (stack == null) {
                // allows it to be embedded on another page
                stack = ctx.getValueStack();
                ctx.getSession().put(SESSION_KEY, stack);
            }
            String cmd = getParameter(EXPRESSION_PARAM);
            ServletActionContext.getRequest().setAttribute("decorator", "none");
            HttpServletResponse res = ServletActionContext.getResponse();
            res.setContentType("text/plain");
            try (PrintWriter writer = ServletActionContext.getResponse().getWriter()) {
                writer.print(stack.findValue(cmd));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            cont = false;
        } else if (BROWSER_MODE.equals(type)) {
            actionOnly = true;
            inv.addPreResultListener(new PreResultListener() {

                public void beforeResult(ActionInvocation inv, String actionResult) {
                    String rootObjectExpression = getParameter(OBJECT_PARAM);
                    if (rootObjectExpression == null) {
                        rootObjectExpression = "action";
                    }
                    String decorate = getParameter(DECORATE_PARAM);
                    ValueStack stack = ctx.getValueStack();
                    Object rootObject = stack.findValue(rootObjectExpression);
                    try (StringWriter writer = new StringWriter()) {
                        ObjectToHTMLWriter htmlWriter = new ObjectToHTMLWriter(writer);
                        htmlWriter.write(reflectionProvider, rootObject, rootObjectExpression);
                        String html = writer.toString();
                        writer.close();
                        stack.set("debugHtml", html);
                        // but we need plain text on the other ones
                        if ("false".equals(decorate))
                            ServletActionContext.getRequest().setAttribute("decorator", "none");
                        FreemarkerResult result = new FreemarkerResult();
                        result.setFreemarkerManager(freemarkerManager);
                        result.setContentType("text/html");
                        result.setLocation("/org/apache/struts2/interceptor/debugging/browser.ftl");
                        result.execute(inv);
                    } catch (Exception ex) {
                        LOG.error("Unable to create debugging console", ex);
                    }
                }
            });
        }
    }
    if (cont) {
        try {
            if (actionOnly) {
                inv.invokeActionOnly();
                return null;
            } else {
                return inv.invoke();
            }
        } finally {
            if (devMode && consoleEnabled) {
                final ActionContext ctx = ActionContext.getContext();
                ctx.getSession().put(SESSION_KEY, ctx.getValueStack());
            }
        }
    } else {
        return null;
    }
}
Also used : ValueStack(com.opensymphony.xwork2.util.ValueStack) ActionInvocation(com.opensymphony.xwork2.ActionInvocation) HttpServletResponse(javax.servlet.http.HttpServletResponse) PreResultListener(com.opensymphony.xwork2.interceptor.PreResultListener) IOException(java.io.IOException) ActionContext(com.opensymphony.xwork2.ActionContext) ServletActionContext(org.apache.struts2.ServletActionContext) IOException(java.io.IOException) FreemarkerResult(org.apache.struts2.views.freemarker.FreemarkerResult) StringWriter(java.io.StringWriter) PrintWriter(java.io.PrintWriter)

Example 5 with PreResultListener

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

the class ConversionErrorInterceptor method doIntercept.

@Override
public String doIntercept(ActionInvocation invocation) throws Exception {
    ActionContext invocationContext = invocation.getInvocationContext();
    Map<String, ConversionData> conversionErrors = invocationContext.getConversionErrors();
    ValueStack stack = invocationContext.getValueStack();
    HashMap<Object, Object> fakie = null;
    for (Map.Entry<String, ConversionData> entry : conversionErrors.entrySet()) {
        String propertyName = entry.getKey();
        ConversionData conversionData = entry.getValue();
        if (shouldAddError(propertyName, conversionData.getValue())) {
            String message = XWorkConverter.getConversionErrorMessage(propertyName, conversionData.getToClass(), stack);
            Object action = invocation.getAction();
            if (action instanceof ValidationAware) {
                ValidationAware va = (ValidationAware) action;
                va.addFieldError(propertyName, message);
            }
            if (fakie == null) {
                fakie = new HashMap<>();
            }
            fakie.put(propertyName, getOverrideExpr(invocation, conversionData.getValue()));
        }
    }
    if (fakie != null) {
        // if there were some errors, put the original (fake) values in place right before the result
        stack.getContext().put(ORIGINAL_PROPERTY_OVERRIDE, fakie);
        invocation.addPreResultListener(new PreResultListener() {

            public void beforeResult(ActionInvocation invocation, String resultCode) {
                Map<Object, Object> fakie = (Map<Object, Object>) invocation.getInvocationContext().get(ORIGINAL_PROPERTY_OVERRIDE);
                if (fakie != null) {
                    invocation.getStack().setExprOverrides(fakie);
                }
            }
        });
    }
    return invocation.invoke();
}
Also used : ValueStack(com.opensymphony.xwork2.util.ValueStack) ActionInvocation(com.opensymphony.xwork2.ActionInvocation) ActionContext(com.opensymphony.xwork2.ActionContext) ConversionData(com.opensymphony.xwork2.conversion.impl.ConversionData) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

PreResultListener (com.opensymphony.xwork2.interceptor.PreResultListener)5 ActionInvocation (com.opensymphony.xwork2.ActionInvocation)3 ValueStack (com.opensymphony.xwork2.util.ValueStack)3 ActionContext (com.opensymphony.xwork2.ActionContext)2 InterceptorMapping (com.opensymphony.xwork2.config.entities.InterceptorMapping)2 ConversionData (com.opensymphony.xwork2.conversion.impl.ConversionData)2 ConfigurationException (com.opensymphony.xwork2.config.ConfigurationException)1 Interceptor (com.opensymphony.xwork2.interceptor.Interceptor)1 WithLazyParams (com.opensymphony.xwork2.interceptor.WithLazyParams)1 MockActionProxy (com.opensymphony.xwork2.mock.MockActionProxy)1 MockInterceptor (com.opensymphony.xwork2.mock.MockInterceptor)1 OgnlUtil (com.opensymphony.xwork2.ognl.OgnlUtil)1 IOException (java.io.IOException)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 Callable (java.util.concurrent.Callable)1