Creating custom function on JavaScript String startsWith and endsWith


if (typeof String.prototype.startsWith != 'function') {
                String.prototype.startsWith = function(str) {
                    return this.slice(0, str.length) == str;
                };
}

if (typeof String.prototype.endsWith != 'function') {
                String.prototype.endsWith = function(str) {
                    return this.slice(-str.length) == str;
                };
}
alert('mankind'.startsWith('man'));
alert('mankind'.endsWith('kind'));

Posted in Javascript, JQuery | Leave a comment

Hibernate Inheritance: Table Per Concrete Class

package taher.javahunter.hibernate;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
 
 
@Entity
@Table(name = "PERSON")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Person {
 
    @Id
    @Column(name = "PERSON_ID")
    private Long personId;
     
    @Column(name = "FIRSTNAME")
    private String firstname;
     
    @Column(name = "LASTNAME")
    private String lastname;
     
    public Person() {
     
    }
    public Person(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }
    // Getter and Setter methods, 
}
package taher.javahunter.hibernate;
 
import java.util.Date;
 
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
 
@Entity
@Table(name="EMPLOYEE")
@AttributeOverrides({
    @AttributeOverride(name="firstname", column=@Column(name="FIRSTNAME")),
    @AttributeOverride(name="lastname", column=@Column(name="LASTNAME"))
})
public class Employee extends Person {
 
    @Column(name="joining_date")
    private Date joiningDate;
     
    @Column(name="department_name")
    private String departmentName;
 
    public Employee() {
    }
     
    public Employee(String firstname, String lastname, String departmentName, Date joiningDate) {
         
        super(firstname, lastname);
         
        this.departmentName = departmentName;
        this.joiningDate = joiningDate;
    }
     
    // Getter and Setter methods, 
}
package taher.javahunter.hibernate;
 
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
 
@Entity
@Table(name="OWNER")
@AttributeOverrides({
    @AttributeOverride(name="firstname", column=@Column(name="FIRSTNAME")),
    @AttributeOverride(name="lastname", column=@Column(name="LASTNAME"))
})
public class Owner extends Person {
 
    @Column(name="stocks")
    private Long stocks;
     
    @Column(name="partnership_stake")
    private Long partnershipStake;
 
    public Owner() {
    }
     
    public Owner(String firstname, String lastname, Long stocks, Long partnershipStake) {
         
        super(firstname, lastname);
         
        this.stocks = stocks;
        this.partnershipStake = partnershipStake;
    }
 
    // Getter and Setter methods, 
}
Output :

Hibernate: insert into PERSON (FIRSTNAME, LASTNAME, PERSON_ID) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME, department_name, joining_date, PERSON_ID) values (?, ?, ?, ?, ?)
Hibernate: insert into OWNER (FIRSTNAME, LASTNAME, partnership_stake, stocks, PERSON_ID) values (?, ?, ?, ?, ?)

Posted in Hibernate | Leave a comment

Hibernate Inheritance: Table Per Subclass

CREATE TABLE `person` (
    `person_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
    `firstname` VARCHAR(50) NOT NULL DEFAULT '0',
    `lastname` VARCHAR(50) NOT NULL DEFAULT '0',
    PRIMARY KEY (`person_id`)
)
 
CREATE TABLE `employee` (
    `person_id` BIGINT(10) NOT NULL,
    `joining_date` DATE NULL DEFAULT NULL,
    `department_name` VARCHAR(50) NULL DEFAULT NULL,
    PRIMARY KEY (`person_id`),
    CONSTRAINT `FK_PERSON` FOREIGN KEY (`person_id`) REFERENCES `person` (`person_id`)
)
 
CREATE TABLE `owner` (
    `person_id` BIGINT(20) NOT NULL DEFAULT '0',
    `stocks` BIGINT(11) NULL DEFAULT NULL,
    `partnership_stake` BIGINT(11) NULL DEFAULT NULL,
    PRIMARY KEY (`person_id`),
    CONSTRAINT `FK_PERSON2` FOREIGN KEY (`person_id`) REFERENCES `person` (`person_id`)
)
package taher.javahunter.hibernate;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
 
 
@Entity
@Table(name = "PERSON")
@Inheritance(strategy=InheritanceType.JOINED)
public class Person {
 
    @Id
    @GeneratedValue
    @Column(name = "PERSON_ID")
    private Long personId;
     
    @Column(name = "FIRSTNAME")
    private String firstname;
     
    @Column(name = "LASTNAME")
    private String lastname;
     
    public Person() {
     
    }
    public Person(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }
 
    // Getter and Setter methods, 
}
package taher.javahunter.hibernate;
 
import java.util.Date;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
 
@Entity
@Table(name="EMPLOYEE")
@PrimaryKeyJoinColumn(name="PERSON_ID")
public class Employee extends Person {
 
    @Column(name="joining_date")
    private Date joiningDate;
     
    @Column(name="department_name")
    private String departmentName;
 
    public Employee() {
    }
     
    public Employee(String firstname, String lastname, String departmentName, Date joiningDate) {
         
        super(firstname, lastname);
         
        this.departmentName = departmentName;
        this.joiningDate = joiningDate;
    }
 
    // Getter and Setter methods, 
}
package taher.javahunter.hibernate;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
 
@Entity
@Table(name="OWNER")
@PrimaryKeyJoinColumn(name="PERSON_ID")
public class Owner extends Person {
 
    @Column(name="stocks")
    private Long stocks;
     
    @Column(name="partnership_stake")
    private Long partnershipStake;
 
    public Owner() {
    }
     
    public Owner(String firstname, String lastname, Long stocks, Long partnershipStake) {
         
        super(firstname, lastname);
         
        this.stocks = stocks;
        this.partnershipStake = partnershipStake;
    }
 
    // Getter and Setter methods, 
}
Output :

Hibernate: insert into PERSON (firstname, lastname) values (?, ?)
Hibernate: insert into PERSON (firstname, lastname) values (?, ?)
Hibernate: insert into Employee (department_name, joining_date, person_id) values (?, ?, ?)
Hibernate: insert into PERSON (firstname, lastname) values (?, ?)
Hibernate: insert into Owner (stocks, partnership_stake, person_id) values (?, ?, ?)

Posted in Hibernate | Leave a comment

Hibernate Inheritance: Table Per Class Hierarchy

* class Person
– firstname
– lastname

* class Employee
– joining_date
– department_name

package taher.javahunter.hibernate;
 
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
 
 
@Entity
@Table(name = "PERSON")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name="discriminator",
    discriminatorType=DiscriminatorType.STRING
)
@DiscriminatorValue(value="P")
public class Person {
 
    @Id
    @GeneratedValue
    @Column(name = "PERSON_ID")
    private Long personId;
     
    @Column(name = "FIRSTNAME")
    private String firstname;
     
    @Column(name = "LASTNAME")
    private String lastname;
     
    // Constructors and Getter/Setter methods, 
}
package taher.javahunter.hibernate;
 
import java.util.Date;
 
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;
 
@Entity
@Table(name="PERSON")
@DiscriminatorValue("E")
public class Employee extends Person {
 
    @Column(name="joining_date")
    private Date joiningDate;
     
    @Column(name="department_name")
    private String departmentName;
 
    // Constructors and Getter/Setter methods, 
}
Output :

Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME, discriminator) values (?, ?, ‘P’)
Hibernate: insert into EMPLOYEE (FIRSTNAME, LASTNAME, department_name, joining_date, discriminator) values (?, ?, ?, ?, ‘E’)

Posted in Hibernate | Leave a comment

Spring AOP

Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.

In Spring AOP, 4 type of advices are supported :

Before advice – Run before the method execution
After returning advice – Run after the method returns a result
After throwing advice – Run after the method throws an exception
Around advice – Run around the method execution, combine all three advices above.
Following example show you how Spring AOP advice works.

Simple Spring example
Create a simple customer service class with few print methods for demonstration later.

package com.javahunter.customer.services;
 
public class CustomerService {
	private String name;
	private String url;
 
	public void setName(String name) {
		this.name = name;
	}
 
	public void setUrl(String url) {
		this.url = url;
	}
 
	public void printName() {
		System.out.println("Customer name : " + this.name);
	}
 
	public void printURL() {
		System.out.println("Customer website : " + this.url);
	}
 
	public void printThrowException() {
		throw new IllegalArgumentException();
	}
 
}

File : Spring-Customer.xml – A bean configuration file

<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-2.5.xsd">
 
	<bean id="customerService" class="com.javahunter.customer.services.CustomerService">
		<property name="name" value="Taher Java Hunter" />
		<property name="url" value="https://javahunter.wordpress.com" />
	</bean>
 
</beans>

Run it

package com.javahunter.common;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.javahunter.customer.services.CustomerService;
 
public class App {
	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(
				new String[] { "Spring-Customer.xml" });
 
		CustomerService cust = (CustomerService) appContext.getBean("customerService");
 
		System.out.println("*************************");
		cust.printName();
		System.out.println("*************************");
		cust.printURL();
		System.out.println("*************************");
		try {
			cust.printThrowException();
		} catch (Exception e) {
 
		}
 
	}
}
Output :

*************************
Customer name : Taher Java Hunter
*************************
Customer website : https://javahunter.wordpress.com
*************************

A simple Spring project to DI a bean and output some Strings.

Spring AOP Advices
Now, attach Spring AOP advices to above customer service.

1. Before advice
It will execute before the method execution. Create a class which implements MethodBeforeAdvice interface.

package com.javahunter.aop;
 
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
 
public class HijackBeforeMethod implements MethodBeforeAdvice
{
	@Override
	public void before(Method method, Object[] args, Object target)
		throws Throwable {
	        System.out.println("HijackBeforeMethod : Before method hijacked!");
	}
}

In bean configuration file (Spring-Customer.xml), create a bean for HijackBeforeMethod class , and a new proxy object named ‘customerServiceProxy‘.

‘target’ – Define which bean you want to hijack.
‘interceptorNames’ – Define which class (advice) you want to apply on this proxy /target object.

<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-2.5.xsd">
 
	<bean id="customerService" class="com.javahunter.customer.services.CustomerService">
		<property name="name" value="Taher Java Hunter" />
		<property name="url" value="https://javahunter.wordpress.com" />
	</bean>
 
	<bean id="hijackBeforeMethodBean" class="com.javahunter.aop.HijackBeforeMethod" />
 
	<bean id="customerServiceProxy" 
                 class="org.springframework.aop.framework.ProxyFactoryBean">
 
		<property name="target" ref="customerService" />
 
		<property name="interceptorNames">
			<list>
				<value>hijackBeforeMethodBean</value>
			</list>
		</property>
	</bean>
</beans>

Note
To use Spring proxy, you need to add CGLIB2 library. Add below in Maven pom.xml file.

	<dependency>
		<groupId>cglib</groupId>
		<artifactId>cglib</artifactId>
		<version>2.2.2</version>
	</dependency>	
	

Run it again, now you get the new customerServiceProxybean instead of the original customerService bean.

package com.javahunter.common;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.javahunter.customer.services.CustomerService;
 
public class App {
	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(
				new String[] { "Spring-Customer.xml" });
 
		CustomerService cust = 
                                (CustomerService) appContext.getBean("customerServiceProxy");
 
		System.out.println("*************************");
		cust.printName();
		System.out.println("*************************");
		cust.printURL();
		System.out.println("*************************");
		try {
			cust.printThrowException();
		} catch (Exception e) {
 
		}
 
	}
}
Output :

*************************
HijackBeforeMethod : Before method hijacked!
Customer name : Taher Java Hunter
*************************
HijackBeforeMethod : Before method hijacked!
Customer website : https://javahunter.wordpress.com
*************************
HijackBeforeMethod : Before method hijacked!

It will run the HijackBeforeMethod’s before() method, before every customerService’s methods are execute.

2. After returning advice
It will execute after the method is returned a result. Create a class which implements AfterReturningAdvice interface.

package com.javahunter.aop;
 
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
 
public class HijackAfterMethod implements AfterReturningAdvice
{
	@Override
	public void afterReturning(Object returnValue, Method method,
		Object[] args, Object target) throws Throwable {
	        System.out.println("HijackAfterMethod : After method hijacked!");
	}
}

Bean configuration file

<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-2.5.xsd">
 
	<bean id="customerService" class="com.javahunter.customer.services.CustomerService">
		<property name="name" value="Taher Java Hunter" />
		<property name="url" value="https://javahunter.wordpress.com" />
	</bean>
 
	<bean id="hijackAfterMethodBean" class="com.javahunter.aop.HijackAfterMethod" />
 
	<bean id="customerServiceProxy" 
                class="org.springframework.aop.framework.ProxyFactoryBean">
 
		<property name="target" ref="customerService" />
 
		<property name="interceptorNames">
			<list>
				<value>hijackAfterMethodBean</value>
			</list>
		</property>
	</bean>
</beans>

Run it again,

Output :

*************************
Customer name : Taher Java Hunter
HijackAfterMethod : After method hijacked!
*************************
Customer website : https://javahunter.wordpress.com
HijackAfterMethod : After method hijacked!
*************************

It will run the HijackAfterMethod’s afterReturning() method, after every customerService’s methods that are returned result.

3. After throwing advice
It will execute after the method throws an exception. Create a class which implements ThrowsAdvice interface, and create a afterThrowing method to hijack the IllegalArgumentException exception.

package com.javahunter.aop;
 
import org.springframework.aop.ThrowsAdvice;
 
public class HijackThrowException implements ThrowsAdvice {
	public void afterThrowing(IllegalArgumentException e) throws Throwable {
		System.out.println("HijackThrowException : Throw exception hijacked!");
	}
}

Bean configuration file

<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-2.5.xsd">
 
	<bean id="customerService" class="com.javahunter.customer.services.CustomerService">
		<property name="name" value="Taher Java Hunter" />
		<property name="url" value="https://javahunter.wordpress.com" />
	</bean>
 
	<bean id="hijackThrowExceptionBean" class="com.javahunter.aop.HijackThrowException" />
 
	<bean id="customerServiceProxy" 
                 class="org.springframework.aop.framework.ProxyFactoryBean">
 
		<property name="target" ref="customerService" />
 
		<property name="interceptorNames">
			<list>
				<value>hijackThrowExceptionBean</value>
			</list>
		</property>
	</bean>
</beans>

Run it again,

Output :

*************************
Customer name : Taher Java Hunter
*************************
Customer website : https://javahunter.wordpress.com
*************************
HijackThrowException : Throw exception hijacked!

It will run the HijackThrowException’s afterThrowing() method, if customerService’s methods throw an exception.

4. Around advice
It combines all three advices above, and execute during method execution. Create a class which implements MethodInterceptor interface. You have to call the “methodInvocation.proceed();” to proceed on the original method execution, else the original method will not execute.

package com.javahunter.aop;
 
import java.util.Arrays;
 
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
 
public class HijackAroundMethod implements MethodInterceptor {
	@Override
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
 
		System.out.println("Method name : "
				+ methodInvocation.getMethod().getName());
		System.out.println("Method arguments : "
				+ Arrays.toString(methodInvocation.getArguments()));
 
		// same with MethodBeforeAdvice
		System.out.println("HijackAroundMethod : Before method hijacked!");
 
		try {
			// proceed to original method call
			Object result = methodInvocation.proceed();
 
			// same with AfterReturningAdvice
			System.out.println("HijackAroundMethod : Before after hijacked!");
 
			return result;
 
		} catch (IllegalArgumentException e) {
			// same with ThrowsAdvice
			System.out.println("HijackAroundMethod : Throw exception hijacked!");
			throw e;
		}
	}
}

Bean configuration file

<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-2.5.xsd">
 
	<bean id="customerService" class="com.javahunter.customer.services.CustomerService">
		<property name="name" value="Taher Java Hunter" />
		<property name="url" value="https://javahunter.wordpress.com" />
	</bean>
 
	<bean id="hijackAroundMethodBean" class="com.javahunter.aop.HijackAroundMethod" />
 
	<bean id="customerServiceProxy" 
                class="org.springframework.aop.framework.ProxyFactoryBean">
 
		<property name="target" ref="customerService" />
 
		<property name="interceptorNames">
			<list>
				<value>hijackAroundMethodBean</value>
			</list>
		</property>
	</bean>
</beans>

Run it again,

Output :

*************************
Method name : printName
Method arguments : []
HijackAroundMethod : Before method hijacked!
Customer name : Taher Java Hunter
HijackAroundMethod : Before after hijacked!
*************************
Method name : printURL
Method arguments : []
HijackAroundMethod : Before method hijacked!
Customer website : https://javahunter.wordpress.com
HijackAroundMethod : Before after hijacked!
*************************
Method name : printThrowException
Method arguments : []
HijackAroundMethod : Before method hijacked!
HijackAroundMethod : Throw exception hijacked!

It will run the HijackAroundMethod’s invoke()method, after every customerService’s method execution.

Conclusion
Most of the Spring developers are just implements the ‘Around advice ‘, since it can apply all the advice type, but a better practice should choose the most suitable advice type to satisfy the requirements.

Posted in Spring | Tagged , | Leave a comment

Check String is Numeric in Java

public static  boolean isNumeric(String nums){
        List<Integer> numbers = Arrays.asList(new Integer[]{46,48,49,50,51,52,53,54,55,56,57});
        int numCnt=0;
        char[] c = nums.toCharArray();
        for (int d : c) {
            if(numbers.contains(d)){
                numCnt++;                
            }
        }
        return numCnt == c.length;
    }
Posted in Core JAVA, Scripting in JAVA | Leave a comment

Reverse AJAX using AsyncServlet support in Servlet 3.0

Introduction

If you already know why and when to use reverse ajax, you can skip this section. But for those novice developers don’t know these answers I prefer go through this section.

Nowadays reverse ajax is used every now and then. Its very much needed in any type of website. Whether is any social network website or some serious business, it is needed to decrease the network traffic and also for better user interaction. Its because of the reverse ajax you gets the instant notification update in facebook(isn’t that fascinating?). But as a web developer I like the way reverse ajax is used in StackOverflow. They always keeps you updated with any new up votes to your answer or any new comments you have got for your answer or question. You can also take example of any chat service provided. Think, how you get to know that the person with whom you are chatting is right now typing something or how you gets the line typed by that person in your chat box. You are not pressing any button to get this responses. You get to know this whenever the other person is performing something and server knows that event is occurred and then it broadcasts that event to you without your request. Simple ajax request-response performed on client’s request to perform some action on server side so that the page doesn’t gets reloaded. Reverse ajax is any response you get from server without client’s request. That response is sent by the server whenever a specific event occurs on the server side. And it keeps on sending such response on every such event occurs on the server side. I think this is enough for you to know why and when reverse ajax is needed in a web application.

Reverse AJAX technologies

There are many ways you can implement reverse ajax. For example apache comet, atmosphere etc. You can use them also. Both of them provide good support with Spring Framework as well. But they require good amount of configuration and including those libraries in your application is some what overhead to your application size. And if you can do the same thing by just playing with the much familiar servlet API itself then why to include other libraries. AsyncServlet is introduced in the Servlet 3.0 version. And I found it very easy to implement and useful. If satisfies our need of reverse ajax very efficiently. We will also use quartz scheduler to perform job of sending the pending responses to the client. We will also use Queue and Map data structure. Queue will hold the pending responses to be sent. And the Map will hold a key(type of your choice as per need) and an ArrayList consisting watchers(waiting for some response from server). You will come to know about usage of these in coming sections one by one. Now just sit back, relax and go through next few sections of real time example.

Chat Box Example

In this example we will try to create a group chat box that can have any number of users chatting in a group created.

Web.xml

Posted in Servlet, Uncategorized | Leave a comment