Wednesday, September 14, 2011

Remote Debugging In Eclipse

Remote debugging capability with different debuggers( IDEs) are nice features for developers. Purpose of this blog is to share this information that how to use remote debugging tools effectively. Here i tried to give example for eclipse IDE.

Remote debugging in eclipse can be done in two ways:
a) Socket Attach
b) Socket Listen


Socket Attach: For e.g. we want to debug an application which is deployed on tomcat and we want to debug that. Attach the application process through eclipse once we start our tomcat in debug mode.

Step 1:
How to start tomcat in debug mode:
$./catalina.sh jpda start (in case of unix based machines) or
> catalina.bat jpda start ( in case of windows based machines)

This is going to start a tomcat in debug mode and a socket with port as 8000 can be attached to it.
In case if user wants to attach to different port than following can be done.
export JPDA_ADDRESS=8000  (in case of unix based machines)
$./catalina.sh jpda start


set JPDA_ADDRESS=8000 (in case of windows based machines)
> catalina.bat jpda start

Step 2:
Open debug configuration on eclipse and add new Remote Java Application.
Connection Type should be Standard (Socket Attach). Give a host name or ip in the value for Host in connection properties where the remote process is running.
For e.g.

















For Other application server like WebSphere:
Open admin console and open Servers->Server Type -> WebSphere Application Servers.
Than choose your server from the list of available servers. And than select Debugging service.
for e.g:
Application servers > server1 > Debugging service
Make check box "Enable service at server startup" as selected.
default port for debug is 7777, change it if you want to debug on different port.
Restart the server and attach your debugger ( IDE or eclipse) to it.


Socket Listen: When we want to start a listener first and the remote application is required to be attached to the eclipse
debugger, in that case. First we need to start the eclipse debugger in Socket Listten mode and attach the application.

Step 1:
Open debug configuration in eclipse and add new Remote Java Application.
Connection Type should be Standard (Socket Listen).
Port in connection properties should be 8000 if you want remote application should connect using this port value.
For e.g.
















Step 2:
Options a) if wants to debug with ant than in your build.xml add
<jvmarg line="-Xdebug -Xrunjdwp:transport=dt_socket,address=10.240.1.14:8000,server=n" /> for e.g.
<target name="execute" description="Test">
  <java classname="${main.class}" fork="true" failonerror="true">
   <classpath refid="class.path" />
   <arg value="${myargument}" />
   <jvmarg value="${myjvmargument}" />
   <jvmarg value="-Xrs" />
   <jvmarg line="-Xdebug -Xrunjdwp:transport=dt_socket,address=10.240.1.14:8000,server=n" />
  </java>
</target>

     
Option b) If you wants to debug with .bat file or on command prompt

Java -Xdebug -Xrunjdwp:transport=dt_socket,address=10.240.1.14:8000 -jar MyJar.jar


Options c) if you wants to debug a application which is again an eclipse ( or eclipse based plugins) than you can start the eclipse application as


eclipse.exe -vmargs -Dosgi.requiredJavaVersion=1.6 -Xms256m -Xmx512m -Xdebug -Xrunjdwp:transport=dt_socket,address=10.240.1.14:8000,suspend=n

10.240.1.14 IP where you want to debug and where your debugger is running.
Debugging in JBoss can be debugged by modifying JAVA_OPTS in the file which is used to start the server in the similar way as mentioned above.
IBM WebSphere is already explained above.

Friday, June 24, 2011

Dynamic Proxy for gui component listener using InvocationHandler.

Listeners for gui is always easy to create and difficult to maintain.
As they will create additional classes for that and in case we need to
give a patch or something it can be a real pain.

Lets say that a Frame (MyFrame.java) has 10 components and each of them has a listener than there will be 10 additional classes ( MyFrame$1.class,... , MyFrame$10.class, etc).
Now if a fix is given for one of the component and we really do not know which one to give as a hot fix, we will be ending up in giving all the 11 classes.
Another thing which might also force to give all the classes if we change the serialversionId.

So how to overcome this, i have tested it and found it works well.
But is it the right thing to do not sure but good to know.

We can use the InvocationHandler to handle this situation which can call the required method of the frame where we can have the logic/code to be run using Dynamic Proxies to call whenever event is raised.


import java.lang.reflect.*;

/**
 * @author deepak.singhvi
 *
 */
public class InvocationHandlerProxy implements 
      InvocationHandler {

private Object obj;

public static Object newInstance(Object obj) {
  return Proxy.newProxyInstance(obj.getClass()
  .getClassLoader(), obj.getClass().getInterfaces(),
  new InvocationHandlerProxy(obj));
}

public InvocationHandlerProxy(Object obj) {
 this.obj = obj;
}

public Object invoke(Object proxy, Method m, Object[] args)
 throws Throwable {
 Object result;
  try {
    result = m.invoke(obj, args);
  } catch (InvocationTargetException e) {
    throw e.getTargetException();
  } catch (Exception e) {
    throw new RuntimeException("unexpected invocation exception: "
 + e.getMessage());
  } 
  return result;
}
}


For every gui component, for e.g. button instead of overriding actionListener for some action event we can call.

ActionListener foo = (ActionListener) InvocationHandlerProxy.newInstance(new FooWithoutArgActionListener(this,"methodWithoutArgument",new Class[0]));

Listener class would implement ActionListener as usual but the method to be called when a
specific event is raised will be defined in the same class where listener is created, without creating lister anonymously.

public class FooWithoutArgActionListener 
implements ActionListener {
  Method method;
  Object parent;
  public FooWithoutArgActionListener(Object classObject, 
    String methodName, Class[] parameterTypes ){
    method = getTargetMethod(classObject, methodName, parameterTypes);
    this.parent = classObject;
}

@Override
public void actionPerformed(ActionEvent e) {
 ....
  method.invoke(parent, new Object[0]);
 ...
}

private Method getTargetMethod(Object target,
  String methodName, Class[] parameter) 
{
// find the target method which should get 
// executed when actionPerformed is called.
}


Click here to get the Complete example

Saturday, June 4, 2011

Find from which jar a class was loaded

In order to find at runtime where from file system a class was loaded, following command would be useful:

System.out.println(<myjavaclassname>.class.getProtectionDomain().getCodeSource().getLocation());

Output will be something like this:
file:/C:/TestWorkSpace/lib/MyLibrary.jar

It can be helpful while debugging some class loading problems.

Friday, March 11, 2011

Hibernate and DAO

UNDER CONSTRUCTION


package com.dao;

public interface DAOIntf<T> {
public void update(T obj);
public void save(T obj);
public void delete(T obj);
}





package com.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.util.HibernateUtil;



public class AbstractDAOImpl<T> implements DAOIntf<T>{

  @Override
  public void update(T obj) {
    save(obj);
  }

  @Override
  public void save(T obj) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();
      session.save(obj);
      transaction.commit();
    } catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
  }

  @Override
  public void delete(T obj) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();
      session.delete(obj);
      transaction.commit();
    } catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
  
   }

}



ProductDAOIntf.java
package com.dao;

import java.util.List;

public interface ProductDAOIntf<T> extends DAOIntf<T> {
  public T getProductByID(int id);
  public List<T> getAllProducts();
}


ProductDAOImpl.java
package com.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.hbm.Product;
import com.util.HibernateUtil;



public class ProductDAOImpl<T> extends AbstractDAOImpl<T> implements ProductDAOIntf<T> {

  @Override
  public T getProductByID(int id) {
  Session session = HibernateUtil.getSessionFactory().openSession();
    T product=null;
    try {
      product =(T) session.get(Product.class,id);  
    } catch (HibernateException e) {
      e.printStackTrace();
    } finally {
      session.close();
    }
    return product;
  }
 
  @Override
    public List<T> getAllProducts(){
    Session session = HibernateUtil.getSessionFactory().openSession();
    List<T> list = null;
    try {
      list = session.createQuery("from Product").list();
    } catch (HibernateException e) {
      e.printStackTrace();
    } finally {
      session.close();
    }
    return list;
  }

}


Product.java
package com.hbm;

import java.io.Serializable;

public class Product implements Serializable {
 
 
  public Integer getProduct_Id() {
    return Product_Id;
  }

  public void setProduct_Id(Integer product_Id) {
    Product_Id = product_Id;
  }

  public String getProduct_Name() {
    return Product_Name;
  }

  public void setProduct_Name(String product_Name) {
    Product_Name = product_Name;
  }

  public Double getProduct_Price() {
    return Product_Price;
  }

  public void setProduct_Price(Double product_Price) {
    Product_Price = product_Price;
  }

  public Integer getProduct_QOH() {
    return Product_QOH;
  }

  public void setProduct_QOH(Integer product_QOH) {
    Product_QOH = product_QOH;
  }

  Integer Product_Id;
  String Product_Name;
  Double Product_Price;
  Integer Product_QOH;

  @Override
    public String toString() {
      return "Id : " + Product_Id + "\t Name " + Product_Name + "\tQOH " + Product_QOH;
    }
}

Product.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

  <class name="com.hbm.Product" table="product" >
   <id name="Product_Id" type="int"> <generator class="identity"></generator></id>
   <property name="Product_Name" type="string" length="50" />
   <property name="Product_Price" type="double" lazy="true" />
   <property name="Product_QOH" type="int"/>
   
  </class>
</hibernate-mapping>

Tuesday, December 14, 2010

Thread Working For Fixed Time Even In Case Of Exceptions (UncaughtExceptionHandler)

Somebody asked me how to keep running a thread for a fixed interval even there is some exception.
At that point of time i had no answer.

But now i think, i have the answer.

And this can be done using the interface Thread.UncaughtExceptionHandler.

UncaughtExceptionHandler is an inner interface of Thread class.

We can implement it and set it using the method setUncaughtExceptionHandler() of Thread class.

Here is an example.

class MyThread extends Thread {
 
private boolean flag; 
protected int counter=0;
MyThread(int counterInitialValue) {
   this.counter = 0;
}

public MyThread(Runnable r,int counterInitialValue) {
   super(r);
   this.counter = counterInitialValue;
   this.flag = true;
}

@Override
public void run() {
 if (!flag) {
 flag = true;
 System.out.println("Thread Exec Started");
 } else {
 System.out.println("Thread Running Again");
 }
 while (counter <20) {
  counter++;
  try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
// do some work here....
  if(counter % 3 == 0){
    System.out.println(" Thread working , 
          counter value is : "+ counter);
  }
  if (counter == 10) {
   throw new RuntimeException("I am throwing exception");
  }
   
  }
 }
}

class MyThreadExceptionHandler implements 
        Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, 
                              Throwable e) {
  MyThread oldThread = (MyThread) t;
  System.out.println("Received exception "+ 
                           e.getMessage());
  if (oldThread.counter < 20) 
  {
   System.out.println("Value of counter 
       (restart required) : " + oldThread.counter);
   
   MyThread newThread = new MyThread(oldThread,11);
   
   newThread.start();
  } 
  else 
  {
   System.out.println("Thread work done");
   System.out.println("Value of counter : " +
                       oldThread.counter);
  }
 }
}



public class ThreadRunningForFixedTime {
public static void main(String[] args) {
  MyThread th = new MyThread(0);
  MyThreadExceptionHandler handler = 
          new MyThreadExceptionHandler();
  th.setUncaughtExceptionHandler(handler);
  th.start();
 }
}

Monday, December 6, 2010

How to make a non-serializable class serializable

I have a class which is not serializable. If i will try to serialize the object of it than i am going to get exception "java.io.NotSerializableException"

And now if this class is not not modifiable/available to modify (may be its a third party), and so we do not have any control.

for e.g following is the non serializable class
class MyNonSerializableClass {
 String str = new String("mystring");
 MyNonSerializableClass(){
  
 }
 MyNonSerializableClass(String s) {
  this.str = s;
 }

 public String getStr() {
  return str;
 }

 public void setStr(String str) {
  this.str = str;
 }

}



In order to serialize the object we can write a wrapper class over MyNonSerializableClass and which is implementing Serializable interface.
And the most important thing, we control the readObject and writeObject methods so that we can decide what need to be written with the wrapper class.

something like this:

class MyNonSerializableClassWrapper extends MyNonSerializableClass implements Serializable {
 MyNonSerializableClassWrapper(){
  super();
 }
 MyNonSerializableClassWrapper(String s) {
  super(s);
 }

 private void writeObject(ObjectOutputStream out) throws IOException {
  // not required the default write object
  // ----> out.defaultWriteObject();
  out.writeObject(super.getStr());
 }

 private void readObject(ObjectInputStream in) throws IOException {
  // not required the default read object
  // ----> in.defaultReadObject();
  try {
   super.setStr((String) in.readObject());
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
}


As the wrapper class itself does not have any properties/attributes so defaultread and write is not required.
By getting the super class value and setting it during the write and read to serialized object we can achieve the serialization and deserialization even if a class is not implementing Serializable interface.


private void WriteObjectToFile() {
try {
  FileOutputStream fo = new FileOutputStream("c:\\test.ser");
  ObjectOutputStream os = new ObjectOutputStream(fo);
  os.writeObject(new MyNonSerializableClassWrapper("This is a test of 
                                           serialization"));
  fo.close();

  } 
  catch (FileNotFoundException e) {
    e.printStackTrace();
  } 
  catch (IOException e) {
    e.printStackTrace();
  }
}


private void ReadObjectFromFile() {
try {
  FileInputStream fi = new FileInputStream("c:\\test.ser");
  ObjectInputStream in = new ObjectInputStream(fi);
  MyNonSerializableClassWrapper mw = (MyNonSerializableClassWrapper) 
  in.readObject();
  fi.close();
  System.out.println("serialized object value is: " + mw.getStr());
  } 
  catch (FileNotFoundException e) {
      e.printStackTrace();
  } 
  catch (IOException e) {
    e.printStackTrace();
  } 
  catch (ClassNotFoundException e) {
    e.printStackTrace();
  }
}




Tuesday, November 30, 2010

XML Writing with Java DOM Parser

I am looking for something like this kind of xml.


Some of the things in very short about the DOM parsers
1. Tree of nodes
2. Memory: Occupies more memory, preffered for small XML documents
3. Slower at runtime
4. Stored as objects
5. Programmatically easy
6. Ease of navigation

DOM which builds a data tree in memory for easier, non-sequential access to XML data fragments.

Now lets jump directly to the example.

******CREATE DOCUMENT OBJECT******

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DB docB = dbf.newDocumentBuilder();
Document doc = docB.newDocument();
******POPULATE DOCUMENT DATA******

// create the root and child tags
// create root node with the name company
Element root = doc.createElement("company");

//create a employee element
Element parent= doc.createElement("employee");

// set empid which is attribute of the element
parent.setAttribute("empid","E1");

// create child element for parent and add a textnode to it.
Element child = doc.createElement("firstname");
child.appendChild(doc.createTextNode("Deepak"));

// append the child "first name" to the parent "employee"
parent.appendChild(child);

******SAVE DOCUMENT TO FILE******
// write into the file
TransformerFactory tfac = TransformerFactory.newInstance();
Transformer transformer = tfac.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);

StreamResult streamResult = new StreamResult(new File("c:/text.xml"));

transformer.transform(source, streamResult);



Download complete example from here: Downlaod Demo Write-Read-Modify Example (Eclipse Project)

Friday, September 3, 2010

Interruptable Background Processing in C#

I was looking for some Interruptable background processing utility in C#.

Background processing can be done with BackgroundWorker but making it interruptable
was the tricky one. Its not only the threading but handling the events too.

Tried to google it did not find the exact one but some good help.


On any activity (user stops the process or work completes ) signal shall be raised to process the main thread.

Doing the process of actual work can be started in the Thread or Worker Thread in the background asynchronously.
Starting Thread ( in InterruptableBGProcess.InitialiseServiceProcess(...))
in the background.

InterruptableBGProcessing.cs
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
isStopped = false;
            
/* initialise the background processing service */
var serviceControlEvents = InterruptableBGProcess.InitialiseServiceProcess((BackgroundWorker)sender);

/* now simulate a waitstate by waiting until the user click on stop orwork completed. */

while (true)
{
 if (isStopped || ProgressBar.Value == 100)
 {
  break;
 }
}
            
/* signal the event to tell the service to stop, then wait for the event
   to be set which indicates the service has stopped*/

 WaitHandle.SignalAndWait(serviceControlEvents[0], serviceControlEvents[1]);
        
}


Once thread started it will look for the event signals
SignalProcessToStop and ProcessHasCompleted of type AutoResetEvent

/*Initialises the processing controller, process events
 and starts the process.*/
public static WaitHandle[] InitialiseServiceProcess(
BackgroundWorker bg)
{
 var processSvc = new InterruptableBGProcess(bg);
 var thread = new Thread(processSvc.ProcessController);
 thread.Start();
 return new[] { 
    processSvc.SignalProcessToStop, processSvc.ProcessHasCompleted };
}


/* when thread runs... */
private void ProcessController()
{
/* wait on the threads SignalProcessToStop event*/
var wh = new WaitHandle[] { SignalProcessToStop };
while (true)
{
 /* SignalProcessToStop.Set(); 
 if above is done (i.e  set) than waitHandles will not 
receive the signal and loop will break;*/

var fTimedOut = !WaitHandle.WaitAll(wh, 100);
if (fTimedOut && counter != 100)
/* if we timed out, do the processing or 
   work not finished completely*/
  ExecuteWork(); 
else
{
  break; /* thread process was signalled to stop*/
}
}
/* indicate the processing service has stopped, allows 
waiting threads to proceed, if don't set this than main thread 
will not proceed.*/            
ProcessHasCompleted.Set();
}



Download complete example from here: Downlaod Demo InterruptableBackGroundProcessing.rar

Tuesday, July 6, 2010

C# LogViewer using FileSystemWatcher

I was facing a problem to get the new log message in the Message Log screen.
FileSystemWatcher which was introduced in .net 2.0 make it very easy to develop Message Log Viewer.

1) Create the FileSystemWatcher and set its properties.



            FileSystemWatcher_Log_1.Path = Directory.GetParent("C:\\temp").FullName;
            FileSystemWatcher_Log_1.Filter = "MyLogFile.log";
            NotifyFilters notifyFileters = new NotifyFilters();
            notifyFileters = notifyFileters | NotifyFilters.LastWrite;
           // You can choose other notification filters


            FileSystemWatcher_Log_1.NotifyFilter = notifyFileters;
            FileSystemWatcher_Log_1.EnableRaisingEvents = true;


2) Set the event handler.




            this.FileSystemWatcher_Log_1.Changed += new 
            System.IO.FileSystemEventHandler(this.FileSystemWatcher_Changed);

3) Update GUI when event occours


            // create stream writer only once so that whenever new log is appended in the log file,
           // only that text will be shown in the list view (or which ever the gui component you are using).
            if (null == sr_Log_1)
            {
                sr_Log_1 = new StreamReader(new FileStream(SelectedFileName_Log1_textbox.Text, 
                FileMode.Open, FileAccess.Read, FileShare.ReadWrite), true);
            }
            string line;
            while (sr_Log_1.EndOfStream != true)
            {
                line = sr_Log_1.ReadLine();
                if (line.Trim().Length == 0)
                {
                    continue;
                }
                Log_1_listBox.Items.Add(line);
                Log_1_listBox.TopIndex = Log_1_listBox.Items.Count - 26 + 1;
                
            }



Refer the code for details.
You can download demo code from here here.
It may not be 100% bug free code.

Sunday, July 4, 2010

Learning art of Mocking by EasyMock

Continuing my earlier post about testing and mocking.
Here is the details about EasyMock.


Download presentation here (ppt)

Or

Here ( google docs)

The Art Of Mocking / Test using Mock Objects .

Quality assurance exists in many products, including software.
Software manufacturers perform software testing to ensure the correctness, completeness and quality of their products.

And the testing should also go with hand in hand along with development.
Find out more about testing and mocking in the provided link.

Click here to get the presentation from the link











Testing is an art. :-)

How to change from Windows Authentication to SQL Server Authentication (2005)

Durng installation of SQL Server 2005 i did not care for SQL Server Authentication and installed it Windows Authentication.
And later other users in the network could not use it for the guest account due to some problem.

Here are the steps if you need to add SQL Server Authentication also for SQL Server.


1) Run the following query to enable SQL Server Authentication using MS SQL Server Management Studio (after login as windows authentication)

"ALTER LOGIN sa ENABLE".

2) Set the password for the sa account 
 "ALTER LOGIN sa WITH PASSWORD = 'sa1234"
Password should be strong enough else it will not be accepted and query will fail.

3) Stop the SQL Server service
 Right click on My Computer -> Manage , Computer Management window will open.
Select Service and Applications -> Services -> all the services which start from SQL and stop them.

4) Change in registry
click on Start  -> Run and Enter regedit press enter.
Registry Editor will be opened
Go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLServer\LoginMode
and change the value to 2 (Hexadecimal), if its not 2.


5) Restart all services of SQL Server 2005 or restart your machine.

Sunday, February 15, 2009

Normalization : 1NF, 2NF, 3NF, BCNF

Normalization:
Database normalization is a process by which an existing schema is modified to bring its component tables into compliance with a series of progressive normal forms.

The goal of database normalization is to ensure that every non-key column in every table is directly dependent on the key, the whole key and nothing but the key and with this goal come benefits in the form of reduced redundancies, fewer anomalies, and improved efficiencies (While normalization tends to increase the duplication of data, it does not introduce redundancy, which is unnecessary duplication.).


About the Key

Column(s) C is primary key for table T if:
Property 1: All columns in T are functionally dependent on C
Property 2: No subcollection of columns in C (assuming C is a collection of
columns and not just a single column) also has Property 1
Candidate Keys -
Column(s) on which all other columns in table are functionally dependent
Alternate Keys -
Candidate keys not chosen as primary keys


First Normal Form

The first normal form (or 1NF) requires that the values in each column of a table are atomic. By atomic we mean that there are no sets of values within a column.


Second Normal Form

Where the First Normal Form deals with atomicity of data, the Second Normal Form (or 2NF) deals with relationships between composite key columns and non-key columns. The normal forms are progressive, so to achieve Second Normal Form, your tables must already be in First Normal Form.
The second normal form (or 2NF) any non-key columns must depend on the entire primary key. In the case of a composite primary key, this means that a non-key column cannot depend on only part of the composite key.

Third Normal Form

Third Normal Form (3NF) requires that all columns depend directly on the primary key. Tables violate the Third Normal Form when one column depends on another column, which in turn depends on the primary key (a transitive dependency).
One way to identify transitive dependencies is to look at your table and see if any columns would require updating if another column in the table was updated. If such a column exists, it probably violates 3NF.


Boyce-Codd Normal Form (BCNF)

When a relation has more than one candidate key, anomalies may result even though the relation is in 3NF. 3NF does not deal satisfactorily with the case of a relation with overlapping candidate keys i.e. composite candidate keys with at least one attribute in common.
BCNF is based on the concept of a determinant. A determinant is any attribute (simple or composite) on which some other attribute is fully functionally dependent. A relation is in BCNF is, and only if, every determinant is a candidate key.

Consider the following relation and determinants.
R(a,b,c,d)
a,c -> b,d
a,d -> b

To be in BCNF, all valid determinants must be a candidate key. In the relation R, a,c->b,d is the determinate used, so the first determinate is fine.
a,d->b suggests that a,d can be the primary key, which would determine b. However this would not determine c. This is not a candidate key, and thus R is not in BCNF.


Example
• Unnormalised
Grade_report(StudNo,StudName,(Major,Advisor(CourseNo,Ctitle,InstrucName,InstructLocn,Grade)))

• 1NF Remove repeating groups
Student(StudNo,StudName)
StudMajor(StudNo,Major,Advisor)
StudCourse(StudNo,Major,CourseNo,
Ctitle,InstrucName,InstructLocn,Grade)

• 2NF Remove partial key dependencies
Student(StudNo,StudName)
StudMajor(StudNo,Major,Advisor)
StudCourse(StudNo,Major,CourseNo,Grade)
Course(CourseNo,Ctitle,InstrucName,InstructLocn)

• 3NF Remove transitive dependencies
Student(StudNo,StudName)
StudMajor(StudNo,Major,Advisor)
StudCourse(StudNo,Major,CourseNo,Grade)
Course(CourseNo,Ctitle,InstrucName)
Instructor(InstructName,InstructLocn)

• BCNF Every determinant is a candidate key
– Student : only determinant is StudNo
– StudCourse: only determinant is StudNo,Major
– Course: only determinant is CourseNo
– Instructor: only determinant is InstrucName
– StudMajor: the determinants are
StudNo,Major, or
Advisor
Only StudNo,Major is a candidate key.


• BCNF

Student(StudNo,StudName)
StudCourse(StudNo,Major,CourseNo,Grade)
Course(CourseNo,Ctitle,InstrucName)
Instructor(InstructName,InstructLocn)
StudMajor(StudNo,Advisor)
Adviser(Adviser,Major)


A complete normalization of tables is desirable, but you may find that in practice that full normalization can introduce complexity to your design and application. More tables often means more JOIN operations, and in most database management systems (DBMSs) such JOIN operations can be costly, leading to decreased performance. The key lies in finding a balance where the first three normal forms are generally met without creating an exceedingly complicated schema.




Thursday, February 21, 2008

Difference between Java Beans and Enterprise Java Beans

A Java Bean is a software component written in the Java programming language that conforms to the JavaBeans component specification. The JavaBeans APIs became part of the "core" Java APIs as of the 1.1 release of the JDK. The JavaBeans specification defines a Java-based software component model that adds a number of features to the Java programming language. Some of these features include:

introspection
customization
events
properties
persistence

Java Beans is a specification developed by Sun Microsystems that defines how Java objects interact. An object that conforms to this specification is called a JavaBean, and is similar to an ActiveX control. It can be used by any application that understands the JavaBeans format.
The principal difference between ActiveX controls and JavaBeans are that ActiveX controls can be developed in any programming language but executed only on a Windows platform, whereas JavaBeans can be developed only in Java, but can run on any platform.

Enterprise JavaBeans (EJBs) are Java-based software components that are built to comply with Java's EJB specification and run inside of an EJB container supplied by a J2EE provider. An EJB container provides distributed application functionality such as transaction support, persistence and lifecycle management for the EJBs.

An Enterprise JavaBeansTM (EJB) component, or enterprise bean, is a body of code having fields and methods to implement modules of business logic. You can think of an enterprise bean as a building block that can be used alone or with other enterprise beans to execute business logic on the Java EE server.

Sunday, February 17, 2008

Aspect-Oriented Programming and Introduction to AspectJ


Aspect-Oriented ProgrammingIntroduction to AspectJ
Programming paradigms
• Procedural programming
– Executing a set of commands in a given sequence
– Fortran, C, Cobol
• Functional programming
– Evaluating a function defined in terms of other functions
– Lisp, ML, OCaml
• Logic programming
– Proving a theorem by finding values for the free variables
– Prolog
• Object-oriented programming (OOP)
– Organizing a set of objects, each with its own set of responsibilities
– Smalltalk, Java, C++ (to some extent)
• Aspect-oriented programming (AOP)
– Executing code whenever a program shows certain behaviors
– AspectJ (a Java extension)
– Does not replace O-O programming, but rather complements it



Introduction• Currently, the dominant programming paradigm is object-oriented programming that:
• Object orientation is a clever idea, but has certain limitations
• has been presented as a technology that can fundamentally aid software engineering
• is reflected in the entire spectrum of current software development methodologies and tools


Introduction AOP
• A new programming technique called aspect-oriented programming (AOP):
- makes it possible to clearly express those programs that OOP fail to support
- enables the modularization of crosscutting concerns by supporting a new unit of

software modularity – aspects – that provide encapsulation for crosscutting concerns

What are aspects?• The current working definition is (May 99, Gregor Kiczales):
- modular units that cross-cut the structure of other modular units
- units that is defined in terms of partial information from other units
- exist in both design and implementation

Aspect: A distinct feature or element in a problem

Concerns• AOP is based on the idea that computer systems are better programmed by separately specifying the various concerns of a system
• Separation of concerns is an important software engineering principle guiding all stage of a software development methodology
• Concerns:
are properties or areas of interest
can range from high-level notion to low level-notion
can be functional or nonfunctional (systemic)

The problem
• Some programming tasks cannot be neatly encapsulated in objects, but must be scattered throughout the code
• Examples:
– Logging (tracking program behavior to a file)
– Profiling (determining where a program spends its time)
– Tracing (determining what methods are called when)
– Session tracking, session expiration
– Special security management
• The result is crosscuting code--the necessary code “cuts across” many different classes and methods


Example
class Fraction {
int numerator;
int denominator;
...
public Fraction multiply(Fraction that) {
traceEnter("multiply", new Object[] {that});
Fraction result = new Fraction( this.numerator * that.numerator, this.denominator * that.denominator);
result = result.reduceToLowestTerms();
traceExit("multiply", result);
return result;
}
...
}
Now imagine similar code in every method you might want to trace



Consequences of crosscutting code• Redundant code
– Same fragment of code in many places
• Difficult to reason about
– Non-explicit structure
– The big picture of the tangling isn’t clear
• Difficult to change
– Have to find all the code involved...
– ...and be sure to change it consistently
– ...and be sure not to break it by accident
• Inefficient when crosscuting code is not needed

AspectJTM
• AspectJ is a small, well-integrated extension to Java
– Based on the 1997 PhD thesis by Christina Lopes, A Language Framework for Distributed Programming
• AspectJ modularizes crosscutting concerns
– That is, code for one aspect of the program (such as tracing) is collected together in one place
• The AspectJ compiler is free and open source
• AspectJ works with JBuilder, Forté, Eclipse, probably others
• Best online writeup: http://www.eclipse.org/aspectj/


Terminology• A join point is a well-defined point in the program flow
• A pointcut is a group of join points
• Advice is code that is executed at a pointcut
• Introduction modifies the members of a class and the relationships between classes
• An aspect is a module for handling crosscutting concerns
– Aspects are defined in terms of pointcuts, advice, and introduction
– Aspects are reusable and inheritable
• Each of these terms will be discussed in greater detail
The Figure Element example




Using Objects• Expressive
– What is going on its clear
• Abstraction
– Focus on more or less detail
• Structure & Modularity
– What goes where
– How parts fit together
–Things are pretty clear, you know every thing about it. If you wanna add new shapes(FigureElement) that also you can add.
–So now lets make it probelamatic… how… Simple Observer Pattern
–If there is any change in the shape…. Drawing Object should be notified.
–So what is this , good design but a worst code.
–So what can we do , we can use aspects , we can have a aspect for observer pattern and which will be weaved with the existing codess and proviides use the way to work with new requirements.
–So we have Good Design and Good Code.
–Lets see how to do that with the help of aspects.



Other Aspects
• Security
– Pointcut for when checking happens
• Optimization
• Distribution
• Synchronization
• Persistance
• And ofcourse Logging/Tracing
• And very many application –specific aspects
- i.e EnsureLiveness

Example I• A pointcut named move that chooses various method calls:
pointcut move(): call(void FigureElement.setXY(int,int))||
call(void Point.setX(int))||
call(void Point.setY(int))||
call(void Line.setP1(Point))||
call(void Line.setP2(Point));||

• Advice (code) that runs before the move pointcut:
before(): move() {
System.out.println("About to move");
}
• Advice that runs after the move pointcut:
after(): move() {
System.out.println("Just successfully moved");
}
Join points
• A join point is a well-defined point in the program flow
– We want to execute some code (“advice”) each time a join point is reached
– AspectJ provides a syntax for indicating these join points “from outside” the actual code
• A join point is a point in the program flow “where something happens”
– Examples:
• When a method is called
• When an exception is thrown
• When a variable is accessed

AspectJ supports 11 different kinds of join points.These are the method call, method execution, constructor call, constructor execution, field get, field set, pre initialization, initialization, static initialization, handler, and advice execution join points.
Pointcuts
• Pointcut definitions consist of a left-hand side and a right-hand side, separated by a colon
– The left-hand side consists of the pointcut name and the pointcut parameters (i.e. the data available when the events happen)
– The right-hand side consists of the pointcut itself
• Example pointcut:pointcut setter(): call(void setX(int));
– The name of this pointcut is setter
– The pointcut has no parameters
– The pointcut itself is call(void setX(int))
– The pointcut refers to any time the void setX(int) method is called
Example pointcut designators I
• When a particular method body executes:
– execution(void Point.setX(int))
• When a method is called:
– call(void Point.setX(int))
• When an exception handler executes:
– handler(ArrayOutOfBoundsException)
• When the object currently executing (i.e. this) is of type SomeType:
– this(SomeType)



Example pointcut designators II• When the target object is of type SomeType
– target(SomeType)
• When the executing code belongs to class MyClass
– within(MyClass)
• When the join point is in the control flow of a call to a Test's no-argument main method
– cflow(call(void Test.main()))
Pointcut designator wildcards
• It is possible to use wildcards to declare pointcuts:
– execution(* *(..))
• Chooses the execution of any method regardless of return or parameter types
– call(* set(..))
• Chooses the call to any method named set regardless of return or parameter type
• In case of overloading there may be more than one such set method; this pointcut picks out calls to all of them
Pointcut designators based on types
• You can select elements based on types. For example,
– execution(int *())
• Chooses the execution of any method with no parameters that returns an int
– call(* setY(long))
• Chooses the call to any setY method that takes a long as an argument, regardless of return type or declaring type
– call(* Point.setY(int))
• Chooses the call to any of Point’s setY methods that take an int as an argument, regardless of return type
– call(*.new(int, int))
• Chooses the call to any classes’ constructor, so long as it takes exactly two ints as arguments
Pointcut designator composition
• Pointcuts compose through the operations or (“”), and (“&&”) and not (“!”)
• Examples:
– target(Point) && call(int *())
• Chooses any call to an int method with no arguments on an instance of Point, regardless of its name
– call(* *(..)) && (within(Line) within(Point))
• Chooses any call to any method where the call is made from the code in Point’s or Line’s type declaration
– within(*) && execution(*.new(int))
• Chooses the execution of any constructor taking exactly one int argument, regardless of where the call is made from
– !this(Point) && call(int *(..))
• Chooses any method call to an int method when the executing object is any type except Point
Pointcut designators based on modifiers• call(public * *(..))
– Chooses any call to a public method
• execution(!static * *(..))
– Chooses any execution of a non-static method
• execution(public !static * *(..))
– Chooses any execution of a public, non-static method
• Pointcut designators can be based on interfaces as well as on classes
Example I, repeated
• A pointcut named move that chooses various method calls:
pointcut move(): call(void FigureElement.setXY(int,int))
call (void Point.setX(int))
call(void Point.setY(int))
call(void Line.setP1(Point))
call(void Line.setP2(Point));

• Advice (code) that runs before the move pointcut:
before(): move() {
System.out.println("About to move");
}

• Advice that runs after the move pointcut:
after(): move() {
System.out.println("Just successfully moved");
}

Kinds of advice
AspectJ has several kinds of advice; here are some of them:
– Before advice runs as a join point is reached, before the program proceeds with the join point
– After advice on a particular join point runs after the program proceeds with that join point
• after returning advice is executed after a method returns normally
• after throwing advice is executed after a method returns by throwing an exception
• after advice is executed after a method returns, regardless of whether it returns normally or by throwing an exception
– Around advice on a join point runs as the join point is reached, and has explicit control over whether the program proceeds with the join point

Example II, with parameters• You can access the context of the join point:
• pointcut setXY(FigureElement fe, int x, int y): call(void FigureElement.setXY(int, int)) && target(fe) && args(x, y);
• after(FigureElement fe, int x, int y) returning: setXY(fe, x, y) { System.out.println(fe + " moved to (" + x + ", " + y + ").");}


Introduction
• An introduction is a member of an aspect, but it defines or modifies a member of type (class). With introduction we can
– add another methods to an existing class
– add fields to an existing class
– extend an existing class with another
– implement an interface in an existing class
– convert checked exceptions into unchecked exceptions

Example introductionpublic aspect CloneSimpleClass {
declare parents: SimpleClass2 implements Cloneable;
declare soft: CloneNotSupportedException: execution(Object clone());
public Object SimpleClass2.clone(){ return super.clone();}
}

/*
* 1. Class which does not implement CloneNotSupportedException, expected output is
* sucessful running of the method calls because we have aspect for cloning.
*/
public class SimpleClass2 {
private String name=null;
public SimpleClass2(String s){
name = s;
}
public static void main(String[] args) {
SimpleClass2 ref1 = new SimpleClass2("Demo");
ref1.funtion();
try {
SimpleClass2 ref2 = (SimpleClass2) ref1.clone();
ref2.funtion();
} catch (Exception e) {
e.printStackTrace();
}
}
private void funtion() {
System.out.println("Name is "+name);
}
}
So what this does, it adds a functionality for cloning to a non
Cloneable class. Deciding about the feature enancement
during runtime …. Amazing capability in the product….



Approximate syntax
• An aspect is: aspect nameOfAspect { body }
– An aspect contains introductions, pointcuts, and advice
• A pointcut designator is: when(signature)
– The signature includes the return type
– The “when” is call, handler, execution, etc.
• A named pointcut designator is: name(parameters): pointcutDesignator
• Advice is: adviceType(parameters): pointcutDesignator { body }
• Introductions are basically like normal Java code
Example aspect I• aspect PointWatching {
private Vector Point.watchers = new Vector();
public static void addWatcher(Point p, Screen s) { p.Watchers.add(s); }
public static void removeWatcher(Point p, Screen s) { p.Watchers.remove(s); }
static void updateWatcher(Point p, Screen s) { s.display(p); }

pointcut changes(Point p): target(p) && call(void Point.set*(int));
after(Point p): changes(p) {
Iterator iter = p.Watchers.iterator();
while ( iter.hasNext() ) {
updateWatcher(p, (Screen)iter.next());
} }}

How to identify which aspect is working


• In case of Introduction, which we applied to SimnpleClass2, aspect scope is for the class







The role of aspects in software design
• AOP aims at providing better means of addressing the well-known problem of separation of concerns
• Three basic approaches to addressing the process of separation of concerns:
Language-based approach• It is based on the definition of a set of language constructs
• Relevant concerns are identified at the problem domain and translated to aspectual construct
• The final application is obtained by weaving the primary structure with the crosscutting aspects
Framework-based approach• Provides more flexible constructs
• Concerns are materialized as aspectual classes at the framework level
• Developers can customize these aspects using the mechanism supported by the framework
• These types of framework are known as AO frameworks (explicitly engineers concerns)
Architecture-oriented approach• Early identification of concerns using architectural organizational models
• Architectural view-point involves a higher level of abstraction than the previous approaches
• It typically comprises two stages
Architecture-oriented approach
• First, developers should determine the problem architecture
• Then, the approach enables several kinds of aspect materialization through different frameworks



Concluding remarks• Aspect-oriented programming (AOP) is a new paradigm--a new way to think about programming
• AOP is somewhat similar to event handling, where the “events” are defined outside the code itself
• AspectJ is not itself a complete programming language, but an adjunct to Java
• AspectJ does not add new capabilities to what Java can do, but adds new ways of modularizing the code
• AspectJ is free, open source software
• AspectJ based on Java Features and which includes
– Annotations
– Generics
– Enumerated Types
– AutoBoxing and UnBoxing
– New Reflection Interfaces
– Load Time Weaving


Will be adding few exampls ............. shortly..........

Saturday, January 19, 2008

Java Tips for ...novice programmers...

Object-Oriented Programming• An abstract method cannot (obviously) be final.
• An abstract method cannot be static because static methods cannot be
overridden.
• An instance method can be both protected and abstract. A static method
can be protected.
• The JVM does not call an object’s constructor when you clone the object.
• Classes can be modified from their default state using any of the three
keywords: public, abstract, and final. So, can’t have a static class,
only static methods.
• A final variable is a constant, and a final method cannot be overridden.
• A call to this in a constructor must also be on the first line.
Note: can’t have an explicit call to super followed by a call to this
in a constructor - only one direct call to another constructor is allowed.


Memory and Garbage Collection• Can’t predict when garbage collection will occur, but it does run
whenever memory gets low.
• If you want to perform some task when your object is about to be
garbage collected, you can override the java.lang.Object method called
finalize(). This method is declared as protected, does not return a value,
and throws a Throwable object, i.e. protected void finalize() throws Throwable.
• Always invoke the superclass’s finalize() method if you override finalize().
• The JVM only invokes finalize() once per object. Since this is the case,
do not resurrect an object in finalize as when the object is finalized
again its finalize() method will not be called. Instead you should create a
clone of the object if you must bring the object back to life.
• Remember that Java passes method parameters by value and not by
reference. Obviously then, anything that happens to a primitive data
type inside a method does not affect the original value in the calling code.
Also, any reassignment of object references inside a method has no effect
on the objects passed in.


Exceptions
• Invoking a method which declares it throws exceptions is not
possible unless either the code is placed in a try-catch, or the calling
method declares that it throws the exceptions, i.e. checked
exceptions must be caught or rethrown. If the try-catch
approach is used, then the try-catch must cope with all of the
exceptions which a method declares it throws.
• RuntimeException and its subclasses are unchecked exceptions.
• Unchecked exceptions do not have to be caught.
• All Errors are unchecked.
• You should never throw an unchecked exception in your own code, even
though the code will compile.

Methods

• A native method does not have a body, or even a set of braces,
e.g. public native void method();
• A native method cannot be abstract.
• A native method can throw exceptions.
• A subclass may make an inherited method synchronized, or it may
leave offthe synchronized keyword so that its version is not synchronized.
If a methodin a subclass is not synchronized but the method in the
superclass is, the threadobtains the monitor for the object when it enters
the superclass’s method.• You cannot make a method in a subclass more
private than it is defined in thesuperclass, ‘though you can make it more public.


Threads

• A Java program runs until the only threads left running are daemon threads.
• A Thread can be set as a user or daemon thread when it is created.
• In a standalone program, your class runs until your main() method
exists - unless your main() method creates more threads.
• You can initiate your own thread of execution by creating a Thread
object, invoking its start() method, and providing the behaviour that
tells the thread what to do. The thread will run until its run() method
exists, after which it will come to a halt - thus ending its life cycle.
• The Thread class, by default, doesn’t provide any behaviour for run().
• A thread has a life cycle. Creating a new Thread instance puts the thread
into the "new thread" state. When the start() method is invoked, the
thread is then "alive" and "runnable". A thread at this point will repond
to the method isAlive () by returning true.
• The thread will continue to return true to isAlive() until it is "dead",
no matter whether it is "runnable" or "not runnable".
• There are 3 types of code that can be synchronized: class methods, i
nstance methods, any block of code within a method.
• Variables cannot take the synchronized keyword.
• Synchronization stays in effect if you enter a synchronized method
and call out to a non-synchronized method. The thread only gives
up the monitor after the synchronized method returns.



Inner Class

• If you define an inner class at the same level as the enclosing class’
instance variables, the inner class can access those instance variables -
no matter what their access control.
• If you define an inner class within a method, the inner class can
access the enclosing class’ instance variables and also the local
variables and parameter for that method.
• If you do reference local variables or parameters from an inner
class, those variables or parameters must be declared as final to
help guarantee data integrity.
• You can also define an anonymous class - a class without a name.
• If you’d like to refer to the current instance of the enclosing class,
you can write EnclosingClassName.this.
• If you need to refer to the inner class using a fully qualified name,
you can write EnclosingClassName.InnerClassName.
• If your inner class is not defined as static you can only create new
instances of this class from a non-static method.
• Anonymous classes cannot have const


Serializing Objects

•It is now possible to read and write objects as well as primitive data
types, using classes that implement ObjectInput and ObjectOutput.
These two interfaces extend DataInput and DataOutput to read or
write an object. ObjectInputStream and ObjectOutputStream
implement these interfaces.
• If a class implements the Serializable interface, then its public and
protected instance variables will be read from and written to the
stream automatically when you use ObjectInputStream and
ObjectOutputStream.
• If an instance variable refers to another object, it will also be
read or written, and this continues recursively.
• If the referenced object does not implement the Serializable
interface, Java will throw a NotSerializableException.
• The Serializable interface serves only to identify those instances
of a particular class that can be read from and written to a stream.
It does not actually define any methods that you must implement.
• If you create your own class and want to keep certain data from
being read or written, you can declare that instance variable
using the transient keyword. Java skips any variable declared as
transient when it reads and writes the object following the Serializable
protocol.


Reflection

• Using the Reflection API, a program can determine a class’ accessible
fields, methods and constructors at runtime.


will be adding moreeeeeeeeeeeee later, guys....... you are also free to add comments on this and more points........

Heroku Custom Trust Store for SSL Handshake

  Working with Heroku for deploying apps (java, nodejs, etc..) is made very easy but while integrating one of the service ho...