Thursday 15 November 2012

Java Blackberry database management

Blackberry java development allows to create a database on the device. There are many possible ways to create database. I have recently used Sqlite database for my application. Following is what I have done to use that with my application.

1) Create a database through through blackberry emulator. Following is the code to do that. 

 URI uri = URI.create("file:///SDCard/Databases/employee.db");
 Database sqliteDB = DatabaseFactory.create(uri);
 Statement st = sqliteDB.createStatement("CREATE TABLE Employee ("
 +"ID       INTEGER PRIMARY KEY,"
 +"name     TEXT,"
 +"number   TEXT,"
 );");
 st.prepare();
 st.execute();
 

2) A db file will be created in the file system. Open that db file. Insert as many data as you need. I have been required to insert data like this. As I had a large number of records that i needed in db on start up time only. I have tried to insert data through java program only. But i was facing issue about memory consumption. If you don't have too many data you can insert run time. 

3) Following is the code to retrieve data from database. 

 Statement st1 = sqliteDB.createStatement("select * from Employee;");
 st1.prepare();
 Cursor c = st1.getCursor();
 Row r;
 int count=0;
 while (c.next()) {
 r = c.getRow();
 String name = r.getString(1);
 }
 

If you have close database connection. You need to open the connection again before you go to retrieve data from the database. 

 sqliteDB = DatabaseFactory.open(uri);
 

This is just an example. Your implementation can be differ as per your requirement. 

Saturday 18 August 2012

Java Design Patterns : Behavioral Patterns

Behavioral patterns are concerned with the flow of control through a system. Some ways of organizing control within a system can yield great benefits in both efficiency and maintainability of that system. Behavioral patterns distill the essence of proven practices into readily understood, well known, and easy-to-apply heuristics.

Following is the list of all Behavioral patterns:

  • Chain of Responsibility
  • Command
  • Interpreter
  • Iterator
  • Mediator
  • Memento
  • Observer
  • State
  • Strategy
  • Visitor
  • Template Method

Tuesday 14 August 2012

Java Design Patterns : Structural Patterns

Structural patterns describe effective ways both to partition and to combine the elements of an application. The ways structural patterns affect applications varies widely: for instance, the Adapter pattern can let two incompatible systems communicate, while Facade lets you present a simplified interface to a user without removing all the options available in the system.

Following is the list of structural patterns :

  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Facade
  • Flyweight
  • Proxy

Thursday 9 August 2012

Four level accordion menu using jQuery

Here is a demo to use jQuery for left hand side menu.

Attaching code for the same also.

Tuesday 7 August 2012

Java Design Patterns : Creational Patterns

These patterns support one of the most common tasks in object-oriented programming—the creation of objects in a system. Most OO systems of any complexity require many objects to be instantiated over time, and these patterns support the creation process by helping to provide the following capabilities:

Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.

Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.

Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system.

The following is the list of creational design patterns:

  • Abstract Factory
  • Builder
  • Factory Method
  • Prototype
  • Singleton

Saturday 4 August 2012

Java Design Patterns : Classification

The 23 design patterns covered in the original Design Patterns book had several known applications and were on a middle level of generality, where they could easily cross application areas and encompass several objects.

The authors divided these patterns into three types: creational, structural, and behavioral.

  • Creational patterns create objects for you rather than having you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case.

  • Structural patterns help you compose groups of objects into larger structures, such as complex user interfaces or accounting data.

  • Behavioral patterns help you define the communication between objects in your system and how the flow is controlled in a complex program.

Java Design Patterns : Learning Process

We have found that, regardless of the language, learning design patterns is a three-step process.

  1. Acceptance

  2. Recognition

  3. Internalization

First, you accept the premise that design patterns are important in your work. Then, you recognize that you need to read about design patterns so you will know when you need them. Finally, you internalize the patterns in sufficient detail that you know which ones might help you solve a given design problem.

For some lucky people, design patterns are obvious tools, and these people can grasp their essential utility just by reading summaries of the patterns. For many of the rest of us, there is a slow induction period after we've read about a pattern followed by the proverbial "Aha!" when we see how we can apply them in our work. This book takes you to that final stage of internalization by providing complete, working programs that you can try out yourself.

The examples in Design Patterns are brief and are in C++ or, in some cases, Smalltalk. If you are working in another language, it is helpful to have the pattern examples in your language of choice. This book attempts to fill that need for C# programmers.

Friday 3 August 2012

Java Design Patterns : Definition

We all talk about the way we do things in our jobs, hobbies, and home life, and we recognize repeating patterns all the time.

  • Sticky buns are like dinner rolls, but I add brown sugar and nut filling to them.

  • Her front garden is like mine, but I grow as till be in my garden.

  • This end table is constructed like that one, but in this one, there are doors instead of drawers.

We see the same thing in programming when we tell a colleague how we accomplished a tricky bit of programming so he doesn't have to recreate it from scratch. We simply recognize effective ways for objects to communicate while maintaining their own separate existences.

Some useful definitions of design patterns have emerged as the literature in this field has expanded.

  • Design patterns are recurring solutions to design problems you see over and over. (The Smalltalk Companion)

  • Design patterns constitute a set of rules describing how to accomplish certain tasks in the realm of software development. (Pree 1995)

  • Design patterns focus more on reuse of recurring architectural design themes, while frameworks focus on detailed design and implementation. (Coplien and Schmidt 1995)

  • A pattern addresses a recurring design problem that arises in specific design situations and presents a solution to it. (Buschmann et al. 1996)

  • Patterns identify and specify abstractions that are above the level of single classes and instances or of components. (Gamma, Johnson, and Vlissides, 1993)

But while it is helpful to draw analogies to architecture, cabinetmaking, and logic, design patterns are not just about the design of objects but about the interaction between objects. One possible view of some of these patterns is to consider them as communication patterns.

Some other patterns deal not just with object communication but with strategies for object inheritance and containment. It is the design of simple, but elegant, methods of interaction that makes many design patterns so important.

Design patterns can exist at many levels from very low-level, specific solutions to broadly generalized system issues. There are now hundreds of patterns in the literature. They have been discussed in articles and at conferences of all levels of granularity. Some are examples that apply widely, and a few writers have ascribed pattern behavior to class groupings that apply to just a single problem (Kurata 1998).

It has become apparent that you don't just write a design pattern off the top of your head. In fact, most such patterns are discovered rather than written. The process of looking for these patterns is called "pattern mining," and it is worthy of a book of its own.

Java Design Patterns : History

It Came From Outer Space... via U.C. Berkeley

The inspiration for design patterns in software development is usually attributed to Christopher Alexander, a professor of architecture at U.C. Berkeley. In the late ‘70s, he published several books that introduced the concept of patterns and provided a catalog of patterns for architectural design.

Alexander's work sparked interest in the object-oriented (OO) community, and within the next decade, a number of pioneers had developed patterns for software design. Kent Beck and Ward Cunningham were among the first, discussing a set of Smalltalk design patterns in a presentation at the 1987 OOPSLA conference. James Coplien was another who actively promoted the tenets of patterns, writing a book about C++ idioms, or patterns for C++ development, in the early ’90s.

OOPSLA was an excellent venue for the growing patterns community, since it offered an environment for them to share their ideas. Another important forum for the evolution of the patterns movement was the Hillside Group, established by Kent Beck and Grady Booch.

Probably the best-known contribution to the popularity of design patterns was the 1995 book Design Patterns: Elements of Reusable Object-Oriented Software. The authors—Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides—are also commonly known as the “Gang of Four” or GoF. The book introduced a comprehensive pattern language, and gave C++ examples for the patterns discussed. Another important work that gave momentum to patterns was the book Pattern-Oriented Software Architecture, A System of Patterns, by Buschmann, Meunier, Rohnert, Sommerlad and Stal.

Wednesday 1 August 2012

Java Design Patterns : Why ?

Sitting at your desk in front of your workstation, you stare into space, trying to figure out how to write a new program feature. You know intuitively what must be done, what data and what objects come into play, but you have this underlying feeling that there is a more elegant and general way to write this program.

In fact, you probably don't write any code until you can build a picture in your mind of what the code does and how the pieces of the code interact. The more that you can picture this "organic whole," or gestalt, the more likely you are to feel comfortable that you have developed the best solution to the problem. If you don't grasp this whole right away, you may keep staring out the window for a time, even though the basic solution to the problem is quite obvious.

In one sense you feel that the more elegant solution will be more reusable and more maintainable, but even if you are the sole likely programmer, you feel reassured once you have designed a solution that is relatively elegant and that doesn't expose too much internal inelegancy.

One of the main reasons that computer science researchers began to recognize design patterns is to satisfy this need for elegant, but simple, reusable solutions. The term design patterns sound a bit formal to the uninitiated and can be somewhat off putting when you first encounter it. But, in fact, design patterns are just convenient ways of reusing object-oriented code between projects and between programmers. The idea behind design patterns is simple: write down and catalog common interactions between objects that programmers have frequently found useful.

One of the frequently cited patterns from early literature on programming frameworks is the Model-View-Controller framework for Smalltalk (Krasner and Pope 1988), which divided the user interface problem into three parts, as shown in Figure 1-1. The parts were referred to as a data model, which contains the computational parts of the program; the view, which presented the user interface; and the controller, which interacted between the user and the view.


Figure 1-1 The Model-View-Controller framework

Each of these aspects of the problem is a separate object, and each has its own rules for managing its data. Communication among the user, the GUI, and the data should be carefully controlled, and this separation of functions accomplished that very nicely. Three objects talking to each other using this restrained set of connections is an example of a powerful design pattern.

In other words, design patterns describe how objects communicate without become entangled in each other's data models and methods. Keeping this separation has always been an objective of good OO programming, and if you have been trying to keep objects minding their own business, you are probably using some of the common design patterns already.

Friday 20 July 2012

XMPP CHAT ROOM MECHANISM # PART-2

In last we have seen how to get list of all available rooms in server. This post is about how to use those information to chat in a room.

Once user get list of all room. He needs to choose one room out of it to chat with. User will send presence to existing room. Here there is a little bit change in presence stanza. User needs to add nick name for the room. All other user will see him as his nick name rather than username. e.g.
<presence from='{user-jid}/{resource}' to='{room-id}@conference.domain/{nick-name}'></presence>
Server will send presence to all the members of the room. As if any user joins room later, he will also be sent the presence. This way server informs all users of chat room about joining and leaving event of any user.
<presence to='{user-jid}/{resource}' from='{room-id}@conference.domain/{nick-name}'>
<x xmlns='http://jabber.org/protocol/muc#user'>
<item role='participant' affiliation='none'></item>
</x>
</presence>
Once user gets successfull presence. I have mentioned "successfully", as there are some conditions when user can not enter in a room. In that case server will return a error presence stanza. You can get more details about such stanze from here. If some user have already sent some message the room. User will get all those message as following format whenever he will join a room.
<message to='{user-jid}/{resource}' from='{room-id}@conference.domain' type='groupchat'>
<subject>us.country</subject>
<delay stamp='2012-07-18T18:02:24.328Z' from='{room-id}@conference.domain' xmlns='urn:xmpp:delay'></delay>
<x stamp='20120718T18:02:24' from='{room-id}@conference.domain' xmlns='jabber:x:delay'></x>
</message>
Once user joins a room. He can start sending message to the room. Here user must provide type attribute for presence stanza having value as "groupchat". Describe as following xml.
<message type='groupchat' from = '{user-jid}/{resource}' to ='{room-id}@conference.domain'>
<body>dfdf</body>
</message>
Whatever message is being sent to chat room. Room will send that message to all current users of the room.
<message to='{user-jid}/{resource}' from='{room-id}@conference.domain/{nick-name}' type='groupchat'>
<body>dfdf</body>
</message>
Now when user gets tired of chatting with bunch of people. He would like to leave the room. He needs to send unavailable presence stanza to room's jid, including nickname also. Here nick name is important because a room identifies user based on their nick name. So when you join a room. It will lock that nick name for you. If you are leaving it, you need to make server to unlock the nick name.
<presence from='{user-jid}/{resource}' to='{room-id}@conference.domain/{nick-name}' type='unavailable'></presence>
Server will send user's presence details to all user who have joined the room. The user, who will join the room after that, will not get details about that user. Here if you notice. Server has added a role related information to stanza. Same type of information have been added when user sends presence stanza for joining. This role defines what can this user do with this room. I will post more details about that afterwards.
<presence to='{user-jid}/{resource}' type='unavailable' from='{room-id}@conference.domain/{nick-name}'>
<x xmlns='http://jabber.org/protocol/muc#user'>
<item role='none' affiliation='none'></item>
</x>
</presence>
Let me know if you have any queries regarding this post.

References : http://xmpp.org/extensions/xep-0045.html/

Thursday 19 July 2012

XMPP Chat room mechanism # Part-1

XMPP protocol provides specification for multi-user chatting(MUC). It is about service provider to implement it. You need to enable MUC from server side. Provider would also give facility to create persistent chat rooms. In terms of XMPP, chat room is known as conference. User can also create a new conference from client program.

When user is loggin in, he needs to ask for available service on server side. User need to send following XML to server.

<iq type='get' from='{user-jid/resource}' to='domain' id='discoitem1'>
<query xmlns='http://jabber.org/protocol/disco#items'/>
</iq>

Server will send back all available services. Services will be sent as XML items. Each item contains service name and service JID.

<iq to='{user-jid/resource}' id='discoitem1' from='domain' type='result'>
<query xmlns='http://jabber.org/protocol/disco#items'>
<item name='User Search' jid='search.domain'></item>
<item name='Socks 5 Bytestreams Proxy' jid='proxy.domain'></item>
<item name='Public Chatrooms' jid='conference.domain'></item>
<item name='Publish-Subscribe service' jid='pubsub.domain'></item>
</query>
</iq>

Once user gets all available services. It needs to be confirm whether conference service is there or not. If it is available user can ask for available chat rooms. These are all persistent chat rooms on the server.

<iq from='{user-jid/resource}' id='discoRooms' to='conference.domain' type='get'>
<query xmlns='http://jabber.org/protocol/disco#items'/>
</iq>

Server will send back all back all available chat rooms in following XML format.

<iq to='{user-jid/resource}' id='discoRooms' from='conference.domain' type='result'>
<query xmlns='http://jabber.org/protocol/disco#items'>
<item name='university' jid='room1@conference.domain'></item>
<item name='country' jid='room2@conference.domain'></item>
</query>
</iq>

Now user is ready to join any room, he wants. User just needs to send one presence to the server. I will include more details about the same topic in next post. Stay in touch

Thursday 12 July 2012

OpenFire Sub Group

XMPP has concept of chat rooms. A chat room is basically a conference room where users can discuss on some points. But Yahoo has provided room facility as social chatting rooms where any member can join the group and chat with other members. In this feature "nested chat rooms" are provided.

XMPP is not basically providing nested or child chat rooms. But twisting the logic little bit can make it possible with normal XMPP also.

Recall the concepts of domain name. Facebook has domain "facebook.com". Then they have started services of application. They bought sub domain. That became "apps.facebook.com".

Similarly in XMPP suppose you are creating chat room with name University. The JID will be something like "university@domain.com". Now you want different universities as sub chat room of this one. Just create sub University as "oxford.university@domain.com". The main logic that you need to take care is at the client side. You need to show this rooms in tree structure so that user will see it as sub chat room instead of independent chat room.

Creating chat rooms from admin panel is very easy. It is just a html form filling task. But for creating a chat room from client is real programming stuff. You can get information about it from this link. Remember in XMPP room has many types. If you want to keep the room alive forever. You will have to create persistent room. Other rooms will be removed as soon as the last occupant will leave the room.

Let me know if you have any queries regarding all this.



Friday 6 July 2012

J2ME Theme development

LWUIT would not be best option for desktop base application. But when you need some good UI in mobile application. The UI that can attract people directly. You must need LWUIT. I have recently completed one project with J2ME with LWUIT.

Here with attaching demo for what you can do with LWUIT.


As well sharing resource file for this theme. Make sure you use same version of LWUIT for editing theme and mobile library otherwise it won't work. click here the resource file for this theme.

Monday 2 July 2012

Hibernate Caching: Part II

In first part of Hibernate Caching, we discussed about overall caching mechanism, strategies, implementation & configurations. Now in part two, we will look into Query cache and Caching association.

In many applications we have certain data sets which are permanent (not changing frequently) in nature but still dynmic like currencies supported, languages supported, countries etc. In such cases, it is useful to cache the exact results of a query, rather than caching certain objects. These queries would return exactly the same data set each time it is called.

To do this, you need to set the hibernate.cache.use_query_cache property in the hibernate.cfg.xml file to true, as follows:

<property name="hibernate.cache.use_query_cache">true</property>

Then, you use the setCacheable() method as follows on any query you wish to cache:

public class CurrencyDAO {
   public List getCurrencies() {
      return SessionManager.currentSession().createQuery("from Currency as c order by c.name")
                           .setCacheable(true)
                           .list();
   }
}

To guarantee the non-staleness of cache results, Hibernate expires the query cache results whenever cached data is modified in the application. However, it cannot anticipate any changes made by other applications directly in the database. So you should not use any second-level caching (or configure a short expiration timeout for class- and collection-cache regions) if your data has to be up-to-date all the time.

Now think of associations in hibernate. Suppose we have a list of students enrolled for different courses. The following is the Hibernate mapping of the Student class:

<hibernate-mapping package="org.avid.hibernate.caching">
<class name="Student" table="tbl_student" dynamic-update="true">
<id name="id" type="long" unsaved-value="null" >
    <column name="student_id" not-null="true"/>
    <generator class="increment"/>
</id>
 
<property column="last_name" name="lastName" type="string"/>
<property column="first_name" name="firstName" type="string"/>

<set name="courses" table="tbl_course_enrollment" lazy="false">
     <key column="student_id"/>
     <many-to-many column="course_id" class="Course"/>
</set>
</class>
</hibernate-mapping>
 
In order to make Hibernate fetch courses when you read student, you can set lazy to true. In practice, deactivating lazy loading is not a good idea. It again depends on your requirement and your EXPERTISE. Let's write DAO for Student while lazy loading is set to false:

public class StudentDAO {
   public List getStudents() {
         return SessionManager.currentSession().createQuery("from Student").list();
   }
} 
 
If you test the code, it will take too much of time even to load 50 or so students. This is typical of the N+1 query problem. Each query on the Student table is followed by literally hundreds of queries on the Course table. Whenever Hibernate retrieves a Student from the cache, it reloads all the associated courses. Let's first activate read/write caching on the Student class as follows:

<hibernate-mapping package="org.avid.hibernate.caching">
   <class name="Student" table="tbl_student" dynamic-update="true">
       <cache usage="read-write"/>
       ... 
   </class>
</hibernate-mapping>
 
We can also activate caching on the Course class. Read-only caching should do here:

    <class name="Language" table="Course" dynamic-update="true">
        <cache usage="read-only"/> ... </class> 
    </hibernate-mapping>
 
Then, you will need to configure the cache rules by adding the following entries to the ehcache.xml file:

<cache name="org.avid.hibernate.caching.Student" eternal="false" 
        overflowToDisk="false" timeToIdleSeconds="300" timeToLiveSeconds="600" />

<cache name="org.avid.hibernate.caching.Course" maxElementsInMemory="100" 
        eternal="true" overflowToDisk="false" />
 
This is fine, but it doesn't solve the N+1 query problem: 50 or so extra queries will still be executed whenever you load a Student. This is a case where you need to activate caching on the Course association in the Course.hbm.xml mapping file, as follows:

<hibernate-mapping package="org.avid.hibernate.caching">
 <class name="Student" table="tbl_student" dynamic-update="true">
   <id name="id" type="long" unsaved-value="null" > 
       <column name="student_id" not-null="true"/> 
       <generator class="increment"/> 
   </id> 

   <property column="last_name" name="lastName" type="string"/>
   <property column="emp_firstname" name="firstname" type="string"/> 


   <set name="courses" table="tbl_course_enrollment" lazy="false">
       <cache usage="read-write"/> 
       <key column="student_id"/>
       <many-to-many column="course_id" class="Course"/>
   </set> 
 </class> 
</hibernate-mapping> 

This configuration would get better or optimal performance.

Finally caching is a powerful technique, and Hibernate provides a powerful, flexible, and unobtrusive way of implementing it. Even the default configuration can provide substantial performance improvements in many simple cases.

However, like any powerful tool, Hibernate needs some thought and fine-tuning to obtain optimal results, and caching—like any other optimization technique—should be implemented using an incremental, test-driven approach. When done correctly, a small amount of well executed caching can boost your applications to their maximum capacities.
 

Sunday 1 July 2012

Hibernate Caching

Caching is widely used for optimizing database applications. A cache is designed to reduce traffic between your application and the database by conserving data already loaded from the database. Database access is necessary only when retrieving data that is not currently available in the cache. The application may need to empty (invalidate) the cache from time to time if the database is updated or modified in some way, because it has no way of knowing whether the cache is up to date.

When we use hibernate as persistence layer framework, we can cache objects using first level cache (associated with Session object) and second level cache (associated with SessionFactory object). The first level cache is used on transaction basis. Hibernate caches objects used in transaction as it may be read or updated multiple times. Whereas second level cache holds the object across multiple transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided.

Also caching mechanism depends on your access strategies. There are four caching strategies:
  • Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
  • Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
  • Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
  • Transactional: This is a fully transactional cache that may be used only in a JTA environment.
 Hibernate supports the following open-source cache implementations out-of-the-box:
  • EHCache (org.hibernate.cache.EhCacheProvider)
  • OSCache (org.hibernate.cache.OSCacheProvider)
  • SwarmCache (org.hibernate.cache.SwarmCacheProvider)
  • JBoss TreeCache (org.hibernate.cache.TreeCacheProvider)

Cache
Read
only
Nonstrict Read/write
Read/write
Transactional
Clustering
Suitable for
EHCache
Yes
Yes
Yes
No
No
lightweight, and easy-to-use
OSCache
Yes
Yes
Yes
No
Basic (JavaGroups or JMS)
JSP pages or arbitrary objects
SwarmCache
Yes
Yes
No
No
Based on JavaGroups
many more read operations than write operations
JBoss TreeCache
Yes
No
No
Yes
Powerful
transaction-capable caching architecture

To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows:

<hibernate-configuration>
<session-factory>
...
<property name="hibernate.cache.provider_class">
org.hibernate.cache.EHCacheProvider
</property>
...
</session-factory>
</hibernate-configuration>
 
Second-level caching can be activated in one of the two following ways:
  1. On a class-by-class basis in the *.hbm.xml file, using the cache attribute:
    
    <hibernate-mapping package="com.avid.hibernate.caching">
    <class name="Currency" table="tbl_currency" dynamic-update="true">
    <meta attribute="implement-equals">true</meta>
    <cache usage="read-only"/>
    ...
    </class>
    </hibernate-mapping>
    
  2.  You can store all cache information in the hibernate.cfg.xml file, using the class-cache  attribute:
    
    <hibernate-configuration>
    <session-factory>
    ...
    <property name="hibernate.cache.provider_class">org.hibernate.cache.EHCacheProvider</property>
    ...
    <class-cache class="com.avid.hibernate.caching.Currency" usage="read-only" />
    </session-factory>
    </hibernate-configuration>
    
 
Next, you need to configure the cache rules for this class. Let's take an example of EHCache, but remember that each cache implementation is different. EHCache needs a configuration file (generally called ehcache.xml) at the classpath root.

<ehcache>
 <diskStore path="java.io.tmpdir"/>
 <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120"
      timeToLiveSeconds="120" overflowToDisk="true" diskPersistent="false"
      diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />
 
  <cache name="com.avid.hibernate.caching.Currency" eternal="true" overflowToDisk="false" />
 </ehcache>

The beauty of hibernate lies in the declarative style. You do all these configurations and are ready to run. No need to change even a single line of code and performance is improved.

Tuesday 19 June 2012

XMPP Plain Authentication

All of the communication between clientand server are done by passing XML. So it is important to getknowledge about XML first. Following are the links to get hands onXML.

For authenticating user to the xmppserver. Client needs to open a stream. XMPP works on stream base.

A stream is a sequence of data ofundetermined length. It's called a stream because it's like a streamof water that continues to flow. There's no definite end to it.

A better analogy might be a queue ofpeople waiting to get on a ride at an amusement park. As people areprocessed at the front (i.e. get on the roller coaster) more areadded at the back of the line. If it's a slow day the roller coastermay catch up with the end of the line and have to wait for people toboard. Other days there may always be people in line until the parkcloses. Each person is a discrete individual and must be put on theroller coaster or not put on the roller coaster. There are nohalf-people. There's always a definite number of people in linethough this number may change from moment to moment as people enterat the back of the line and exit from the front of the line. Althoughall the people are discrete, you'll sometimes have a family that mustbe put together in the same car. Thus although the individuals arediscrete, they aren't necessarily unrelated.

In Java a stream is composed ofdiscrete bytes. The bytes may represent chars or other kinds of data.They may come faster than you can handle them, or your thread mayblock while waiting for the next one to arrive. It often doesn'tmatter.

To open a stream in XMPP user needs tosend following XML to the server. Here because of you are using itwith client application it is necessary to ass jabber:client inxmlns.
<?xml version='1.0'?>

<stream:stream to='{server name}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>
Server would open a stream for thatclient. Server must notify client with opened stream. If the streamhas been opened successfully. Server will also send starttls."starttls" is basically being used for securing thecommunication client-server.
      <xml encoding='UTF-8'version='1.0'></xml>

<stream:stream id='95360e39'from='{server name}' version='1.0' xml:lang='en' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>

</stream:stream>

<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'>
</starttls>
Server will also send details aboutmethods of communication which is called stream-features. All of thestream features are explained in details athttp://xmpp.org/registrar/stream-features.html. Following are someexamples of the stream-features.
      <mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>
<mechanism>DIGEST-MD5</mechanism>
<mechanism>PLAIN</mechanism>
<mechanism>ANONYMOUS</mechanism>
<mechanism>CRAM-MD5</mechanism>
</mechanisms>

<compression xmlns='http://jabber.org/features/compress'>
<method>zlib</method>
</compression>

<auth xmlns='http://jabber.org/features/iq-auth'></auth>

<register xmlns='http://jabber.org/features/iq-register'></register>

<stream:features>

<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>
<mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>
<mechanism>DIGEST-MD5</mechanism>
<mechanism>PLAIN</mechanism>
<mechanism>ANONYMOUS</mechanism>
<mechanism>CRAM-MD5</mechanism>
</mechanisms>

<compression xmlns='http://jabber.org/features/compress'>
<method>zlib</method>
</compression>

<auth xmlns='http://jabber.org/features/iq-auth'></auth>

<register xmlns='http://jabber.org/features/iq-register'></register>

</stream:features>
In my case i have been using plainauthentication. For that you need to make sure that server is enabledto use plain authentication. This detail would have been given inmechanism XML in stream-features. Auth XML needs to have base64 valueof (username + password). As given below.
      <auth id='sasl2' xmlns="urn:ietf:params:xml:ns:xmpp-sasl"mechanism="PLAIN">"\0" + username + "\0"+ password</auth>
if user gets logged in successfully.Client will get a success XML in return. If authentication will befailed on server side. It will send back a failure XML. Examples aregiven below
 <success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'></success>  
<not-authorized></not-authorized>

<failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>
<not-authorized></not-authorized>
</failure>

Wednesday 6 June 2012

Chat Application Protocol Suggestion


        Using XMPP is the easiest way toimplement chat application for any of the platform. There are manyoptions available in market which can be used to develop a chatapplication. There are many limitations and drawbacks of using someother protocol for chatting.

        Following are some of the benefits ofusing XMPP.

Decentralization

        The architecture of the XMPP network is similar to email; anyone canrun their own XMPP server and there is no central master server.
Open standards
        TheInternetEngineering Task Force hasformalized XMPP as an approved instant messaging and presencetechnology under the name of XMPP (the latest specifications are RFC6120 andRFC6121).No royalties are required to implement support of thesespecifications and their development is not tied to a single vendor.
History
        XMPP technologies have been in usesince 1999. Multiple implementations of the XMPP standards exist forclients, servers, components, and code libraries.
Security
        XMPPservers can be isolated from the public XMPP network (e.g., on acompany intranet), and strong security (via SASLandTLS)has been built into the core XMPP specifications.
Flexibility
        Custom functionality can be builton top of XMPP; to maintain interoperability, common extensions aremanaged by the XMPP Software Foundation. XMPP applications beyond IMinclude groupchat, network management, content syndication,collaboration tools, file sharing, gaming, remote systems control andmonitoring, geolocation, middleware and cloud computing, VoIP andIdentity services.
Integration
        Most of the chatting applicationprovider are exposing their service as XMPP. So it is easy tointegrate your application with others. As you are using standardprotocol, any customer who ask you for application. You can easilymarket it. As well you can provide specifications to them. That willcut off your cost of development also.

Following link contains list ofall XMPP server providers.
XMPPServer http://xmpp.org/xmpp-software/servers/

References have been taken from wikipedia.