Search This Blog

Friday 30 August 2013

Spring bean scopes and Spring bean life cycle

Spring Bean scopes


There are six bean scopes in spring. Two scopes are related with normal beans, these are singleton and prototype. Other three related with web-aware beans, these are request, session global session.
Singleton
Spring container creates single object instance for a bean definition.
Prototype
Spring container creates any number of object instances for a bean definition.
Request
Spring container creates bean object instance for a bean definition for each HTTP request. This scope is valid in the web-aware spring context.
Session
Spring container creates one bean object instance for a bean definition for the lifetime of a single HTTP Session. This scope is valid in the web-aware spring context.
Global session
A global Session that is shared amongst all of the various portlets that make up a single portlet web application.
Spring container creates one bean object instance for a bean definition for the lifetime of a single HTTP Session. This scope is valid in the web-aware spring context.



Spring bean life cycle
Bean Instantiation – Instantiating  the bean
Set Bean Name – by using setBeanName method
Populate properties – Injecting  bean  properties
Set Bean Factory – by using setBeanFactory method, if bean implements BeanFactoryAware
Bean Pre Initialization - by postProcesserBeforeInitialization method, if bean implements
                                     BeanFactoryAware
Bean Initalization – by using init method
Bean Post initialization – by using postProcessAfterinitalization method, if bean 
                                          implements BeanFactoryAware
Bean Ready to Use - Now the bean is ready to use
Destroy bean – by using destroy method

Sample Code:

//XML declaration

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
    default-init-method="dInitMethod"
    default-destroy-method="dDestroymethod">
      <bean id="springBean" 
          class="SpringLifeCycleMehodBean" />
</beans>

-------------------------------------------------------------
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;

public class SpringBean implements BeanFactoryAware, BeanNameAware,
{

//Member variables declaration
@Override
public void setBeanName(String arg0) {
System.out.println("Method setBeanName...");
}

@Override
public void setBeanFactory(BeanFactory arg0) throws BeansException {
System.out.println("Method setBeanFactory...");
}

@PostConstruct
public void postConstruct() 
{
System.out.println("Method postConstruct...");
}

@PreDestroy
public void preDestroy() 
{
System.out.println("Method pre Destroy...");
}

}


 

Wednesday 28 August 2013

Drools Demo with three rules and agenda-group and using hash map



Drools Demo with three rules and agenda-group and using hash map




KnowledgeBuilder

This is responsible for taking source files, such as a .drl file, a .bpmn2 file or an .xls file, and turning them into a KnowledgePackage of rule and process definitions which a KnowledgeBase can consume. It uses the ResourceType enum to tell it the type of the resource it is being asked to build.

KnowledgeBuilderFactory

This factory is used to build the knowledge base resources that are held collectively in KnowledgePackages. The KnowledgePackage also provides the role of 'namespacing

KnowledgeBase

This is a repository of all the application's knowledge definitions. It will contain rules, processes, functions, type models. The KnowledgeBase itself does not contain runtime data, instead sessions are created from the KnowledgeBase in which data can be inserted and process instances started. Creating the KnowledgeBase can be heavy, where as session creation is very light, so it is recommended that KnowledgeBases be cached where possible to allow for repeated session creation.

StatefulKnowledgeSession

StatefulKnowledgeSession is the most common way to interact with the engine. A StatefulKnowledgeSession allows the application to establish an iterative conversation with the engine, where the state of the session is kept across invocations.







DecisionTableTest.java
=====================================
package com.sample;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.DecisionTableConfiguration;
import org.drools.builder.DecisionTableInputType;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;

/**
 * This is a sample class to launch a decision table.
 */
public class DecisionTableTest {

    public static final void main(String[] args) {
        StatefulKnowledgeSession ksession = null;
        try {
            // load up the knowledge base
            KnowledgeBase kbase = readKnowledgeBase();
            ksession = kbase.newStatefulKnowledgeSession();
            KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
            // go !
            Message message = new Message();
            message.setMessage("Hello World1");
            ksession.insert(message);
            Set<String> keys = message.getTextHashMap().keySet();
           System.out.println("Hash map start");
            for (String key:keys) {
               
                System.out.println(key +"  " +message.getTextHashMap().get(key));
            }
            System.out.println("Hash map end");
            //workingMemory.getAgenda().activateRuleFlowGroup(String name)

            ksession.getAgenda().getAgendaGroup("abcactiongroup1").setFocus();
            ksession.getAgenda().getAgendaGroup("abcactiongroup2").setFocus();
            //ksession.getAgenda().getAgendaGroup("abcactiongroup3").setFocus();
            //ksession.getAgenda().getActivationGroup("abcactiongroup2");
            //getRuleFlowGroup( "abcactiongroup1");
            //ksession.getAgenda().getActivationGroup("abcactiongroup2");//getRuleFlowGroup( "abcactiongroup2");
            //ksession.getAgenda().getRuleFlowGroup( "abcactiongroup3");
            //ksession.getAgenda().getActivationGroup( "abcactiongroup1").clear();
            //ksession.getAgenda().getActivationGroup( "abcactiongroup2").clear();
            ksession.fireAllRules();
            //DAO calling to insert output into data base
            //DroolsDAO.insertRuleDetails(message.getOutputList());
            List<String> outList = message.getOutputList();
            for (String s:outList) {
                System.out.println("111" +s);
            }
            logger.close();
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            ksession.dispose();
        }
    }

    private static KnowledgeBase readKnowledgeBase() throws Exception {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        DecisionTableConfiguration config = KnowledgeBuilderFactory.newDecisionTableConfiguration();
        config.setInputType(DecisionTableInputType.XLS);
        kbuilder.add(ResourceFactory.newClassPathResource("Book1000.xls"), ResourceType.DTABLE, config);
        KnowledgeBuilderErrors errors = kbuilder.getErrors();
        if (errors.size() > 0) {
            for (KnowledgeBuilderError error: errors) {
                System.err.println(error);
            }
            throw new IllegalArgumentException("Could not parse knowledge.");
        }
        KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
        return kbase;
    }
   
    public static class Message {

        private Map<String, String> textHashMap = null;
        private Map<String, Integer> numberHashMap = null;
        private Map<String, Date> dateHashMap = null;
        public List<String>outputList = null;
       
        public List<String> textListData = null;
        public List<Integer> numberListData = null;
        public List<Date> dateListData = null;
        public static final  String PASS = "Passed";
        public static final  String PASS1 = "Passed1";

        private String message;

        private int status;
        private String msgStatus = "Failed";
       
       
        public Message() {
            textHashMap = new HashMap<String, String>();
            numberHashMap = new HashMap<String, Integer>();
            dateHashMap = new HashMap<String, Date>();
            outputList = new LinkedList<String>();
            String rulesData = null;
            /*try {
                 rulesData = DroolsDAO.getRulesData("LON0001");
            } catch (SQLException sqlEx) {
                sqlEx.printStackTrace();
            }*/
            rulesData = "string-employee_name-ABC,string-student_name-ABC,string-employee_uid-UID0081,string-student_uid-UID008,number-employee_marks-980,number-student_marks-980,date-employee_dob-02/14/2013,date-student_dob-02/14/2013";
            DroolsRulesDataSeparator.separateDroolsRulesDataAndAddToMaps(rulesData, textHashMap,
                    numberHashMap, dateHashMap);
        }
        /**
         * @return the msgStatus
         */
        public String getMsgStatus() {
            return msgStatus;
        }

        /**
         * @param msgStatus the msgStatus to set
         */
        public void setMsgStatus(String msgStatus) {
            this.msgStatus = msgStatus;
        }

        public String getMessage() {
            return this.message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getStatus() {
            return this.status;
        }

        public void setStatus(int status) {
            this.status = status;
        }
        /**
         * @return the textHashMap
         */
        public Map<String, String> getTextHashMap() {
            return textHashMap;
        }
        /**
         * @param textHashMap the textHashMap to set
         */
        public void setTextHashMap(Map<String, String> textHashMap) {
            this.textHashMap = textHashMap;
        }
        /**
         * @return the numberHashMap
         */
        public Map<String, Integer> getNumberHashMap() {
            return numberHashMap;
        }
        /**
         * @param numberHashMap the numberHashMap to set
         */
        public void setNumberHashMap(Map<String, Integer> numberHashMap) {
            this.numberHashMap = numberHashMap;
        }
        /**
         * @return the dateHashMap
         */
        public Map<String, Date> getDateHashMap() {
            return dateHashMap;
        }
        /**
         * @param dateHashMap the dateHashMap to set
         */
        public void setDateHashMap(Map<String, Date> dateHashMap) {
            this.dateHashMap = dateHashMap;
        }
        /**
         * @return the outputList
         */
        public List<String> getOutputList() {
            return outputList;
        }
        /**
         * @param outputList the outputList to set
         */
        public void setOutputList(List<String> outputList) {
            this.outputList = outputList;
        }
    }

}

DroolsRulesDataSeparator.java
===========================================





package com.sample;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class DroolsRulesDataSeparator {
    public static void separateDroolsRulesDataAndAddToMaps(String ruleData,Map<String, String> textHashMap,
                Map<String, Integer> numberHashMap,Map<String, Date> dateHashMap) {
        if (ruleData != null && !"".equals(ruleData)) {//if 1 start
            String[] ruleDataArr = ruleData.split(",");
            for (int index = 0; index < ruleDataArr.length; index++) {//for 1 start
                if (ruleDataArr[index] != null && !"".equals(ruleDataArr[index])) {//if 2 staart
                    //System.out.println(ruleDataArr[index]);
                    String[] typeColumnData = ruleDataArr[index].split("-");
                    //if (index == 0 || index%2 == 0) {
                        if (typeColumnData[0].equalsIgnoreCase("string")) {
                            if (null == typeColumnData[2]) {
                                textHashMap.put(typeColumnData[1], " ");
                            } else {
                                //System.out.println("if:" + typeColumnData[1] + ":" + typeColumnData[2]);
                                textHashMap.put(typeColumnData[1], typeColumnData[2]);
                            }
                        } else if (typeColumnData[0].equalsIgnoreCase("number")) {
                            if (null == typeColumnData[2] || "".equalsIgnoreCase(typeColumnData[2].trim())) {
                                numberHashMap.put(typeColumnData[1], new Integer(Integer.parseInt("0")));
                            } else {
                                //System.out.println("if:" + typeColumnData[1] + " " + Integer.parseInt(typeColumnData[2]));
                                numberHashMap.put(typeColumnData[1], new Integer(Integer.parseInt(typeColumnData[2].trim())));
                            }
                        } else if (typeColumnData[0].equalsIgnoreCase("date")) {
                            String dateStr;
                            if (null == typeColumnData[2] || "".equalsIgnoreCase(typeColumnData[2].trim())) {
                                dateStr = "01/01/0001";
                            } else {
                                dateStr = typeColumnData[2];
                            }
                            DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
                            try {
                                Date columnDate = df.parse(dateStr);
                                dateHashMap.put(typeColumnData[1], columnDate);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                }//if 2 end               
            }//for 1 start
        }//if 1 end       
    }
}