Wednesday, 22 January 2014

Textual description of firstImageUrl

Webxml Attribute Is Required Error in Maven

Servlet 3.0 API has many nice features in it . One of the most important feature of this release is ease of development . Now you don't have to write configurations related things in web.xml , you can write all these things by using annotations . So , from servlet 3.0 , web.xml is optional (however , if web.xml is present , it will be given preference over annotations ) . If you are using maven for packaging your war , you might get following error if you don't have web.xml in your application .

 Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war (default-war) on project webSocketExample: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]

You can resolve this error by adding following lines in your pom.xml
<plugin>
      <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-war-plugin</artifactId>
       <configuration>
          <failOnMissingWebXml>false</failOnMissingWebXml>
       </configuration>
</plugin>


Friday, 27 December 2013

Textual description of firstImageUrl

Convert Xsd Files In Java Classes

We can convert xsd files to java file vert easily using xjc tool .

Just type the following command in command prompt ( assuming you have the xsd file in same working directory )
xjc test.xsd
After running the command successfully , you will find all the classes generated automatically with correct package structure .









XJC is inbuilt for java version 6 and higher .

Post Comments and Suggestions !!

Wednesday, 22 May 2013

Textual description of firstImageUrl

Configure CAS Server and Client in Java

Central Authentication Service also known as CAS provides single sign on (SSO)functionality to various applications.

CAS application has two parts , first part is in the form of web application which can run on any java EE compliant web server (like tomcat) and act as a server which provides authentication. Second part is in the form of client , which you need to add with your application. In this post , we will try to configure CAS in tomcat , and create a java web application which will use CAS authentication service.

First we will configure CAS server to run as WAR application on tomcat. For this, first download CAS from Here.

Extract the zip file and there you find different implementation of CAS server.Just Copy the cas-server-webapp folder and build a cas.war from pom.xml located in it.By default CAS Server web app will work on only for HTTPS connections , if you want to enable Http connection for CAS , then go to the web app folder and under /WEB-INF/spring-configuration/ticketGrantingTicketCookieGenerator.xml and change the p:cookieSecure="true" to p:cookieSecure="false" , then again create the cas.war from maven.

Now if you want to use it on https connections as well , prepare the tomcat to accept https connections which is explained in this Post.

Now deploy this war on server and you can access cas server at https://localhost:8443/cas or http://localhost:8080/cas.

Now we will create a simple java web application to use SSO of CAS. First download CAS client for java from this link. I have used cas-client-3.1.1-release.Run the pom.xml and add the jars created in the java web application . You should have following jars in your web app :

cas-client-core-3.1.1.jar (from cas-client 3.1.1)
commons-logging-1.1.jar (from cas-client 3.1.1)
xercesImpl.jar (from Apache Xerces release 2.9.1)
xml-apis.jar (from Apache Xerces release 2.9.1)
xmlsec-1.3.0.jar (from cas-client 3.1.1)

Now add these filter configurations to your web.xml.
<filter>
  <filter-name>CAS Authentication Filter</filter-name>
  <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>
  <init-param>
   <param-name>casServerLoginUrl</param-name>
   <param-value>http://localhost:8080/cas/login</param-value>
  </init-param>
  <init-param>
   <param-name>serverName</param-name>
   <param-value>http://localhost:8080</param-value>
  </init-param>
  <init-param>
   <param-name>renew</param-name>
   <param-value>false</param-value>
  </init-param>
  <init-param>
   <param-name>gateway</param-name>
   <param-value>false</param-value>
  </init-param>
 </filter>
 
 <filter>
  <filter-name>CAS Validation Filter</filter-name>
  <filter-class>org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter</filter-class>
  <init-param>
   <param-name>casServerUrlPrefix</param-name>
   <param-value>http://localhost:8080/cas/</param-value>
  </init-param>
  <init-param>
   <param-name>serverName</param-name>
   <param-value>http://localhost:8080</param-value>
  </init-param>
  <init-param>
   <param-name>proxyCallbackUrl</param-name>
   <param-value>http://localhost:8080/webappcas2/proxyCallback</param-value>
  </init-param>
  <init-param>
   <param-name>proxyReceptorUrl</param-name>
   <param-value>/webappcas2/proxyCallback</param-value>
  </init-param>
 </filter>
 
 <filter>
  <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>
  <filter-class>org.jasig.cas.client.util.HttpServletRequestWrapperFilter</filter-class>
 </filter>
 
 <filter>
  <filter-name>CAS Assertion Thread Local Filter</filter-name>
  <filter-class>org.jasig.cas.client.util.AssertionThreadLocalFilter</filter-class>
 </filter>

 <!-- ************************* -->

<!-- Sign out not yet implemented -->
<!-- 
 <filter-mapping>
  <filter-name>CAS Single Sign Out Filter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
-->

 <filter-mapping>
  <filter-name>CAS Authentication Filter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 <filter-mapping>
  <filter-name>CAS Validation Filter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
  
 <filter-mapping>
  <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 
 <filter-mapping>
  <filter-name>CAS Assertion Thread Local Filter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 
 <filter-mapping>
  <filter-name>CAS Validation Filter</filter-name>
  <url-pattern>/proxyCallback</url-pattern> 
 </filter-mapping>
That's it . Now if you try to access your web app , you will be redirected to cas login page to login first.Right now CAS web app is configured to allow access with same username and password.You can configure cas-web-app as you wish. Upon successful authentication you will be served the web page from web app .

you can get NullPointerException like this :
java.lang.NullPointerException
    org.jasig.cas.client.util.HttpServletRequestWrapperFilter$CasHttpServletRequestWrapper.getRemoteUser(HttpServletRequestWrapperFilter.java:80)
    org.apache.jsp.include_005fheader_jsp._jspService(include_005fheader_jsp.java:57)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
...

To solve this you can apply patch from this link , or download the patched version from here .

Post Comment and suggestions !!


Tuesday, 5 March 2013

Textual Representation of logo

How to use Custom DAO class in Spring Security for authentication and authorization


Objective 1 : Use Custom DAO classes in Spring Security Spring Security provides mechanism by which we can specify database queries in spring security xml file , but sometimes we want to use our own custom dao classes which are already built.
Objective 2 : Forward the request to different home pages based on the authorized role



First , to use your custom dao class , we have to create a bean which implements org.springframework.security.userdetails.UserDetailsService interface. Override the loadUserByUserName method of this interface. We have to create org.springframework.security.userdetails.User from our custom dao object.
package com.security;

import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.User;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import com.dal.interfaces.UserDAO;
import com.exceptions.DAOException;

/**
 * //this class is used by spring controller to authenticate and authorize user
 * modified this class to user our Database and defined user roles
 * 
 * @author abhishek.somani
 * 
 */
public class UserDetailServiceImpl implements UserDetailsService {
 private UserDAO userdao;

 public void setUserdao(UserDAO userdao) {
  this.userdao = userdao;
 }

 // this class is used by spring controller to authenticate and authorize
 // user
 @Override
 public UserDetails loadUserByUsername(String userId)
   throws UsernameNotFoundException {
  com.model.User u;
  try {
   u = userdao.get(userId);
   if (u == null)
    throw new UsernameNotFoundException("user name not found");

  } catch (DAOException e) {
   throw new UsernameNotFoundException("database error ");
  }
  return buildUserFromUserEntity(u);

 }

 private User buildUserFromUserEntity(com.model.User userEntity) {
  // convert model user to spring security user
  String username = userEntity.getUserId();
  String password = userEntity.getPassword();
  boolean enabled = true;
  boolean accountNonExpired = true;
  boolean credentialsNonExpired = true;
  boolean accountNonLocked = true;
  GrantedAuthority[] authorities = new GrantedAuthorityImpl[1];
  authorities[0] = new GrantedAuthorityImpl(userEntity.getRole());

  User springUser = new User(username, password, enabled,
    accountNonExpired, credentialsNonExpired, accountNonLocked,
    authorities);
  return springUser;
 }

}

In Spring-security.xml we have to give reference of this bean in user-service-ref in authentication-provider tag.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:security="http://www.springframework.org/schema/security"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
                         http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                        http://www.springframework.org/schema/security
                         http://www.springframework.org/schema/security/spring-security-2.0.1.xsd
                          http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<!-- this is security configuration file which maps urls according to user roles authorization -->

 <security:http auto-config="true">
 <security:logout logout-success-url="/login" invalidate-session="true" logout-url="/logout"/>
  <security:intercept-url pattern="/login.jsp" filters="none" />
  <security:intercept-url pattern="/login" filters="none" />
  <security:intercept-url pattern="/logout" filters="none" />
  <security:intercept-url pattern="/Test"  access="ROLE_ADMIN" />
  <security:intercept-url pattern="/home" access="ROLE_ADMIN,ROLE_USER"/>
  <security:intercept-url pattern="/user/*" access="ROLE_USER" />
  <security:intercept-url pattern="/admin/*" access="ROLE_ADMIN" />
  <security:intercept-url pattern="/*" filters="none"/>
  <security:form-login login-page="/login"
   default-target-url="/home" authentication-failure-url="/login?error=1"
   always-use-default-target="true"/>
  
   
 </security:http>
 <security:authentication-provider
  user-service-ref="userDetailsService" />

 <bean id='userDetailsService' class='com.security.UserDetailServiceImpl'>
  <property name='userdao' ref='userDao' />
 </bean>

</beans>
Now we want to redirect user after authentication and authorization by user. If a user has User role , it should go to home page of user or if a user has admin role then it should go to home page of admin .

For this , create a simple controller .After successfull authorization and authentication request.getUserPrinicipal will have the Prinicipal object containing userName which is set in UserDetailServiceImpl and we can check the roles by request.isUserInRole method.

In spring-security.xml , set target url to this controller and set always-use-default-target attribute to true in form-login tag , because we always want this controller to execute after user successfully authenticate the user. Sometimes if the request contains referer header , spring security redirect it to that previous link.That is why we set always-use-default-target attribute to true.
package com.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import com.constants.Constants;
import com.model.UserRoles;
import com.util.CustomLogger;

/**
 * home controller redirects the user based on the roles 
 * @author abhishek.somani
 *
 */
public class HomeController extends AbstractController
{

 @Override
 protected ModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse arg1) throws Exception
 {
  //this is the home controller to redirect user to their home pages based on role name 
  // for Admin it should be /admin/home
  //for user it should be /user/home
    
  if (request.isUserInRole("ROLE_USER"))
  {
   request.setAttribute("appendURL", "user");
   return new ModelAndView("user/home", "welcome ", null);
  }
  if (request.isUserInRole("ROLE_ADMIN"))
  {
   request.setAttribute("appendURL", "admin");
   return new ModelAndView("admin/home", "welcome ", null);
  }
  
  throw new Exception("No roles Detected");
 }

}
Do Comment if you face any difficulty.

Monday, 4 March 2013

Textual Representation of logo

Spring Security Not Working with particular url pattern

Spring security provides greater flexibility and ease in terms of securing your web application.Recently i found that a particular url was not working in spring security[whereas other urls were working perfectly]. it completely bypassing the url although it was defined in the same way as other urls . Here is my spring security configuration all urls are secured except /TestServlet
<security:http auto-config="true">
 <security:logout logout-success-url="/login" invalidate-session="true" logout-url="/logout"/>
 <security:intercept-url pattern="/login.jsp" filters="none" />
 <security:intercept-url pattern="/login" filters="none" />
 <security:intercept-url pattern="/logout" filters="none" />
 <security:intercept-url pattern="/TestServlet"  access="ROLE_ADMIN" />
 <security:form-login login-page="/login"
 default-target-url="/home" authentication-failure-url="/login?error=1"
  always-use-default-target="true"/> 
</security:http>
Later , i found out that spring security filter converts the matching url pattern[which we define in intercept-url pattern tag] to lower case , so if you have camel case or upper case url pattern(one or more capital letters in url pattern), it will not match with the spring security pattern , thus this pattern will be ignored by spring security filter. There is a tag available to disable this converting of matching url pattern to lower case. just add lowercase-comparisons attribute to false in http tag in spring security like this :
<security:http auto-config="true" lowercase-comparisons="false">
 <security:logout logout-success-url="/login" invalidate-session="true" logout-url="/logout"/>
 <security:intercept-url pattern="/login.jsp" filters="none" />
 <security:intercept-url pattern="/login" filters="none" />
 <security:intercept-url pattern="/logout" filters="none" />
 <security:intercept-url pattern="/TestServlet"  access="ROLE_ADMIN" />
 <security:form-login login-page="/login"
 default-target-url="/home" authentication-failure-url="/login?error=1"
  always-use-default-target="true"/> 
</security:http>

Friday, 25 January 2013

Textual Representation of logo

Servlet Request URL Pattern Explained

Every servlet is mapped with url pattern in web.xml . Container tries to find the appropriate Servlet using following rules :
  •  it will try to find the web application context root by matching the request url . it will match longest web application path . 
  •  after finding the web application context root , it will try to match the remaining part of url with the      available pattern in following order , any successful match will stop further matching                                                             

  1. it will try to find a exact match
  2. it will recursively match the longest path where path separator is '/'. if a path matching pattern is provided. 
  3. if url contains some extension , it will try to match extension pattern.
  4. if no pattern is matched , it will go to default servlet , if defined by web application .

a path matching pattern is a url pattern which starts from / and end with '*' .

if a servlet is mapped with url pattern '/' then it is called the default servlet 

if a servlet is mapped with empty string url pattern then it is mapped to context root of web application

HttpServletRequest Provide two methods for accessing url provided by user :

getServletPath()  provides servlet path.

getPathInfo()  provides excess path info if path matching pattern is used in finding the servlet.


now let's take examples to understand the process :
<servlet-mapping>
    <servlet-name>ExactMatchServlet</servlet-name>
    <url-pattern>/abc</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>DefaultServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>PathInfoServlet</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>LongPathInfoServlet</servlet-name>
    <url-pattern>/abc/*</url-pattern>
  </servlet-mapping>
if a request is /abc it will match to ExactMatchServlet
 here Servlet Path is /abc whereas path info is null

 if a request is /abc/pqr , it will match to LongPathInfoServlet instead of PathInfoServlet because this path matched is longer .
 here Servlet Path is /abc and path info will be /pqr .

 if a request is /something/random , it will match to PathInfoServlet
 here ServletPath is empty string whereas path info will be /something/random

if we change the PathInfoServlet's url mapping from /* to /something
and then , a request is made  /something/random , then it will match to DefaultServlet .
here ServletPath is /something/random and path info is null .


Thursday, 10 January 2013

Textual Representation of logo

how to avoid re sending post response on refresh or click

i faced this problem while submitting post data , if a user clicks it again , it again gets submitted in database or if the page is refreshed. the solution for this problem is using a simple token which is generated every time user requests for the post form and checking this token again . i have used jsp , and jstl for this . this is a jsp page which will post the data to the servlet . please note here i am using a hidden input along with our custom tag .
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="/WEB-INF/tld/token.tld" prefix="token"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="shortcut icon" href="/favicon.ico" />
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/css/style.css">
<title>Create Customer</title>
</head>
<body>
<form name="createUser" action="createUser" method="post"><label
for="email Id">email</label> <input type="text" name="email">
<div class="clear"></div>
<input type="hidden" name="token"
value="<token:generate/>"></input>
<label for="name">Name</label>
<input type="text" name="name">
<div class="clear"></div>

<label for="name">Address</label>
<input type="text" name="address">
<div class="clear"></div>

<label for="name">Account Type</label>
<input type="text" name="accountType">
<div class="clear"></div>

<label for="name">Openiing Balance</label>
<input type="text" name="initialBalance">
<div class="clear"></div>

<input type="submit" style="margin: -20px 0 0 287px;" class="button"
name="commit" value="Create User"></form>
<div style="color: Red">${validationError}</div>

<a href="view.jsp">back</a>

</body>
</html>
this is tag class which will pass the token value in request attribute as well as set it in session attribute .
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;

public class TokenGenerator implements Tag
{

 private PageContext pageCtx;
 private final int digits = 1000000;
 @Override
 public int doEndTag() throws JspException
 {
  // TODO Auto-generated method stub
  return 0;
 }

 @Override
 public int doStartTag() throws JspException
 {
  int randomInt = (int) (Math.random() * digits);
  try
  {
   System.out.println("in tag class" + randomInt);
   pageCtx.getOut().print(randomInt);
   System.out.println("after writing to pagectx");
   pageCtx.getSession().setAttribute("token", randomInt);
  }
  catch(IOException e)
  {
   System.out.println("in exception of tag cl;ass");
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return 0;
 }
 @Override
 public Tag getParent()
 {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public void release()
 {
  // TODO Auto-generated method stub

 }

 @Override
 public void setPageContext(PageContext arg0)
 {
  pageCtx = arg0;
 }

 @Override
 public void setParent(Tag arg0)
 {
  // TODO Auto-generated method stub

 }

}
Token Validator Filter will check , if the request and session has same token ,means it is coming from the form, otherwise the filter will redirect to home page .
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.HttpServletResponse;

/**
 * Servlet Filter implementation class TokenValidator
 */
public class TokenValidator implements Filter {

 /**
  * Default constructor.
  */
 public TokenValidator() {
  // TODO Auto-generated constructor stub
 }

 /**
  * @see Filter#destroy()
  */
 public void destroy() {
  // TODO Auto-generated method stub
 }

 /**
  * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
  */
 public void doFilter(ServletRequest request1, ServletResponse response1,
   FilterChain chain) throws IOException, ServletException {
  System.out.println("token validator called");
  HttpServletRequest request = (HttpServletRequest) request1;
  HttpServletResponse response = (HttpServletResponse) response1;

  boolean validRequest = false;
  Object token1 = request.getParameter("token");
  Object token2 = request.getSession().getAttribute("token");
  
  if (token1 != null && token2 != null) {
   Integer first = Integer.parseInt(token1.toString());
   Integer second = Integer.parseInt(token2.toString());
   if (first.equals(second))
    validRequest = true;
  }

  if (!validRequest) {
   System.out.println("redirecting response");
   response.sendRedirect("view.jsp");
  } else {
   chain.doFilter(request1, response1);
  }

 }

 /**
  * @see Filter#init(FilterConfig)
  */
 public void init(FilterConfig fConfig) throws ServletException {
  // TODO Auto-generated method stub
 }

}


the tld file of token
<taglib version="2.1" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="
            http://java.sun.com/xml/ns/javaee 
            http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
    <tlib-version>1.0</tlib-version> 
    <short-name>MyTag</short-name>
    <uri>/WEB-INF/customTag</uri>
     
   <tag>
  <name>generate</name>
  <tag-class>TokenGenerator</tag-class>
  <body-content>empty</body-content>
  </tag>

</taglib>
Feel Free to ask questions

Friday, 5 October 2012

Textual Representation of logo

Name Is Too Long To Represent Error in JSP

SMAP is defined in jsr-45 to provide debugging support for other languages . For example , jsp files are converted in to java files . to debug jsp source file , we will need jsp source line numbers as well as generated java file line numbers . This mapping is done in SMAP . So web servers , after generating java source file from jsp pages , also generates SMAP information and append it to compiled class files . This SMAP info is saved in a classpath attribute called SourceDebugExtension . The maximum permissible size of this attribute is 64KB . If you a have a very large jsp , it might happen that generated SMAP information is also big , exceeding 64KB threshold . When we enable debugger , and try to run this big jsp files , we will get following error
java.lang.InternalError: name is too long to represent .


The only solution to this problem is to reduce the size of your jsp . We can check the  smap information in generated class file which is appended in the end and will start something like this :  
SMAP
* JSPFILENAME
1 : 3,5
2,2 : 8
1#0 : 1
 

each row of smap is called stratum and contains line mappings  in this example ,
first row :
line number 1 in jsp is mapped to line numbers 3,4,5 in output java file
second row:
line number 2 is mapped to line number 8
; line number 3 is mapped ot line number 9
; third row :
# denotes included files in the jsp which are declared on top of smap definition.