Skip Java Filter based on Condition

paramupk

I have looked in to How to skip a filter in the filter chain in java and followed the solution but this didn't help.

I have three filters in my web.xml. Struts filter, custom filter and IAM Agent filter in this order. I want to skip IAM filter based on some condition. I do not have control on IAM filter its external peace of code. So when ever the front end parameter says that the usertype is internal I need to call IAM agent filter else I need to skip this filter.

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
id="WebApp_ID" 
version="2.5">
<display-name>App</display-name>
<!-- Struts2 Filter -->
<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
    <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>*.action</url-pattern>
</filter-mapping>
 <!-- Custom App Filter for Handling Internal And External User-->
<filter>
   <filter-name>UserType</filter-name>
   <filter-class>com.App.web.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
   <filter-name>UserType</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

<!-- IAM Filter for Internal Users only-->
<filter>
   <filter-name>Agent</filter-name>
   <filter-class>com.sun.identity.agents.filter.AmAgentFilter</filter-class>
</filter>
<filter-mapping>
   <filter-name>Agent</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>   

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
    <listener-class>org.apache.tiles.web.startup.TilesListener</listener-class>
</listener>
<listener> 
    <listener-class>com.App.init.InitListener</listener-class>
</listener>
<context-param>
    <param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
    <param-value>/WEB-INF/tiles.xml</param-value>
</context-param>

<!-- Web Service -->
<servlet>
    <servlet-name>EventManagementWS</servlet-name>
    <servlet-class>com.App.eventmanagement.ws.EventManagementWS</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>EventManagementWS</servlet-name>
    <url-pattern>/EventManagementWS</url-pattern>
</servlet-mapping>
<resource-ref>
       <res-ref-name>url/ConfigProperty</res-ref-name>
       <res-type>java.net.URL</res-type>
       <res-auth>Container</res-auth>
       <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

I am using RequestDispatcher#forward(), but I not getting anything in my index.jsp page output, just a blank page. The css files are giving 404 error. When I was using Struts tag it gave error

Uncaught exception created in one of the service methods of the servlet /index.jsp in application App. Exception created: The Struts dispatcher cannot be found.  This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag.

So i removed S tag and used hard coding, but now I am getting 404 error in all css which i was trying to include.

I feel as if the forward is not working fine.

Java Filter Code:

package com.App.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.App.constant.Constant;
import com.App.init.WIMSInitListener;
import com.App.log.WIMSMessageLogger;

public class LoginFilter implements Filter{

FilterConfig _filterConfig = null;
@Override
public void destroy(){
    // TODO Auto-generated method stub

}

@Override
public void doFilter(ServletRequest request, ServletResponse response, 
       FilterChain filterChain) throws IOException, ServletException{
    // Check IAM is enabled
    if (InitListener.isIAMEnabled()){
        HttpSession session = httpRequest.getSession();
        String userType = (String) session.getAttribute(Constant.USER_TYPE);
        if(userType == null || "".equals(userType)){
            MessageLogger.putMessageLog("User type is null : First Request" + userType, getClass());
            userType = request.getParameter(Constant.USER_TYPE);
            session.setAttribute(Constant.USER_TYPE, userType);
            request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() + 
                    StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()))
                        .forward(request, response);

        }
        if("external".equals(userType)){
            MessageLogger.putMessageLog("External User" + userType, getClass());
            request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() + 
                    StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()))
                        .forward(request, response);

        }
        else if("internal".equals(userType)){
            MessageLogger.putMessageLog("Internal User" + userType, getClass());
            //IAM Filter com.sun.identity.agents.filter.AmAgentFilter
            filterChain.doFilter(request, response);
        }
   }
   //Its always External User
   else{
       MessageLogger.putMessageLog("User IAM Not Enabled", getClass());
       request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() + 
               StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()) )
                      .forward(request, response);

   }
}

@Override
public void init(FilterConfig filterConfig) throws ServletException{
    this._filterConfig = filterConfig;
} 
}

Index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01     Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>App</title>
<link rel="stylesheet" type="text/css" media="screen"
href="/App/css/common.css" />
<link rel="stylesheet" type="text/css" media="screen"
href="/App/css/rcorp.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/style.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/rcorp.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/default.css" />
<script type="text/javascript">
function selectUserType(){
var frm = document.forms["UserTypeForm"];
if(document.getElementById("userTypeInternal").checked){
    //frm.action='<s:url action="loginAction.action?usertype=internal" namespace="" />';
    frm.action='/App/loginAction.action?usertype=internal';
}
else{
    //frm.action='<s:url action="loginAction.action?usertype=external" namespace="" />';
    frm.action='/App/loginAction.action?usertype=external';
}   
frm.target='_parent';
frm.submit();
}
function checkUserType(){   
//var userType = '<s:property value="#session.usertype" />';
var userType = '<%= session.getAttribute("usertype") %>';
if(userType == 'internal'){
    //frm.action='<s:url action="loginAction.action?usertype=internal" namespace="" />';
    frm.action='/App/loginAction.action?usertype=internal';
    frm.target='_parent';
    frm.submit();
}
else if(userType == 'external'){
    //frm.action='<s:url action="loginAction.action?usertype=external" namespace="" />';
    frm.action='/App/loginAction.action?usertype=external';
    frm.target='_parent';
    frm.submit();
}
}
</script>
</head>
<body onload="javascript:checkUserType();">
<form method="POST" action="loginAction.action" name="UserTypeForm">
    <div id="display_option"
        style="DISPLAY: none; position: absolute; top: 40%; width: 100%;"
        align="center">
        <div class="rcorp-tbl">
            <div style="width: 340px;">
                <div style="border: 1px solid #6da6fe; padding: 5px;">
                    <table style="background-color: #f0f8ff;" cellspacing=2 border=0>
                        <tr>
                            <td class="t-cellsecnowrap">Select User type:</td>
                            <td>
                            <td class="t-cell">
                                <div id="wwgrp_systemType" class="wwgrp">
                                    <div id="wwctrl_systemType" class="wwctrl">
                                        <input type="radio" name="UserType" id="internal" value="internal" checked/>
                                            <label for="userTypeInternal">Internal User (Sydney Trains Users)</label>&nbsp; 
                                        <input type="radio" name="userType" id="external" value="external"/>
                                            <label for="userTypeExternal">External User</label>&nbsp;&nbsp;&nbsp;&nbsp;
                                        <input type="button" name="applyBtn" id="applyBtn" class="btn" value="Go" title="Go" onclick="javascript:selectUserType();"/>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>
</form>
</body>
</html>
Foxsly

Instead of trying to control it in your LoginFilter, create a new class that extends com.sun.identity.agents.filter.AmAgentFilter and configure that in your web.xml. You class would look something like this:

public class CustomFilter extends AmAgentFilter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (InitListener.isIAMEnabled()) {
            HttpSession session = httpRequest.getSession();
            String userType = (String) session.getAttribute(Constant.USER_TYPE);
            if ("internal".equals(userType)) {
                super.doFilter(servletRequest, servletResponse, filterChain);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}

The super.doFilter() call will only perform the actions in AmAgentFilter if the criteria in that if-block is met; otherwise, we ignore that filter and move on to the next one in the chain.

You would configure this filter in your web.xml instead of the AmAgentFilter.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

using Java 8 How to filter by list and group by based on filter condition and convert to Map with their count

From Dev

conditionally apply skip_before_filter with :if => condition in rails 4

From Dev

Filter data from models based on some condition

From Dev

D3: Skip Item based on condition

From Dev

Skip a component based on condition in Talend

From Dev

Skip Java Filter based on Condition

From Dev

How to filter in dplyr based upon an associated condition

From Dev

Condition Filter in dplyr based on Shiny input

From Dev

How to filter JavaScript object based on property condition?

From Dev

How can I automatically skip certain JUnit tests based on a condition?

From Dev

How to skip line in spark rdd map action based on if condition

From Dev

Filter pandas columns based on row condition

From Dev

Add/Skip WHERE CLAUSE based on Condition

From Dev

Java 8 Filter list based on condition from the part of the list

From Dev

Java 8 Applying stream filter based on a condition

From Dev

filter MyDjango data based on condition and calculation in django

From Dev

Java streams, filter based on condition in an object, set value to a string and a an array

From Dev

using Java 8 How to filter by list and group by based on filter condition and convert to Map with their count

From Dev

Skip elements on a condition based in a list comprehension in python

From Dev

Filter pandas columns based on row condition

From Dev

conditionally apply skip_before_filter with :if => condition in rails 4

From Dev

Java Concurrency based on condition

From Dev

Skip a component based on condition in Talend

From Dev

Search filter on two fields based upon condition

From Dev

Condition Filter in dplyr based on Shiny input

From Dev

Python: skip lines of programming based on a condition in a while loop?

From Dev

[Pushbullet Feature Suggestion]: Filter messages based on condition

From Dev

Skip to next in array for batch based off of IF condition

From Dev

Filter data based on condition

Related Related

  1. 1

    using Java 8 How to filter by list and group by based on filter condition and convert to Map with their count

  2. 2

    conditionally apply skip_before_filter with :if => condition in rails 4

  3. 3

    Filter data from models based on some condition

  4. 4

    D3: Skip Item based on condition

  5. 5

    Skip a component based on condition in Talend

  6. 6

    Skip Java Filter based on Condition

  7. 7

    How to filter in dplyr based upon an associated condition

  8. 8

    Condition Filter in dplyr based on Shiny input

  9. 9

    How to filter JavaScript object based on property condition?

  10. 10

    How can I automatically skip certain JUnit tests based on a condition?

  11. 11

    How to skip line in spark rdd map action based on if condition

  12. 12

    Filter pandas columns based on row condition

  13. 13

    Add/Skip WHERE CLAUSE based on Condition

  14. 14

    Java 8 Filter list based on condition from the part of the list

  15. 15

    Java 8 Applying stream filter based on a condition

  16. 16

    filter MyDjango data based on condition and calculation in django

  17. 17

    Java streams, filter based on condition in an object, set value to a string and a an array

  18. 18

    using Java 8 How to filter by list and group by based on filter condition and convert to Map with their count

  19. 19

    Skip elements on a condition based in a list comprehension in python

  20. 20

    Filter pandas columns based on row condition

  21. 21

    conditionally apply skip_before_filter with :if => condition in rails 4

  22. 22

    Java Concurrency based on condition

  23. 23

    Skip a component based on condition in Talend

  24. 24

    Search filter on two fields based upon condition

  25. 25

    Condition Filter in dplyr based on Shiny input

  26. 26

    Python: skip lines of programming based on a condition in a while loop?

  27. 27

    [Pushbullet Feature Suggestion]: Filter messages based on condition

  28. 28

    Skip to next in array for batch based off of IF condition

  29. 29

    Filter data based on condition

HotTag

Archive