Tagged: servlet Toggle Comment Threads | Keyboard Shortcuts

  • Subinkrishna Gopi 8:17 pm on August 2, 2009 Permalink |
    Tags: app engine, , free, , hosting, , , , servlet   

    An interesting find ! Google App Engine with Java support 

    image

    I was just going through code.google.com, and just find a link titled “App Engine”. I was not at all surprised as they do this every time. With Google something is new every time. I went on reading. Oh God! Free J2EE app engine where we can host our archives ! This is one of the coolest things I was waiting to happen. The server where I hosted (and I’m still with them) my website does not have Java support and I spend many hours in writing Php codes after many hours of searching and testing, which I could have done in minutes with Java. And most importantly it’s almost FREE ! We have to pay them only if we are crossing the specified bandwidth & page view limits.

    We can write code with Google’s Eclipse plug-in (with GWT support !), test them with in Eclipse and deploy them from Eclipse! Isn’t that cool? All you need is to have a Google account and just get it done. We can have up to nine applications each with a unique URL to access and we can even link them with our Google Apps too.

    Check this video: Get an overview of App Engine’s new Java runtime and see a demo of a sample app from creation to deployment.

    URL: http://www.youtube.com/watch?v=P3GT4-m_6RQ

    • For me this is nicest offer from Google in the recent times. I don’t know whether all of you are going to agree with this. But at least I’m happy. Hope all of you will find it nice.

    Google App Engine: http://code.google.com/appengine/
    FAQ: http://code.google.com/appengine/kb/
    App Engine Blog: http://googleappengine.blogspot.com/
    Getting started: http://code.google.com/appengine/docs/java/gettingstarted/

    Advertisements
     
  • Subinkrishna Gopi 11:12 am on April 21, 2009 Permalink |
    Tags: , filter, , , , servlet   

    Code: ByteStreamResponseWrapper 

    Maxi was asking for the source code of ByteStreamResponseWrapper. This is related to this post (How to: write a servlet filter).

    package subin.rnd.enterprise.servlet.wrapper;
    
    import java.io.ByteArrayOutputStream;
    import java.io.PrintWriter;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpServletResponseWrapper;
    import subin.rnd.enterprise.servlet.io.ServletOutputStreamImpl;
    
    public class ByteStreamResponseWrapper
    extends HttpServletResponseWrapper
    {
        private ByteArrayOutputStream byteStream;
    
        public ByteStreamResponseWrapper(HttpServletResponse response)
        {
            super(response);
        }
    
        @Override
        public ServletOutputStream getOutputStream()
        {
            ServletOutputStreamImpl outputStream = null;
    
            this.byteStream =  (null == this.byteStream)
                ? new ByteArrayOutputStream() : this.byteStream;
            outputStream = new ServletOutputStreamImpl(this.byteStream);
    
            return (outputStream);
        }
    
        @Override
        public PrintWriter getWriter()
        {
            PrintWriter printWriter = null;
    
            this.byteStream =  (null == this.byteStream)
                ? new ByteArrayOutputStream() : this.byteStream;
            printWriter = new PrintWriter(this.byteStream);
    
            return (printWriter);
        }
    
        @Override
        public String toString()
        {
            return ((null == this.byteStream)
                    ? null : new String(this.byteStream.toByteArray()));
        }
    
        public byte[] toBytes()
        {
            return ((null == this.byteStream)
                    ? null : this.byteStream.toByteArray());
        }
    }
    

    Then there is ServletUtility & ServletOutputStreamImpl.

    Code: ServletUtility

    package subin.rnd.enterprise.servlet.util;
    
    import java.io.OutputStream;
    import javax.servlet.ServletResponse;
    
    public class ServletUtility
    {
        /**
         * Writes the bytes to the {@link OutputStream}
         *
         * @param response
         * @param bytes
         */
        public static void write(ServletResponse response, byte[] bytes)
        {
            int contentLength = -1;
            OutputStream outputStream = null;
    
            if ((null != response) &&
                (null != bytes) &&
                (bytes.length > 0))
            {
                contentLength = bytes.length;
    
                try
                {
                    response.setContentLength(contentLength);
                    outputStream = response.getOutputStream();
                    outputStream.write(bytes);
                }
                catch (Exception exception)
                {
                    outputStream = null;
                }
                finally
                {
                    try
                    {
                        if (null != outputStream) outputStream.close();
                    }
                    catch (Exception e){}
                }
            }
        }
    }
    

    ServletOutputStreamImpl is an implementation of ServletOutputStream. I think I don’t need to put the source code of it.

     
    • spablos 7:50 pm on August 13, 2012 Permalink

      ServletOutputStreamImpl is an implementation of ServletOutputStream. I think I don’t need to put the source code of it.

      Can you please this (ServletOutputStreamImpl) implementation too?

  • Subinkrishna Gopi 12:14 pm on February 11, 2009 Permalink |
    Tags: , , , , servlet, servlet filter, , , ,   

    How-to: Write a simple servlet filter 

    What is a filter?
    From the JSR 154 specification,

    A filter is a reusable piece of code that can transform the content of HTTP requests, responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.

    How to write a filter?
    We can create a filter by writing a new class which implements javax.servlet.Filter. We need to specify the filters in the deployment descriptor so that the container can create a filter chain to process the request/response.

    The filters in deployment descriptor:

    <web-app>
    	<filter>
    		<filter-name>MyFilter</filter-name>
    		<filter-class>subin.rnd.enterprise.filter.MyFilter</filter-class>
    	</filter>
    	<filter-mapping>
    		<filter-name>MyFilter</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>
    	<filter-mapping>
    		<filter-name>MyFilter</filter-name>
    		<servlet-name>MyServlet</servlet-name>
    		<dispatcher>REQUEST</dispatcher>
    	</filter-mapping>
    </web-app>

    We can have a filter (or a chain of filters) processing the request/response. In the above descriptor, we are linking a filter for a URL pattern as well as for a specific servlet. So in the above case, for MyServlet, the filter will get executed twice as we have mapped the filter MyFilter to all URLs and for MyServlet. So the order of execution will be MyFilter.doFilter() > MyFilter.doFilter() > MyServlet.doGet().

    MyServlet.java

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class MyServlet
    extends HttpServlet
    {
      @Override
      public void doGet(HttpServletRequest request,
        HttpServletResponse response)
      throws ServletException
      {
        System.out.println("doGet()");
        response.setContentType("text/plain");
        ServletUtility.write(response, "Hello world!".getBytes());
      }
    }
    

    MyFilter.java

    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.HttpServletResponse;
    
    public class MyFilter
    implements Filter
    {
      public void destroy()
      {
      }
    
      public void doFilter(ServletRequest request, ServletResponse response,
         FilterChain filterChain)
      throws IOException, ServletException
      {
         System.out.println("doFilter()");
    
         ByteStreamResponseWrapper responseWrapper = null;
         byte[] responseAsBytes = null;
         String processedResponse = null;
    
         // Creating a response wrapper
         responseWrapper = new ByteStreamResponseWrapper(
            (HttpServletResponse) response);
         filterChain.doFilter(request, responseWrapper);
    
         // Process the response
         processedResponse = responseWrapper.toString();
         if (null != processedResponse)
         {
           processedResponse = processedResponse.toUpperCase();
           responseAsBytes = processedResponse.getBytes();
         }
    
         // Writing the response (as bytes) to the servlet output stream
         ServletUtility.write(response, responseAsBytes);
      }
    
      public void init(FilterConfig filterConfig)
      throws ServletException
      {
        // We can initialize a filter using the init-params here
        // (which we defined in the deployment descriptor - web.xml)
      }
    }
    

    Other files
    There are two more Java files – ByteStreamResponseWrapper & ServletUtility. ByteStreamResponseWrapper is an extension of javax.servlet.http.HttpServletResponseWrapper with some methods – toString(), getOutputStream() & getWriter() – overriden. ServletUtility is a utility class to write a byte stream to the servlet output stream.

    Output
    The “Hello world!” from MyServlet is filtered to “HELLO WORLD!”  by MyFilter.

    Fig: Output in browser

    Output
    Fig: Jboss console output

    Jboss Console output

    Note:
    I wanted to put above XML in syntax-highlighted mode; but the WordPress plug-in failed miserably. Tough luck.

     
c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel