Thursday, June 20, 2013

How to override activate/passivate default methods in Application module Impl class

I came across a situation where I have a instance variable in AM impl class and needed to make it passivation safe.

Actually Instances variables are not passivated by the framework. It recommends not to use instance variables by the developer. If at all someone badly needs instance variables in an AM Impl class, he needs to explicitly override 'passivateState' and 'activateState' methods(in corresponding Impl) to passivate and activate those variables.

Below code snippet is for activating/passivating a specific intance variable in an AM Impl class.

 @Override
    protected void activateState(Element parent) {
        super.activateState(parent);
        activateState(parent, LOV_FLAG);
    }
    private void passivate(Document doc,Element parent,String elemName){
        // 1. Retrieve the value of the value to save
          String value = (String)getSession().getUserData().get(elemName);
          if(value==null){
              return; //no need to passivate
          }
          // 2. Create an XML element to contain the value
          Node node = doc.createElement(elemName);
          // 3. Create an XML text node to represent the value
          Node cNode = doc.createTextNode(value);
          // 4. Append the text node as a child of the element
          node.appendChild(cNode);
          // 5. Append the element to the parent element passed in
          parent.appendChild(node);
    }
    private  void activateState(Element elem,String elemName) {
      super.activateState(elem);
      String value = null;
      if (elem != null) {
        // 1. Search the element for any  elements by elemName
        NodeList nl = elem.getElementsByTagName(elemName);
        if (nl != null) {
          // 2. If any found, loop over the nodes found
          for (int i=0, length = nl.getLength(); i < length; i++) {
            // 3. Get first child node of the  element
            Node child = nl.item(i).getFirstChild();
            if (child != null) {
              // 4. Set the  value to the activated value
              //setCounterValue(new Integer(child.getNodeValue()).intValue()+1);
              value = child.getNodeValue(); 
              break;
            }
          }
        }
      }
  
      if(value!=null){
          getSession().getUserData().put(elemName, value);
      }else{
          getSession().getUserData().remove(elemName);
      }
    }

    @Override
    protected void passivateState(Document document, Element element) {
        super.passivateState(document, element);
        passivate(document, element, LOV_FLAG);
    }