Saturday, November 5, 2011

Memories !!!!

How will you feel when you meet a long missing friend?
How will you feel when you find a missing book?

I felt the same happiness when I came to be coimbatore after 11 years and 4 months for job. Yes I did my engineering in coimbatore and I left coimbatore in 2010. And I came back here at 2011 and never imagined that I will get a job here. But life is full of surprises and currently enjoying job and coimbatore. We all know the beauty of coimbatore !!! yes, its the sweet language.

Thursday, August 11, 2011

Working with Java Sound API

Recently had a chance to work with Java Sound API where I am able to play and record sound through my laptop speaker and microphone.

I used below code to play a wav clip.

public class PlaySound
{
     private void playClip()
    {
        try {
            File file = new File("Z:\\songs\\song.wav");
            AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
            AudioFormat format = audioStream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class,format);
            Clip clip = (Clip) AudioSystem.getLine(info);   
            clip.addLineListener(this);
            clip.open(audioStream);

            clip.loop(5);
        } catch (LineUnavailableException ee) {
            ee.printStackTrace();
        }
        catch(IOException ee)
        {
            ee.printStackTrace();
        }
        catch(Exception ee)
        {
            ee.printStackTrace();
        }
    }


    public static void main(String a[])
   {
          new PlaySound().playClip();
   }

}

My bad, it was not working. After struggling to find the reason, finally found that 
Clip clip = (Clip) AudioSystem.getLine(info); 

is creating a new Sound Dispatcher daemon thread which expects some non daemon thread to run in the jvm. Finally added some Thread.sleep(5000) in the main method to keep jvm running and it started working.


Tuesday, July 26, 2011

Difference between Jsp:forward and jsp:include

When you do jsp:forward, pageContext.forward() method is invoked with the given jsp or html resource. When you do jsp:include, JspRuntimeLibrary.include() method is getting invoked. jsp:forward means, browser will show only the resource given as an input to jsp:forward. No new HttpServletRequest and HttpServletResponse objects are created hence all parameters/attributes in HttpServletRequest are passed to the new resource as well. jsp:forward does not change the Url in the browser but HttpServletResponse.sendRedirect() changes the url as well since the request is redirected to the browser and coming back to the servlet/action class.

Monday, June 27, 2011

Debugging a JBoss application

Recently had a chance to debug a Jboss application through eclipse. Below are the steps I did.

1. JBoss version is 6.0.0.
2. edited <JBossHome>/bin/run.conf.bat and added the below line
set "JAVA_OPTS=%JAVA_OPTS% -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
3. Started jboss server and got the below print
Listening for transport dt_socket at address: 8000
4. Then in the eclipse, select the project and then Run ----> Debug Configurations-----> Remote Java Application. On the right side, select the project, and set the connection type as Standard (Socket Attach), Host as localhost and give port as 8000. Click on Debug.
5. Then select Window ----> Show View ---> Debug, you will be able to see the stack traces.
6. Most of the standalone debugging operations i.e setting a break point, adding a watch would work in remote debugging also.

Friday, June 24, 2011

Dead Lock Example

How to create dead lock?  Here is the fine example.
Lets talk about money transfer from one account to another account. Money has to be debited from one account and it has to be credited into another account.


public class Transfer extends Thread
{
           private Credit credit  = null;
           private Debit debit = null;
           private boolean odd = false;

           public Transfer(Credit credit, Debit debit,boolean odd)
           {
                       this.credit=credit;
                       this.debit=debit;
                      this.odd=odd;
            }

            public void run()
            {
                       if(odd)
                      {
                                transferMethod1();
                       }
                       else
                       {
                                 transferMethod2();
                        }
             }

            //first lock credit and then do debit
           public void transferMethod1()
           {
                 credit.credit();
                 //thread.sleep() can be added just to ensure that dead lock is happening
                 debit.debit();
           }

          //first lock debit and then do credit
          public void transferMethod2()
          {
                   debit.debit();
                   //thread.sleep() can be added just to ensure that dead lock is happening  
                  credit.credit();
          }

          public static void main(String a[])
          {
                      Credit c = new Credit();
                      Debit d  = new Debit();
                      Transfer t1 = new Transfer(c,d,true);                     
                      Transfer t2 = new Transfer(c,d,false);
          }
}

class Credit
{
public synchronized credit()
{
//credit implementation
}
}

class Debit
{
public synchronized debit()
{
  //debit implementation
}

When thread t1 calls transferMethod1(), credit object is locked and its waiting for debit object. At the same time, when thread t2 calls transferMethod2(), debit object is locked and its waiting for credit object. t1 can proceed when t2 releases debit object and t2 can proceed when t1 releases credit object. Hence program hangs. One way to avoid this deadlock is, combine those two resources. i.e synchronize both these credit and debit operations. i.e in other words synchronize methods in Transfer object. Make transferMethod1() and transferMethod2() methods synchronized.

Sunday, June 5, 2011

Regex to find Email

Wrote a regular expression to find e-mail which has below conditions.

1. User name must start with a character.
2. It can contain _-. characters but not two consequetive hypens (--). It can contain numbers.
3. Domain name must start with a character or a number it can have any number of subdomains i.e .co.in etc

(\b[a-zA-Z][\w\.^[--]]*)@([a-zA-Z][\w^[--]]*)(\.[\w^[--]]+)+

My idea is to group email as username,domainname. First lets take username. This can be identified by (\b[a-zA-Z][\w^[--]]*).

\b means it should start with a word boundary. It should start with a character, so the character class [a-zA-Z] confirms the same.  Then it could contain any number of characters but not two hypens which can be achieved by a word character \w (a-zA-Z0-9) and a character class ^[--].
Email can have any number of sub domains i.e .co.in. so I split it as (.\w) i.e a . followed by a word character. And the rest is self explanatory.

Thursday, May 19, 2011

Some real world java examples

Just thought about some real world examples.

1. Polymorphism:

In simple terms polymorphism means one interface - multiple implementations. Users can choose the
implementation based on their own interests. For example Vehicle could be the interface and travel
is the method. There could be n number of implementations for Vehicle interface. i.e Van, Car, Bus etc.
Uses can choose their own Vehicle implementation based on their need i.e capacity, cost etc. Polymorphism can
be used for grouping.

2. Inheritance:

In object oriented programming, users can map real world entities into java objects. Through inheritance
parent object's properties are passed to children object properties. This reduces the amount of code
to be written and also increases the maintainability of the code. For example employee is the class that could
have details as name, id, start date of employment, address etc. Also Lead is also an employee but he has
more details as module he owns, review permission etc. Manager is also an employee who has additional responsibilites
like performance review etc., along with the default employee details.

3. Encapsulation:

Encapsulation means providing right access details for the right entities. For example in a hotel,customers are not allowed
inside cooking room. Servers are not allowed inside owner's cabin.

4. Queue:

Queue means first in first out. Railway booking counters.

4. Stack:

Stack means last in first out. Assume a movie theatre has 1000 seats which has only one gate in which people are allowed based on the seat number. Once the
show is over person who sat in 1000th seat, can come out as a first person.

5. Deque:

Deque means addition/removal is supported on both ends. Same theatre example could be applied here where it has two gates. One front gate and one back gate, visitors are allowed in both the gates.

Monday, May 16, 2011

ClassCastException while trying to cast to the same object

Recently I wanted to know how application servers are reloading jsp file.  So thought of finding it myself. Tried writing a ClassLoader that extends java.lang.ClassLoader which always loads class files from the disc and not from the memory.

public class PrintObj
{
         public void print()
         {
                  System.out.println(" one ");
          }
}


public class MyClassLoader extends ClassLoader
{
           public Class findClass()
           {
                      //load it from the disc and return the Class object 
            }
}


public class ClassLoaderTest
{
       public static void main(String a[])
       {
                 ClassLoader sysLoader = DynamicClassLoader.class.getClassLoader();
                 //it loads it from the memory
                  PrintObj l1 = (PrintObj)sysLoader.loadClass("PrintObj").newInstance();
                  l1.print();
                 

                 MyClassLoader loader = new MyClassLoader();   
                 PrintObj l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
                 l2.print();
                 

        }
}

When I am trying to execute the below code, it throws
Exception in thread "main" java.lang.ClassCastException: PrintObj cannot be cast to PrintObj. Bolded line shows ClassCastException. Interested to know that it collides with the existing PrintObj loaded by the system class loader. Then had to create an interface call Print and then made PrintObj implements that Print interface.

public interface Print
{
       public void print();
}


public class PrintObj implements Print
{
       System.out.println(" one ");
}


After doing the above change below code runs with out any problem.

ClassLoader sysLoader = DynamicClassLoader.class.getClassLoader();
//it loads it from the memory
Print l1 = (PrintObj)sysLoader.loadClass("PrintObj").newInstance();
l1.print();

MyClassLoader loader = new MyClassLoader();   
Print l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
l2.print();


Now other issue when I tried to load the class second time it throws ,

MyClassLoader loader = new MyClassLoader();   
 Print l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
  l2.print();

 Print l3 = loader.loadClass("PrintObj").newInstance();

Exception in thread "main" java.lang.LinkageError: loader (instance of  MyClassLoader): attempted  duplicate class definition for name: "PrintObj". Then finally realized that a new ClassLoader() instance has to be created to reload a class every time from the disc. 

Monday, April 25, 2011

Writing an Ant Task

Many are having a need to write their own ant task, just like I had. I wanted to search some strings in a set of files and write the result into some destination files. Just listing the steps to achieve the same.

1. I work with Eclipse. Created a Java project and created the below build.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="Search" basedir="." default="jar">

    <target name="clean" description="Delete all generated files">
        <delete dir="classes"/>
        <delete file="search.jar"/>
    </target>

    <target name="compile" description="Compiles the Task">
        <javac srcdir="src" destdir="classes"/>
    </target>

    <target name="jar" description="JARs the Task" depends="compile" >
        <jar destfile="search.jar" basedir="classes"/>
    </target>
  
</project>

2. Wrote a Java code which extends Task class. I wanted to have sourceFile, destFile and searchString as parameters and hence having three  instance variables as sourceFileString, destFileString and searchString.  On execute() method functionality has been implemented.

import org.apache.tools.ant.Task;
import java.io.*;

public class SearchTask extends Task {
   
    private String sourceFileString = null;
    private String destFileString = null;
    private String searchString = null;
   
    public void setSourceFile(String sourceFile)
    {   
        this.sourceFileString = sourceFile;
        System.out.println(" Source file set to "+sourceFile);
    }
   
    public void setDestFile(String destFile)
    {
        this.destFileString = destFile;
        System.out.println(" dest file set to "+destFile);
    }
   
    public void setSearchString(String searchString)
    {
        this.searchString = searchString;
        System.out.println(" search string set to "+searchString);
    }
   
    public void execute()
    {
        System.out.println(" Execute called ");
        File sourceFile = new File(sourceFileString);
        if(sourceFile.isDirectory())
        {
            File[] array = sourceFile.listFiles();
            for(int i=0;i<array.length;i++)
            {
                File file = array[i];
                search(file);
            }
        }
        else
        {
            search(sourceFile);
        }
    }
   
    private void search(File sourceFile)
    {
        System.out.println(" searching starts ");
       
        BufferedReader reader = null;
        BufferedWriter writer = null;
       
        try
        {
            reader = new BufferedReader(new FileReader(sourceFile));
            writer = new BufferedWriter(new FileWriter(destFileString));
            String line  = null;
           
            while( (line = reader.readLine()) != null)
            {
                System.out.println(" line =="+line+" searchString "+searchString);
                if(line.indexOf(searchString) > -1)
                {
                    writer.write(line);
                    writer.newLine();
                }
            }
        }
        catch(Exception ee)
        {
            ee.printStackTrace();
        }
        finally
        {
            try
            {
                writer.close();
                reader.close();
            }
            catch(Exception ee)
            {
                ee.printStackTrace();
            }
        }
    }
}


3. Executed jar task and created search.jar. Then added the below task.

<target name="search" depends="jar" description="searching the file">
        <taskdef name="search" classname="SearchTask" classpath="search.jar"/>
        <search sourceFile="e:\\searchFile.txt" destFile="e:\\searchresult.txt" searchString="cool" >
        </search>

</target>

Friday, April 22, 2011

My Passport renewal Experience

Had my passport expired and wanted to renew it. Thought of writing it here so that it will help some people who are yet to renew their passport.

http://passport.gov.in/ is the website where we shall get all related details.

1. We can download the application form from the above site and get appointment to visit the passport office.
2. To renew we need two solid address proof.  Old passport can be considered as one address proof when there is no address change. Otherwise bank passbook can be used. Ration card is not accepted as address proof.  List of documents can be found in the below link.
http://passport.gov.in/cpv/checklist.htm
3. When I entered Madurai passport office, there is a long queue for certification verification. They rejected my application just because I wrote one reference address in pen. I went to ex-servicemen and filled-in a new application which had some other date of appointment. Very frustrated and left that office.
4. Second time I went there and since I had ration card as address proof they rejected my application.
5. My native is in Aruppukottai which falls in Virudhunagar district. So I went to Virudhunagar collectorate and gave 200 to get D.D and filled-in application form. This time my application entered into the system.
6. I got police verification in two weeks and they asked me to come to the police station. I went to Aruppukottai police station and waited for 3 hours to see superindent of police. He asked me two or three questions and its over.
7. I got a letter from madurai passport office saying that I need to submit the damage sworn affidavit. In fact my old passport is not at all damaged and I went there and submitted. Passport office asked me some basic questions.
8. Finally in three weeks I got the passport.

Here comes the interesting part, following are the differences in 10 years.

1. Process is very fast. In one week you can get a tatkal passport and in three weeks you can get normal passport if you have all the documents.
2. Some passport officers are very kind in nature and they are really helping the needy people.
3. Having ex-serviceman booth in passport office is really a good idea.
4. Still some passport officers are not people friendly. This is not changed even in the last 10 years.

Thursday, April 21, 2011

My UDP based JMS Solution

Just wondered and searched udp based JMS solutions for high performance need. Could not find any and hence decided to write one through java. Till now able to create Queues and made them communicate each other. My design has,

1.  A communication provider maintains a list of Queues and Topics. Mainly list of Queue Initiators and on subscription it will have Queue Clients too. It will have a list of Topic subscribers too.
2. A Queue initiator that communicates with ConnectionProvider to register the queue name and its ip/port details.
3. A Queue client that subscribes with ConnectionProvider and get the details of Queue initiator.
4. Queue initiator and Queue client can communicate each other with high performance. On closure, commuincation provider can be updated.
5. Communication Provider , Queue initiator , Queue clients are distributed. They can run in three different jvm.
6. Currently all objects are extending Thread object. But it can be enhanced by having one thread per jvm that receives all packets and then notifies clients.

Have made a working version that supports create, delete, subscribe and unsubscribe. On a i3 CPU 64 bit, 3 GB, 2.27 GHz, 2.26 GHz machine, it is able to send/receive 6700 udp packets per second. Recently have made it to support topic also.

Thursday, March 31, 2011

Setting up logging for Hibernate

In fact it took me a while to find out that I am actually missing a jar in the classpath while doing the same. Had the below jars in the application classpath,

slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
log4j-1.2.16.jar and had log4j.properties in the classpath. Make sure you have your log4j.properties preceeding over other files (if at all others exist).

My log4j.properties are copied from hibernate's example properties
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=info,stdout,R

log4j.logger.org.hibernate=debug
log4j.logger.org.hibernate.test=info
log4j.logger.org.hibernate.tool.hbm2ddl=debug
log4j.logger.org.hibernate.sql.ordering.antlr.OrderByFragmentTranslator=warn

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=hibernate.log

log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

Monday, March 28, 2011

Regex - difference between reluctant, greedy and possessive quantifiers

This one , I keep on forgetting so I thought of putting a post so that I shall not forget this again and it benefits others who had a hard time in understanding java's regex tutorial.

There are three types of regex quantifiers in regex possessive (a + character identifies this), greedy ( default so no character to identify this), reluctant ( a - character identifies this).

For example \w means any word character. Let take a word "blackdogishere". Regex "\w*dog" matches "blackdogishere". First lets examine what "\w*dog" represents, "*" means zero or more character. "\w*" means zero or more word character. "\w*dog" means, zero or more word charactesr followed by "dog". Note that dog also represents a word character. By default the quantifier is greedy so when "\w*dog" matches against "blackdogishere", \w* matches the entire string "blackdogishere" but then as the regex character moves on, it backtracks and hence "\w*dog" matches "blackdogishere".

Now if we consider reluctant quantifier which is identified by ? charcter. "\w*?dog" also matches "blackdogishere" but in some different way.  Reluctant quantifier eats the character one by one. So "\w*?" matches "black" and then "\w*?dog" matches "blackdog".

Possessive quantifiers (identified by + character) eats the character in a full stretch and never back tracks. "\w*+" eats all characters in "blackdogishere" which never returns back and hence "\w*+dog" does not match the string "blackdogishere".

Believe I have explained the three types of quantifiers in a simple way.

Tuesday, March 22, 2011

Java an In - Memory Indexing Technique

Scenerio Given to me:

You have a set of XML documents that have data related to Bank. i.e name, place, account name, country etc. Users would like to search based on some important fields. For example a Bank data could have 10 columns and users would like to search based on 2-3 columns. Search has to be as fast as possible. 

My Solution:

1. Create an ArrayList that holds the list of BankData object. Each XML bank data corresponds to Java BankData object.
2. Create an Index object for each column that needs to be searched. Index object is a wrapper over java's TreeMap object where TreeMap's key is the column value and TreeMap's value is the index at which corresponding BankData exist in the ArrayList.
3. While reading each XML data construct a BankData object and put it in an ArrayList. Note the index at which BankData has been added in the ArrayList.
4. For each searchable columns, get the corresponding Index object and put column value and Arraylist index the TreeMap.
5. On search give the user input to the corresponding Index Object. It searches the TreeMap and identifies the ArrayList index and gets the real BankData from the ArrayList.

Monday, March 7, 2011

England Vs South Africa My First world cup - on stadium experience

It was on 6th March 2011. I bought ticket for this match for Rs 1000.
Tried hard to get a ticket for India match but could not get it
and got ticket for the above match believing that it will be a good
entertainer. I am not disappointed and it was a nail bitting finish.


Match starts at 9.30 am and I started from my room at 8 am as it will take 1 hour to reach
Chepauk from pallikaranai where I am staying. In the train able to see lot of
enthuthiastic fans chatting about cricket. It was at 9.20 am when I reached the stadium.
People started running as soon as train stopped there since there was a music
and loud cheer coming from the stadium.

Felt excited when entering as the atmosphere is very cheerful and staff are giving
plastic boards with runs printed on it. Also flags were given and some one gave me an England
flag. My neighboure in the queue asked for both the flags hoping that its a t-shirt. Found that
there are lot of freshers for that match just like me. While I entered saw de-villiers standing
near deep square leg ropes.

There are two jiant screens in which replays are shown immediately and in fact players are also referring
the jiant screen. Main difference between watching the match in the TV and the stadium is the elecrifying
atmosphere and the athletics shown by the players. International player standard is far far better than
league players. South Afrians fielders are true athletics in the field. Able to see the wonderful sight
of seeing Steyn bowling bouncers to england batsmen. Just wondering about the atmosphere when India is playing against pakistan. Its a game of spirit and its a game of emotions.

I spent 7.30 hours in the stadium and it was not at all boring as we get bored between 16 to 34 overs while watching it in the tv. It was all South Africa for almost all 90 overs. In the last 10 overs england got vital wickets and won the match. Eager to see more such matches and willing to spend for IPL matches too.

Saturday, March 5, 2011

Java garbage collection algorithms

There are two major types namely reference counting and tracing.

 Reference Counting:

Each object has a referenceCount that measures the number of reference objects that are pointing to it. i.e in other words if you create one more reference to that object, that count should increase by one. On garbage collection cycle, objects that have referenceCount as zero, will be removed from heap.

Tracing :

Starting from the root object, trace each object that are having references from the root object. Remove the objects that are not referenced from the root.

Tracing is achived through various techniques like Mark and Sweep, Copying,  Mark and Compact.

Mark and Sweep:

It has two steps. On first step live objects are marked through tracing. On second step all objects are visited and unmarked objects are removed from heap. Marked objects are unmarked for next tracing cycle.
Disadvantage of this approach is it has two steps and it could create holes in the heap. Garbage collection is done after stopping all the threads in the jvm.

Copying Collector:

Herealso all threads are stopped before staring the garbage collection. Heap is divided into active and inactive part. Once the active part is full, threads are stopped and tracing is started. During tracing, live objects are moved to the inactive part. While doing so, fragmentation is automatically done i.e objects are compacted in the other part. Once copying is completed active part is made as inactive part and vice versa. After copying inactive part is garbage collected. Garbage is collected through single pass, but twice the memory is needed as copying is performed from active part to inactive part.

Mark and Compact Collector:

It combines the advantages of both mark & sweep and copying collector. It has two phases as mark and compact phase.  During mark phase, objects are marked. In mark and sweep collection, boolean marked is stored in the object itself. Whereas here, it is stored in the handle. Handle is an object which has reference to the Class.object that it refers to and the pointer to the original object created in the heap. During mark phase, marked boolean is added here and not in the object. So when an object is changed, it is enough to update the handle and not reference objects that are pointing to it.  During compact phase ALL objects in the heap are examined. Objects that are marked are slided to the lower portion of the heap. First I took some time to understand this as I had questions like what will happen to the existing object? Then I realized that memory allocation is contigeous. Root element is starting with zero and then subsequent elements are sequentially stored in the heap.

Monday, February 28, 2011

Beware of helping

When you do help, just make sure you are 100% aware of whom you are helping and what kind of person he is and what kind of habits he is having though you know him from your college days. Otherwise surely you will be in trouble. This happened to me since I shared my room to a ...

My Learnings today

Attended one interview today and learned something about OOPS.

Example for Abstract Class and interface:

Interface is for generalization and Abstract class in for specification. For example if you would like to manage car, bike, lorry etc. They all belong to Vehicle category which is generalization, car has wiper and bike does not have wiper which is specialization.

Tuesday, February 22, 2011

Good technical certification sites

Tried these two sites which are really good technical certification sites.

http://www.ucertify.com
http://www.brainbench.com

Ucertify has very good format for the test. It makes us to learn concepts with intuitive questions.  Brainbench has lot of free tests and relatively its easy to pass brain bench test than ucertify. There are two free practice tests in ucertify that helps you to qualify for the other practice tests and the real test.

Friday, February 18, 2011

Glassfish - Form Based Authentication

One interesing thing I missed out is role name defined in web.xml should be mapped to user group name in glassfish server. I have set role name as admin in web.xml and created an user in glassfish through Admin Console ----> Security ----> Realms ---->  File ---> Manager Users. On creating the user set the groupname as given in web.xml and it works.

Thursday, February 17, 2011

Adding xml entries in Blogs

Today suddenly I am getting xml entries are not getting displayed properly in my blog post. Then found it is because of Compose Settings in Post Options. If you set Compose Settings as Interpret typed HTML, xml entries are not displayed correctly i.e xml to html translation is not happening properly. If I set Compose Settings as Interpret typed HTML, then translation is happening properly.

JBoss - Form Based Authentication

This is how I made Form Based authentication work for JBoss.

web.xml entries:

<security-role>
                <role-name>admin</role-name>
        </security-role>             
   <security-constraint>

    <display-name>User Name/ Password </display-name>

    <web-resource-collection>
        <web-resource-name>Makes User Authentication Necessary for all</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>

    <auth-constraint>
        <role-name>admin</role-name>
    </auth-constraint>

</security-constraint>
 
  <login-config>
           <auth-method>FORM</auth-method>
            <realm-name>file</realm-name>
           <form-login-config>
                        <form-login-page>/WEB-INF/jsp/login.jsp</form-login-page>
                        <form-error-page>/WEB-INF/jsp/error.jsp</form-error-page>
                </form-login-config>
  </login-config>

Then <jbosshome>/server/default/conf/login-config.xml has to be edited to update web-console application-policy. My login-config.xml looks like,

<application-policy name="web-console">
    <authentication>
      <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"
        flag="required">
        <module-option name="usersProperties">users.properties</module-option>
        <module-option name="rolesProperties">roles.properties</module-option>
      </login-module>
    </authentication>
  </application-policy>

Added users.properties and roles.properties in <jbosshome>/server/default/conf directory. This setup works for me.

Wednesday, February 16, 2011

Morning Dreams History

During my child hood I used to get dreams like fighting with soldiers, fighting with snakes. I get sequence of events and not persons. I normally wake up before identifying the persons with whom I am fighting. But now a days I am getting persons and faces. One day Sachin saying to me that he knows me in the dreams. Hummmmm.. but in reality I am unable to get a ticket for a World Cup India match in Chennai.

Monday, February 14, 2011

Friday, February 11, 2011

Issues on Jboss ear file creation


While creating ear file as specified in my earlier blog post faced below issues. Believe it could help someone to save some time.


1. Tried creating a service by writing a class then extends ServiceMBeanSupport and implementing methods like createService(), startService(), stopService(). But on deployment it throwed JMXNotComplaintException. What you need to do is you have to write an Interface (either with some method you would like to expose through JMX or empty interface). And the important point here to note is that interface's name should end with MBean otherwise jboss complains the above. Funny thing but many users faced the same.

2. Creating default users for jboss. Its straight forward as I used default form based authentication. Edited /server/default/conf/login-config.xml and changed users properties and roles properties file for web-console policy.

3. Loading an xml file from the ear file.

My ear has the below directory structure for a xml file. If you would like to bundle an xml file in the ear, then have it under <WEB-INF>/classes directory.

Create your first EAR file

What and all you ear file can have?

For example, it can have Jar (Java Archive), War (Web Archive) and Sar (Service Archive). Jar file has all class files. War has the directory structure as below

WEB-INF------------->classes   -- All client classes are bundled here
WEB-INF-------------->lib  --- All client side dependent jars are bundled here
WEB-INF -------->web.xml ----> web deployment descriptor

It could contain struts bean configuration file or spring controller configuration file based on the technology you are using.

Sar files are Service Archive files where it has service configuration files. For example jboss application server has jboss-service.xml as service bean configuration file. My Sar has the below directory structure

Sar
    --------> SearchService.jar     (it has all service related beans)
    ---------> META-INF ----> jboss-service.xml (it has service bean configurations)

Complete ear has the below directory structure

ear
    -------> SearchService.sar
    --------> job.war                      
    --------->META-INF/application.xml
    --------->META-INF/jboss-app.xml

where application.xml has entries for job.war and jboss-app.xml has entries for SearchService.sar










Tuesday, January 25, 2011

Communication Link Failure - Mysql

Recently I have been trying mysql with Hibernate. After setting the classpath with all related jars, I am puzzled to see communication link failure error while trying to connect from Hibernate.

Finally when I tried netstat -a, I found mysql was listening at port 3336 where as the default port is 3306. After changing connection url in the hibernate-cfg.xml with port entry, all are working fine. Bad thing is it took some 2 hours to find out that the port is the real curprit. Hummmmmm learning with time.