Dec 30, 2012

Exploring Iterator Design Pattern

Intent
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation
Applicability
1. To access an aggregate object's contents without exposing its internal representation.
2. To support multiple traversals of aggregate objects.
3. To provide a uniform interface for traversing different aggregate structures (support polymorphic iteration).
In this post, we will be dealing only with the External Iterators. A typical ExternalIterator interface is as such
package com.devfaqs.designpatterns;

public interface ExternalIterator<E>
{
    public boolean hasNext();
    public E next();
}

Read more ...

Dec 28, 2012

Spring Framework - Autowiring a map, list or array using Annotation

You can auto-wire a particular property in spring, using @Autowired annotation. For using @Autowired annotation, you will have to register AutowiredAnnotationBeanPostProcessor bean instance in the spring IOC container

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
OR
You can simply include the <context:annotation-config /> element in your bean configuration file. The <context:annotation-config /> automatically registers an instance of AutowiredAnnotationBeanPostProcessor for you

For including <context:annotation-config /> element, you need to include context namespace in the bean definition file
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  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/context 
  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

Auto wiring is supported for
1. Constructors
2. Setter Methods
3. Arbitrary Methods
4. Fields

Read more ...

Dec 26, 2012

Advantages of Base64 Encoding

Base64 encoding is a technique used for converting binary data into blocks of printable ASCII characters. The Base64 encoding algorithm uses a special conversion table to assign one of the 64 ASCII characters to every 6 bits of the bytestream. That is to say, a binary stream is divided into blocks of six bits and each block is mapped to an ASCII character. The ASCII character with the value of 64 (character =) is used to signify the end of the binary stream.

Advantages
1. 7 Bit ASCII characters are safe for transmission over the network and between different systems
2. SMPT protocol for emails supports only 7 Bit ASCII Characters. Base64 is the commonly used technique to send binary files as attachments in emails.

Disadvantages
1. Base64 encoding bloats the size of the original binary stream by 33 percent
2. Encoding/Decoding process consumes resources and can cause performance problems

Read more ...

Dec 24, 2012

Spring Framework - Injecting java properties

In this example we demonstrate how to inject Properties in our application.

The bean configuration file for injecting properties

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  <bean id="databaseConnectionPool" class="com.examples.spring.SQLConnectionPool">
    <property name="properties">
        <props>
            <prop key="connections">5</prop>
            <prop key="timeout">3600</prop>
        </props>
    </property>
  </bean>
</beans>

The two properties are defined for the SQLConnectionPool class. These properties are injected using the setProperties setter method

Read more ...

Spring Framework - Injecting a Map

In this example we will try to populate employees map using spring's setter injection.

Bean Configuration File

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  <bean id="myCompany" class="com.examples.spring.Company">
    <property name="name" value="myWorld" />
    <property name="employees">
      <map>
        <entry>
          <key>
            <value>pankaj</value>
          </key>
          <bean class="com.examples.spring.Employee">
            <constructor-arg name="name" value="Pankaj Tiwari" />
          </bean>
        </entry>
        <entry>
          <key>
            <value>paresh</value>
          </key>
          <bean class="com.examples.spring.Employee">
            <constructor-arg name="name" value="Paresh Tiwari" />
          </bean>
        </entry>
        <entry>
          <key>
            <value>ankit</value>
          </key>
          <bean class="com.examples.spring.Employee">
            <constructor-arg name="name" value="Ankit Rawat" />
          </bean>
        </entry>
      </map>
    </property>
  </bean>
</beans>

Read more ...

HTML escape tool

A HTML escape tool is a must for the people who share a lot of code in their blogs. There are many special characters which hinder in rendering your post properly if not escaped.

The below program has characters < and > which should be escaped with characters &lt; and &gt; respectively

#include 

int main()
{
    std::cout << "Hello World";
    return 0;
}
I use Postify to escape special characters before using them. Below is the escaped version of the above program using Postify
#include &lt;iostream&gt;

int main()
{
    std::cout &lt;&lt; &quot;Hello World&quot;;
    return 0;
}

Read more ...

Dec 23, 2012

Spring Framework - Injecting a list

The example below demonstrates a Company bean class with two properties namely company name and the employees list. Both these properties are injected by the spring container.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 <bean id="myCompany" class="com.examples.spring.Company">
     <property name="name" value="myWorld"/>
  <property name="employees">
      <list>
          <bean class="com.examples.spring.Employee">
              <constructor-arg name="name" value="Pankaj Tiwari" />
          </bean>
          <bean class="com.examples.spring.Employee">
              <constructor-arg name="name" value="Paresh Tiwari" />
          </bean>
          <bean class="com.examples.spring.Employee">
              <constructor-arg name="name" value="Ankit Rawat" />
          </bean>
      </list>
  </property>
 </bean>
</beans>

Shown above is the spring's bean definition file. Make sure that the Company class has a setter method setEmployees as shown below

Read more ...

Dec 22, 2012

Sharepoint 2010 - Access denied Exception

The below code retrieves sharepoint SPList item when executed through a .net console application. The same piece of code when run through ASP.NET application throws Access is denied exception.

SPWeb web = GetWeb(SiteURL);
return web.Lists[ListName];
The exception message through the visual studio watch window
{"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"} System.Exception {System.UnauthorizedAccessException}
To fix this problem, you need to run the above snippet with elevated privileges using SPSecurity.RunWithElevatedPrivileges
SPList list = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    SPWeb web = GetWeb(SiteURL);
    list = web.Lists[ListName];
});

return list;

Read more ...

Dec 19, 2012

VI Editor - A great tool for testing Regular Expressions

VI is one of the fastest and most successful editor used by the unix users. VI can also boast of having a regular expression search feature which I found amongst easiest to use and easy to test your regular expressions as well

Consider the file pom.xml below. We are going to demonstrate a step by step way of selecting only line numbers in the file and finally performing a search and replace to remove all the leading line numbers from the text

1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 3   <modelVersion>4.0.0</modelVersion>
 4   <groupId>com.examples.spring</groupId>
 5   <artifactId>HelloSpring</artifactId>
 6   <packaging>jar</packaging>
 7   <version>1.0-SNAPSHOT</version>
 8   <name>HelloSpring</name>
 9   <url>http://maven.apache.org</url>
10   <dependencies>
11     <dependency>
12       <groupId>junit</groupId>
13       <artifactId>junit</artifactId>
14       <version>3.8.1</version>
15       <scope>test</scope>
16     </dependency>
17   </dependencies>
18 </project>

Read more ...

Spring Framework - Constructor Injection

Constructor Injection is another basic operation performed by the Spring Framework. The AppTest class tests the validity of the service name property set via Constructor Injection.

package com.examples.spring;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * File: AppTest.java 
 * 
 * Setting property via constructor argument
 */
public class AppTest {

 ApplicationContext ctx = null;

 @Before
 public void setup() {
  ctx = new ClassPathXmlApplicationContext("service-beans.xml");
 }

 @After
 public void cleanup() {
 }

 @Test
 public void testPropertyInjection() {
  Service srvc = (Service) ctx.getBean("myservice");
  Assert.assertEquals(srvc.getServiceName(), "TimerService");
 }
}

Read more ...

Spring Framework - Setter Injection

The most elementary operation performed by the Spring Framework is setting the property value via Setter Injection. The AppTest class is a junit test class which validates the property set through setter injection.

package com.examples.spring;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * File: AppTest.java 
 * 
 * Setting property via Setter Injection
 */
public class AppTest {

 ApplicationContext ctx = null;

 @Before
 public void setup() {
  ctx = new ClassPathXmlApplicationContext("service-beans.xml");
 }

 @After
 public void cleanup() {
 }

 @Test
 public void testPropertyInjection() {
  Service srvc = (Service) ctx.getBean("myservice");
  Assert.assertEquals(srvc.getServiceName(), "TimerService");
 }
}

Read more ...

Dec 13, 2012

Configuring build path in Eclipse for Maven projects

The .classpath file generated after executing maven mvn eclipse:eclipse looks like the following

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry including="**/*.java" kind="src" output="target/test-classes" path="src/test/java"/>
    <classpathentry including="**/*.java" kind="src" path="src/main/java"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
    <classpathentry kind="output" path="target/classes"/>
</classpath>

When the same project is imported into eclipse, the build path is configured accordingly. The parameter including=**/*.java specifies that only java files are included in the class path.
In the example above, no other files are included in the class path and will throw FileNotFoundException if referenced

Read more ...

Setting up Spring Development Environment using Maven

The step by step guide for creating a java project using Maven and configuring it for Spring Framework

#1. Setup a simple Java project using Maven
Use mvn archetype:generate command for creating a sample java project. When prompted hit enter to select the version as 1.0-SNAPSHOT and package as com.examples.spring

mvn archetype:generate -DgroupId=com.examples.spring -DartifactId=HelloSpring -DarchetypeArtifactId=maven-archetype-quickstart

Read more ...

Importing a maven project in eclipse

You can import a maven project to eclipse without installing the maven plugin by following these simple steps

Generate Eclipse specific files
Eclipse looks for .classpath and .project files in your project. Use the maven command mvn eclipse:eclipse to generate files for your project

Importing the Project in Eclipse

1. Start Eclipse. Goto File and select Import...
2. Select Existing Projects into Workspace. Click Next
3. When asked to select root directory, browse and point it to the project folder you want to import
4. Click Finish and your project is successfully imported into eclipse

Note: Make sure that M2_REPO variable is set to Maven Local Repository in eclipse

Read more ...

Nov 23, 2012

Strategy Design Pattern

Strategy Pattern
The strategy pattern allows you to use different business rules or algorithms depending on the context in which they occur

When should I use the Strategy Pattern?
1. You can perform an operation in different ways
2. You want to select the operation dynamically at the runtime
3. You want to add new ways without modifying the application code

Real World Examples
1. File Compression Techniques
2. Layout Managers used by Containers in Java Swing
3. Comparators used in Arrays sort function

Read more ...

Nov 22, 2012

Insertion Sort in Java using Generics

A generic implementation of Insertion Sort in Java

 1 import org.junit.Assert;
 2 import org.junit.Test;
 3 
 4 class GenericInsertionSorter
 5 {
 6     public <T extends Comparable<T>> void sort(T[] elems) {
 7         int size = elems.length;
 8 
 9         for (int outerLoopIdx = 1; outerLoopIdx < size; ++outerLoopIdx) {
10             for (int innerLoopIdx = outerLoopIdx; innerLoopIdx > 0; --innerLoopIdx) {
11                 if (elems[innerLoopIdx - 1].compareTo(elems[innerLoopIdx]) > 0) {
12                     T temp = elems[innerLoopIdx - 1];
13                     elems[innerLoopIdx - 1] = elems[innerLoopIdx];
14                     elems[innerLoopIdx] = temp;
15                 }
16             }
17         }
18     }
19 }
20 
21 public class InsertionSortTester
22 {
23     private String[] unsortedNames = new String[] {
24             "Pankaj",
25             "Paresh",
26             "Ankit",
27             "Sankalp",
28             "Aditya",
29             "Prem",
30             "Rocket",
31             "Singh",
32             "Alabama",
33             "Alaska",
34             "Animal" };
35 
36     private String[] sortedNames = new String[] {
37             "Aditya",
38             "Alabama",
39             "Alaska",
40             "Animal",
41             "Ankit",
42             "Pankaj",
43             "Paresh",
44             "Prem",
45             "Rocket",
46             "Sankalp",
47             "Singh" };
48 
49     @Test
50     public void testStringSort() {
51         GenericInsertionSorter ss = new GenericInsertionSorter();
52         ss.sort(unsortedNames);
53         Assert.assertArrayEquals(unsortedNames, sortedNames);
54     }
55 }

Read more ...

Insertion Sort in C++ using templates

Insertion Sort
An efficient elementary sort method which places each element in it's proper place among the elements which are already placed
  1 #include <iostream>
  2 #include <string.h>
  3 
  4 template <typename T>
  5 class InsertionSort
  6 {
  7     public:
  8         InsertionSort();
  9         ~InsertionSort();
 10 
 11         void sort(T arr[], int size);
 12     private:
 13         void compareExchange(T arr[], int l, int r);
 14         bool greater(T left, T right);
 15 };
 16 
 17 //Constructor
 18 template <typename T>
 19 InsertionSort<T>::InsertionSort(){}
 20 
 21 //Destructor
 22 template <typename T>
 23 InsertionSort<T>::~InsertionSort(){}
 24 
 25 template <typename T>
 26 void InsertionSort<T>::sort(T arr[], int size)
 27 {
 28     for(int i = 1; i < size; ++i)
 29     {
 30         for(int j = i; j > 0; --j)
 31         {
 32             compareExchange(arr, j-1, j);
 33         }
 34     }
 35 }
 36 
 37 template <typename T>
 38 void InsertionSort<T>::compareExchange(T arr[], int l, int r)
 39 {
 40     if(greater(arr[l], arr[r]))
 41     {
 42         T temp = arr[l];
 43         arr[l] = arr[r];
 44         arr[r] = temp;
 45     }
 46 }
 47 
 48 template <typename T>
 49 bool InsertionSort<T>::greater(T left, T right)
 50 {
 51     return left > right;
 52 }
 53 
 54 template <>
 55 bool InsertionSort<const char*>::greater(const char *left, const char *right)
 56 {
 57     return strcmp(left, right) > 0;
 58 }
 59 
 60 template <typename T>
 61 void print(T arr[], int size)
 62 {
 63     for(int i = 0; i < size; ++i)
 64         std::cout << arr[i] << " ";
 65     std::cout << std::endl;
 66 }
 67 
 68 template <>
 69 void print(std::string arr[], int size)
 70 {
 71     for(int i = 0; i < size; ++i)
 72         std::cout << arr[i].c_str() << " ";
 73     std::cout << std::endl;
 74 }
 75 
 76 template <>
 77 void print(const char *ptrArray, int size)
 78 {
 79     for(int i = 0; i < size; ++i)
 80         std::cout << ptrArray[i] << " ";
 81     std::cout << std::endl;
 82 }
 83 
 84 int main()
 85 {
 86     int arr[] = { 10, 65, 35, 25, 15, 75, 85, 45, 65 };
 87     InsertionSort<int> isInt;
 88     isInt.sort(arr, 9);
 89     print(arr, 9);
 90 
 91     std::string strArr[] = { "pankaj", "paresh", "hello", "world", "ankit", "aditya", "sankalp", "aladdin" };
 92     InsertionSort<std::string> isString;
 93     isString.sort(strArr, 8);
 94     print(strArr, 8);
 95 
 96     const char* ptrArray[] = { "pankaj", "paresh", "hello", "world", "ankit", "aditya", "sankalp", "aladdin", "george"};
 97     InsertionSort<const char*> isPtr;
 98     isPtr.sort(ptrArray, 9);
 99     print(ptrArray, 9);
100 
101     return 0;
102 }

Read more ...

Nov 21, 2012

Selection Sort in Java using Generics

A generic implementation of Selection Sort in Java using Generics

 1 import org.junit.Assert;
 2 import org.junit.Test;
 3 
 4 class GenericSelectionSorter
 5 {
 6     public <T extends Comparable<T>> void sort(T[] elems) {
 7         int size = elems.length;
 8 
 9         for (int outerLoopIdx = 0; outerLoopIdx < size - 1; ++outerLoopIdx) {
10             int min = outerLoopIdx;
11             for (int innerLoopIdx = outerLoopIdx; innerLoopIdx < size; ++innerLoopIdx) {
12                 if (elems[min].compareTo(elems[innerLoopIdx]) > 0) {
13                     min = innerLoopIdx;
14                 }
15             }
16 
17             // exchange elements at outerIndexLoop and min positions
18             T temp = elems[min];
19             elems[min] = elems[outerLoopIdx];
20             elems[outerLoopIdx] = temp;
21         }
22     }
23 }
24 
25 public class SelectionSortTester
26 {
27     private String[] unsortedNames = new String[] {
28             "Pankaj",
29             "Paresh",
30             "Ankit",
31             "Sankalp",
32             "Aditya",
33             "Prem",
34             "Rocket",
35             "Singh",
36             "Alabama",
37             "Alaska",
38             "Animal" };
39 
40     private String[] sortedNames = new String[] {
41             "Aditya",
42             "Alabama",
43             "Alaska",
44             "Animal",
45             "Ankit",
46             "Pankaj",
47             "Paresh",
48             "Prem",
49             "Rocket",
50             "Sankalp",
51             "Singh" };
52 
53     @Test
54     public void testStringSort() {
55         GenericSelectionSorter ss = new GenericSelectionSorter();
56         ss.sort(unsortedNames);
57         Assert.assertArrayEquals(unsortedNames, sortedNames);
58     }
59 }

Read more ...

The Selection Sort in C++

Selection Sort
An elementary sorting technique which finds the smallest element in the array and then exchanges it with the element in the first position
 1 #include <iostream>
 2 
 3 class SelectionSort
 4 {
 5     public:
 6         SelectionSort();
 7         ~SelectionSort();
 8 
 9         void sort(int arr[], int size);
10 
11     private:
12         void exchange(int &x, int &y);
13 };
14 
15 //Constructor
16 SelectionSort::SelectionSort() {}
17 
18 //Destructor
19 SelectionSort::~SelectionSort() {}
20 
21 void SelectionSort::sort(int arr[], int size)
22 {
23     for(int outerLoopIdx = 0; outerLoopIdx < size - 1; ++outerLoopIdx)
24     {
25         int min = outerLoopIdx;
26         for(int innerLoopIdx = outerLoopIdx + 1; innerLoopIdx < size; ++innerLoopIdx)
27         {
28             if(arr[min] > arr[innerLoopIdx])
29             {
30                 min = innerLoopIdx;
31             }
32         }
33         exchange(arr[outerLoopIdx], arr[min]);
34     }
35 }
36 
37 void SelectionSort::exchange(int &x, int &y)
38 {
39     int t = x;
40     x = y;
41     y = t;
42 }
43 
44 void print(int arr[], int size)
45 {
46     for(int i = 0; i < size; ++i)
47         std::cout << arr[i] << " ";
48 }
49 
50 int main()
51 {
52     int arr[] = { 10, 65, 35, 25, 15, 75, 85, 45, 65 };
53     SelectionSort ss;
54     ss.sort(arr, 9);
55     print(arr, 9);
56 }

Output:

Read more ...

Bubble Sort in Java using Generics

Below is a generic implementation of Bubble Sort in Java

 1 import org.junit.Assert;
 2 import org.junit.Test;
 3 
 4 class GenericBubbleSorter<T extends Comparable<T>>
 5 {
 6     public void sort(T[] elems) {
 7         int size = elems.length;
 8 
 9         for (int outerLoopIdx = 0; outerLoopIdx < size; ++outerLoopIdx) {
10             for (int innerLoopIdx = 0; innerLoopIdx < (size - outerLoopIdx - 1); ++innerLoopIdx) {
11                 if (elems[innerLoopIdx].compareTo(elems[innerLoopIdx + 1]) > 0) {
12                     T temp = elems[innerLoopIdx];
13                     elems[innerLoopIdx] = elems[innerLoopIdx + 1];
14                     elems[innerLoopIdx + 1] = temp;
15                 }
16             }
17         }
18     }
19 }
20 
21 public class BubbleSortTester
22 {
23     private String[] unsortedNames = new String[] {
24             "Pankaj",
25             "Paresh",
26             "Ankit",
27             "Sankalp",
28             "Aditya",
29             "Prem",
30             "Rocket",
31             "Singh",
32             "Alabama",
33             "Alaska",
34             "Animal" };
35 
36     private String[] sortedNames = new String[] {
37             "Aditya",
38             "Alabama",
39             "Alaska",
40             "Animal",
41             "Ankit",
42             "Pankaj",
43             "Paresh",
44             "Prem",
45             "Rocket",
46             "Sankalp",
47             "Singh" };
48 
49     @Test
50     public void testStringSort() {
51         GenericBubbleSorter<String> bs = new GenericBubbleSorter<String>();
52         bs.sort(unsortedNames);
53         Assert.assertArrayEquals(unsortedNames, sortedNames);
54     }
55 }

Read more ...

Nov 20, 2012

The Bubble Sort in C++

Bubble Sort
This sort gets its name from the way smaller/larger elements gets to the top of the list using bubble comparison
 1 #include <iostream>
 2 
 3 class BubbleSort
 4 {
 5     public:
 6         BubbleSort(){}
 7         ~BubbleSort(){}
 8         void sort(int arr[], int size);
 9 };
10 
11 void BubbleSort::sort(int arr[], int size)
12 {
13     //With every iteration in outer loop, the next maximum element is moved to it's correct position
14     for(int outerLoopIdx = 0; outerLoopIdx < size ; ++outerLoopIdx)
15     {
16         for(int innerLoopIdx = 0; innerLoopIdx < (size - outerLoopIdx - 1); ++innerLoopIdx)
17         {
18             //Comparing two subsequent elements OR bubble comparison
19             //Placing the larger element on the right
20             if(arr[innerLoopIdx] > arr[innerLoopIdx + 1])
21             {
22                 int temp = arr[innerLoopIdx];
23                 arr[innerLoopIdx] = arr[innerLoopIdx + 1];
24                 arr[innerLoopIdx + 1] = temp;
25             }
26         }
27     }
28 }
29 
30 void print(int arr[], int size)
31 {
32     for(int i = 0; i < size; ++i)
33         std::cout << arr[i] << " ";
34     std::cout << std::endl;
35 }
36 
37 int main()
38 {
39     int arr[] = { 10, 65, 35, 25, 15, 75, 85, 45, 65 };
40     BubbleSort bs;
41     bs.sort(arr, 9);
42     print(arr, 9);
43     return 0;
44 }

Output

References:
Bubble Sort Animation
Read more ...

Nov 14, 2012

Template Method Design Pattern

Template Method Pattern
Template method pattern defines the skeleton of an algorithm in a method referred to as the Template Method deferring some steps to subclasses. The pattern is mostly used for building application frameworks where the framework implement the invariant pieces of the application's architecture and provide place holders or hooks for client customizations.

Examples from Java API
1. The Comparable interface defines the compareTo method which is a template method
2. The java applet class provides init, start, stop, paint and destroy hook methods for creating an applet
3. The actionPerformed method in ActionListener interface is a template method
4. The doGet and doPost methods in abstract class HttpServlet are examples of template methods


Read more ...

Nov 11, 2012

A simple http server in java

A web server is an application which delivers web pages using HTTP protocol
The application explained below is a simple http server application which runs on port 8080 and serves contents from the directory C:/Web. The server handles each client request in a new worker thread.
package com.pankaj.webserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * File: WebServer.java
 */
public class WebServer
{
    private static final int PORT = 8080;
    private static ServerSocket listenerSocket = null;
    private static int requestId = 0;

    public static void main(String[] args) throws IOException
    {
        ConsoleLogger.LogMessage("Starting simple http server");
        listenerSocket = new ServerSocket(PORT);

        ConsoleLogger.LogMessage("Server started on port " + listenerSocket.getLocalPort());
        while (true) {
            Socket socket = listenerSocket.accept();
            ConsoleLogger.LogMessage("Client connected on port " + socket.getPort());
            new Worker(new RequestHandler(++requestId, socket));
        }
    }
}

Read more ...

Nov 4, 2012

Removing BOM character from a string in Java

The below code checks if the BOM character is present in a string. If present, removes and prints the string with skipped bom.

import java.io.UnsupportedEncodingException;

/**
 * File: BOM.java
 * 
 * check if the bom character is present in the given string print the string
 * after skipping the utf-8 bom characters print the string as utf-8 string on a
 * utf-8 console
 */

public class BOM
{
    private final static String BOM_STRING = "Hello World";
    private final static String ISO_ENCODING = "ISO-8859-1";
    private final static String UTF8_ENCODING = "UTF-8";
    private final static int UTF8_BOM_LENGTH = 3;

    public static void main(String[] args) throws UnsupportedEncodingException {
        final byte[] bytes = BOM_STRING.getBytes(ISO_ENCODING);
        if (isUTF8(bytes)) {
            printSkippedBomString(bytes);
            printUTF8String(bytes);
        }
    }

    private static void printSkippedBomString(final byte[] bytes) throws UnsupportedEncodingException {
        int length = bytes.length - UTF8_BOM_LENGTH;
        byte[] barray = new byte[length];
        System.arraycopy(bytes, UTF8_BOM_LENGTH, barray, 0, barray.length);
        System.out.println(new String(barray, ISO_ENCODING));
    }

    private static void printUTF8String(final byte[] bytes) throws UnsupportedEncodingException {
        System.out.println(new String(bytes, UTF8_ENCODING));
    }

    private static boolean isUTF8(byte[] bytes) {
        if ((bytes[0] & 0xFF) == 0xEF && 
            (bytes[1] & 0xFF) == 0xBB && 
            (bytes[2] & 0xFF) == 0xBF) {
            return true;
        }
        return false;
    }
}


The following stackoverflow article talks in detail about detecting and skipping the BOM

Read more ...

Byte Order Mark (BOM) character

BOM character
1. BOM is a Unicode character used to identify the endianness of the text file or stream.
2. The UTF-8 representation of the BOM is the byte sequence 0xEF, 0xBB, 0xBF.
3. A text editor using ISO-8859-1 as character encoding will display the characters  for BOM.
4. BOM has no meaning in UTF-8 apart from signalling that the byte stream that follows is encoded in UTF-8

import java.nio.charset.Charset;

/**
 * File: BOM.java
 * 
 * The following class converts a string having bom character
 * from ISO-8859-1 encoding type to UTF-8 and back
 */
public class BOM
{
    public static void main(String[] args) throws Exception
    {
        System.out.println("Default Encoding: " + Charset.defaultCharset());

        //
        // Displays a simple string with bom prepended.
        // Uses system default character encoding
        //
        String bomString = "Hello World";
        System.out.println(bomString + " Length: " + bomString.length());

        //
        // convert string with bom character to utf string
        //
        byte[] byteArrayISO = bomString.getBytes("ISO-8859-1");
        String utfString = new String(byteArrayISO, "UTF-8");
        System.out.println(utfString + " Length: " + utfString.length());

        //
        // convert the utf string back to windows character encoding
        //
        byte[] byteArrayUTF = utfString.getBytes("UTF-8");
        String winString = new String(byteArrayUTF, "ISO-8859-1");
        System.out.println(winString + " Length: " + winString.length());
    }
}

Output of the above program when run on a UTF-8 supported console
$ java BOM
Default Encoding: windows-1252
Hello World Length: 17
Hello World Length: 14
Hello World Length: 17

Read more ...

Oct 29, 2012

Visitor Design Pattern

Definition
A behavioral pattern which lets you define new methods to a class hierarchy without changing the class hierarchy on which it operates
Applicability
1. When the primary class hierarchy is fixed or it is coming from a different vendor and you cannot make any changes to that hierarchy
2. Several different operations have to be performed on all or some of the classes in the hierarchy

Visitor and Composite Pattern normally go hand in hand together. First, we will try to create an example of composite pattern. A composite pattern is a structural pattern which helps to create tree like hierarchial structures. Consider a linux filesystem where every element is considered as a file. We are trying to achieve the same tree structure using Directory, File and Link elements. All of these classes implement the interface FileSystemElement

Read more ...

Oct 26, 2012

A Servlet Refresher

A Servlet is a dynamic web component developed in Java technology, loaded and run by Java technology enabled web server. The Servlet interface is the core of the Java Servlet API. The two classes which implement the Servlet interface are the GenericServlet and the HttpServlet. The Servlet interface defines the init(), service() and the destroy() methods which are implemented by GenericServlet class. The HttpServlet is an abstract class extending GenericServlet and basically helps in processing HTTP requests.

Servlet Life Cycle
The Servlet life cycle is expressed in the API by the init, service and destroy methods of the Servlet interface

Read more ...

Oct 22, 2012

Configuring and retrieving a DataSource object

In the JDBC API, a DataSource object is a means to access a database. A DataSource object is identified by set of properties which is used to communicate with the server. These properties include information such as the location of the database server, the name of the database, the protocol used to communicate with the server, the username and password of the privileged database user.
In the application server, a data source is known as JDBC Resource

The rest of the post demonstrates how to configure a JDBC Resource in GlassFish application server and retrieve the same data source using JNDI through a simple web servlet

Read more ...

Oct 8, 2012

Prototype Design Pattern

Definition
A creational pattern which allows creation of new instances by copying existing instance or prototype.

Applicability
1. When the classes to instantiate are specified at the run time
2. When creating a new instance is more expensive due to high computation or a call over the network

Read more ...

Jun 17, 2012

Getting started with Objective C on Ubuntu with GNUStep

Setting up the Environment

1. Install the following packages using the apt-get command.

sudo apt-get install build-essential
sudo apt-get install gnustep
sudo apt-get install gnustep-make
sudo apt-get install gobjc
sudo apt-get install libgnustep-base-dev
sudo apt-get install libgnustep-gui-dev

Read more ...

May 19, 2012

A simple java web application in minutes

You can set up your simple java web application in no time using maven. The application can be downloaded from maven's site.

Maven comes up with a single line command to create Hello World web application for you. The value to the argument archetypeArtifactId identifies that the project to be created is of type web application. In case you are running this command for the first time, it will take some time for the maven to download the dependent plugins first and then create the sample application

Create Web Application Project
mvn archetype:create -DgroupId=com.simple.web -DartifactId=webapp -DarchetypeArtifactId=maven-archetype-webapp
Your sample application is created and ready to be packaged and deployed

Read more ...

May 18, 2012

Maven cheat sheet for the beginners

Maven is a build automation tool used by the java developers. Some of the commands which I use on daily basis are:

Create a Java Project
mvn archetype:create -DgroupId=com.devfaqs.project -DartifactId=MyProject
Above is a single line command to create hello world java project. The command creates the project in a well defined directory structure along with the provision to write and execute junit test cases for the project created

Read more ...

May 1, 2012

Array Multiplication Problem - II

The Problem
Given an array A[n] of n numbers. You have to modify A[n] such that A[i] will be equal to multiplication of all the elements of A[n] except A[i] e.g.
A[0] = A[1] * A[2] * ... * A[n-1] and
A[1] = A[0] * A[2] * ... * A[n-1]
You have to solve the problem without using the division operator and in O(n). You cannot make use of another array

Read more ...

Array Multiplication Problem

The Problem

Given an array A[n] of n numbers. You have to compose an array O[N] such that O[i] will be equal to multiplication of all the elements of A[n] except A[i] e.g.
O[0] = A[1] * A[2] * ... * A[n-1] and
O[1] = A[0] * A[2] * ... * A[n-1]
You have to solve the problem without using the division operator and in O(n).
C++ Program
#include <iostream>
#define MAX 5

int main()
{
  int arr[MAX] = { 4, 3, 5, 1, 2 };
  int product;

  int product_of_elems_before[MAX] = {0};
  product = 1;
  for(int i = 0; i < MAX; ++i)
  {
    product_of_elems_before[i] = product;
    product *= arr[i];
  }

  int product_of_elems_after[MAX] = {0};
  product = 1;
  for(int i = MAX - 1; i >= 0; --i)
  {
    product_of_elems_after[i] = product;
    product *= arr[i];
  }

  for(int i = 0; i < MAX; ++i)
  {
    arr[i] = product_of_elems_before[i] * product_of_elems_after[i];
    std::cout << arr[i] << " ";
  }
  std::cout << std::endl;
}
Java Program
public class ArrayMultiplication
{
  public static void main(String args[])
  {
    int[] arr = new int[]{ 3, 2, 1, 4, 5 };
    int product;
    
    int productOfElemsBefore[] = new int[arr.length];
    product = 1;
    for(int i = 0; i < arr.length; ++i)
    {
      productOfElemsBefore[i] = product;
      product *= arr[i];
    }

    int productOfElemsAfter[] = new int[arr.length];
    product = 1;
    for(int i = arr.length - 1; i >= 0; --i)
    {
      productOfElemsAfter[i] = product;
      product *= arr[i];
    }

    for(int i = 0; i < arr.length; ++i)
    {
      arr[i] = productOfElemsBefore[i] * productOfElemsAfter[i];
      System.out.print(arr[i] + " ");
    }
  }
}

Read more ...

Apr 28, 2012

Tower of Hanoi Problem

The Problem

There are 3 pegs source ,auxillary and target. n disks of different sizes are given which can slide onto any peg . In the beginning all of the disks are in the source peg in the order of size with largest disk at the bottom and smallest disk at the top. We have to move all the disks from source peg to target peg such that in the end the target peg will have all the disks in the same order of size.

Rules:
1. Only one disk can be moved from one peg to another peg at a time
2. A larger disk cannot be placed on top of the smaller disk
C++ Program
#include <iostream>
#include <cstdlib>

static int moveCounter = 0;
void towerOfHanoi(int ndisk, char source, char auxillary, char target)
{
  if(ndisk == 1)
  {
    std::cout << "Move [" << ndisk << "]   [" << source << "] to [" <<
      target << "]" << std::endl;
    ++moveCounter;
    return;
  }

  //place ndisk - 1 disks from source to auxillary peg
  towerOfHanoi(ndisk - 1, source, target, auxillary);
  
  //place ndisk to target peg
  std::cout << "Move [" << ndisk << "]   [" << source << "] to [" <<
      target << "]" << std::endl;
  ++moveCounter;

  //place ndisk - 1 disks from auxillary to target peg
  towerOfHanoi(ndisk - 1, auxillary, source, target);
}

int main(int args, char *argv[])
{
  if(argv[1] == NULL)
  {
    std::cout << "ERROR: Insufficient Arguments\n";
    std::cout << "Usage: ./a.out number_of_disks\n";
    exit(-1);
  }
  int disks = atoi(argv[1]);
  
  char peg1 = 'A', peg2 = 'B', peg3 = 'C';
  towerOfHanoi(disks, peg1, peg2, peg3);
  std::cout << "Total Moves = " << moveCounter << std::endl;
}

Read more ...

Apr 24, 2012

Check if the linked list is a palindrome

The following code checks if the given singly linked list is a palindrome using recursion. 
Time Complexity: O(n) 
Space Complexity: O(n)
C++ Program
bool isPalindrome() const
    {
      Node* node = isPalindrome(head, head);
      if(node)
        return true;
      return false;
    }

    Node* isPalindrome(Node *left, Node *right) const
    {
      if(right == NULL)
      {
        return left;
      }

      left = isPalindrome(left, right->link);
      if(left)
      {
        bool palindrome = left->ch == right->ch ? true : false;
        if(palindrome)
        {
          left = left->link ? left->link : left;
          return left;
        }
      }
      return NULL;
    }
Java Program
public boolean isPalindrome()
  {
    Node node = isPalindrome(head, head);
    if(node == null)
      return false;
    return true;
  }

  private Node isPalindrome(Node left, Node right)
  {
    if(right == null)
    {
      return left;
    }
  
    left = isPalindrome(left, right.link);
    if(left != null)
    {
      boolean palindrome = left.data == right.data ? true : false;
      if(palindrome)
      {
        left = (left.link != null) ? left.link : left;
        return left;
      }
    }
    return null;
  }

Read more ...

Apr 22, 2012

Reverse a linked list

One of the frequently asked question in the interviews is to reverse a singly-linked list using iterative and recursive approach.

Iterative Approach
void ireverse()
    {
      Node *current = head;
      Node *prev = NULL;
      Node *next = current->link;

      while(next != NULL)
      {
        current->link = prev;
        prev = current;
        current = next;
        next = next->link;
      }

      current->link = prev;
      head = current;
    }
Recursive Approach
void reverse(Node *current, Node *prev, Node *next)
    {
      if(next == NULL)
      {
        current->link = prev;
        head = current;
        return;
      }
      current->link = prev;
      reverse(next, current, next->link);
    }

1. The complete C++ program can be viewed here
2. Java programmers can find the Java version of the above problem here
Read more ...

Mar 31, 2012

Reverse the words of a string

Given a string My name is Antonio Gonsalves. You have to reverse all the letters of the words in the string so that the resultant string looks like yM eman si oinotnA sevlasnoG

int main()
{
    char str[] = "My name is Antonio Gonsalves", 
         *startPtr = str,
         *endPtr = str,
         *spacePtr;

    while(*spacePtr != '\0')
    {
        while(*endPtr != ' ' && *endPtr != '\0')
            ++endPtr;

        spacePtr = endPtr;
        endPtr = spacePtr - 1;
       
        char temp;
        while(startPtr < endPtr)
        {
            temp = *endPtr;
            *endPtr-- = *startPtr;
            *startPtr++ = temp;
        }
        
        startPtr = spacePtr + 1;
        endPtr = spacePtr + 1;
    }
    printf("%s\n", str);
    return 0;
}
$ ./a.out 
yM eman si oinotnA sevlasnoG

Read more ...

Difference between a char [] and char *

There is an important difference between the following two definitions:

char amessage[] = "Hello World"; /* an array */
char *pmessage  = "Hello World"; /* a pointer */

1. amessage is just an array, big enough to hold the sequence of characters and '\0'
2. amessage refers to the same memory location and cannot be changed
3. Individual characters within amessage can be changed
#include <stdio.h>
int main()
{
    char amessage[] = "Hello World from the C Program";

    amessage[0] = 'P';
    printf("%s\n", amessage);
    return 0;
}

1. pmessage is a pointer pointing to a string constant
2. The string constant "Hello World" is stored in a read only memory location and cannot be modified
3. pmessage can be changed to point to some other memory location
#include <stdio.h>
int main()
{
    char *pmessage = "Hello World from the C Program";

    pmessage[0] = 'P'; //throws segmentation fault
    printf("%s\n", pmessage);
    return 0;
}

Read more ...

Mar 25, 2012

Vertical Sum of a Binary Tree

The binary tree above can be represented as the following to calculate the vertical sum of the nodes

Read more ...

Mar 24, 2012

Remove a node from Binary Search Tree

C++
A node can be removed from a Binary Search Tree using two approaches.
1. Double Pointer Approach
2. Single Pointer Approach

Read more ...

Insert a node in Binary Search Tree

C++
A node can be inserted in a binary search tree using two approaches
Double pointer approach
void insert(BinaryTreeNode **node, int data)
   {
      if(*node == NULL)
      {
        *node = getNewNode(data);
      }
      
      if(data == (*node)->data)
      {
        //do  nothing
      }
      else if(data < (*node)->data)
      {
        insert(&(*node)->left, data);
      }
      else
      {
        insert(&(*node)->right, data);
      }
   }

Single pointer approach
BinaryTreeNode* insert(BinaryTreeNode *node, int data)
    {
      if(node == NULL)
      {
        node = getNewNode(data);
        return node;
      }
      
      if(data == node->data)
      {
        //do  nothing
      }
      else if(data < node->data)
      {
        node->left = insert(node->left, data);
      }
      else
      {
        node->right = insert(node->right, data);
      }

      return node;
   }

Read more ...

Mar 23, 2012

Configuring CMIS Consumer in Sharepoint 2010 server

In our previous post, we have configured SharePoint 2010 Server with CMIS Connector Services Producer. This post talks about adding and configuring CMIS Connector Services Consumer Web Part to a Web Page. We will also be testing the CMIS Consumer service by listing down all the documents uploaded to a particular sharepoint document repository.

Read more ...

Configuring CMIS in Sharepoint 2010 server

Content Management Interoperability Services a.k.a CMIS is a standard defined for Enterprise Content Management (ECM) systems such as SharePoint server, Documentum, Alfresco and others. The standard defines a domain model plus Web Services and Restful AtomPub bindings that can be used by other applications.

Installing the SharePoint CMIS Connector
1. Install Microsoft SharePoint Server 2010

2. Complete the SharePoint 2010 Products configuration wizard
3. Download Microsoft SharePoint 2010 Administration Toolkit from here and save the file to hard disk
SharePoint 2010 Administration Toolkit installs two components:
CMIS Producer Services
This allows CMIS client applications to interact with the SharePoint document libraries by using interfaces defined in the CMIS standard

CMIS Consumer Services Web Part
The Consumer Web part can be added to any SharePoint page and allows users to connect with any CMIS compliant repository
4. Double click SharePoint2010AdministrationToolkit.exe file to start the installation.
5. Accept the license agreement and click next. Make sure CMIS connectors are selected for the install. Click Next
6. Use the default installation directory. Click Next and Finish. CMIS Connector is successfully installed


Read more ...

Mar 17, 2012

Configuring password less access to remote systems using ssh-keygen utility

When we say password less authentication, we mean that the client authentication is carried out using public and private keys.

Generate public/private key pair
The ssh-keygen utility is used to generate the public/private key pair. The keys generated are stored under .ssh directory in the user home directory. The private key is never shared and stored in the local machine whereas the public key is distributed to the machines you want to login to.

Read more ...

Mar 16, 2012

Installing And Configuring SSH server on Windows

We will be making use of Cygwin utilities to configure and run ssh as service on windows machine. Installing Cygwin on a windows machine is pretty straight forward. Download the latest Cygwin installation setup.exe from the Cygwin site and follow the below instructions.

1. Installing Cygwin
Step 1. Double click setup.exe


Step 2. Choose the download source

Step 3. Select the root directory of the Cygwin. This directory is synonymous to / in linux

Step 4. Select the directory where you want to keep the installation files. You can save this directory and use at a later point to install Cygwin on any windows machine using this directory.

Click 'OK' if prompted to create the directory if it does not exists

Step 5. Select the type of connection you are using to connect to internet.

Step 6. Choose a download site.

Step 7. Clicking next opens up the 'Select Packages' screen.

Step 8. Select the Open SSH server and client programs from the 'Select Packages' screen.

Step 9. Click next to start the installation.

This will install the following utilities in your Cygwin's /usr/bin directory
ssh-add.exe
ssh-agent.exe
ssh-host-config
ssh-keygen.exe
ssh-keyscan.exe
ssh-user-config
ssh.exe

2. Configuring ssh as Windows service

Run ssh-host-config utility to configure sshd server on windows. Select 'no' when prompted for 'Should privilege separation be used? (yes/no)'. Select 'yes' when prompted for 'Do you want to install sshd as service?'. Choose default options for other options.
The above will install CYGWIN sshd service on Windows. To start the service execute
net start sshd

3. Connecting using Cygwin ssh client (ssh.exe)
ssh.exe user@ssh-server

4. Connecting through putty

Add the server's host key to registry. This will add an entry into the ~/.ssh/known_hosts file

Login using windows user and password

Read more ...

Feb 10, 2012

Reverse a stack in place

Write a C/C++ Program to reverse a stack in place?

You can only use the following ADT functions on the stack:
1. empty()
2. push()
3. pop()
4. top()

Solution:
1. Whenever in place conversion is required, use recursion which will make use of function stack to store the variables
2. Pop out all the elements from the given stack recursively and store them in a variable.
3. As the stack unwinding happens, push the variable obtained at each unwinding step to the bottom of the stack. Refer method push_to_bottom below

//pop out all the elements, use function stack to store the elements
void stack_reverse(std::stack<int> &s)
{
  if(s.empty())
  {
    return;
  }
  int elem = s.top(); s.pop();
  stack_reverse(s);

  //pass the element obtained during the unwinding of the function 
  //stack and store it at the bottom of the given stack 's'
  push_to_bottom(s, elem);
}

void push_to_bottom(std::stack<int> &s, int elem)
{
  //stack is empty so elem will be placed at the bottom of the stack 's'
  if(s.empty())
  {
    s.push(elem);
    return;
  }

  //stack is not empty, so popping out the elements, using function
  //stack to store the elements and storing the given element at the
  //bottom of the given stack 's'
  int top = s.top(); s.pop();
  push_to_bottom(s, elem);
  s.push(top);
}


Read more ...