Solved

How to add a cookie using Java filters

Posted on 2011-09-22
7
356 Views
Last Modified: 2012-05-12
Hello,

I need to add a cookie from a filter. I have created a very simple class. Please see attached file. All it does is to cast the ServletResponse object passed to doFilter method and try to add a cookie with HttpServletResponse object. However, I get an exception. Please, could some one help me to add a cookie from a filter?

Thanks

AppFilter.txt
0
Comment
Question by:vielkacarolina1239
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36584764

I am not sure it applies to your situation, but maybe it makes sense to read it if you ahven't seen it:
http://stackoverflow.com/questions/2158548/adding-a-cookie-to-the-response-in-java-after-the-header-has-been-flushed

But you see an Exception (as opposed to those folks); so you probably have some details of where and what is happneing
0
 
LVL 27

Expert Comment

by:rrz
ID: 36584772
Your attached code didn't retain it's formatting. Please post your code in a code box provided with comment form.
>I get an exception.  
Please show us the error message or stacktrace.
0
 

Author Comment

by:vielkacarolina1239
ID: 36584814
Please see below code snippet

Thanks,
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Filters;

import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
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.annotation.WebFilter;


import javax.servlet.http.*;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebFilter(filterName = "AppFilter", urlPatterns =
{
   "/*"
})
public class AppFilter implements Filter
{
   
   HttpServletRequest httpRequest = null;
   HttpServletResponse httpResponse = null;
   
      
   private static final boolean debug = true;
   
   private FilterConfig filterConfig = null;
   
   public AppFilter()
   {
   }   
   
   private void doBeforeProcessing(ServletRequest request, ServletResponse response)
      throws IOException, ServletException
   {
      try
      {
         if (debug)
         {
            log("AppFilter:DoBeforeProcessing");
         }

      }
      catch(Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());
      }
   }   
   
   private void doAfterProcessing(ServletRequest request, ServletResponse response)
      throws IOException, ServletException
   {
      try
      {
         if (debug)
         {
            log("AppFilter:DoAfterProcessing");
         }
      }
      catch(Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());
      }
   }


   public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain)
      throws IOException, ServletException
   {
      

      if (debug)
      {
         log("AppFilter:doFilter()");
      }

      httpRequest = (HttpServletRequest)request;
      httpResponse = (HttpServletResponse)response;


      HttpSession session = httpRequest.getSession();
      
      String cookiePath = httpRequest.getContextPath();

      Cookie myCookie = null;
     

      myCookie = new Cookie("application","cookieVal");
      

      myCookie.setMaxAge(999999999);         


      httpResponse.addCookie(myCookie);

      doBeforeProcessing(request, response);

      Throwable problem = null;
      try
      {
         chain.doFilter(request,httpResponse);         
      }
      catch (Throwable t)
      {
         
         problem = t;
         t.printStackTrace();         
      }

      doAfterProcessing(request, response);
      
      if (problem != null)
      {
         if (problem instanceof ServletException)
         {
            throw (ServletException) problem;
         }
         if (problem instanceof IOException)
         {
            throw (IOException) problem;
         }
         sendProcessingError(problem, response);
      }

   }

   
   public FilterConfig getFilterConfig()
   {      
      return (this.filterConfig);
   }

   
   public void setFilterConfig(FilterConfig filterConfig)
   {
      try
      {
      this.filterConfig = filterConfig;
      }
      catch(Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());
      }
   }


   public void destroy()
   {      
   }

   public void init(FilterConfig filterConfig)
   {      
      try
      {
         this.filterConfig = filterConfig;
         if (filterConfig != null)
         {
            if (debug)
            {            
               log("AppFilter:Initializing filter");
            }
         }
      }
      catch(Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());
      }
   }

   
   @Override
   public String toString()
   {
      StringBuffer sb = new StringBuffer("AppFilter(");
      
      try
      {
         if (filterConfig == null)
         {
            return ("AppFilter()");
         }

         sb.append(filterConfig);
         sb.append(")");
      }
      catch(Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());   
      }
      
      return (sb.toString());
   }
   
   private void sendProcessingError(Throwable t, ServletResponse response)
   {
      String stackTrace = getStackTrace(t);      
      
      if (stackTrace != null && !stackTrace.equals(""))
      {
         try
         {
            response.setContentType("text/html");
            PrintStream ps = new PrintStream(response.getOutputStream());
            PrintWriter pw = new PrintWriter(ps);            
            pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N

            // PENDING! Localize this for next official release
            pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");            
            pw.print(stackTrace);            
            pw.print("</pre></body>\n</html>"); //NOI18N
            pw.close();
            ps.close();
            response.getOutputStream().close();
         }
         catch (Exception ex)
         {
            System.out.println("Error in AppFilter.java : " + ex.getMessage());
         }
      }
      else
      {
         try
         {
            PrintStream ps = new PrintStream(response.getOutputStream());
            t.printStackTrace(ps);
            ps.close();
            response.getOutputStream().close();
         }
         catch (Exception ex)
         {
            System.out.println("Error in AppFilter.java : " + ex.getMessage());
         }
      }
   }
   
   public static String getStackTrace(Throwable t)
   {
      String stackTrace = null;
      try
      {
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         t.printStackTrace(pw);
         pw.close();
         sw.close();
         stackTrace = sw.getBuffer().toString();
      }
      catch (Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());
      }
      return stackTrace;
   }
   
   public void log(String msg)
   {
      try
      {
         filterConfig.getServletContext().log(msg);      
      }
      catch(Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());
      }
   }
}

Open in new window

0
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 
LVL 47

Expert Comment

by:for_yan
ID: 36584820
And waht about the exception stacktrace ?
0
 

Author Comment

by:vielkacarolina1239
ID: 36584838
please see below exception in code snippet. This exception is issued once the code reaches: chain.doFilter(request,httpResponse);    

Thanks,
SEVERE: java.lang.ArrayIndexOutOfBoundsException
	at java.lang.System.arraycopy(Native Method)
	at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:201)
	at com.sun.grizzly.http.SocketChannelOutputBuffer.realWriteBytes(SocketChannelOutputBuffer.java:290)
	at com.sun.grizzly.tcp.http11.InternalOutputBuffer$OutputStreamOutputBuffer.doWrite(InternalOutputBuffer.java:898)
	at com.sun.grizzly.tcp.http11.filters.IdentityOutputFilter.doWrite(IdentityOutputFilter.java:159)
	at com.sun.grizzly.tcp.http11.InternalOutputBuffer.doWrite(InternalOutputBuffer.java:658)
	at com.sun.grizzly.tcp.Response.doWrite(Response.java:685)
	at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:422)
	at com.sun.grizzly.util.buf.ByteChunk.flushBuffer(ByteChunk.java:453)
	at com.sun.grizzly.util.buf.ByteChunk.append(ByteChunk.java:375)
	at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:452)
	at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:439)
	at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:160)
	at org.apache.catalina.servlets.DefaultServlet.copyRange(DefaultServlet.java:2229)
	at org.apache.catalina.servlets.DefaultServlet.copy(DefaultServlet.java:1965)
	at org.apache.catalina.servlets.DefaultServlet.serveResource(DefaultServlet.java:987)
	at org.apache.catalina.servlets.DefaultServlet.doGet(DefaultServlet.java:413)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
	at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
	at Filters.AppFilter.doFilter(AppFilter.java:116)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
	at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
	at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
	at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
	at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
	at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
	at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
	at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
	at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
	at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
	at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
	at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
	at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
	at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)

Open in new window

0
 
LVL 27

Accepted Solution

by:
rrz earned 500 total points
ID: 36585011
>This exception is issued once the code reaches: chain.doFilter(request,httpResponse);  
I am guessing that the problem is not in your Filter. To test, remove the Filter, does your web app run without error when your Filter is not called ?
0
 

Author Closing Comment

by:vielkacarolina1239
ID: 36598918
I found the issue. It was similar to what you said. A store procedure was blowing up. Got it fix. Thanks.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Running JavaFX on JDeveloper 12C 1 77
java example issue 5 44
Fast way to search item into Java Array (Rhino compatible) 2 39
Regarding swagger API 1 36
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question