Custom Http Servlet Response Wrapper

One day, I had a requirement to change the response before it sent to the client. My application contains many servlet and jsp files so I needed some mechanism to change the response without updating each and every servlet and jsp. I found that this can be handled via custom http servlet response. In this post, I create sample wrapper and filter to give you a brief idea that how I have achieved this. In this sample wrapper, I convert response content to upper case but trust me, a lot can be done here.

Custom response wrapper class

Refer below sample response wrapper class which extends HttpServletResponseWrapper. It overrides getOutputStream() and getWriter()> methods of the super class. From getWriter() method I create PrintWriter object which wrap the instance variable stringWriter. I have declared stringWriter as an instance variable and I return the reference of the same so whatever is written by the servlet or jsp would be written to this stringWriter. Later we can examine/update the content of stringWriter.

package com.elitejavacoder.wrapper;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
*
* @author Atul Prajapati
*
*/
public class CustomResponseWrapper extends HttpServletResponseWrapper{
	private StringWriter stringWriter;
	private boolean isOutputStreamCalled;

	public CustomResponseWrapper(HttpServletResponse response) {
		super(response);
	}

	@Override
	public ServletOutputStream getOutputStream() throws IOException {
		if (this.stringWriter != null) {
			throw new IllegalStateException("The getWriter() is already called.");
		}
		isOutputStreamCalled = true;
		return super.getOutputStream();
	}

	@Override
	public PrintWriter getWriter() throws IOException {
		if (isOutputStreamCalled) {
			throw new IllegalStateException("The getOutputStream() is already called.");
		}

		this.stringWriter = new StringWriter();

		return new PrintWriter(this.stringWriter);
	}

	public String getResponseContent() {
		if (this.stringWriter != null) {
			return this.stringWriter.toString();
		}
		return "";
	}
}

Sample filter class

Below is the sample filter which I have used to intercept the request so I can customize whatever content is written by the servlet or jsp. In this filter, I check the parameter “custom” which indicates that content should be customized or not. So we can apply the wrapper dynamically and check it’s effect runtime in browser. If the value of the “custom” parameter is true then the response would be converted to upper case otherwise the response wrapper would not be applied hence the response would be returned as it is.

package com.elitejavacoder.filter;

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;

import com.elitejavacoder.wrapper.CustomResponseWrapper;

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

	public void init(FilterConfig filterConfig) throws ServletException {
	}

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

		boolean custom = false;
		if (request instanceof HttpServletRequest && response instanceof HttpServletResponse && ((HttpServletRequest)request).getParameter("custom") != null) {
			custom = Boolean.parseBoolean(((HttpServletRequest)request).getParameter("custom"));
		}

		if (custom) {
			CustomResponseWrapper wrapper = new CustomResponseWrapper((HttpServletResponse)response);
			filterChain.doFilter(request, wrapper);

			String originalResponse = wrapper.getResponseContent();
			System.out.println("Original Response: " + originalResponse);

			// Let's convert response content to upper case
			response.getWriter().print(originalResponse.toUpperCase());
		}
		else {
			filterChain.doFilter(request, response);
		}
	}

	public void destroy() {
	}
}

I have posted a complete sample application along with the instructions to run it on github. It is available at https://github.com/atulprajapati/samples/tree/master/custom-http-servlet-response-wrapper. You can try it yourself. Your questions and comments are welcome.

How to install Docker on Ubuntu

To explore Docker, I have installed it on VirtualBox running with Ubuntu 14.04. I have followed following steps to install Docker.

Run below command to add Docker repository key to local keychain.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9

Run below commands to install docker.

sudo sh -c "echo deb http://get.docker.com/ubuntu docker main > /etc/apt/sources.list.d/docker.list" 
sudo apt-get update 
sudo apt-get install lxc-docker

To verify installation, let’s print version information using following command.

sudo docker version

The output should be similar to below. It might be different as it depends on docker version.

Client version: 1.5.0
Client API version: 1.17
Go version (client): go1.4.1
Git commit (client): a8a31ef
OS/Arch (client): linux/amd64
Server version: 1.5.0
Server API version: 1.17
Go version (server): go1.4.1
Git commit (server): a8a31ef

I hope this post might help someone.

How to minify javascript and css files using maven plugin

It is advisable that all the production javascript and css files are minified and most of the javascript libraries do this. This post explains how to minify javascript and css files using maven plugin.I have minified sample javascript and css files using minify-maven-plugin. This sample application uses 1.7.2 version of minify-maven-plugin which requires jdk 7 so it does not work with jdk 6 or prior versions.

In this sample application, I have used embedded jetty web container so minification can be tested from browser as well. Please note that I have tested this sample application on windows with jdk 7 64 bit and maven 3.0.4.

This application contains two sample javascript and two sample css files which will be minified using minify-maven-plugin.

sample1.css

H1 {
	color: white;
	background: teal;
	FONT-FAMILY: arial, helvetica, lucida-sans, sans-serif;
	FONT-SIZE: 18pt;
	FONT-STYLE: normal;
	FONT-VARIANT: normal
}
H2 {
	COLOR: #000000;
	FONT-FAMILY: lucida-sans, sans-serif;
	FONT-SIZE: 12pt;
	FONT-STYLE: normal;
	FONT-VARIANT: normal
}

sample2.css

body {
	COLOR: #000000;
	FONT-FAMILY: lucida-sans, sans-serif; FONT-SIZE: 18pt;
	FONT-STYLE: normal;
	FONT-VARIANT: normal;
	background-color:yellow;
}

Above two sample css files are placed under the $sample-web-appsrcmainwebappstyles.

sample1.js

function popupFromSample1() {
	alert("Hello World from sample 1");
}

sample2.js

function popupFromSample2() {
	alert("Hello World from sample 2");
}

Above two sample javascript files are placed under the $sample-web-app\src\main\webapp\scripts.

I have also created index.jsp page as below to test minified javascripts and css files.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">

<link rel="stylesheet" type="text/css" href="/styles/minified/sample1.css" />
<link rel="stylesheet" type="text/css" href="/styles/minified/sample2.css" />

<script type="text/javascript" src="/scripts/minified/sample1.js"></script>
<script type="text/javascript" src="/scripts/minified/sample2.js"></script>

<html>
	<body>
		<H1>Header 1!</H1>
		<H2>Header 2!</H2>

		Something in body

		<button type="button" onclick="popupFromSample1()">Try popup from sample1.js</button>
		<button type="button" onclick="popupFromSample2()">Try popup from sample2.js</button>
	</body>
</html>

Refer following pom.xml.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>com.elitejavacoder</groupId>
<artifactId>sample-web-app</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Sample Maven Web App</name>
<url>http://maven.apache.org</url>

	<build>
		<finalName>sample-web-app</finalName>
		<plugins>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>maven-jetty-plugin</artifactId>
				<version>6.1.15</version>
				<configuration>
					<contextPath>/</contextPath>
					<scanIntervalSeconds>2</scanIntervalSeconds>
					<webAppSourceDirectory>${basedir}/target/sample-web-app</webAppSourceDirectory>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<warSourceExcludes>/styles/*.css,/scripts/*.js</warSourceExcludes>
				</configuration>
			</plugin>

			<plugin>
				<groupId>com.samaxes.maven</groupId>
				<artifactId>minify-maven-plugin</artifactId>                   
				<version>1.7.2</version>
				<executions>
					<execution>
						<id>minify</id>
						<phase>process-resources</phase>
						<goals>
							<goal>minify</goal>
						</goals>
						<configuration>
							<charset>utf-8</charset>
							<jsEngine>CLOSURE</jsEngine>
							<skipMerge>true</skipMerge>
							<nosuffix>true</nosuffix>

							<cssSourceDir>styles</cssSourceDir>
							<cssTargetDir>styles/minified</cssTargetDir>
							<cssSourceIncludes>
								<cssSourceInclude>*.css</cssSourceInclude>
							</cssSourceIncludes>

							<jsSourceDir>scripts</jsSourceDir>
							<jsTargetDir>scripts/minified</jsTargetDir>
							<jsSourceIncludes>
								<jsSourceInclude>*.js</jsSourceInclude>
							</jsSourceIncludes>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

In the above pom.xml, minify-maven-plugin is the only plugin required and responsible for minification of javascript and css files. maven-jetty-plugin is used to test this application with jetty web container and maven-war-plugin is used to exclude original javascript and css files from the packaged WAR file.

Take a look at the configuration provided for minify-maven-plugin. I have created minified files in a separate directory (refer <cssTargetDir> and <jsTargetDir> elements) as I don’t want any suffix to be added to minified files. I have specified <nosuffix>true</nosuffix> so name of minified file remains same as source file otherwise it creates *.min.css or *.min.js (i.e. sample1.min.css, sample1.min.css).

I have specified <cssTargetDir> and <jsTargetDir> for resultant minified files otherwise minified files are created in the same directory as source file. Please be informed that <nosuffix> with true value won’t create minified files if target directory is not specified, to avoid file overwriting issue.

In the above sample pom file, I have minified all the javascript and css files available in the directory however you can minify some specific files as described below (replace <cssSourceIncludes> element with the following).

<cssSourceFiles>
	<cssSourceFile>sample1.css</cssSourceFile>
	<cssSourceFile>sample2.css</cssSourceFile>
</cssSourceFiles>

<jsSourceFiles>
	<jsSourceFile>sample1.js</jsSourceFile>
	<jsSourceFile>sample2.js</jsSourceFile>
</jsSourceFiles>

One more thing, note that I have specified true for the <skipMerge>true</skipMerge> which stops the plugin to create one single(one merged file for css and one for javascript) file by combining all the files in one. The default value for skipMerge is false so it creates one style.css for all the css files and one script.js file for all the javascript files. If you do not like these names then you can specify merged file names of your choice using jsFinalFile and cssFinalFile element under plugin configuration.

Now run the mvn clean install –DskipTests from command propmpt, check your generated war file. It should have minified javascript and css files.

Run application in Jetty and test from the browser.

Run mvn jetty:run command from command prompt from project base directory. It deploys war file to embedded web container and which will be accessible at http://127.0.0.1:8080/index.jsp.

Now you can check that javascripts and css are minified or not by accessing the following urls.

http://127.0.0.1:8080/styles/minified/sample1.css – Returns minified css as below:

H1{color:white;background:teal;FONT-FAMILY:arial,helvetica,lucida-sans,sans-serif;FONT-SIZE:18pt;FONT-STYLE:normal;FONT-VARIANT:normal}H2{COLOR:#000;FONT-FAMILY:lucida-sans,sans-serif;FONT-SIZE:12pt;FONT-STYLE:normal;FONT-VARIANT:normal}

http://127.0.0.1:8080/styles/minified/sample2.css – Returns minified css as below:

body{COLOR:#000;FONT-FAMILY:lucida-sans,sans-serif;FONT-SIZE:18pt;FONT-STYLE:normal;FONT-VARIANT:normal;background-color:yellow}

http://127.0.0.1:8080/scripts/minified/sample1.js – Returns minified javascript as below:

function popupFromSample1(){alert("Hello World from sample 1")};

http://127.0.0.1:8080/scripts/minified/sample2.js – Returns minified javascript as below:

function popupFromSample2(){alert("Hello World from sample 2")};

If you have any query on this then feel free to ask me by putting comment below.

Sample application is available on GitHub at https://github.com/elitejavacoder/maven-minify-javascript-and-css

Maven – Run web project in Jetty

Jetty has a slogan, “Don’t deploy your application in Jetty, deploy Jetty in your application.” and that is really amazing thing specially when we are in development phase. It makes developer’s life more easy. In this post I will explain you how to run jetty web server in your web application. I will create a sample web application and then I will run that application in jetty by embedding jetty in application. I will use maven-jetty-plugin to demonsrate this.

Sample web application

Create one directory in your file system. In my case I have created directory with name “sample-web-app” in my file system.

Create pom.xml under root directory (i.e. under sample-web-app directory) as described below.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.elitejavacoder</groupId>
	<artifactId>sample-web-app</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>Sample Maven Web App</name>
	<url>http://maven.apache.org</url>

	<build>
		<finalName>sample-web-app</finalName>
		<plugins>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>maven-jetty-plugin</artifactId>
				<version>6.1.15</version>

				<configuration>
					<contextPath>/</contextPath>
					<scanIntervalSeconds>2</scanIntervalSeconds>
					<webAppSourceDirectory>${basedir}/target/sample-web-app</webAppSourceDirectory>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Create web.xml file under $sample-web-appsrcmainwebappWEB-INF as described below.


Jetty test web application

Create sample index.jsp file under $sample-web-appsrcmainwebapp directory as below.

<html>
	<body>
		<h2>Hello World - This page is served by Jetty!</h2>
	</body>
</html>

Run following maven command from your root directory (i.e. sample-web-app directory) to build your application.

mvn clean install

Run web application with Jetty

Now run following maven command from your root directory (i.e. sample-web-app directory) to start jetty with your application.

mvn jetty:run

Now access “http://127.0.0.1:8080/index.jsp” url from your browser which will display content of index.jsp page we have created as below.

Hot deployment with Jetty

Now update sample index.jsp file which we have created under $sample-web-appsrcmainwebapp directory as below.

<html>
	<body>
		<h2>Hello World - This page is served by Jetty!</h2>
		<h2>Testing hot deployment</h2>
	</body>
</html>

Now access “http://127.0.0.1:8080/index.jsp” url from your browser which will display updated content of index.jsp page as below without restarting the server.

MySql – Take/Restore database backup


This post will explain how to take database backup from mysql as well as how to restore database backup to mysql from console using commands.

How to take mysql database dump/backup from console

Open command window. Go to bin directory under your mysql installation. In my case it is C:Program FilesMySQLMySQL Server 5.1bin.

mysqldump.exe --skip-lock-tables -h127.0.0.1 -udbuser -pdbpassword mydatabase > C:db_backupmydatabase_28_11_2013.dump

How to restore mysql database dump/backup from console

Open command window. Go to bin directory under your mysql installation. In my case it is C:Program FilesMySQLMySQL Server 5.1bin.

mysql -udbuser -pdbpassword mydatabase < C:db_backupmydatabase_28_11_2013.dump