Saturday, 22 November 2014

Adding internationalization support to spring mvc with thymeleaf

For basic Thymeleaf configuration check Spring MVC with Thymeleaf

Thymeleaf uses Standerd messange resolver unless specified which on to use. We can also use Spring internationalization support which will be supported by default by Thymeleaf.

Steps:

  1. Add messages_en file to src/main/resources/

  2. Add spring beans those will support internationalization.
    <?xml version="1.0" encoding="UTF-8"?>
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages" />
    <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lang" />
    </bean>

    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <property name="defaultLocale" value="en" />
    </bean>

    <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="interceptors">
    <ref bean="localeChangeInterceptor" />
    </property>
    </bean>


  3. LocaleChangeInterceptor is handler mapping that need to supports the multiple languages. The "paramName" is the parameter value that’s used to set the locale.

  4. Use ?lang=fr to change language to French from default English.


Source: Source Code

Thursday, 20 November 2014

Java Concurrency - Processes and Threads

Process


Process is self contained environment meaning it got its own basic resources importantly own memory space. For communication between processes we need interprocess communication (sockets, pipes etc) provide by operating system.

Most implementations of JMV runs as single process. Java application can create multiple or additional processes by using java.lang.ProcessBuilder object.

Threads


Threads exists within process and every process has at least one thread. Thread share process's resources that includes memory, open files etc; hence creating new thread requires few resources. Threads sometime called as lightweight process. Each thread is associated with instance of class Thread.

Their are two strategies of  Thread
1. Manual - Control thread creation and management by instantiating Thread each time application want to perform asynchronous task
2. Executors - Separate thread management from application by passing tasks to Executor.

Defining and starting a thread

1. Provide Runnable object - Implement Runnable interface which defines a single method run()
2. Subclass Thread class - Extends Thread class.

It will be wise to implement Runnable interface instated of extending Thread class. Coz we can extend other classes if required if we implement Runnable interface but we can not if we extend Thread class.

Thread.sleep(long miliSeconds) causes current thread to suspend execution for specific time. Sleep timings are not guarantied to be precise as it depends on facilities provided by underlaying operating system.

Good example of basic thread working

Ref: Java SE tutorials

Saturday, 15 November 2014

Design Pattern - Singleton

Singleton is simple pattern which guaranty  only one instance of object is present. Singleton is term taken from mathematical concept "Singleton is a set with exactly one element"

Singleton is achieved in java by

  1. By making default constructor private - hence you can not initialised the class .

  2. Having static method that can return you instance - control over how to create object

  3. Having self instance private static and volatile - Thread safe unique instance.


Note: volatile from Java 5 means value of variable will not be tread-locally cached. Value will be updated directly in main memory. Variable will act like its synchronised on its self.

Below is sample for double check singleton:
public class Singleton {
private volatile static Singleton INSTANCE;

private Singleton() {

}

public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}

Reference:  WikiHead First Design Patterns

Tuesday, 11 November 2014

StringBuffer vs StringBuilder

To check StringBuffer vs StringBuilder we must check AbstractStringBuffer first coz both StringBuffer and StringBuilder extends AbstractStringBuilder.


AbstractStringBuilder


AbstractStringBuilder has 'char value[]' that is used for holding string in from of char sequence. 'int count' is used for storing number of characters stored.


Important methods in AbstractStringBuilder:

  1. capacity(): Capacity is amount of store available for newly inserted characters

  2.  insert(int, <T>): insert <T> into character sequence at int.

  3. reverse(): Reverse of the character sequence

  4. append(): Append to the character sequence

  5.  toString(): Only abstract method in AbstractStringBuilder


  6. getValue(): This is a final method that returns char value[];




In simple words all operations are done on array of characters which is present in AbstractStringBuilder.

Now StringBuffer vs StringBuilder

  1. StringBuffer and StringBuilder extends AbastractStringBuilder

  2. Both use AbastractStringBuilder for logical operation and has minimal code written in them

  3. Both implements toString() where they create new String and do not share char value[] with String.

  4. Both implements writeObject() &  readObject()


Now the major and important difference is all important methods in StringBuffer are synchronized. Due to non synchronized methonds StringBuilder performs better than StringBuffer.

Friday, 7 November 2014

String Basics

Strings: String is a class used for manipulating strings. String is character array and implemented in same way. String is object in java.

Creating String:
String can be created in multiple ways

  1. By using one of thirteen constructors provided by String class (or using new keyword)

  2. By using '=' operator (or String literal)


Important difference between them is when we create String object using String literal JVM checks string pool if found string object will be returned else new object will be created; but in case of new JVM will create new object without checking in string pool.

String equality:
String equal method check each character in character array that is present inside String; where as '==' checks object memory location.

String pool:
String pool is special memory location where JVM keeps all string objects

String and security:
If we keep sensitive data in String due to immutable nature we can't erase that data. Someone who got access to java memory like access to heap dump can read that information.
We should keep password in char array and reset them once they are no longer needed.

Character encoding:
By default String will use same encoding as underlaying platform i.e. character encoding of server. This can cause issues if server is not supporting unicode encoding like UTF-8 or UTF-16. This can be changed by using system property "file.encoding"

Wednesday, 5 November 2014

Java Database Connectivity (JDBC) basics

Simple JDBC program demonstrating java connectivity with database.

Drivers:
The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to connect to the target URL.

When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a driver by calling

Class.forName("foo.bah.Driver")

Connection:
A Connection is like a session with database. Applications should not invoke SQL commands directly to change the connection's configuration when there is a JDBC method available. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved. Following code is used for getting connection.
DriverManager.getConnection(java.lang.String, java.util.Properties)

Note:In JDBC 4.0, we no longer need to explicitly load JDBC drivers using Class.forName().

Statement:
Statements are  used for executing a static SQL statement and returning the results it produces.

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
Connection.createStatement(),

ResultSet:
ResultSet is a table of data representing a database result set.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.
A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable.
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, name FROM employees");

 

Monday, 3 November 2014

Hibernate entity manager and persistence.xml

Hibernate entity manager and persistence.xml 

javax.persistence.jdbc.driver: The JDBC driver class
H2 – org.h2.Driver
Oracle – oracle.jdbc.driver.OracleDriver
MySql – com.mysql.jdbc.Driver

javax.persistence.jdbc.url: The JDBC URL to the database instance.
H2 – jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE
Oracle – jdbc:oracle:thin:@127.0.0.1:1521:DBNAME
MySql – jdbc:mysql://localhost/DBNAME

javax.persistence.jdbc.user: The database user name

javax.persistence.jdbc.password: The database user password

Other hibernate properties can be used as required like below
<property name="hibernate.show_sql" value="true" />

Example:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="com.njoshi.hibernate.employeemanager">
<description>Persistence unit for employee manager</description>

<class>com.njoshi.hibernate.employeemanager.entity.Employee</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />

<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>

</persistence-unit>
</persistence>

Source: Employee Manager

Sunday, 2 November 2014

Hibernat basic: annotations

Hibernate basic without annotations

@Entity [javax.persistence.Entity]: Specifies that the class is an entity
-name: (Optional) The entity name. Defaults to the unqualified name of the entity class. This name is used to refer to the entity in queries. The name must not be a reserved literal in the Java Persistence query language

@Table [javax.persistence.Table]: Specifies the primary table for the annotated entity. Additional tables may be specified using SecondaryTable or SecondaryTables annotation. If no Table annotation is specified for an entity class, the default values apply.
-name: (Optional) The name of the table
-catalog: (Optional) The catalog of the table
-schema: (Optional) The schema of the table.
-uniqueConstraints: (Optional) Unique constraints that are to be placed on the table.

@Column [javax.persistence.Column]: Specifies the mapped column for a persistent property or field.
-String name: (Optional) The name of the column. Defaults to the property or field name.
-boolean unique: (Optional) Whether the column is a unique key. This is a shortcut for the UniqueConstraint annotation at the table level and is useful for when the unique key constraint corresponds to only a single column. This constraint applies in addition to any constraint entailed by primary key mapping and to constraints specified at the table level.
-boolean nullable: (Optional) Whether the database column is nullable.
-int length: (Optional) The column length. (Applies only if a string-valued column is used.) Default 255
-int precision: (Optional) The precision for a decimal (exact numeric) column. (Applies only if a decimal column is used.) Value must be set by developer if used when generating the DDL for the column.
-int scale: (Optional) The scale for a decimal (exact numeric) column. (Applies only if a decimal column is used.)
-String table: (Optional) The name of the table that contains the column. If absent the column is assumed to be in the primary table.
-String columnDefinition: (Optional) The SQL fragment that is used when generating the DDL for the column. Defaults to the generated SQL to create a column of the inferred type.
-boolean insertable: (Optional) Whether the column is included in SQL INSERT statements generated by the persistence provider.
-boolean updatable: (Optional) Whether the column is included in SQL UPDATE statements generated by the persistence provider.

@GeneratedValue [javax.persistence.GeneratedValue]:  Provides for the specification of generation strategies for the values of primary keys.
-GenerationType strategy: (Optional) The primary key generation strategy that the persistence provider must use to generate the annotated entity primary key.
-String generator: (Optional) The name of the primary key generator to use as specified in the SequenceGenerator or TableGenerator annotation. Default:javax.persistence.GenerationType.AUTO

javax.persistence.GenerationType
-AUTO: Indicates that the persistence provider should pick an appropriate strategy for the particular database.
-IDENTITY: Indicates that the persistence provider must assign primary keys for the entity using a database identity column.
-SEQUENCE: Indicates that the persistence provider must assign primary keys for the entity using a database sequence.
-TABLE: Indicates that the persistence provider must assign primary keys for the entity using an underlying database table to ensure uniqueness.

@Id [javax.persistence.Id]: Specifies the primary key of an entity. The field or property to which the Id annotation is applied should be one of the following types: any Java primitive type; any primitive wrapper type; String; java.util.Date; java.sql.Date; java.math.BigDecimal; java.math.BigInteger. The mapped column for the primary key of the entity is assumed to be the primary key of the primary table. If no Column annotation is specified, the primary key column name is assumed to be the name of the primary key property or field.

@Temporal [javax.persistence.Temporal]: This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.
-TemporalType value: The type used in mapping java.util.Date or java.util.Calendar.
javax.persistence.TemporalType: Type used to indicate a specific mapping of java.util.Date or java.util.Calendar.
DATE: Map as java.sql.Date
TIME: Map as java.sql.Time
TIMESTAMP: Map as java.sql.Timestamp

Example:
package com.njoshi.hibernate.employeemanager.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "employees", uniqueConstraints = @UniqueConstraint(columnNames = {
"emp_no", "emp_name" }))
public class Employee {

@Id
@Column(name = "emp_no", nullable = false)
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
private Long empNo;

@Column(name = "emp_name", length = 16, nullable = false)
private String empName;

@Column(name = "first_name", length = 14, nullable = false)
private String firstName;

@Column(name = "last_name", length = 16, nullable = false)
private String lastName;

@Temporal(TemporalType.DATE)
@Column(name = "hire_date", nullable = false)
private Date hireDate;

@Temporal(TemporalType.DATE)
@Column(name = "birth_date", nullable = false)
private Date birthDate;

public Employee() {

}

public Employee(String firstName, String empName, String lastName,
Date birthDate, Date hireDate) {
this.empName = empName;
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
this.hireDate = hireDate;
}

public Long getEmpNo() {
return empNo;
}

public void setEmpNo(Long empNo) {
this.empNo = empNo;
}

public Date getBirthDate() {
return birthDate;
}

public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Date getHireDate() {
return hireDate;
}

public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}

@Override
public String toString() {
return "Employee [empNo=" + empNo + ", firstName=" + firstName
+ ", lastName=" + lastName + ", hireDate=" + hireDate
+ ", birthDate=" + birthDate + "]";
}

}

Source: Employee Manager