State.java :  » Content-Management-System » harmonise » org » openharmonise » rm » publishing » Java Open Source

Java Open Source » Content Management System » harmonise 
harmonise » org » openharmonise » rm » publishing » State.java
/*
 * The contents of this file are subject to the 
 * Mozilla Public License Version 1.1 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
 * See the License for the specific language governing rights and 
 * limitations under the License.
 *
 * The Initial Developer of the Original Code is Simulacra Media Ltd.
 * Portions created by Simulacra Media Ltd are Copyright (C) Simulacra Media Ltd, 2004.
 *
 * All Rights Reserved.
 *
 * Contributor(s):
 */
package org.openharmonise.rm.publishing;

import java.io.*;
import java.util.*;

import org.openharmonise.commons.cache.CacheException;
import org.openharmonise.commons.dsi.AbstractDataStoreInterface;
import org.openharmonise.commons.xml.*;
import org.openharmonise.commons.xml.parser.*;
import org.openharmonise.rm.DataAccessException;
import org.openharmonise.rm.config.*;
import org.openharmonise.rm.factory.*;
import org.openharmonise.rm.metadata.*;
import org.openharmonise.rm.resources.*;
import org.openharmonise.rm.resources.metadata.values.Value;
import org.openharmonise.rm.resources.publishing.WebPage;
import org.openharmonise.rm.resources.users.User;
import org.openharmonise.rm.sessions.*;
import org.openharmonise.rm.view.servlet.utils.HttpRequestManager;
import org.w3c.dom.*;


/**
 * This class provides an XML representation of a context with the process of 
 * publishing content within the Harmonise framework. Extending <code>XMLDocument</code>, it is
 * generally a XML representation of the HTTP query string which the <code>Harmonise</code>
 * servlet receives.
 * 
 * @author Michael Bell
 * @version $Revision: 1.2 $
 *
 */
public class State extends XMLDocument {
  
  private Map m_requestHeaders;
  private String m_requestRemoteAddress = null;

  //config constant prop names
  protected static final String PNAME_DEFAULT_PAGE = "DEFAULT_PAGE";

  //XML constants
  public static final String TAG_STATE = "State";
  public static final String ATTRIB_STATE_ID = "stateId";
  public static final String TAG_REFERER = "Referer";

  protected User m_User = null;
  protected Profile m_UserProf = null;
  protected String m_stringcontent = "";
  protected File m_filecontent = null;
  protected PublishFilter m_publishFilter = null;
  protected AbstractDataStoreInterface m_dsi = null;
  protected boolean m_bIsPopulated = false;
  private static HashSet ignoreTags = new HashSet(89);
  
  static {
    ignoreTags.add("show_xml");
    ignoreTags.add("ignore_submit");
    ignoreTags.add("ignore_submit.x");
    ignoreTags.add("ignore_submit.y");
    ignoreTags.add("ignore_filename");
    ignoreTags.add("ignore_filepath");
  }

  /**
   * Constructs State object from a W3C Document.
   *
   * @param document - The document to use
   */
  public State(AbstractDataStoreInterface dbintrf) throws StateException {
    super();
    m_dsi = dbintrf;
    setBlankUserDetails();
  }
  
  /**
   * Constructs State object from a W3C Document.
   *
   * @param document - The document to use
   */
  public State(AbstractDataStoreInterface dbintrf, User usr) throws StateException {
    super();
    m_dsi = dbintrf;
    m_User = usr;
  }

  /**
   * Constructs State object from W3C Document.
   *
   * @param document - The document to use
   */
  public State(
    org.w3c.dom.Document document,
    AbstractDataStoreInterface dbintrf) throws StateException {
    super(document);
    m_dsi = dbintrf;
    setBlankUserDetails();
  }

  /** 
   * Finds element in state which matches the given element
   *
   * @param el Element to match in state
   * @param state XML representation of state
   * @exception Exception
   * @return Matching Element found in state
   */
  public Element findElement(Element el) {
    Element foundEl = null;
    String sTagName = el.getTagName();

    NodeList nodes = getElementsByTagName(sTagName);

    String sFindName = el.getAttribute(AbstractObject.ATTRIB_NAME);
    String sFindId = el.getAttribute(AbstractObject.ATTRIB_ID);
    String sFindStateId = el.getAttribute(ATTRIB_STATE_ID);

    for (int i = 0; i < nodes.getLength(); i++) {
      Element next = (Element) nodes.item(i);
      String sNextName = next.getAttribute(AbstractObject.ATTRIB_NAME);
      String sNextId = next.getAttribute(AbstractObject.ATTRIB_ID);
      String sNextStateId = next.getAttribute(ATTRIB_STATE_ID);

      boolean bFoundName = false;
      boolean bFoundId = false;
      boolean bFoundStateId = false;

      if (!sFindName.equalsIgnoreCase("")
        && !sNextName.equalsIgnoreCase("")) {
        if (sFindName.equals(sNextName)) {
          bFoundName = true;
        }
      } else {
        bFoundName = true;
      }

      if (!sFindId.equalsIgnoreCase("")
        && !sNextId.equalsIgnoreCase("")) {
        if (sFindId.equals(sNextId)) {
          bFoundId = true;
        }
      } else {
        bFoundId = true;
      }

      if (!sFindStateId.equalsIgnoreCase("")
        && !sNextStateId.equalsIgnoreCase("")) {
        if (sFindStateId.equals(sNextStateId)) {
          bFoundStateId = true;
        }
      } else {
        bFoundStateId = true;
      }

      if (bFoundId && bFoundName && bFoundStateId) {
        foundEl = next;
      }
    }

    return foundEl;
  }

  /** 
   * Finds elements in state which matches the given element.
   *
   * @param el Element to match in state
   * @param state XML representation of state
   * @exception Exception
   * @return Matching Element found in state
   */
  public List findElements(Element el) {
    Element foundEl = null;
    String sTagName = el.getTagName();
    List vRetn = new ArrayList();

    NodeList nodes = getElementsByTagName(sTagName);

    String sFindName = el.getAttribute(AbstractObject.ATTRIB_NAME);
    String sFindId = el.getAttribute(AbstractObject.ATTRIB_ID);
    String sFindStateId = el.getAttribute(ATTRIB_STATE_ID);

    for (int i = 0; i < nodes.getLength(); i++) {
      Element next = (Element) nodes.item(i);
      String sNextName = next.getAttribute(AbstractObject.ATTRIB_NAME);
      String sNextId = next.getAttribute(AbstractObject.ATTRIB_ID);
      String sNextStateId = next.getAttribute(ATTRIB_STATE_ID);

      boolean bFoundName = false;
      boolean bFoundId = false;
      boolean bFoundStateId = false;

      if (!sFindName.equalsIgnoreCase("")
        && !sNextName.equalsIgnoreCase("")) {
        if (sFindName.equals(sNextName)) {
          bFoundName = true;
        }
      } else {
        bFoundName = true;
      }

      if (!sFindId.equalsIgnoreCase("")
        && !sNextId.equalsIgnoreCase("")) {
        if (sFindId.equals(sNextId)) {
          bFoundId = true;
        }
      } else {
        bFoundId = true;
      }

      if (!sFindStateId.equalsIgnoreCase("")
        && !sNextStateId.equalsIgnoreCase("")) {
        if (sFindStateId.equals(sNextStateId)) {
          bFoundStateId = true;
        }
      } else {
        bFoundStateId = true;
      }

      if (bFoundId && bFoundName && bFoundStateId) {
        vRetn.add(next);
      }
    }

    return vRetn;
  }


  /** 
   * Resolves a relative path to an absolute one. Only copes 
   * with relative tokens at the beginning of a path.
   *
   * @param sClassName The tag name for the class that the path is in the context of
   * @param sPath The path
   * @return An absolute version of the path
   * @throws Exception
   */
  public String resolveRelativePath(String sClassName, String sPath)
    throws StateException {
    String sReturn = null;

    if (sPath.startsWith(".")) {
      StringTokenizer tokenizer = new StringTokenizer(sPath, "/");
      StringBuffer sNewPath = new StringBuffer();
      AbstractChildObject obj =
        (AbstractChildObject) getHarmoniseObject(sClassName);

      // if there is not an object of the required type, see if any
      // children are in the state
      if (obj == null) {
        Element el = createElement(sClassName);
        AbstractObject ohObj = null;
        try {
          ohObj = HarmoniseObjectFactory.instantiateHarmoniseObject(m_dsi, el, this);
        } catch (HarmoniseFactoryException e) {
          throw new StateException("Error getting object from factory",e);
        }

        if (ohObj instanceof AbstractParentObject) {
          AbstractParentObject parent = (AbstractParentObject) ohObj;
          
          List childClassNames = parent.getChildClassNames();
          
          Iterator iter = childClassNames.iterator();
          
          boolean bFound = false;
          
          while(iter.hasNext() == true && bFound == false) {
            sClassName = (String) iter.next();

            if (sClassName.indexOf('.') >= 0) {
              sClassName =
                sClassName.substring(
                  sClassName.lastIndexOf('.') + 1);
            }
            
            obj = (AbstractChildObject) getHarmoniseObject(sClassName);
            
            bFound = (obj != null);
          }
  
        } else {
          // must be a child object
          sClassName =
            ((AbstractChildObject) ohObj)
              .getParentObjectClassName();

          if (sClassName.indexOf('.') >= 0) {
            sClassName =
              sClassName.substring(
                sClassName.lastIndexOf('.') + 1);
          }

          obj = (AbstractChildObject) getHarmoniseObject(sClassName);
        }
      }

      if (obj != null) {
        String sNext = null;

        while (tokenizer.hasMoreTokens()) {
          sNext = tokenizer.nextToken();

          try {
            if (sNext.equals("..")) {
              if (sNewPath.length() > 0) {
                sNewPath.append("/");
              }
            
              obj = (AbstractChildObject) obj.getRealParent();
              sNewPath = new StringBuffer(obj.getPath());
              sNewPath.append("/");
              sNewPath.append(obj.getName());
            } else if (sNext.equals(".")) {
              if (sNewPath.length() > 0) {
                sNewPath.append("/");
              }
            
              sNewPath.append(obj.getPath());
              sNewPath.append("/");
              sNewPath.append(obj.getName());
            } else {
              if (sNewPath.length() > 0) {
                sNewPath.append("/");
              }
            
              sNewPath.append(sNext);
            
              while (tokenizer.hasMoreTokens()) {
                sNewPath.append("/");
                sNext = tokenizer.nextToken();
                sNewPath.append(sNext);
              }
            }
          } catch (DataAccessException e) {
            throw new StateException("Error occured accessing object data",e);
          }
        }

        sReturn = sNewPath.toString();
      }
    } else {
      sReturn = sPath;
    }

    return sReturn;
  }

  /**
   * Adds the file as extra contents to this representation of the state.
   * 
   * @param fileContent
   */
  public void addFileContents(File fileContent) {
    this.m_filecontent = fileContent;
  }

  /**
   * Adds <code>sContent</code> as extra content to this state.
   * 
   * @param stringContent
   */
  public void addStringContents(String sContent) {
    this.m_stringcontent = sContent;
  }

  /**
   * Returns the <code>File</code> contents of this state.
   * 
   * @return
   */
  public File getFile() {
    return m_filecontent;
  }

  /**
   * Returns the <code>String</code> contents of this state.
   * 
   * @return
   */
  public String getStringContent() {
    return m_stringcontent;
  }

  /** 
   * Finds logged in User from Session in the state and returns their Profile.
   *
   * @param state XML state representation
   * @exception Exception
   * @return Profile of current logged in user
   */
  public Profile getLoggedInUserProfile() {

    return m_UserProf;
  }

  /** 
   * Finds and returns the logged-in User found from Session in the state.
   *
   * @param state XML representation of the state
   * @exception Exception
   * @return User found in the state
   */
  public User getLoggedInUser() {

    return m_User;
  }
  
  /**
   * Adds a user to this state representation.
   * 
   * @param usr
   */
  public void setLoggedInUser(User usr) {
    m_User = usr;
  }

  /** 
   * Returns the current Webpage id found in the state.
   *
   * @param state XML representation of the state
   * @exception Exception
   * @return Current Webpage id
   */
  public int getCurrentPageId() throws Exception {
    Element pageEl =
      XMLUtils.getFirstNamedChild(getDocumentElement(), WebPage.TAG_PAGE);

    int nId = -1;

    if (pageEl != null) {
      nId =
        Integer.parseInt(pageEl.getAttribute(AbstractObject.ATTRIB_ID));
    }

    return nId;
  }


  /**
   * Returns the page id from state.
   * 
   * @return
   */
  public int getPageId() {
    NodeList xnlPage = getElementsByTagName(WebPage.TAG_PAGE);
    int nId = -1;

    if (xnlPage.getLength() > 0) {
      nId =
        Integer.parseInt(
          ((Element) xnlPage.item(0)).getAttribute(
            AbstractObject.ATTRIB_ID));
    }

    return nId;
  }

  /**
   * Returns the  session id from state.
   * 
   * @return
   */
  public String getSessionId() {
    NodeList xnlSession = getElementsByTagName(Session.TAG_SESSION);
    String sSessionId = null;

    if (xnlSession.getLength() > 0) {
      sSessionId =
        ((Element) xnlSession.item(0)).getAttribute(
          AbstractObject.ATTRIB_ID);
    }

    return sSessionId;
  }
  
  /**
   * Returns the session associated with this state.
   * 
   * @return
   * @throws DataAccessException
   */
  public Session getSession() throws DataAccessException {
    Session session = null;
    try {
      String sSessionId = getSessionId();
      if(sSessionId != null) {
        session = SessionCache.getInstance(m_dsi).getSession(sSessionId);
      }
    } catch (CacheException e) {
      throw new DataAccessException("Error getting session from cache",e);
    }
    
    return session;
  }

  /** 
   * Returns a String that is this state converted to a list of HTTP params.
   *
   * @return The parameters
   */
  public String encodeAsHttpParams() {
    NodeList nodes = getDocumentElement().getChildNodes();
    StringBuffer sUrl = new StringBuffer();

    for (int i = 0; i < nodes.getLength(); i++) {
      if (nodes.item(i).getNodeType() != Node.ELEMENT_NODE) {
        continue;
      }

      if (sUrl.length() != 0) {
        sUrl.append("&");
      }

      Element elNext = (Element) nodes.item(i);
      addHttpParams(sUrl, new StringBuffer(), elNext);
    }

    return sUrl.toString();
  }

  /** 
   * Adds HTTP parameters to a URL, recurses to grow the URL.
   *
   * @param sUrl  The URL that is being built
   * @param sCurrentFragment The current context
   * @param el The Element to start at
   */
  protected void addHttpParams(
    StringBuffer sUrl,
    StringBuffer sCurrentFragment,
    Element el) {

    sCurrentFragment.append(el.getTagName());
    String sId = el.getAttribute(AbstractObject.ATTRIB_ID);

    StringBuffer sValue = new StringBuffer();
    Vector elements = new Vector();
    Vector names = new Vector();

    NodeList nodes = el.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
      if (nodes.item(i).getNodeType() == Node.TEXT_NODE) {
        String sText = nodes.item(i).getNodeValue();
        if (sText.trim().length() > 0) {
          sValue.append(sText);
        }
      } else if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element elNext = (Element) nodes.item(i);
        String sName = elNext.getTagName();
        if (sName.equals(Profile.TAG_PROFILE)
          || sName.equals(
            AbstractPropertyInstance.TAG_PROPERTYINSTANCE)) {
          sName = elNext.getAttribute(AbstractObject.ATTRIB_NAME);
        }
        if (names.contains(sName)) {
          if (elNext.getAttribute(AbstractObject.ATTRIB_ID)
            == null) {
            elNext.setAttribute(
              AbstractObject.ATTRIB_ID,
              Integer.toString(i));
          }
        } else {
          names.add(sName);
        }
        elements.add(elNext);
      }
    }

    if (sValue.length() > 0) {
      sUrl.append(sCurrentFragment);
      sUrl.append("=");
      sUrl.append(sValue);
    } else if (elements.size() == 0) {
      sUrl.append(sCurrentFragment);
      sUrl.append("/");
      sUrl.append("@id=");
      sUrl.append(sId);
    } else {
      if (sId != null) {
        sCurrentFragment.append("[@id=");
        sCurrentFragment.append(sId);
        sCurrentFragment.append("]/");
      }
      for (int j = 0; j < elements.size(); j++) {
        addHttpParams(
          sUrl,
          sCurrentFragment,
          (Element) elements.elementAt(j));
      }
    }
  }

  /**
   * Sets the <code>PublishFilter</code> for this state.
   * 
   * @param filter
   * 
   * @see PublishFilter
   */
  public void setPublishFilter(PublishFilter filter) {
    m_publishFilter = filter;
  }

  /**
   * Returns the <code>PublishFilter</code> for this state.
   * 
   * @return
   * 
   * @see PublishFilter
   */
  public PublishFilter getPublishFilter() {
    return m_publishFilter;
  }
  
  /**
   * Returns the headers included in the HTTP request.
   * 
   * @return
   */
  public Map getHeaders() {
    return m_requestHeaders;
  }
  
  /**
   * Returns the remote address associated with the HTTP request.
   * 
   * @return
   */
  public String getRemoteAddress() {
    return m_requestRemoteAddress;
  }
  
  /**
   * Populates this object from the given <code>HttpRequestManager</code>.
   * 
   * @param req_man
   * @throws StateException
   */
  public void populate(HttpRequestManager req_man) throws StateException {
    if(m_bIsPopulated == true) {
      throw new StateException("Already populated!!");
    }
    
    //hold on to request headers
    m_requestHeaders = req_man.getHeaders();
    
    //hold on to remote address
    m_requestRemoteAddress = req_man.getRemoteAddress();
    
    try {
      if (req_man.hasUploadedFiles() == true) {
        if (req_man.isContentBinary() == true) {
          addFileContents(req_man.getUploadedFile());
        } else {
          
          addStringContents(req_man.getContentAsString(true));
        }
      }
      
      if (req_man.containsXMLFeed() == true) {
        addStringContents(req_man.getContentAsString(true));
      }
    } catch (IOException e) {
      throw new StateException("Error accessing file or string content from request",e);
    }

    
    Element root = createElement(TAG_STATE);
    appendChild(root);

    Enumeration attribs = req_man.getParameterNames();
    ArrayList tokanizedName = new ArrayList(89);

    String sParamName = "";
    String sTokElem = "";

    Vector vAttNames = new Vector();
    Vector vAttVals = new Vector();

    String sTempAttName = "";
    String sTempAttVal = "";
    String sTempNodeName = "";

    boolean isAttributeValue = false;

    Element appendNode = null;
    Element currentNode = null;
    Element tempPropVal = null;
    Element tempPropAV = null;
    Element tempPropDesc = null;
    Text textNode = null;

    while (attribs.hasMoreElements()) {
      appendNode = root;
      isAttributeValue = false;

      sParamName = ((String) attribs.nextElement()).trim();

      if (ignoreTags.contains(sParamName) ||
          (sParamName.indexOf("ignore") >= 0)) {
        continue;
      }

      StringTokenizer sTok = new StringTokenizer(sParamName, "/");

      while (sTok.hasMoreTokens()) {
        vAttNames.removeAllElements();
        vAttVals.removeAllElements();

        sTempNodeName = "";
        sTempAttName = "";
        sTempAttVal = "";

        sTokElem = sTok.nextToken().trim();
        sTempNodeName = sTokElem;

                if (sTokElem.indexOf("[") > -1) {
          try {
            sTempNodeName = sTokElem.substring(0,
                               sTokElem.indexOf("["));
            boolean bEqualsSign=true;
            if( sTokElem.indexOf("=")==-1 ) {
              bEqualsSign=false;
              sTempAttName = sTokElem.substring(sTokElem.indexOf("@") + 1,
                              sTokElem.indexOf("_eq_"));
            } else {
              sTempAttName = sTokElem.substring(sTokElem.indexOf("@") + 1,
                              sTokElem.indexOf("="));
            }
            vAttNames.add(sTempAttName);

            if (sTokElem.indexOf("]") == -1) {
              if( bEqualsSign ) {
                sTempAttVal = sTokElem.substring(sTokElem.indexOf(
                                     "=") + 1) +
                      "/";
              } else {
                sTempAttVal = sTokElem.substring(sTokElem.indexOf(
                                     "_eq_") + 4) +
                      "/";
              }
              sTokElem = sTok.nextToken().trim();

              while (sTok.hasMoreTokens() &&
                   (sTokElem.indexOf("]") == -1)) {
                sTempAttVal = sTempAttVal + sTokElem + "/";
                sTokElem = sTok.nextToken().trim();
              }

              sTempAttVal = sTempAttVal +
                      sTokElem.substring(0,
                               sTokElem.indexOf(
                                   "]"));
            } else {
              if( bEqualsSign ) {
                sTempAttVal = sTokElem.substring(sTokElem.indexOf(
                                     "=") + 1,
                                 sTokElem.indexOf(
                                     "]"));
              } else {
                sTempAttVal = sTokElem.substring(sTokElem.indexOf(
                                     "_eq_") + 4,
                                 sTokElem.indexOf(
                                     "]"));
              }
            }

            vAttVals.add(sTempAttVal);
          } catch (Exception e) {
            throw new StateException("token=" + sTokElem);
          }

          
          currentNode = findNode(appendNode, sTempNodeName,
                         vAttNames, vAttVals);
          

          if (currentNode == null) {
            currentNode = createNode(appendNode,
                         sTempNodeName, vAttNames,
                         vAttVals);
          }
        } else if (sTokElem.indexOf("@") > -1) {
          isAttributeValue = true;
        } else {
          
          currentNode = findNode(appendNode, sTokElem, vAttNames,
                         vAttVals);
          

          if (currentNode == null) {
            currentNode = createNode(appendNode, sTokElem,
                         vAttNames, vAttVals);
          }
        }

        appendNode = currentNode;
      }

      if (isAttributeValue) {
        if (req_man.getParameterValues(sParamName).length > 1) {
          String sTagName = currentNode.getNodeName();
          Element tempElem = null;

          for (int i = 1;
             i < req_man.getParameterValues(sParamName).length;
             i++) {
            tempElem = createElement(sTagName);
            tempElem.setAttribute(sTokElem.substring(1),
            req_man.getParameterValues(
                            sParamName)[i]);
            currentNode.getParentNode().appendChild(tempElem);
          }

          ((Element) currentNode).setAttribute(sTokElem.substring(1),
          req_man.getParameterValues(sParamName)[0]);
        } else {
          ((Element) currentNode).setAttribute(sTokElem.substring(1),
          req_man.getParameterValues(sParamName)[0]);
        }

                
      } else {
        if (((Element) currentNode).getTagName()
                     .equalsIgnoreCase(AbstractPropertyInstance.TAG_PROPERTYINSTANCE)) {
          if (req_man.getParameterValues(sParamName).length > 1) {
            for (int i = 0;
               i < req_man.getParameterValues(sParamName).length;
               i++) {
              if (req_man.getParameterValues(sParamName)[i].equals(
                     "XXXX") == false) {
                                

                tempPropAV = createElement(
                           AbstractPropertyInstance.TAG_AVAILABLEOPTIONS);
                tempPropAV.setAttribute("selected", "1");
                tempPropVal = createElement(
                            Value.TAG_VALUE);
                textNode = createTextNode(
                          req_man.getParameterValues(
                               sParamName)[i]);

                tempPropVal.appendChild(textNode);
                tempPropAV.appendChild(tempPropVal);
                currentNode.appendChild(tempPropAV);
              }
            }
          } else {
            if (req_man.getParameterValues(sParamName)[0].equals(
                   "XXXX") == false) {
                            

              tempPropVal = createElement(
                          Profile.TAG_PROPERTY_VALUE);
              textNode = createTextNode(
                    req_man.getParameterValues(
                             sParamName)[0]);
              tempPropVal.appendChild(textNode);
              currentNode.appendChild(tempPropVal);
            }
          }
        } else {

          String sFragment = req_man.getParameterValues(sParamName)[0];

          if ((sFragment != null) && (sFragment.length() > 0)) {
            XMLFragmentParser parser = new XMLFragmentParser(
                               sFragment);
            try {
              parser.parse(currentNode);
            } catch (ParseException e) {
              throw new StateException("Error occured parsing fragment",e);
            }
          } else {
            textNode = createTextNode(sFragment);
            currentNode.appendChild(textNode);
          }

        }
      }
    }

    String sReferer = (String) req_man.getHeaders().get("Referer");
    String sRefererId = "";

    if (sReferer != null) {
      int nStart = sReferer.indexOf("Page/@id=") + 9;
      int nEnd = sReferer.indexOf('&', nStart);

      if (nEnd < 0) {
        sRefererId = sReferer.substring(nStart);
      } else {
        sRefererId = sReferer.substring(nStart, nEnd);
      }
    } else {
      try {
        sRefererId = ConfigSettings
                        .getProperty(PNAME_DEFAULT_PAGE, "1");
      } catch (ConfigException e) {
        throw new StateException("Error occured getting default page number",e);
      }
    }

    Element elReferer = createElement(TAG_REFERER);
    Element elPage = createElement(WebPage.TAG_PAGE);

    elPage.setAttribute(AbstractObject.ATTRIB_ID, sRefererId);
    elReferer.appendChild(elPage);
    getDocumentElement().appendChild(elReferer);
    
    m_bIsPopulated = true;
  }
  

  /*--------------------------------------------------------------------------
   
   Private methods
   -------------------------------------------------------------------------*/
   

  /**
   * initialises the default user details.
   */
  private void setBlankUserDetails() throws StateException {
    m_User = new User(m_dsi);

    m_UserProf = new Profile(m_dsi);

    try {
      m_User = (User)HarmoniseObjectFactory.instantiatePublishableObject(m_dsi,User.class.getName(),"/root/public/guest");
    } catch (HarmoniseFactoryException e) {
      throw new StateException("Error getting default user from Database", e);
    }
  }

  /**
   * Returns an <code>AbstractObject</code> which matches the given element name and
   * is represented in the state.
   * 
   * @param sClassname
   * @return
   * @throws Exception
   */
  private AbstractObject getHarmoniseObject(String sTagName) throws StateException {
    AbstractObject obj = null;
    Element stateElement = findElement(createElement(sTagName));

    if (stateElement != null) {
      try {
        obj =
          HarmoniseObjectFactory.instantiateHarmoniseObject(
            m_dsi,
            stateElement,
            this);
      } catch (HarmoniseFactoryException e) {
        throw new StateException("Error occured getting object from factory",e);
      }
    }

    return obj;
  }
  
  /**
   * Finds node under <code>appendNode</code> which matches <code>sNodeName</code>. Returns
   * <code>null</code> if there's no match.
   * 
   * @param appendNode
   * @param sNodeName
   * @param vAttNames
   * @param vAttVals
   * @return
   */
  private Element findNode(Element appendNode, String sNodeName,
               Vector vAttNames, Vector vAttVals) {
    Element foundNode = null;
    boolean bAttsFound = true;

        

    NodeList nlNodes = appendNode.getChildNodes();

    if (vAttNames.size() > 0) {
      for (int i = 0; i < nlNodes.getLength(); i++) {
        if ((nlNodes.item(i).getNodeType() == Node.ELEMENT_NODE) &&
            nlNodes.item(i).getNodeName().equals(sNodeName)) {
          bAttsFound = true;

          Element tempElem = (Element) nlNodes.item(i);

          for (int j = 0; j < vAttNames.size(); j++) {
            if (!tempElem.getAttribute(
                   (String) vAttNames.elementAt(j))
                   .equals((String) vAttVals.elementAt(j))) {
              bAttsFound = false;
            }
          }

          if (bAttsFound) {
            foundNode = (Element) nlNodes.item(i);
          }
        }
      }
    } else {
      if (nlNodes.getLength() > 0) {
        for (int j = 0; j < nlNodes.getLength(); j++) {
          if ((nlNodes.item(j).getNodeType() == Node.ELEMENT_NODE) &&
              nlNodes.item(j).getNodeName().equals(sNodeName)) {
            foundNode = (Element) nlNodes.item(j);
          }
        }
      }
    }

       

    return foundNode;
  }
  
  /**
   * Creates an <code>Element</code> with the name <code>sNodeName</code> and atttribute
   * values taken from the vectors <code>vAttNames</code> and <code>vAttVals</code>. 
   * 
   * @param appendNode
   * @param sNodeName
   * @param vAttNames
   * @param vAttVals
   * @return
   */
  private Element createNode( Element appendNode,
                 String sNodeName, Vector vAttNames,
                 Vector vAttVals) {
    Element newNode = createElement(sNodeName);

        

    if (vAttNames.size() > 0) {
      for (int i = 0; i < vAttNames.size(); i++) {
        newNode.setAttribute((String) vAttNames.elementAt(i),
                   (String) vAttVals.elementAt(i));

                
      }
    }

    appendNode.appendChild(newNode);

    return newNode;
  }

  /**
   * Sets the session id associated to this object.
   * 
   * @param sessionId the session id
   */
  public void setSessionId(String sessionId) {
    NodeList xnlSession = getElementsByTagName(Session.TAG_SESSION);
    
    Element sessEl = null;
    
    if (xnlSession.getLength() > 0) {
      sessEl = ((Element) xnlSession.item(0));
    } else {
      sessEl = createElement(Session.TAG_SESSION);
      Element rootEl = getDocumentElement();
      
      if(rootEl == null) {
        rootEl = createElement(TAG_STATE);
        appendChild(rootEl);
      }
      
      rootEl.appendChild(sessEl);
    }
    
    sessEl.setAttribute(
        AbstractObject.ATTRIB_ID,sessionId);
    
  }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.