Monday, July 5, 2010

Lets do some XStream test

Aim: Keep a finite state machine configuration in a xml file.

A sample synthetic scenario for this ;
    Get messageBoxes of the users. Put the messageBoxes into a blockingQueue , let some threads process the mailboxes and get new and old messeges from the boxes and seperate them to different queues .
    Then process new messages (exm:delete if it is keeped longer than expected) and put some data for notification sms to the owner of expired message.Some threads will process this queue and will send smses and they will put some data to the edr queue.
    If the message is old (read message) threads on the oldMessageQueue put data to the edr queue directly without sending sms.

Maybe we want to use this states and conditions in a state manager base implementation/code generator which is not written yet ;)

public class StateList {
    public StateList () {
    }

    public List getFsm () {
        return fsm;
    }

    public void setFsm (List fsm) {
        this.fsm = fsm;
    }

    private Listfsm = new ArrayList();
}


public class State {
    public State () {
    }

    private String queueName;
    private int threadCount;
    private int queueSize;
    private String executorClassName;
    private List transitions = new java.util.ArrayList();

    public String getExecutorClassName () {
        return executorClassName;
    }

    public String getQueueName () {
        return queueName;
    }

    public int getThreadCount () {
        return threadCount;
    }

    public int getQueueSize () {
        return queueSize;
    }

    public List getTransitions () {
        return transitions;
    }

    public void setExecutorClassName (String executorClassName) {
        this.executorClassName = executorClassName;
    }

    public void setQueueName (String queueName) {
        this.queueName = queueName;
    }

    public void setThreadCount (int threadCount) {
        this.threadCount = threadCount;
    }

    public void setQueueSize (int queueSize) {
        this.queueSize = queueSize;
    }

    public void setTransitions (List transitions) {
        this.transitions = transitions;
    }
}


public class Transition {
    public Transition () {
    }

    public String getCondition () {
        return condition;
    }

    public String getName () {
        return name;
    }

    public void setCondition (String condition) {
        this.condition = condition;
    }

    public void setName (String name) {
        this.name = name;
    }

    private String name ;
    private String condition;
}


package XstreamTester;

import java.util.*;
import com.thoughtworks.xstream.*;
import java.io.*;


public class XStreamTester {
    public XStreamTester () {
 
    /* messageboxGetter->//newMsgProcessor ->SmsSender->EdrWrite
                                       ->//oldMsgProcessor ->EdrWrite
     */

    }

    public static void main (String[] args) {
        XStreamTester xstreamtester = new XStreamTester ();

        XStream stateConfiguration = new XStream ();
        stateConfiguration.alias ("state", State.class);
        stateConfiguration.alias ("transition", Transition.class);
        stateConfiguration.alias ("states", StateList.class);

        StateList stateConfig = new StateList();
        List stateList = new ArrayList();
        // messagebox state
        State mboxState = new State ();
        mboxState.setExecutorClassName ("MboxGetter");

        List mboxTransitions = new ArrayList();
        Transition newMessageTransition = new Transition ();
        newMessageTransition.setName ("newMessageQueue");
        newMessageTransition.setCondition ("new");
        mboxTransitions.add (newMessageTransition);
        Transition oldMessageTransition = new Transition ();
        oldMessageTransition.setName ("oldMessageQueue");
        oldMessageTransition.setCondition ("old");
        mboxTransitions.add (oldMessageTransition);
        mboxState.setTransitions (mboxTransitions);

        mboxState.setQueueName ("messageBoxQueue");
        mboxState.setThreadCount (10);
        mboxState.setQueueSize (1000);
        stateList.add (mboxState);


        // new message state
        State newMsgState = new State ();
        newMsgState.setExecutorClassName ("newMessageProcessor");

        List newMsgTransitionList = new ArrayList();
        Transition smsTransition = new Transition ();
        smsTransition.setName ("smsQueue");
        smsTransition.setCondition ("deleted");
        newMsgTransitionList.add (smsTransition);
        newMsgState.setTransitions(newMsgTransitionList);

        newMsgState.setQueueName ("newMessageQueue");
        newMsgState.setThreadCount (10);
        newMsgState.setQueueSize (1000);
        stateList.add (newMsgState);

        // old message state
        State oldMsgState = new State ();
        oldMsgState.setExecutorClassName ("oldMessageProcessor");

        List oldMsgTransitionList = new ArrayList();
        Transition edrTransition = new Transition ();
        edrTransition.setName ("edrQueue");
        edrTransition.setCondition ("deleted");
        oldMsgTransitionList.add (edrTransition);
        oldMsgState.setTransitions(oldMsgTransitionList);

        oldMsgState.setQueueName ("oldMessageQueue");
        oldMsgState.setThreadCount (10);
        oldMsgState.setQueueSize (1000);
        stateList.add (oldMsgState);


        //sms state
        State smsState = new State ();
        smsState.setExecutorClassName ("smsQueueProcessor");

        List smsTransitionList = new ArrayList();
        Transition sms2EdrTransition = new Transition ();
        sms2EdrTransition.setName ("edr");
        sms2EdrTransition.setCondition ("smsSent");
        smsTransitionList.add (sms2EdrTransition);

        smsState.setTransitions(smsTransitionList);
        smsState.setQueueName ("smsQueue");
        smsState.setThreadCount (10);
        smsState.setQueueSize (1000);
        stateList.add (smsState);


        //edr state
        State edrState = new State ();
        smsState.setExecutorClassName ("edrQueueProcessor");

        edrState.setQueueName ("edrQueue");
        edrState.setThreadCount (10);
        edrState.setQueueSize (1000);
        stateList.add (edrState);


        stateConfig.setFsm(stateList);
        String xml = stateConfiguration.toXML (stateConfig);
        try {
            BufferedWriter out = new BufferedWriter (new FileWriter (
                "/home/serkans/jbproject/UM_Test/xml/stateConfiguration.xml"));
            out.write (xml);
            out.close ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
        System.exit (0);
    }
}


Generated xml will be something like this.
<states>
  <fsm>
    <state>
      <queueName>messageBoxQueue</queueName>
      <threadCount>10</threadCount>
      <queueSize>1000</queueSize>
      <executorClassName>MboxGetter</executorClassName>
      <transitions>
        <transition>
          <name>newMessage</name>
          <condition>new</condition>
        </transition>
        <transition>
          <name>oldMessage</name>
          <condition>old</condition>
        </transition>
      </transitions>
    </state>
    <state>
      <queueName>newMessageQueue</queueName>
      <threadCount>10</threadCount>
      <queueSize>1000</queueSize>
      <executorClassName>newMessageProcessor</executorClassName>
      <transitions>
        <transition>
          <name>sms</name>
          <condition>deleted</condition>
        </transition>
      </transitions>
    </state>
    <state>
      <queueName>oldMessageQueue</queueName>
      <threadCount>10</threadCount>
      <queueSize>1000</queueSize>
      <executorClassName>oldMessageProcessor</executorClassName>
      <transitions>
        <transition>
          <name>edr</name>
          <condition>deleted</condition>
        </transition>
      </transitions>
    </state>
    <state>
      <queueName>smsQueue</queueName>
      <threadCount>10</threadCount>
      <queueSize>1000</queueSize>
      <executorClassName>edrQueueProcessor</executorClassName>
      <transitions>
        <transition>
          <name>edr</name>
          <condition>smsSent</condition>
        </transition>
      </transitions>
    </state>
    <state>
      <queueName>edrQueue</queueName>
      <threadCount>10</threadCount>
      <queueSize>1000</queueSize>
      <transitions/>
    </state>
  </fsm>
</states>

Wednesday, June 30, 2010

Are u sure about Oracle ROWNUM ?

http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html

A simple implementation with JPA  on oracle dbms

    /*
     I had to make some improvements in query with oracle bec.of performance of the default jpa implementation.
     */
    public User[] getUsersInPage (int startIndex, int stopIndex) throws Exception {

        EntityManager em = createEntityManager ();
        List ret = new ArrayList();
        try {
            if (isOracle()){
                Query selectQuery = em.createNativeQuery ("SELECT * FROM (select a.*,rownum rnum from (select * from provisioning_subsys.VIP_USERS) a where ROWNUM <= " +
                    stopIndex + ") where rnum >=" + startIndex + "", User.class);
                ret = (List) selectQuery.getResultList ();
            }else{
                String qry = "select u from User u";
                Query selectQuery = em.createQuery (qry);
                selectQuery.setMaxResults (stopIndex - startIndex);
                selectQuery.setFirstResult (startIndex);
                ret = (List) selectQuery.getResultList ();
            }
        } finally {
            em.close ();
        }

        return getUserArrayFromList (ret);
    }

    private boolean isOracle () {
        if (emf instanceof EntityManagerFactoryImpl) {
            Properties jpaProperties = ((EntityManagerFactoryImpl) emf).getProperties ();
            String dbms = (String) jpaProperties.get ("Platform");
            if (dbms.indexOf ("Oracle") != -1) {
                return true;
            } else return false;
        }
        return false;
    }

Tuesday, June 15, 2010

CyclicBarrier Test

import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTester {
    private static final int numOfThreads = 5;
   
    public static void main (String[] args) {
        startTasks ();
    }


    private static void startTasks () {
        try {
            CyclicBarrier barrier = buildBarrier();
            startThreads(barrier);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

 
    private static CyclicBarrier buildBarrier () {
        CyclicBarrier barrier = new CyclicBarrier (numOfThreads, new Runnable () {
            public void run () {
                Logger.log (LogLevel.LOG, " -- barrier action done");
            }
        });
        return barrier;
    }
   
    private static void startThreads (CyclicBarrier barrier) {
        Thread[] threads = new Thread[numOfThreads];
        for (int i = 0; i < threads.length; i++) {
            TaskExecuter executor = new TaskExecuter ();
            executor.setName ("CleanupThread-" + i);
            executor.setBarrier (barrier);
            threads[i] = executor;
            threads[i].start ();
        }
        for (int i = 0; i < threads.length; i++) {
            try {
                threads[i].join ();
            } catch (InterruptedException ignore) {
            }
        }
    }

}









import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.BrokenBarrierException;

public class TaskExecuter extends Thread {
    private CyclicBarrier barrier ;

    public void setBarrier (CyclicBarrier barrier){
        this.barrier = barrier;
    }

    public void run () {
            Logger.log (LogLevel.LOG, "   --- {0} is started processing....", this.getName ());
            try {
                doAction ();
            } catch (Exception e) {
                Logger.log(LogLevel.EXCEPTION,"[{0}]",e);
            }
            Logger.log (LogLevel.LOG, "   --- {0} is finished processing....", this.getName ());
    }

    private void doAction () {
            try {
                //do your work
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                waitForOthers ();
            }
    }

    private void waitForOthers () {
            try {
                Logger.log (LogLevel.LOG, "{0} is waiting for the others, currentwaiters count :{1}",
                    getName (), barrier.getNumberWaiting ());
                barrier.await (100000L, TimeUnit.MILLISECONDS);
                Logger.log (LogLevel.LOG, "{0} is out of the barrier ", getName ());
            } catch (BrokenBarrierException e) {
                barrier.reset();
                Logger.log (LogLevel.WARNING, " -- resetting the barrier for the exception : {0}", e);
            } catch (InterruptedException ex) {
                Logger.log (LogLevel.EXCEPTION, " --{0}", ex);
            } catch (TimeoutException ex) {
                Logger.log (LogLevel.EXCEPTION, " --{0}", ex);
            }
    }

}

introduction-to-google-guice

introduction-to-google-guice

update date column in mysql

update `myDb`.`myTable` set myColumn = (DATE_SUB(sysdate(), INTERVAL 1 DAY));