A Developer's Diary

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 ...