I was getting trained on design patterns and this question came into my mind when we were discussing about ‘Prototype Design Pattern’ – when should I used object cloning in java ?

Finally after a bit of google search, i found a satisfactory answer or scenario where it can be of great help.

Quite often you want to use immutable objects, in which case cloning is an essential part of your code. If for example you have an immutable object that has a list or array type field, your getter should always return a clone of the list or array to preserve immutability.

The other typical use case is when you want “transactional” modifications, when you call several state changing methods but only want the result to be visible if all of them are successful.

We are making use of the isWhitespace(char ch) method of the java.lang.Character class.

public static String ltrim(String s) {
int i = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
i++;
}
return s.substring(i);
}

public static String rtrim(String s) {
int i = s.length() – 1;
while (i > 0 && Character.isWhitespace(s.charAt(i))) {
i–;
}
return s.substring(0, i + 1);
}

Unicode Surrogate characters do not represent characters by themselves, but are used in the representation of supplementary characters in the UTF-16 encoding.
A char value is a surrogate code unit if and only if it is either a low-surrogate code unit or a high-surrogate code unit.

java.lang.Character class provides a method

public static boolean isSurrogate(char ch)

ch – is the character that you have to check for
This method returns true if the char value is between MIN_SURROGATE and MAX_SURROGATE inclusive; false otherwise.

MIN_SURROGATE and MAX_SURROGATE are already defined in Character class

public static final char MIN_SURROGATE = “\uDFFF”;
public static final char MIN_SURROGATE = “\uD800″;

Example :

You can try either of the following 2 code snippets

public static String trimUnicodeSurrogateCharacters(String text) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (!Character.isSurrogate(ch)) {
sb.append(ch);
}
}
return sb.toString();
}

OR

public static String trimUnicodeSurrogateCharacters(String text) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (!Character.isHighSurrogate(ch) && !Character.isLowSurrogate(ch)) {
sb.append(ch);
}
}
return sb.toString();
}

 

 

Recently I was working on primefaces and happen to come across this scenario,
where I had to remove all the leading & trailing white spaces along with successive spaces
from a string field.

I guess you guys are here for the below script. ENJOY !!

<h:outputLabel>Vehicle Make<span>*</span></h:outputLabel>
<p:inputText id=”veh_make” value=”#{vinBean.make}” maxlength=”50″ onchange=”trim(this)”>

<script language=”javascript”>
function trim(inputText) {
inputText.value = inputText.value.replace(/\s+/g,’ ‘).replace(/^\s+|\s+$/,”);
}
</script>

This is one of the common problems that might arise if you are using MySQL Database for your project.

Often our project encoding is UTF-8 but many are not aware of the fact that MySQL supports utf8-support_ci format for the database columns. In such cases, while we are trying to persist the application data into the MySQL database, we will encounter the following error. 

 SQL state [HY000]; error code [1366]

This is due to Unicode Surrogates. (You can read more about them here http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Surrogates ) Surrogate characters are not real characters. They are reserved for UTF-16 encoding.

So the fix for this problem is to trim these character using the method  

boolean java.lang.Character.isHighSurrogate(char ch)   and   boolean java.lang.Character.isLowSurrogate(char ch)

Example :

public static String trimUnicodeSurrogateCharacters(String message) {
    StringBuilder sb = new StringBuilder();
   for (int i = 0; i < message.length(); i++) {
         char ch = text.charAt(i);
         if (!Character.isHighSurrogate(ch) && !Character.isLowSurrogate(ch)) {
             sb.append(ch);
      }
  }
 return sb.toString();
}

Quartz

Posted: April 12, 2012 in Database
Tags: , , ,

Quartz

  • Quartz is an open source job scheduling framework written in Java.
  • Quartz contains all of the core Quartz functionality and it is distributed as a small java library (quartz.jar).
  • Scheduler Interface is the main interface (API) which provides some simple operations like scheduling jobs, unscheduling jobs, starting/stopping/pausing the scheduler.
  • If we want a scheduler in our application, then we must implement the Job Interface and override the execute() method.
  • We implement the TriggerListener or JobListener interface when we want to be notified when the scheduled trigger time arrives.
  • When the Scheduler determines the notifying time to your job, the Quartz framework will call the execute() method on your Job class.

Now let’s see how to create a scheduler and use it.

The first step is to instantiate the scheduler using ‘SchedulerFactory’

SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();

Scheduler sched = schedFact.getScheduler();

Once a scheduler is instantiated, it can be started, paused, and shutdown. Note that once a scheduler is shutdown, it cannot be restarted without being re-instantiated. Triggers do not fire (jobs do not execute) until the scheduler has been started, nor while it is in the paused state.

Now let’s start the scheduler and schedule a job for execution

sched.start();

JobDetail jobDetail = new JobDetail(“myJob”, sched.DEFAULT_GROUP, MyJob.class);  // MyJob.class is the Job class

SimpleTrigger trigger = new SimpleTrigger(“myTrigger”, sched.DEFAULT_GROUP, new Date(), null, 0, 0L);

sched.scheduleJob(jobDetail, trigger);

Job Detail

Quartz needs to be informed about various attributes that you may wish the job to have. This is done via the JobDetail class through it arguments -’ job name,

job group and the java class to execute‘ respectively.

The JobDetail object is created by the Quartz client (your program) at the time the Job is added to the scheduler.

Every time the scheduler gets executed, a new instance of the Job class is created.

Suppose, you want to pass some properties/configuration to the job instance. In that case we use JobDataMap, which is a part of the JobDetail object.

The JobDataMap can be used to hold any number of (serializable) objects which you wish to have made available to the job instance when it executes. JobDataMap is an implementation of the Java Map interface, and has some added convenience methods for storing and retreiving data of primitive types.

jobDetail.getJobDataMap( ).put(“adminEmail”, “admin@apple.com”) ;

And we can read this configuration parameter in our Job class by including this code snippet in the execute() method

JobDataMap dataMap = context.getJobDetail().getJobDataMap();

String adminEmail = dataMap.getString(“adminEmail”);

Stateful vs. Non-Stateful Jobs

Non-stateful jobs only have their JobDataMap stored at the time they are added to the scheduler.

Any changes made to the contents of the job data map during execution of the job will be lost, and will not seen by the job the next time it executes.

For Stateful Jobs, JobDataMap is re-stored after every execution of the job but this means that the jobs cannot be executed concurrently. A job can be made Stateful by implementing the interface StatefulJob  instead of the Job interface.

The other attributes of a Job

  • Durability  if a job is non-durable, it is automatically deleted from the scheduler once there are no longer any active triggers associated with it.
  • Volatility –  if a job is volatile, it is not persisted between re-starts of the Quartz scheduler.
  • Request Recovery –  if a job “requests recovery”, and it is executing during the time of a ‘hard shutdown’ of the scheduler (i.e. the process it is running within crashes, or the machine is shut off), then it is re-executed when the scheduler is started again. In this case, the JobExecutionContext.isRecovering() method will return true.
  • Job Listeners =  a job can have a set of zero or more JobListeners associated with it. When the job executes, the listeners are notified.

Jobs

We can make Java component executable by the scheduler simply by making it implement the Job interface.

package org.quartz;

public interface Job {

public void execute(JobExecutionContext context)  throws JobExecutionException;

}

When the Job’s trigger fires (more on that in a moment), the execute(..) method is invoked by the scheduler.

Triggers

Trigger objects are used to trigger the execution (or ‘firing’) of jobs. When you wish to schedule a job, you instantiate a trigger and ‘tune’ its properties to provide the scheduling you wish to have.

There are currently two types of triggers, SimpleTrigger and CronTrigger.

SimpleTrigger is handy if you need ‘one-shot’ execution (just single execution of a job at a given moment in time), or if you need to fire a job at a given time, and have it repeat N times, with a delay of T between executions.

CronTrigger is useful if you wish to have triggering based on calendar-like schedules – such as “every Friday, at noon” or “at 10:15 on the 10th day of every month.”


IBM MQ Basics

Posted: March 27, 2012 in Uncategorized

Recently I started working on a project that uses IBM Websphere MQ.  Whatever I mention in this document can be found in detail if you read the Redbook for MQ Series. This article is intended to give you a quick overview and idea about WebSphere MQ and the technical terms associated with it.

Messaging

  • Program-to-program communication by sending and receiving messages to and from the queue without having a logical connection between them.

Queuing

  • Programs communicate with each other through queues.

There are 2 types of messaging

  1. Asynchronous Messaging - the sending program proceeds with its own processing without waiting for  the reply of the message.
  2. Synchronous Messaging

Note : Programmer can’t specify the name of the target application to which the message is sent. Instead, he specifies the target Queue as each queue is associated with a program.

A Message has 2 part – Data & Message Header.

  • Message Header(Message Descriptor) identifies the message(message ID) and contains information(attributes)
  • Common attributes are message type, expiry time, correlation ID, priority and name of the queue for reply.

Message Segmenting and Queuing.

  • Segmenting a  large message if it does not fit the queue and receiver can get the message in one piece or as multiple segments based on the buffer size.
  • Programmer can even segment the messages and each segment is treated as a separate physical message. Thus several physical messages building one logical message.
  • To reduce network traffic, sometimes many small messages are grouped together and sent to destination.

MQ Message Types

  1. Datagram – Message containing information, but no response is expected.
  2. Request – Message for which a reply is requested.
  3. Reply – Reply to a request message
  4. Report – A message that describes an event such as occurrence of error or confirmation or arrival or delivery.

Persistent vs Non-Persistent Messages

Deliveries of persistent messages are assured. They are written into logs to survive system failures.

Message Descriptor

  1. Version – depends on MQ version and the platform in use.
  2. Message ID / Correlation ID -  these fields are used to identity a specific request or reply.
  3. Persistent/Non-Persistent
  4. Priority
  5. Date and time
  6. Expiration Date (when is date is reached, MQGET is called and the message is discarded)
  7. Return address – (reply-to-queue or reply-to-queue manager)
  8. Format – sender can specify a value which receiver can use to decide whether data conversion is done or not.
  9. Sender application and type.
  10. Report options and Feedback Code – used for request information like confirmation of delivery
  11. Back out Counter
  12. Message Segment and Grouping

MQ Manager (MQM)

  • Manages queues and message for the application
  • Provided Message Queuing Interface (MQI) for communication between programs.

Program A  ( via MQPUT) — > Remote Queue à CHANNEL  à Local Queue à Program B (via MQGET)

Program A  (via MQPUT) — > Shared Queue à Program B (via MQGET)

Queue Manager Clusters

  • MQM’s are joined together in clusters which may run in the same machine or different machine.
  • They maintain a repository that contains the information about all the queue managers and queues in the cluster. (Full Repository)
  • The un-clustered MQM’s manage a repository that contains the information of the objects they are interested in (Partial Repository)
  • MQM uses special cluster channels to exchange information

Queue Manager Objects

  1. Queues
  2. Process Definitions
  3. Channels

Queues

Queues are classified as

  1. Local Queue                             – a real queue
  2. Remote Queue                          – structure describing a queue
  3. Transmission Queue                  – local queue with special purpose
  4. Initiation Queue                       – local queue with special purpose
  5. Dynamic Queue                         – local queue created on the fly to store intermediate results
  6. Alias Queue                              – not real queues but definitions in case you want alias names
  7. Dead-letter Queue                   – one for each queue manager to store the messages when handling situations like destination queue is full, dest queue doesn’t exist, message is too large, duplicate message sequence number etc.
  8. Reply-to Queue             – specified in request message
  9. Model Queue                            – model for local queues
  10. Repository Queue                     – holds the cluster information

Process Definitions

  • Defines an application to a queue manager.
  • Eg: the name of the program (and its path) to be triggered when a message arrives for it.

MQ Channels

Channels are classified into

Message Channels

  • connects 2 queue managers via Message Channel Agents (MCA or movers)
  • unidirectional
  • Comprises of 2 MCAs, a sender and a receiver and a communication protocol.
  • MCA is a program that transfers messages from transmission queue to communication link and vice versa

 MQI Channels

  • Message Queue Interface channel
  • Connects MQ client to a MQM in the server machine.
  • Bi-directional.

 

2011 in review

Posted: January 1, 2012 in Uncategorized

The WordPress.com stats helper monkeys prepared a 2011 annual report for this blog.

Here’s an excerpt:

A San Francisco cable car holds 60 people. This blog was viewed about 2,800 times in 2011. If it were a cable car, it would take about 47 trips to carry that many people.

Click here to see the complete report.

We often use a separate spring config file for each layer in our project – say springConfig-delegate.xml for the delegate layer, springConfig-service.xml for the service layer and springConfig-dao.xml for the dao layer.

Normally, people load them like

ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {“springConfig-delegate.xml”,”springConfig-service.xml”,”springConfig-dao.xml”});

This is not a good practice when we have the provision to organize all our spring configuration files into a single XML file & load it.

Create a single spring config file names “springConfig.xml”

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

	<import resource="common/Spring-Common.xml"/>
        <import resource="connection/Spring-Connection.xml"/>
        <import resource="moduleA/Spring-ModuleA.xml"/>

</beans>

and then load it like

ApplicationContext context =
new ClassPathXmlApplicationContext(springConfig.xml);

Auto-wiring in Spring

Posted: December 9, 2011 in Spring

In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the “autowire” attribute in <bean>.

There are 5 auto-wiring modes in spring

  1. no – Default, no auto wiring, set it manually via “ref” attribute
  2. byName – Auto wiring by property name. If the name of a bean is same as the name of other bean property, auto wire it.
  3. byType – Auto wiring by property data type. If data type of a bean is compatible with the data type of other bean property, auto wire it.
  4. constructor – byType mode in constructor argument.
  5. autodetect – If a default constructor is found, use “autowired by constructor”; Otherwise, use “autowire by type”.

Hope the following examples will help you understand auto-wiring much better

Consider the following classes – Customer.java and Person.java

public class Customer {
        private Person person;

        public Customer(Person person) {
            this.person = person;
        }

        public void setPerson(Person person) {
            this.person = person;
        }
    }

    public class Person {
        // some code..
    }

1. NO

This is the default mode. We have to use <ref> tag here

<bean id="customer" class="de.suhas.Customer">
          <property name="person" ref="person" />
</bean>

<bean id="person" class="de.suhas.Person" />

2. byName

Auto-wire a bean by property name.

In this case, since the name of “person” bean is same with the name of the “customer” bean’s property (“person”), so, Spring will auto wired it via setter method – “setPerson(Person person)“.

<bean id="customer" class="de.suhas.Customer" autowire="byName" />
<bean id="person" class="de.suhas.Person" />

3. byType

Auto-wire a bean by property data type. In this case, since the data type of “person” bean is same as the data type of the “customer” bean’s property. so, Spring will auto wired it via setter method – “setPerson(Person person)“.

<bean id=”customer” class=”de.suhas.Customer” autowire=”byType” />
<bean id=”person” class=”de.suhas.Person” />

4. constructor

Auto-wire a bean by property data type in constructor argument.
This is used when we go for constructor based dependency injection.
In this case, since the data type of “person” bean is same as the constructor argument data type in “customer” bean’s property (Person object)
So, Spring auto wired it via constructor method – “public Customer(Person person)“.

<bean id=”customer” class=”de.suhas.Customer” autowire=”constructor” />
<bean id=”person” class=”de.suhas.Person” />

5. autodetect

If a default constructor is found, uses “constructor”, otherwise, uses “byType”.
<bean id="customer" class="de.suhas.common.Customer" autowire="autodetect" />
<bean id="person" class="de.suhas.Person" />
Tip : It’s always good to combine both ‘auto-wire’ and ‘dependency-check’ together, to make sure the property is always auto-wire successfully.
<bean id="customer" class="de.suhas.Customer"
			autowire="autodetect" dependency-check="objects />
<bean id="person" class="de.suhas.Person" />