A Developer's Diary

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Oct 2, 2013

Automatically registering the jdbc driver

A jdbc driver can be registered with the Driver Manager in four ways.
1. Automatic Registration
2. Using Class.forName("DRIVER_NAME")
3. Using property -Djdbc.drivers=DRIVER_NAME
4. Explicit registration using the new operator

Automatic Registration
Starting JDBC 4.0, the DriverManager methods getConnection() and getDrivers() have been enhanced to support automatic registration of the driver using the Service Provider mechanism.

Read more ...

Sep 2, 2013

Find depth of the deepest odd level leaf node in a binary tree

Write a program to find maximum height of the odd level leaf node of a binary tree. The problem has been picked up from GeeksforGeeks

A quick solution will be to use the solution for finding the max depth of the tree and modifying it to calculate the depth using only the odd level leaf nodes.

Read more ...

Aug 29, 2013

Find max height of a binary tree

Program for finding maximum depth or height of a binary tree

/**
     * find height of the tree recursively
     */
    public static int maxHeight()
    {
        return maxHeight(root, 0);
    }
 
    private static int maxHeight(Node node, int h)
    {
        if (node == null)
        {
            return h;
        }
 
        int lh = maxHeight(node.left, h + 1);
        int rh = maxHeight(node.right, h + 1);
 
        return (lh > rh) ? lh : rh;
    }

Read more ...

Aug 25, 2013

Creating a binary search tree using iterative approach in Java

Program for creating a binary search tree using iterative method

private void addNode(Node node, int n)
{
    while (node != null)
    {
        if(n < node.data)
        {
            if(node.left != null)
            {
                node = node.left;
            }
            else
            {
                node.left = new Node(n);
                return;
            }
        }
        else if(n > node.data)
        {
            if(node.right != null)
            {
                node = node.right;
            }
            else
            {
                node.right = new Node(n);
                return;
            }
        }
        else
        {
            System.out.println("WARNING: Elements are equal");
            return;
        }
    }
}

Read more ...

Creating a binary search tree using recursion in Java

Program for creating binary search tree using recursive method

private void addNode(Node node, int n)
{
    if (n < node.data)
    {
        if (node.left != null)
        {
            addNode(node.left, n);
        }
        else
        {
            node.left = new Node(n);
        }
    }
    else if (n > node.data)
    {
        if (node.right != null)
        {
            addNode(node.right, n);
        }
        else
        {
            node.right = new Node(n);
        }
    }
    else
    {
        System.out.println("WARNING: Number exists already");
    }
}

Read more ...

Jan 20, 2013

Consuming a webservice using Apache Axis2

The post assumes one to be familiar with the steps to create and host a web service using Apache Axis2. If not, you can refer the following tutorial.

Configuring Apache Axis2
1. Download the Apache Axis2 Binary packages from here
2. Extract the binary package and set the variable AXIS2_HOME to point to the extracted location
3. Append %AXIS2_HOME%\bin to your path

Read more ...

Jan 13, 2013

Axis2 Web Service - A Simple tutorial using Maven

Creating a Web Service using Axis2
A plain java class can be declared as a web service provided
1. It has a public method and the class has been defined in the services.xml file
2. The services.xml file should be placed under META-INF directory of the archive file

Read more ...

Jan 12, 2013

Maven - Copying artifacts to specific folder

Above is the directory structure of web application generated using maven. Use maven-dependency-plugin for copying artifacts to desired folder under WEB-INF directory

Read more ...

Jan 10, 2013

Dealing with cache issues in Jnlp applications

Even though I had disabled the temporary internet files setting in the java control panel as shown below, my jnlp application will still not pick up the latest changes. This is a common issue faced by java web start application developers and becomes quite annoying if changes are not getting reflected. javaws -uninstall is an useful command related to java web start which clears up the cache for you and you need not struggle with deleting the jar files in the %temp% or other folders.

Command for deleting Java Web Start Cache
javaws -uninstall

Read more ...

Debugging Java Web Start / JNLP Applications

Steps for debugging a java web start jnlp application

Step 1. Open a command prompt window (Windows)
Step 2. set JAVAWS_TRACE_NATIVE=1
Step 3. set JAVAWS_VM_ARGS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
Step 4. Run javaws http://server:port/appname/application.jnlp
Step 5. Goto eclipse debug configuration screen and create a new Remote Java Application debug configuration
Step 6. Under the connection properties, specify the hostname of the machine where you have started the terminal and port as 8000, apply and click debug


Read more ...

Jan 1, 2013

Stack implementation using a singly linked list

The below is a stack implementation using a singly linked list.
1. push adds node on top of the stack
2. pop removes the top most node from the stack
3. top returns the top most node of the stack without modifying it
4. isEmpty checks if the stack does not have any elements

The details of the StackNode class

package com.ds.programs;

class StackNode<E>
{
    E data;
    StackNode<E> next;
}

Read more ...

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

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 19, 2012

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