Search in sources :

Example 61 with Result

use of com.opensymphony.xwork2.Result in project struts by apache.

the class ExecuteAndWaitInterceptor method doIntercept.

/* (non-Javadoc)
     * @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation)
     */
protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
    ActionProxy proxy = actionInvocation.getProxy();
    String name = getBackgroundProcessName(proxy);
    ActionContext context = actionInvocation.getInvocationContext();
    Map session = context.getSession();
    HttpSession httpSession = ServletActionContext.getRequest().getSession(true);
    Boolean secondTime = true;
    if (executeAfterValidationPass) {
        secondTime = (Boolean) context.get(KEY);
        if (secondTime == null) {
            context.put(KEY, true);
            secondTime = false;
        } else {
            secondTime = true;
            context.put(KEY, null);
        }
    }
    // on every request
    synchronized (httpSession) {
        BackgroundProcess bp = (BackgroundProcess) session.get(KEY + name);
        // WW-4900 Checks if from a de-serialized session? so background thread missed, let's start a new one.
        if (bp != null && bp.getInvocation() == null) {
            session.remove(KEY + name);
            bp = null;
        }
        if ((!executeAfterValidationPass || secondTime) && bp == null) {
            bp = getNewBackgroundProcess(name, actionInvocation, threadPriority);
            session.put(KEY + name, bp);
            // first time let some time pass before showing wait page
            performInitialDelay(bp);
            secondTime = false;
        }
        if ((!executeAfterValidationPass || !secondTime) && bp != null && !bp.isDone()) {
            actionInvocation.getStack().push(bp.getAction());
            final String token = TokenHelper.getToken();
            if (token != null) {
                TokenHelper.setSessionToken(TokenHelper.getTokenName(), token);
            }
            Map results = proxy.getConfig().getResults();
            if (!results.containsKey(WAIT)) {
                LOG.warn("ExecuteAndWait interceptor has detected that no result named 'wait' is available. " + "Defaulting to a plain built-in wait page. It is highly recommend you " + "provide an action-specific or global result named '{}'.", WAIT);
                // no wait result? hmm -- let's try to do dynamically put it in for you!
                // we used to add a fake "wait" result here, since the configuration is unmodifiable, that is no longer
                // an option, see WW-3068
                FreemarkerResult waitResult = new FreemarkerResult();
                container.inject(waitResult);
                waitResult.setLocation("/org/apache/struts2/interceptor/wait.ftl");
                waitResult.execute(actionInvocation);
                return Action.NONE;
            }
            return WAIT;
        } else if ((!executeAfterValidationPass || !secondTime) && bp != null && bp.isDone()) {
            session.remove(KEY + name);
            actionInvocation.getStack().push(bp.getAction());
            // if an exception occured during action execution, throw it here
            if (bp.getException() != null) {
                throw bp.getException();
            }
            return bp.getResult();
        } else {
            // this interceptor
            return actionInvocation.invoke();
        }
    }
}
Also used : FreemarkerResult(org.apache.struts2.views.freemarker.FreemarkerResult) ActionProxy(com.opensymphony.xwork2.ActionProxy) HttpSession(javax.servlet.http.HttpSession) ServletActionContext(org.apache.struts2.ServletActionContext) ActionContext(com.opensymphony.xwork2.ActionContext) Map(java.util.Map)

Example 62 with Result

use of com.opensymphony.xwork2.Result in project struts by apache.

the class ActionConfigMatcherTest method testCheckSubstitutionsMatch.

public void testCheckSubstitutionsMatch() {
    ActionConfig m = matcher.match("foo/class/method");
    assertTrue("Class hasn't been replaced", "foo.bar.classAction".equals(m.getClassName()));
    assertTrue("Method hasn't been replaced", "domethod".equals(m.getMethodName()));
    assertTrue("Package isn't correct", "package-class".equals(m.getPackageName()));
    assertTrue("First param isn't correct", "class".equals(m.getParams().get("first")));
    assertTrue("Second param isn't correct", "method".equals(m.getParams().get("second")));
    ExceptionMappingConfig ex = m.getExceptionMappings().get(0);
    assertTrue("Wrong name, was " + ex.getName(), "fooclass".equals(ex.getName()));
    assertTrue("Wrong result", "successclass".equals(ex.getResult()));
    assertTrue("Wrong exception", "java.lang.methodException".equals(ex.getExceptionClassName()));
    assertTrue("First param isn't correct", "class".equals(ex.getParams().get("first")));
    assertTrue("Second param isn't correct", "method".equals(ex.getParams().get("second")));
    ResultConfig result = m.getResults().get("successclass");
    assertTrue("Wrong name, was " + result.getName(), "successclass".equals(result.getName()));
    assertTrue("Wrong classname", "foo.method".equals(result.getClassName()));
    assertTrue("First param isn't correct", "class".equals(result.getParams().get("first")));
    assertTrue("Second param isn't correct", "method".equals(result.getParams().get("second")));
}
Also used : ActionConfig(com.opensymphony.xwork2.config.entities.ActionConfig) ResultConfig(com.opensymphony.xwork2.config.entities.ResultConfig) ExceptionMappingConfig(com.opensymphony.xwork2.config.entities.ExceptionMappingConfig)

Example 63 with Result

use of com.opensymphony.xwork2.Result in project struts by apache.

the class FreemarkerResult method doExecute.

/**
 * Execute this result, using the specified template locationArg.
 * <p>
 * The template locationArg has already been interpolated for any variable substitutions
 * </p>
 * <p>
 * this method obtains the freemarker configuration and the object wrapper from the provided hooks.
 * It them implements the template processing workflow by calling the hooks for
 * preTemplateProcess and postTemplateProcess
 * </p>
 *
 * @param locationArg location argument
 * @param invocation  the action invocation
 * @throws IOException       in case of IO errors
 * @throws TemplateException in case of freemarker template errors
 */
public void doExecute(String locationArg, ActionInvocation invocation) throws IOException, TemplateException {
    this.location = locationArg;
    this.invocation = invocation;
    this.configuration = getConfiguration();
    this.wrapper = getObjectWrapper();
    ActionContext ctx = invocation.getInvocationContext();
    HttpServletRequest req = ctx.getServletRequest();
    String absoluteLocation;
    if (location.startsWith("/")) {
        absoluteLocation = location;
    } else {
        String namespace = invocation.getProxy().getNamespace();
        if (namespace == null || namespace.length() == 0 || namespace.equals("/")) {
            absoluteLocation = "/" + location;
        } else if (namespace.startsWith("/")) {
            absoluteLocation = namespace + "/" + location;
        } else {
            absoluteLocation = "/" + namespace + "/" + location;
        }
    }
    Template template = configuration.getTemplate(absoluteLocation, deduceLocale());
    TemplateModel model = createModel();
    // Give subclasses a chance to hook into preprocessing
    if (preTemplateProcess(template, model)) {
        try {
            final boolean willWriteIfCompleted;
            if (writeIfCompleted != null) {
                willWriteIfCompleted = isWriteIfCompleted();
            } else {
                willWriteIfCompleted = template.getTemplateExceptionHandler() == TemplateExceptionHandler.RETHROW_HANDLER;
            }
            // Process the template
            Writer writer = getWriter();
            if (willWriteIfCompleted) {
                CharArrayWriter parentCharArrayWriter = (CharArrayWriter) req.getAttribute(PARENT_TEMPLATE_WRITER);
                boolean isTopTemplate;
                if (isTopTemplate = (parentCharArrayWriter == null)) {
                    // this is the top template
                    parentCharArrayWriter = new CharArrayWriter();
                    // set it in the request because when the "action" tag is used a new VS and ActionContext is created
                    req.setAttribute(PARENT_TEMPLATE_WRITER, parentCharArrayWriter);
                }
                try {
                    template.process(model, parentCharArrayWriter);
                    if (isTopTemplate) {
                        parentCharArrayWriter.flush();
                        parentCharArrayWriter.writeTo(writer);
                    }
                } catch (TemplateException | IOException e) {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Error processing Freemarker result!", e);
                    }
                    throw e;
                } finally {
                    if (isTopTemplate) {
                        req.removeAttribute(PARENT_TEMPLATE_WRITER);
                        parentCharArrayWriter.close();
                    }
                }
            } else {
                template.process(model, writer);
            }
        } finally {
            // Give subclasses a chance to hook into postprocessing
            postTemplateProcess(template, model);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) TemplateException(freemarker.template.TemplateException) TemplateModel(freemarker.template.TemplateModel) IOException(java.io.IOException) ActionContext(com.opensymphony.xwork2.ActionContext) ServletActionContext(org.apache.struts2.ServletActionContext) CharArrayWriter(java.io.CharArrayWriter) Writer(java.io.Writer) CharArrayWriter(java.io.CharArrayWriter) Template(freemarker.template.Template)

Example 64 with Result

use of com.opensymphony.xwork2.Result in project struts by apache.

the class DefaultActionInvocationTester method testNullResultPossible.

public void testNullResultPossible() throws Exception {
    ActionProxy actionProxy = actionProxyFactory.createActionProxy("", "NullFoo", "nullMethod", new HashMap<String, Object>());
    DefaultActionInvocation defaultActionInvocation = (DefaultActionInvocation) actionProxy.getInvocation();
    defaultActionInvocation.init(actionProxy);
    String result = defaultActionInvocation.invoke();
    assertNull(result);
}
Also used : MockActionProxy(com.opensymphony.xwork2.mock.MockActionProxy)

Example 65 with Result

use of com.opensymphony.xwork2.Result in project struts by apache.

the class DefaultActionInvocationTester method testUnknownHandlerManagerThatReturnsSuccess.

public void testUnknownHandlerManagerThatReturnsSuccess() throws Exception {
    // given
    DefaultActionInvocation dai = new DefaultActionInvocation(ActionContext.getContext().getContextMap(), false);
    container.inject(dai);
    UnknownHandlerManager uhm = new DefaultUnknownHandlerManager() {

        @Override
        public boolean hasUnknownHandlers() {
            return true;
        }

        @Override
        public Object handleUnknownMethod(Object action, String methodName) throws NoSuchMethodException {
            return "success";
        }
    };
    MockActionProxy proxy = new MockActionProxy();
    proxy.setMethod("notExists");
    dai.stack = container.getInstance(ValueStackFactory.class).createValueStack();
    dai.proxy = proxy;
    dai.ognlUtil = new OgnlUtil();
    dai.unknownHandlerManager = uhm;
    // when
    String result = dai.invokeAction(new SimpleAction(), null);
    // then
    assertNotNull(result);
    assertEquals("success", result);
}
Also used : OgnlUtil(com.opensymphony.xwork2.ognl.OgnlUtil) MockActionProxy(com.opensymphony.xwork2.mock.MockActionProxy)

Aggregations

ActionSupport (com.opensymphony.xwork2.ActionSupport)63 Test (org.junit.Test)52 ActionProxy (com.opensymphony.xwork2.ActionProxy)51 List (java.util.List)49 ValueStack (com.opensymphony.xwork2.util.ValueStack)38 Result (edu.stanford.CVC4.Result)35 ResultConfig (com.opensymphony.xwork2.config.entities.ResultConfig)34 ActionContext (com.opensymphony.xwork2.ActionContext)33 Expr (edu.stanford.CVC4.Expr)32 SExpr (edu.stanford.CVC4.SExpr)32 CVC4.vectorExpr (edu.stanford.CVC4.vectorExpr)31 ArrayList (java.util.ArrayList)31 ActionInvocation (com.opensymphony.xwork2.ActionInvocation)30 HashMap (java.util.HashMap)29 Rational (edu.stanford.CVC4.Rational)25 ActionConfig (com.opensymphony.xwork2.config.entities.ActionConfig)22 Map (java.util.Map)21 ServletActionContext (org.apache.struts2.ServletActionContext)21 Result (com.opensymphony.xwork2.Result)18 PackageConfig (com.opensymphony.xwork2.config.entities.PackageConfig)18