Creating a Spring MVC REST WebService

To get started let’s create a simple dynamic web project in Eclipse.

1. Modify web.xml to let it know about Spring

 <servlet-name>springapp</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>

Additional Step: Add Spring Jars or Maven dependencies for Spring- core, aop, context, web and webmvc jars.

2. create springapp-servlet.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:mvc=”http://www.springframework.org/schema/mvc” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:p=”http://www.springframework.org/schema/p” xmlns:context=”http://www.springframework.org/schema/context”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”
>
<!– the application context definition for the springapp DispatcherServlet –>

<mvc:annotation-driven />
<context:annotation-config />

<context:component-scan base-package=”com.kamal.test” />

<!–   <bean name=”/hello.app” class=”com.kamal.test.Hello”/> –>

</beans>

Note that we are using annotation driven implementation. where our package com.kamal.test would be scanned for any available components.

3. Create the service

package com.kamal.test;

import java.io.IOException;
import javax.servlet.ServletException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(“/sample”)
public class SampleService {
@RequestMapping(method = RequestMethod.GET, value=”/details/{id}”)

public @ResponseBody String LepService(@PathVariable(“id”) String id )
throws ServletException, IOException {
String success=”Sucess”;
//Do something here
return success;
}
}

 

Unicode value for your text

 

Following code demonstrate how to get unicode value for your text

public static String getUnicodeText(String original)
{
String unicode=””;
String temp=””;
//Loop through original string and convert each character to unicode equivalent
for( char c : original.toCharArray() ){
temp=Integer.toHexString(c).toUpperCase();
//We do not want to convert space
if(temp.equals(“20″))
{
unicode+=” “;
}
else
{
//For symmetry we will keep unicodes of length 4
while(temp.length()<4)
{
temp=”0″+temp;
}
//Append \\u to let compiler know it is unicode
unicode+=”\\u”+temp;
}
}
//return final unicode string created
return unicode;
}

Submitting Special characters in your Form

If you will try to submit special characters like chinese or spanish text, you will see some junk boxes being submitted to the server. We need to make sure proper encoding, say UTF-8 is being in place. In your HTML (JSP/PHP etc) page, you will need to let browser know that your page works with UTF-8.

<filter>
<filter-name>SessionFilter</filter-name>
<filter-class>com.mysite.SessionFilter</filter-class>
<init-param>
<param-name>PARAMETER_ENCODING</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

In addition, you might want to enforce the settings onto your server to let it know that you are expecting UTF-8 content in request. For example in JBOSS, we will create a filter and enforce UTF-8 content type

And create the filter class like

public class SessionFilter implements Filter {
private String encoding="";

/**
* destroy method to clean up any activities
*/
public void destroy() {
}

/**
* Override the doFilter method to apply any action, in this case setting request encoding
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException
{
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}

/**
* Override init method to set parameter encoding as provided by web.xml
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
if (filterConfig.getInitParameter("PARAMETER_ENCODING") != null)
{
encoding= filterConfig.getInitParameter("PARAMETER_ENCODING");
System.out.println("encoding "+encoding);

}
}

}

Dust me- clean up unused CSS

Recently came accross a legacy code which had a lot of css code and files, which was written over years and most of it was obsolete. Dust-me, firefox plugin helped to figure out all the unused css code. Though I had to traverse all possible flows in the application, but end result was good as few files were identified which were not being used completely and were removed, saving page load time.

Core Dump files slowing down website

For last few days, or rather weeks, my blog was really slow. Infact the site was throwing resource limit error at times. I contacted my webhosting provider, but they just replied they cannot find anything. So I decided to do some investigation on my own.

First step was to check memory and CPU usage, which turned out to be very high, almost 100%. The fishy thing I figured out was disk space usage, which was way above data I have, so I checked the file system. I figured out hundreds of core.XXXXX files. A little googling showed that these were dump files created by Apache for memory dump, in case some error / crash occured. Deleting these extra files did solve the issue.

More info on the topic

https://wordpress.org/support/topic/hacked-with-strange-core-files

https://wordpress.org/support/topic/arrrg-so-many-core-files

http://en.wikipedia.org/wiki/Core_dump

Are you a makkhichoose

We know that future of online shopping is bright in countries like India. With sites like snapdeal, flipkart, amazon, shopclues, jabong, myntra etc, things will heat up further, which will be beneficial for end customer as he will get multiple options.

With Online shopping, people are also moving away from loyalty to one vendor or brand. Earlier we used to go for same shop for various electronics needs, but now before buying we can compare prices and offers on different websites (plus nearby stores). And with this knowledge, there are various player which are ready to help you with comparison among online sites. There are websites like Junglee, which will help you compare various prices, and I recently came across some browser extensions which will help you compare prices on the fly when you are viewing the product itself. Makkhichoose is one such extensions. Though it is not cooked up completely yet (I could see some products on various sites which were not reported correctly), but it definitely shows the where the future of online shopping heading to.

Division problem

Problem statement- 3 divides 111 , 13 divides 111111 etc.. find a number having all one’s which is shortest divisible by a given number which has 3 as its last digit.

Logic- The challenge here is that you will soon run out of limit for int or long if you keep on increasing the number. So the idea is to divide in a way which you used to do on paper for large numbers

13)111111(8547
104
——-
71
65
——–
61
54
———-
71
71
————
0

Start with 1 (or 11) and keep adding one, keep a count of 1s added, divide by the required number unless the reminder is 0.

Implementation
public static void divide(int num)
{
int division=11;
int count=2;
while(true)
{
if(division%num==0)
{
System.out.println("count:"+count);
break;
}
else
{
int remindor=division%num;
division=remindor*10+1;
count++;
}
}
}

InOrder, PreOrder and PostOrder traversal

I had discussed Breadth first and Depth First traversal algorithms sometime back.

There are 3 important traversing algorithms for tress. http://en.wikipedia.org/wiki/Tree_traversal

InOrder
-Travel Left, Travel Root, Travel Right.

PreOrder
-Root, Left, Right

PostOrder
-Left, Right, Root

Here is recursive implemenation
public void inOrder(Node root)
{
if(root.left!=null)
inOrder(root.left);
System.out.println(root.number);
if(root.right!=null)
inOrder(root.right);
}


public void preOrder(Node root)
{

System.out.println(root.number);
if(root.left!=null)
preOrder(root.left);
if(root.right!=null)
preOrder(root.right);
}

public void postOrder(Node root)
{
if(root.left!=null)
postOrder(root.left);
if(root.right!=null)
postOrder(root.right);
System.out.println(root.number);
}