Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Thursday, November 14, 2013

Dynamic Array Example in Java


DynamicArrayExample.java

package com.ranga;

/**
 *
 * This program demonstrates the creating dynamic arrays.
 * User: ranga
 * Date: 11/14/13
 * Time: 4:40 PM
 */

class DynamicArray {
 
  // the variable data[] is used to store the array elements.
  private int data[];
  // the variable size is used to specify the number of array elements.
  // the variable capacity is used to specify the how many elements we can   store.
  private int size, capacity;

  // Constructs an empty DynamicArray
  public DynamicArray() {
    size = 0;
    capacity = 10;
    data = new int[capacity];
  }

// Constructs an empty DynamicArray with the specified initial capacity.
  public DynamicArray(int capacity) {
    if(capacity < 0)
      throw new NegativeArraySizeException("NegativeArraySizeException - capacity is "+capacity);
    else
      this.capacity = capacity;
    size = 0;
    data = new int[capacity];
  }

// fetching the array size
  public int size() {
    return size;
  }
// fetching the array element based on index
  public int get(int index) {
    validateIndex(index);
    return data[index];
  }
// setting array the element at the end of the array
  public void set(int item) {
    if(capacity <= size) {
      ensureCapacity();
    }
    data[size++] = item;
  }
// checking the capacity if array elements size exceeds the default capacity //then increasing the capacity

  private void ensureCapacity() {
    capacity = (capacity * 2);
    int oldData[] = data;
    data = new int[capacity];
    for(int i =0; i< oldData.length; i++) {
      data[i] = oldData[i];
    }
  }
// validating the array index
  private void validateIndex(int index) {
    if (index < 0 || index > size)
      throw new ArrayIndexOutOfBoundsException("ArrayIndexOutOfBoundsException - Index is " + index + ", Size is " + size);
  }

// removing the all array elements
  public void removeAll() {
    size = 0;
    capacity = 10;
  }

// checking the array is empty or not
  public boolean isEmpty() {
    return size == 0;
  }

}

public class DynamicArrayExample
{
  public static void main (String[] args)
  {
    DynamicArray dynamicArray = new DynamicArray();
    for(int i=0; i< 25; i++) {
      dynamicArray.set(i*2);
    }

    System.out.println("Array Elements : ");
    for(int i =0; i< dynamicArray.size(); i++) {
      System.out.println("Index : "+ ( i + 1 )+" Element : " + dynamicArray.get(i));
    }
    System.out.println("Is Array Empty: "+dynamicArray.isEmpty());

    System.out.println("Fetching the array element : "+dynamicArray.get(6));

    System.out.println("Clear the Array Elements");
    dynamicArray.removeAll();

    System.out.println("After Clearing Array Elements : ");
    for(int i =0; i< dynamicArray.size(); i++) {
      System.out.println("Index : "+ ( i + 1 )+" Element : " + dynamicArray.get(i));
    }

    System.out.println("Is Array Empty: "+dynamicArray.isEmpty());
  }
}

Output:

Array Elements :
Index : 1 Element : 0
Index : 2 Element : 2
Index : 3 Element : 4
Index : 4 Element : 6
Index : 5 Element : 8
Index : 6 Element : 10
Index : 7 Element : 12
Index : 8 Element : 14
Index : 9 Element : 16
Index : 10 Element : 18
Index : 11 Element : 20
Index : 12 Element : 22
Index : 13 Element : 24
Index : 14 Element : 26
Index : 15 Element : 28
Index : 16 Element : 30
Index : 17 Element : 32
Index : 18 Element : 34
Index : 19 Element : 36
Index : 20 Element : 38
Index : 21 Element : 40
Index : 22 Element : 42
Index : 23 Element : 44
Index : 24 Element : 46
Index : 25 Element : 48
Is Array Empty: false
Fetching the array element : 12
Clear the Array Elements
After Clearing Array Elements :
Is Array Empty: true

Sunday, November 10, 2013

Hibernate4.X Application example by using Gradle

Prerequisite requirement

- Installed and configured Maven, MySQL, Eclipse IDE.
- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpuf

Prerequisite requirement

- Installed and configured Maven, MySQL, Eclipse IDE.
- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpufPrerequisite requirement
- Installed and configured Maven, MySQL, Eclipse IDE.
- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpu

Prerequisite requirement

- Installed and configured Maven, MySQL, Eclipse IDE.
- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.
Step1: Create a Java project with Maven

Run the following command in terminal or command prompt to generate a standard java project.
Create a quick project file structure with Maven command ‘mvn archetype:generate‘ - See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpuf

[ranga@ranga gradle]$ mvn archetype:generate -DgroupId=com.ranga -DartifactId=HibernateExample1 -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Project structure:

HibernateExample1/
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── ranga
    │               └── App.java
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java

9 directories, 3 files

Step2: Create build file to execute App.java application.

create a new file called build.gradle under HibernateExample1 and the following content.

build.gradle
 
apply plugin: 'java'

task runApp(dependsOn: 'classes', type: JavaExec) {
    main = 'com.ranga.App'
    classpath = sourceSets.main.runtimeClasspath
}

defaultTasks 'runApp'

Project structure:

HibernateExample1/
├── build.gradle
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── ranga
    │               └── App.java
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java
9 directories, 4 files

Step3: Run the Java project by using gradle.

[ranga@ranga HibernateExample1]$ gradle -q runApp
Hello World!


Step4: Create a resources folder

Create a new folder called resources under src/main. Here we are adding the Configuration files and Mapping files.

Project structure:

HibernateExample1/
├── build.gradle
├── pom.xml
└── src
    ├── build.gradle
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── ranga
    │   │           └── App.java
    │   └── resources
    ├── pom.xml
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java

10 directories, 6 files

Step5: Hibernate configuration file

Create a Hibernate configuration file and put under the resources root folder, “src/main/resources/hibernate.cfg.xml“. Add the following content.

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>


        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="connection.username">ranga</property>
        <property name="connection.password">ranga</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>


       <!-- Mapping files  -->  

       <mapping resource="com/ranga/mapping/Employee.hbm.xml" />

    </session-factory>
</hibernate-configuration>


Step6: Hibernate Mapping file

Create a Employee.hbm.xml file and put it in “src/main/resources/com/ranga/mapping“ folder. 

Employee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.ranga.mapping">
    <class name="Employee" table="Employees">
        <id name="id" type="java.lang.Long">
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String" />
        <property name="age" type="java.lang.Integer">
    </class>
</hibernate-mapping> 


Project structure:

HibernateExample1/
├── build.gradle
├── pom.xml
└── src
    ├── build.gradle
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── ranga
    │   │           └── App.java
    │   └── resources
    │       ├── com
    │       │   └── ranga
    │       │       └── mapping
    │       │           └── Employee.hbm.xml
    │       └── hibernate.cfg.xml
    ├── pom.xml
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java

13 directories, 8 files
 

Step7: POJO class or Model class

Create a Employee.java file and put it in “src/main/java/com/ranga/mapping”

Employee.java

package com.ranga.mapping;

import java.io.Serializable;

public class Employee implements Serializable {
        private long id;
        private String name;
        private int age;

        public long getId() {
                return id;
        }
        public void setId(long id) {
                this.id = id;
        }
        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        public int getAge() {
                return age;
        }
        public void setAge(int age) {
                this.age = age;
        }

        @Override
        public String toString() {
           return "Employee [id = "+id+", name = "+name+", age = "+age+"]";
        }
}


Step8: Create Hibernate Utility class

Create a HibernateUtil.java class to take care of Hibernate start up and retrieve the session easily. Create a util folder and put this file in it, “src/main/java/com/ranga/util”.

HibernateUtil.java

package com.ranga.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
        private static final SessionFactory sessionFactory;
        private static final ServiceRegistry serviceRegistry;
        static {
                try {
                        // Create the SessionFactory from hibernate.cfg.xml
                        Configuration configuration = new Configuration();
                        configuration.configure();
                        serviceRegistry = new ServiceRegistryBuilder().applySettings(
                                        configuration.getProperties()).buildServiceRegistry();
                        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
                } catch (Throwable ex) {
                        // Make sure you log the exception, as it might be swallowed
                        System.err.println("Initial SessionFactory creation failed." + ex);
                        throw new ExceptionInInitializerError(ex);
                }
        }

        public static SessionFactory getSessionFactory() {
                return sessionFactory;
        }

        public static void closeSessionFactory() {
        if (sessionFactory != null)
            sessionFactory.close();
    }
}



Step 9: Client Application

App.java

package com.ranga;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.ranga.mapping.Employee;
import com.ranga.util.HibernateUtil;

public class App
{
    public static void main( String[] args )
    {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        Employee employee = new Employee();
        employee.setName("Ranga Reddy");
        employee.setAge(25);

        long employeeId  = (Long)session.save(employee);
        employee = (Employee) session.get(Employee.class, employeeId);

        System.out.println(employee);

        session.close();
    }
}


Project structure:

HibernateExample1/
├── build.gradle
├── pom.xml
└── src
    ├── build.gradle
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── ranga
    │   │           ├── App.java
    │   │           ├── mapping
    │   │           │   └── Employee.java
    │   │           └── util
    │   │               └── HibernateUtil.java
    │   └── resources
    │       ├── com
    │       │   └── ranga
    │       │       └── mapping
    │       │           └── Employee.hbm.xml
    │       └── hibernate.cfg.xml
    ├── pom.xml
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java

15 directories, 10 files


Now the Hibernate Application is ready.

Step10: Run the hibernate application

[ranga@ranga HibernateExample1]$ gradle runApp
 

Output:

Employee [id = 1, name = Ranga Reddy, age = 25]

Download

Developing a Sample HelloWorld Java Program by using Maven

Step1: Create a HelloWorld java project by using mvn command.

[ranga@ranga Documents]$ mvn archetype:generate -DgroupId=com.ranga -DartifactId=HelloWorld -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Project Structure looks like

HelloWorld
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── ranga
    │               └── App.java
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java

9 directories, 3 files

Step2:

edit the pom.xml and add the following line to run a application  

<build>
    <plugins>
        <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.0.2</version>
        <configuration>
                <source>1.6</source>
                <target>1.6</target>
        </configuration>
     </plugin>
        <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <configuration>
             <mainClass>com.ranga.App</mainClass>
        </configuration>
        </plugin>
    </plugins>
   </build>
 
Step3: Run the following command to compile and run. 

[ranga@ranga HelloWorld]$ mvn compile exec:java

Hello World!