a cup of java

Here’s your cup of hot java & web 2.0 cookies. Enjoy it.

Posts Tagged ‘server

An interesting find ! Google App Engine with Java support

without comments

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/

Written by Subinkrishna G

August 2, 2009 at 8:17 pm

Code: ByteStreamResponseWrapper

without comments

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.

Written by Subinkrishna G

April 21, 2009 at 11:12 am

How-To: Create a WAR file using ANT

without comments

In one of my previous posts I mentioned about building a JAR using ANT.  This post – building a WAR (Web Application Archive) – is just an add-on to that.

Structure of a WAR file

Application.war
|-- META-INF
|  |-- manifest.mf
|-- WEB-INF
|  |-- web.xml   - deployment descriptor
|  |-- classes   - class files organized in packages
|  |-- lib       - other libraries
|
|-- <other files, directories etc.>

Deployment descriptor
This is a sample deployment descriptor from Java Servlet Specification version 2.4. Get the descriptor (.pdf)

Build file

<project name="my.enterprise.project" default="build.my.war">
<property name="deploy.dir" value="/my/deploy/dir" />
<property name="file.name" value="Application.war" />
  <target name="build.my.war">
    <fileset dir="contents">
      <include name="**/*"/>
    </fileset>
    <war destfile="${file.name}" webxml="conf/web.xml">
      <classes dir="bin" />
    </war>
    <echo>Copying ${file.name}...</echo>
    <copy file="${file.name}" todir="${deploy.dir}" />
    <delete file="${file.name}" />
  </target>
</project>

The above build file assumes that all the non-java resources and JSPs are within the “contents” directory. The build file will pick the class files from the “bin” directory within the base. Here the build file is not compiling existing source files. To compile Java files there is another ANT task -  javac.

<javac srcdir="src" destdir="bin" classpathref="application.classpath"/>

Add the javac task before the war task in the build file.

Defining the class path

<path id="application.classpath">
   <fileset dir="/path/to/my/lib">
      <include name="javax.servlet.jar"/>
   </fileset>
</path>

Define the path before the target – build.my.war.

Read more
http://ant.apache.org/manual/CoreTasks/war.html
http://ant.apache.org/manual/CoreTasks/javac.html
http://ant.apache.org/manual/dirtasks.html

Written by Subinkrishna G

February 12, 2009 at 10:31 am

Another JBoss 5 hack by Venu

without comments

jbosscorp_logo

Venu had another JBoss hack and he was able to fix one more issue that may bubble up during the migration from JBoss 4.x to 5. This time found out how solve “Adding multiple last resources is disallowed. Current resource is ….” exception which happens while trying to access an EJB from a different EAR with in a transaction and trying to commit that transaction.

Read the article here

Written by Subinkrishna G

February 11, 2009 at 4:22 pm

How-to: Write a simple servlet filter

with 6 comments

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.

Written by Subinkrishna G

February 11, 2009 at 12:14 pm