Search in sources :

Example 61 with Interceptor

use of com.opensymphony.xwork2.interceptor.Interceptor 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("&", "&");
                        xml = xml.replaceAll(">", ">");
                        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 62 with Interceptor

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

the class PlexusObjectFactory method buildInterceptor.

/* (non-Javadoc)
     * @see com.opensymphony.xwork2.ObjectFactory#buildInterceptor(com.opensymphony.xwork2.config.entities.InterceptorConfig, java.util.Map)
     */
public Interceptor buildInterceptor(InterceptorConfig interceptorConfig, Map interceptorRefParams) throws ConfigurationException {
    String interceptorClassName = interceptorConfig.getClassName();
    Map thisInterceptorClassParams = interceptorConfig.getParams();
    Map params = (thisInterceptorClassParams == null) ? new HashMap() : new HashMap(thisInterceptorClassParams);
    params.putAll(interceptorRefParams);
    String message;
    Throwable cause;
    try {
        Map extraContext = new HashMap();
        extraContext.put(PLEXUS_COMPONENT_TYPE, Interceptor.class.getName());
        Interceptor interceptor = (Interceptor) buildBean(interceptorClassName, extraContext);
        reflectionProvider.setProperties(params, interceptor);
        interceptor.init();
        return interceptor;
    } catch (InstantiationException e) {
        cause = e;
        message = "Unable to instantiate an instance of Interceptor class [" + interceptorClassName + "].";
    } catch (IllegalAccessException e) {
        cause = e;
        message = "IllegalAccessException while attempting to instantiate an instance of Interceptor class [" + interceptorClassName + "].";
    } catch (ClassCastException e) {
        cause = e;
        message = "Class [" + interceptorClassName + "] does not implement com.opensymphony.xwork2.interceptor.Interceptor";
    } catch (Exception e) {
        cause = e;
        message = "Caught Exception while registering Interceptor class " + interceptorClassName;
    } catch (NoClassDefFoundError e) {
        cause = e;
        message = "Could not load class " + interceptorClassName + ". Perhaps it exists but certain dependencies are not available?";
    }
    throw new ConfigurationException(message, cause);
}
Also used : HashMap(java.util.HashMap) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException) HashMap(java.util.HashMap) Map(java.util.Map) Interceptor(com.opensymphony.xwork2.interceptor.Interceptor) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException)

Example 63 with Interceptor

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

the class DateTextFieldInterceptorTest method setUp.

protected void setUp() throws Exception {
    super.setUp();
    param = new HashMap<>();
    interceptor = new DateTextFieldInterceptor();
    ai = new MockActionInvocation();
    ai.setInvocationContext(ActionContext.getContext());
}
Also used : MockActionInvocation(com.opensymphony.xwork2.mock.MockActionInvocation)

Example 64 with Interceptor

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

the class FetchMetadataInterceptorTest method testSetExemptedPathsInjectionIndirectly.

public void testSetExemptedPathsInjectionIndirectly() throws Exception {
    // Perform a multi-step test to confirm (indirectly) that the method parameter injection of setExemptedPaths() for
    // the FetchMetadataInterceptor is functioning as expected, when configured appropriately.
    // Ensure we're using the specific test configuration, not the default simple configuration.
    XmlConfigurationProvider configurationProvider = new StrutsXmlConfigurationProvider("struts-testing.xml");
    container.inject(configurationProvider);
    loadConfigurationProviders(configurationProvider);
    // The test configuration in "struts-testing.xml" should define a "default" package.  That "default" package should contain a "defaultInterceptorStack" containing
    // a "fetchMetadata" interceptor parameter "fetchMetadata.setExemptedPaths".  If the parameter method injection is working correctly for the FetchMetadataInterceptor,
    // the exempted paths should be set appropriately for the interceptor instances, once the configuration is loaded into the container.
    final PackageConfig defaultPackageConfig = configuration.getPackageConfig("default");
    final InterceptorStackConfig defaultInterceptorStackConfig = (InterceptorStackConfig) defaultPackageConfig.getInterceptorConfig("defaultInterceptorStack");
    final Collection<InterceptorMapping> defaultInterceptorStackInterceptors = defaultInterceptorStackConfig.getInterceptors();
    assertFalse("'defaultInterceptorStack' interceptors in struts-testing.xml is empty ?", defaultInterceptorStackInterceptors.isEmpty());
    InterceptorMapping configuredFetchMetadataInterceptorMapping = null;
    Iterator<InterceptorMapping> interceptorIterator = defaultInterceptorStackInterceptors.iterator();
    while (interceptorIterator.hasNext()) {
        InterceptorMapping currentMapping = interceptorIterator.next();
        if (currentMapping != null && "fetchMetadata".equals(currentMapping.getName())) {
            configuredFetchMetadataInterceptorMapping = currentMapping;
            break;
        }
    }
    assertNotNull("'fetchMetadata' interceptor mapping not present after loading 'struts-testing.xml' ?", configuredFetchMetadataInterceptorMapping);
    assertTrue("'fetchMetadata' interceptor mapping loaded from 'struts-testing.xml' produced a non-FetchMetadataInterceptor type ?", configuredFetchMetadataInterceptorMapping.getInterceptor() instanceof FetchMetadataInterceptor);
    FetchMetadataInterceptor configuredFetchMetadataInterceptor = (FetchMetadataInterceptor) configuredFetchMetadataInterceptorMapping.getInterceptor();
    request.removeHeader(SEC_FETCH_SITE_HEADER);
    request.addHeader(SEC_FETCH_SITE_HEADER, "foo");
    request.setContextPath("/foo");
    assertEquals("Expected interceptor to NOT accept this request [/foo]", SC_FORBIDDEN, configuredFetchMetadataInterceptor.intercept(mai));
    request.setContextPath("/fetchMetadataExemptedGlobal");
    assertNotEquals("Expected interceptor to accept this request [/fetchMetadataExemptedGlobal]", SC_FORBIDDEN, configuredFetchMetadataInterceptor.intercept(mai));
    request.setContextPath("/someOtherPath");
    assertNotEquals("Expected interceptor to accept this request [/someOtherPath]", SC_FORBIDDEN, configuredFetchMetadataInterceptor.intercept(mai));
    // The test configuration in "struts-testing.xml" should also contain three actions configured differently for the "fetchMetadata" interceptor.
    // "fetchMetadataExempted" has an override exemption matching its action name, "fetchMetadataNotExempted" has an override exemption NOT matching its action name,
    // and "fetchMetadataExemptedGlobal" has an action name matching an exemption defined in "defaultInterceptorStack".
    final RuntimeConfiguration runtimeConfiguration = configuration.getRuntimeConfiguration();
    final ActionConfig fetchMetadataExemptedActionConfig = runtimeConfiguration.getActionConfig("/", "fetchMetadataExempted");
    final ActionConfig fetchMetadataNotExemptedActionConfig = runtimeConfiguration.getActionConfig("/", "fetchMetadataNotExempted");
    final ActionConfig fetchMetadataExemptedGlobalActionConfig = runtimeConfiguration.getActionConfig("/", "fetchMetadataExemptedGlobal");
    assertNotNull("'fetchMetadataExempted' action config not present in 'struts-testing.xml' ?", fetchMetadataExemptedActionConfig);
    assertNotNull("'fetchMetadataNotExempted' action config not present in 'struts-testing.xml' ?", fetchMetadataExemptedActionConfig);
    assertNotNull("'fetchMetadataExemptedGlobal' action config not present in 'struts-testing.xml' ?", fetchMetadataExemptedActionConfig);
    // Test fetchMetadata interceptor for the "fetchMetadataExempted" action.
    Collection<InterceptorMapping> currentActionInterceptors = fetchMetadataExemptedActionConfig.getInterceptors();
    assertFalse("'fetchMetadataExempted' interceptors in struts-testing.xml is empty ?", currentActionInterceptors.isEmpty());
    configuredFetchMetadataInterceptorMapping = null;
    interceptorIterator = currentActionInterceptors.iterator();
    while (interceptorIterator.hasNext()) {
        InterceptorMapping currentMapping = interceptorIterator.next();
        if (currentMapping != null && "fetchMetadata".equals(currentMapping.getName())) {
            configuredFetchMetadataInterceptorMapping = currentMapping;
            break;
        }
    }
    assertNotNull("'fetchMetadata' interceptor mapping for action 'fetchMetadataExempted' not present in 'struts-testing.xml' ?", configuredFetchMetadataInterceptorMapping);
    assertTrue("'fetchMetadata' interceptor mapping for action 'fetchMetadataExempted' in 'struts-testing.xml' produced a non-FetchMetadataInterceptor type ?", configuredFetchMetadataInterceptorMapping.getInterceptor() instanceof FetchMetadataInterceptor);
    configuredFetchMetadataInterceptor = (FetchMetadataInterceptor) configuredFetchMetadataInterceptorMapping.getInterceptor();
    request.removeHeader(SEC_FETCH_SITE_HEADER);
    request.addHeader(SEC_FETCH_SITE_HEADER, fetchMetadataExemptedActionConfig.getName());
    request.setContextPath("/" + fetchMetadataExemptedActionConfig.getName());
    assertNotEquals("Expected interceptor to accept this request [" + "/" + fetchMetadataExemptedActionConfig.getName() + "]", SC_FORBIDDEN, configuredFetchMetadataInterceptor.intercept(mai));
    // Test fetchMetadata interceptor for the "fetchMetadataNotExempted" action.
    currentActionInterceptors = fetchMetadataNotExemptedActionConfig.getInterceptors();
    assertFalse("'fetchMetadataNotExempted' interceptors in struts-testing.xml is empty ?", currentActionInterceptors.isEmpty());
    configuredFetchMetadataInterceptorMapping = null;
    interceptorIterator = currentActionInterceptors.iterator();
    while (interceptorIterator.hasNext()) {
        InterceptorMapping currentMapping = interceptorIterator.next();
        if (currentMapping != null && "fetchMetadata".equals(currentMapping.getName())) {
            configuredFetchMetadataInterceptorMapping = currentMapping;
            break;
        }
    }
    assertNotNull("'fetchMetadata' interceptor mapping for action 'fetchMetadataNotExempted' not present in 'struts-testing.xml' ?", configuredFetchMetadataInterceptorMapping);
    assertTrue("'fetchMetadata' interceptor mapping 'fetchMetadataExempted' in 'struts-testing.xml' produced a non-FetchMetadataInterceptor type ?", configuredFetchMetadataInterceptorMapping.getInterceptor() instanceof FetchMetadataInterceptor);
    configuredFetchMetadataInterceptor = (FetchMetadataInterceptor) configuredFetchMetadataInterceptorMapping.getInterceptor();
    request.removeHeader(SEC_FETCH_SITE_HEADER);
    request.addHeader(SEC_FETCH_SITE_HEADER, fetchMetadataNotExemptedActionConfig.getName());
    request.setContextPath("/" + fetchMetadataNotExemptedActionConfig.getName());
    assertEquals("Expected interceptor to NOT accept this request [" + "/" + fetchMetadataNotExemptedActionConfig.getName() + "]", SC_FORBIDDEN, configuredFetchMetadataInterceptor.intercept(mai));
    // Test fetchMetadata interceptor for the "fetchMetadataExemptedGlobal" action.
    currentActionInterceptors = fetchMetadataExemptedGlobalActionConfig.getInterceptors();
    assertFalse("'fetchMetadataExemptedGlobal' interceptors in struts-testing.xml is empty ?", currentActionInterceptors.isEmpty());
    configuredFetchMetadataInterceptorMapping = null;
    interceptorIterator = currentActionInterceptors.iterator();
    while (interceptorIterator.hasNext()) {
        InterceptorMapping currentMapping = interceptorIterator.next();
        if (currentMapping != null && "fetchMetadata".equals(currentMapping.getName())) {
            configuredFetchMetadataInterceptorMapping = currentMapping;
            break;
        }
    }
    assertNotNull("'fetchMetadata' interceptor mapping for action 'fetchMetadataExemptedGlobal' not present in 'struts-testing.xml' ?", configuredFetchMetadataInterceptorMapping);
    assertTrue("'fetchMetadata' interceptor mapping 'fetchMetadataExemptedGlobal' in 'struts-testing.xml' produced a non-FetchMetadataInterceptor type ?", configuredFetchMetadataInterceptorMapping.getInterceptor() instanceof FetchMetadataInterceptor);
    configuredFetchMetadataInterceptor = (FetchMetadataInterceptor) configuredFetchMetadataInterceptorMapping.getInterceptor();
    request.removeHeader(SEC_FETCH_SITE_HEADER);
    request.addHeader(SEC_FETCH_SITE_HEADER, fetchMetadataExemptedGlobalActionConfig.getName());
    request.setContextPath("/" + fetchMetadataExemptedGlobalActionConfig.getName());
    assertNotEquals("Expected interceptor to accept this request [" + "/" + fetchMetadataExemptedGlobalActionConfig.getName() + "]", SC_FORBIDDEN, configuredFetchMetadataInterceptor.intercept(mai));
}
Also used : InterceptorStackConfig(com.opensymphony.xwork2.config.entities.InterceptorStackConfig) ActionConfig(com.opensymphony.xwork2.config.entities.ActionConfig) StrutsXmlConfigurationProvider(org.apache.struts2.config.StrutsXmlConfigurationProvider) StrutsXmlConfigurationProvider(org.apache.struts2.config.StrutsXmlConfigurationProvider) XmlConfigurationProvider(com.opensymphony.xwork2.config.providers.XmlConfigurationProvider) InterceptorMapping(com.opensymphony.xwork2.config.entities.InterceptorMapping) PackageConfig(com.opensymphony.xwork2.config.entities.PackageConfig) RuntimeConfiguration(com.opensymphony.xwork2.config.RuntimeConfiguration)

Example 65 with Interceptor

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

the class MessageStoreInterceptorTest method testRequestOperationMode3.

public void testRequestOperationMode3() {
    ActionContext actionContext = ActionContext.of(new HashMap<>()).bind();
    actionContext.setParameters(HttpParameters.create().build());
    ActionInvocation mockActionInvocation = EasyMock.createControl().createMock(ActionInvocation.class);
    mockActionInvocation.getInvocationContext();
    EasyMock.expectLastCall().andReturn(actionContext);
    EasyMock.expectLastCall().anyTimes();
    EasyMock.replay(mockActionInvocation);
    MessageStoreInterceptor interceptor = new MessageStoreInterceptor();
    String operationMode = interceptor.getRequestOperationMode(mockActionInvocation);
    assertEquals(operationMode, MessageStoreInterceptor.NONE);
    EasyMock.verify(mockActionInvocation);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ActionInvocation(com.opensymphony.xwork2.ActionInvocation) ServletActionContext(org.apache.struts2.ServletActionContext) ActionContext(com.opensymphony.xwork2.ActionContext)

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