Wednesday, 26 June 2013

Textual description of firstImageUrl

IllegalStateException in Response.SendRedirect

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.IllegalStateException
 org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:436)TestFilter.doFilter(TestFilter.java:42)



ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/webtest].[jsp]] (http--127.0.0.1-8080-1) Servlet.service() for servlet jsp threw exception: java.lang.IllegalStateException
        at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:436) [jbossweb-7.0.13.Final.jar:]
        at TestFilter.doFilter(TestFilter.java:42)      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
        at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
        at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_17]





This Exception occurs when you try to send response again when the response is already committed and flushed to user.The above exception stack trace is from JBoss AS 7.1.1.Final . For example , consider this sample code of a filter :
/**
  * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
  */
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  
 
 
  request.getRequestDispatcher("index.jsp").forward(request, response);
  ((HttpServletResponse)response).sendRedirect("new.jsp");
  chain.doFilter(request, response);
 }
Here in this code ,first the request will be forwarded to index.jsp and response will be flushed to user , then the control will again come back to filter and try to send another response (redirect)to user , and it will fail.

Usually we check multiple conditions in filter and accordingly forward and redirect , if two conditions are met , then it will create a problem .

To avoid this , you should have a return statement , or avoid redirecting or forwarding request , or these kind of things should be done by the last filter in the filter chain.

The apache Tomcat 7.x gives a more detailed description in error stack trace like this :


HTTP Status 500 - Cannot call sendRedirect() after the response has been committed

type Exception report

message Cannot call sendRedirect() after the response has been committed

description The server encountered an internal error 
(Cannot call sendRedirect() after the response has been committed) that prevented it from fulfilling this request.

exception

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
 org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:483)
 TestFilter.doFilter(TestFilter.java:42)
Post comments and suggestions !!!

Tuesday, 21 May 2013

Textual description of firstImageUrl

No Name Matching localhost found Error : Tomcat and CAS configuration

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching localhost found
This error occurs when we try to connect to https enabled web service using standalone java program for localhost configuration.
This Post provides the solution by adding javax.net.ssl.HostnameVerifier in the java program.
But , sometimes we can not change the code because of third party code restriction . For example , setting up and configuring CAS. CAS also uses http client to connect to the CAS server war application deployed on server.
To overcome this problem , we can import the certificate for localhost in our java environment by following these simple steps :
First of all , create a keystore by using keytool present in your $JDK_HOME/bin directory.
keytool -genkey -alias tomcat -keystore ./keystore -keyalg RSA

Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  localhost
What is the name of your organizational unit?
  [Unknown]:  localhost
What is the name of your organization?
  [Unknown]:  localhost
What is the name of your City or Locality?
  [Unknown]:  localhost
What is the name of your State or Province?
  [Unknown]:  localhost
What is the two-letter country code for this unit?
  [Unknown]:  in
Is CN=localhost, OU=localhost, O=localhost, L=localhost, ST=localhost, C=in correct?
  [no]:  yes


make sure you enter localhost for first name and last name .
Now copy the generated key to tomcat home directory and configure the tomcat to enable SSL like this :
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
 maxThreads="150" scheme="https" secure="true" keystoreFile="keystore" keystorePass="changeit"
               clientAuth="false" sslProtocol="TLS" />

Now restart tomcat and you should be able to access https on https://localhost:8443 Now export the certificate of this localhost:8443 to disk using your browser.(In mozilla you will find option to export in certificate viewer tab )
Now use the keytool in your jdk to import this certificate in your jvm certificates.
keytool -importcert -alias tomcat -file ${PATH_WHERE_CERT_IS_EXPORTED} -keystore $JDK_HOME\jre\lib\security\cacerts

That's it . Now you can run your standalone java program without modifying it.
Post your comments and Suggestions !!!


Monday, 11 March 2013

Textual description of firstImageUrl

Why Do we need ContextClassLoader

ContextClassLoader is the subject which is very little known and very useful.

Some basics about class and classloader in java :

Every Object in java has associated Class Object which defines its class meta data and stored in a separate space called perm gen in java memory. infect, every type in java[primitive or user defined] has a class objects ,even keyword void in java has a class object.
Classloader are the objects which loads the class from file system and converts the byte code in the file to Class Object.It preserves the class object in the cache , so the classloader doesn't have to load and define it again. Classloaders in java follows hierarchical structure, where a child classloader first checks whether the class is already loaded by parent classloader, if not then only it loads the class.

ContextClassLoader :

Image here represnts a simple classloader architecture for a container , this is very simple architecture and the actual architecture of the server may be more complex than this.

So the top three classloader are java defined classloader which loads classes from rt.jar , ext library and classpath respectively.and below that server classloader are present which loads server specific classes and then application specific classes .
For each application , server creates a new classloader. because of this hierarchical structure that classloader follows [untill somebody creates a custom classloader which deliberately breaks classloader rules], parent classloader can never see the classes which are loaded by child classloader. Now in some condition we need to load class which is loaded by child classloader , in to the class which is loaded by parent classloader.
For example , in JNDI classes which are loaded by java classloaders , we need to load web application specific classes.That is where ContextClassloader comes in to the picture , which provides a hook in to other classloaders which are otherwise not accessible to higher level classloaders . So every server sets it's web application classloader in the Thread class , so that other classes can get hold of this classloader.
Ref

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

Thursday, 13 December 2012

Textual description of firstImageUrl

Steps to deploy Mule ESB Application on Jboss 7.1.1


first create WAR application structure of mule application

structure of war file is like this

application root
  WEB-INF
    classes
    lib
    web.xml
  META-INF

put all your java classes and along with configuration files like mule-config.xml in WEB-INF/classes folder .
put all mule specific and application jars in WEB-INF/lib folder.
modify web.xml and add following configuration in it.

<context-param>
    <param-name>org.mule.config</param-name>
    <param-value>mule-config.xml</param-value>
</context-param>

<listener>
    <listener-class>org.mule.config.builders.MuleXmlBuilderContextListener</listener-class>
</listener>




to configure jboss to deploy mule application , we have to remove jaxr and jaxrs modules from jboss

go to standalone/configuration/standalone.xml

remove jaxr and jaxrs modules from file

remove extensions tag as well as subsystmes tag of jaxr ,jaxrs

if jboss is not able to find jdk specific classes and if you are getting classnotfoundexception then you have to add that path in


$JBOSS_HOME/modules/sun/jdk/main/module.xml .

for example getting ClassNotFoundException for com.sun.net.ssl.internal.ssl.Provider class , (Mule uses this class internally )

then we have to add the path <path name="com/sun/net/ssl/internal/ssl"/>  to $JBOSS_HOME/modules/sun/jdk/main/module.xml .


Configure Servlet Endpoint in mule-config.xml

for example

 <flow name="servletTestFlow2" doc:name="servletTestFlow2">
        <servlet:inbound-endpoint path="addtweet" responseTimeout="10000" doc:name="Servlet"/>
        <echo-component doc:name="Echo"/>
   </flow>

in this Path is the servlet request url path where this flow will be mapped

add servlet mapping in your web.xml like this


<servlet>
    <servlet-name>muleReceiverServlet</servlet-name>
    <servlet-class>org.mule.transport.servlet.MuleReceiverServlet</servlet-class>
    <load-on-startup />
  </servlet>

  <servlet-mapping>
    <servlet-name>muleReceiverServlet</servlet-name>
    <url-pattern>/mule/*</url-pattern>
  </servlet-mapping>


now all the requests like /${context}/mule/addtweet will go to this servletTestFlow2 .





Saturday, 6 October 2012

Textual Representation of logo

keep alive connections

HTTP 1.1 introduced keep alive connections and request pipe lining . In HTTP 1.0 every connection was closed after response is served to user , so for every new request , user has to establish connection with server and then send the request . In keep alive connections , server keep the connection alive for a specific time which is called keep alive timeout . So the socket connection which is created by server , will be active for keep alive time out period . If this keep alive timeout expires , then server closes this connection.

Http Header which is used for this is Connection : Keep-Alive . So, keep alive connection is very efficient because client does not need to establish the connection every time .In server if a worker thread is assigned to each connection , then this thread will be busy for keep alive time out period , even if there is not activity by client . so , we can not set keep alive time out value to a large number . for example server is configured like this :
worker thread : 100
keep alive connections :100
keep alive time out : 60 seconds

when a user sends a request , server creates a connection and assigns a worker thread. But after sending one request , user don't send next requests , this thread will be idle in server , waiting for next keep alive request for 60 seconds .