Friday, December 7, 2012

Observer Pattern

The observer pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.
The object which is being watched is called the subject.The objects which are watching the state changes are called observer. Alternatively observer are also called listener.

When To Use
  1. In a mailing list, where every time an event happens (a new product, a gathering, etc.) a message is sent to the people subscribed to the list.
  2. When a change to one object requires changing others, and you don't know how many objects need to be changed.
  3. When an object should be able to notify other objects without making assumptions about who these objects are (avoid tight-coupling). 
 Example Code :

interface Observer {
 public void update(Subject o);
}

interface Subject {
 public void addObserver(Observer o);
 public void removeObserver(Observer o);
 public String getState();
 public void setState(String state);
}


class ObserverImpl implements Observer {
 private String state = "";
 public void update(Subject o) {
   state = o.getState();
   System.out.println("Update received from Subject, state changed to : " + state);
   try{
       Thread.sleep(1000);
       System.err.println("Update received from Subject, state changed to : " + state);
   } catch(Exception ex) {
      ex.printStackTrace();
   }
 }
}
 

import java.util.*;
class SubjectImpl implements Subject {
 private List observers = new ArrayList();

 private String state = "";

 public String getState() {
   return state;
 }

 public void setState(String state) {
   this.state = state;
   notifyObservers();
 }

 public void addObserver(Observer o) {
   observers.add(o);
 }

 public void removeObserver(Observer o) {
   observers.remove(o);
 }

 public void notifyObservers() {
   Iterator i = observers.iterator();
   while (i.hasNext()) {
     Observer o = (Observer) i.next();
     o.update(this);
   }
 }
}

Observer Test Class
public class ObserverTest {
 public static void main(String[] args) {
     for( int i =0 ; i< 10; i++ ) {
       Observer o = new ObserverImpl();
       Subject s = new SubjectImpl();
       s.addObserver(o);
       s.setState("New State"+i);
     }
   }
}

Singleton Desgin Pattern

 
There are only two points in the definition of a singleton design pattern,
  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance.
Sample code : singleton + early Initialization
 
public class Singleton {
  // Private constructor prevents instantiation from other classes
  private Singleton() {}
 
  /**
   * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
   * or the first access to SingletonHolder.INSTANCE, not before.
   */
  private static class SingletonHolder { 
    private static final Singleton INSTANCE = new Singleton();
  }

  public static Singleton getInstance() {
    return SingletonHolder.INSTANCE;
  }
}

Sample code : singleton + lazy Initialization
public class Singleton {
  private static Singleton singleInstance;
    private Singleton() {}
  public static Singleton getSingleInstance() {
    if (singleInstance == null) {
      synchronized (Singleton.class) {
        if (singleInstance == null) {
          singleInstance = new Singleton();
        }
      }
    }
    return singleInstance;
  }
 

Thursday, December 6, 2012

Alfresco Content search example

This method will allows to search the Alfresco document repository by content in the document.
returen the result  
/**
     * Alfresco Document search by Content.
     * @param alfrescoSearchVO
     */
    public List<String> searchByContent(AlfrescoSearchVO alfrescoSearchVO) {
        LOGGER.entering("searchByContent");
        List<String> documentList = null;
        try {
            initiate();
           
            RepositoryServiceSoapBindingStub repositoryService = alfrescoServices
            .getRepositoryService();
           
            Query query = new Query(Constants.QUERY_LANG_LUCENE,
                    DOCUMENT_SEARCH_PATH1
            +  " AND TEXT:(\""+ alfrescoSearchVO.getText() +"\")");
            QueryResult queryResult = repositoryService.query(STORE, query, false);
            ResultSet resultSet = queryResult.getResultSet();
            ResultSetRow[] rows = resultSet.getRows();
            if (rows == null) {
                System.out.println("No query results found.");
                if (alfrescoSearchVO.getText().trim().contains(" ")) {
                    String textArray[] = alfrescoSearchVO.getText().split(" ");
                    StringBuffer queryBuffer = new StringBuffer();
                    queryBuffer.append(" AND (");
                    for (int i=0; i<textArray.length; i++) {
                        if (i == 0) {
                            queryBuffer.append(
                            " TEXT:\""+ textArray[i].trim() +"\"");
                        } else {
                            queryBuffer.append(
                            " OR TEXT:\""+ textArray[i].trim() +"\"");
                        }
                    }
                    queryBuffer.append(" )");
                    if (queryBuffer.toString().length() > 0) {
                        System.out.println("Query :" + queryBuffer.toString());
                        query = new Query(Constants.QUERY_LANG_LUCENE,
                        DOCUMENT_SEARCH_PATH
                        +  queryBuffer.toString());
                        queryResult = repositoryService.query(STORE, query, false);
                        resultSet = queryResult.getResultSet();
                        rows = resultSet.getRows();
                        if (rows != null) {
                            documentList = iterateQueryResultSet(rows);
                        } else {
                            System.out.println("Final No query results found.");
                        }
                    }
                }
               
            } else {
                documentList = iterateQueryResultSet(rows);
            }
            alfrescoServices.endSession();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        LOGGER.exiting("searchByContent");
        return documentList;
    }
    /**
     * The result will be iterate to content the document information.
     * @param rows
     */
    public List<String> iterateQueryResultSet(ResultSetRow[] rows){
        LOGGER.entering("iterateQueryResultSet");
        List<String> documentList = new ArrayList<String>();
        try {
            for (ResultSetRow row : rows) {
                System.out.println("UID: " + row.getNode().getId());
                System.out.println("Type: " + row.getNode().getType());
               
                NamedValue[] values = row.getColumns();
                System.out.println("Properties: ");
                for (NamedValue col : values) {
                    /*if (col.getName().endsWith("title") || col.getName().endsWith("path")) {
                        System.out.println("\tName: " + col.getName());
                        System.out.println("\tValue: " + col.getValue());
                        System.out.println("------------------------");
                    }*/
                    if (col.getName().endsWith("path")) {
                        System.out.println("\tName: " + col.getName());
                        System.out.println("\tValue: " + col.getValue());
                        String path = col.getValue();
                        path = path.replace("/{http://www.alfresco.org/model/application/1.0}", "/app:");
                        path = path.replace("/{http://www.alfresco.org/model/site/1.0}", "/st:");
                        path = path.replace("/{http://www.alfresco.org/model/content/1.0}", "/cm:");
                        System.out.println("------------------------");
                        System.out.println("path:" + path);
                        documentList.add(path);
                    }
               
                    /*System.out.println("\tName: " + col.getName());
                    System.out.println("\tValue: " + col.getValue());*/
                   
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        LOGGER.exiting("iterateQueryResultSet");
        return documentList;
    }


/*Alfresco serach vo*/
public class AlfrescoSearchVO {
    private String name;
    private String title;
    private String text;
    private String author;
    private String modifier;
    private String creator;
    private String contentType;
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return the title
     */
    public String getTitle() {
        return title;
    }
    /**
     * @param title the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }
    /**
     * @return the text
     */
    public String getText() {
        return text;
    }
    /**
     * @param text the text to set
     */
    public void setText(String text) {
        this.text = text;
    }
    /**
     * @return the author
     */
    public String getAuthor() {
        return author;
    }
    /**
     * @param author the author to set
     */
    public void setAuthor(String author) {
        this.author = author;
    }
    /**
     * @return the modifier
     */
    public String getModifier() {
        return modifier;
    }
    /**
     * @param modifier the modifier to set
     */
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
    /**
     * @return the creator
     */
    public String getCreator() {
        return creator;
    }
    /**
     * @param creator the creator to set
     */
    public void setCreator(String creator) {
        this.creator = creator;
    }
    /**
     * @return the contentType
     */
    public String getContentType() {
        return contentType;
    }
    /**
     * @param contentType the contentType to set
     */
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
   
}

Hibernate Reverse Engineering

Hibernate Reverse Engineering using Eclipse + plugin

Eclipse helios hibernate plugins URL

 Latest Stable Release - http://download.jboss.org/jbosstools/updates/stable/

Steps : filter by hibernate and select all hibernate tools , say next.

After installing the plugin cross check in  by selecting the new project -> others

Add caption


Steps to generate the Entities or Hbm files.

Step1 : create the normal java project and then right click on project -> new project - > others-> select the console configuration
Add this file hibernate.cfg.xml in classpath of the project

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.session_factory_name">MySessionFactory</property>
        <property name="hibernate.connection.driver_class">
            com.mysql.jdbc.Driver</property>
        <property name="current_session_context_class">thread</property>
        <property name="hibernate.connection.url">jdbc:mysql://192.168.42.40:3306/portal</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.pool_size">10</property>
        <property name="show_sql">true</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
       
        <!-- Mapping files -->
    </session-factory>
</hibernate-configuration>





Click next

By default configuration file will be selected

For Database connection select has new

Select a db u required and click next

after that click finish

Reverse engineering step.