KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openharmonise > rm > publishing > State


1 /*
2  * The contents of this file are subject to the
3  * Mozilla Public License Version 1.1 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
6  *
7  * Software distributed under the License is distributed on an "AS IS"
8  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
9  * See the License for the specific language governing rights and
10  * limitations under the License.
11  *
12  * The Initial Developer of the Original Code is Simulacra Media Ltd.
13  * Portions created by Simulacra Media Ltd are Copyright (C) Simulacra Media Ltd, 2004.
14  *
15  * All Rights Reserved.
16  *
17  * Contributor(s):
18  */

19 package org.openharmonise.rm.publishing;
20
21 import java.io.*;
22 import java.util.*;
23
24 import org.openharmonise.commons.cache.CacheException;
25 import org.openharmonise.commons.dsi.AbstractDataStoreInterface;
26 import org.openharmonise.commons.xml.*;
27 import org.openharmonise.commons.xml.parser.*;
28 import org.openharmonise.rm.DataAccessException;
29 import org.openharmonise.rm.config.*;
30 import org.openharmonise.rm.factory.*;
31 import org.openharmonise.rm.metadata.*;
32 import org.openharmonise.rm.resources.*;
33 import org.openharmonise.rm.resources.metadata.values.Value;
34 import org.openharmonise.rm.resources.publishing.WebPage;
35 import org.openharmonise.rm.resources.users.User;
36 import org.openharmonise.rm.sessions.*;
37 import org.openharmonise.rm.view.servlet.utils.HttpRequestManager;
38 import org.w3c.dom.*;
39
40
41 /**
42  * This class provides an XML representation of a context with the process of
43  * publishing content within the Harmonise framework. Extending <code>XMLDocument</code>, it is
44  * generally a XML representation of the HTTP query string which the <code>Harmonise</code>
45  * servlet receives.
46  *
47  * @author Michael Bell
48  * @version $Revision: 1.2 $
49  *
50  */

51 public class State extends XMLDocument {
52     
53     private Map m_requestHeaders;
54     private String JavaDoc m_requestRemoteAddress = null;
55
56     //config constant prop names
57
protected static final String JavaDoc PNAME_DEFAULT_PAGE = "DEFAULT_PAGE";
58
59     //XML constants
60
public static final String JavaDoc TAG_STATE = "State";
61     public static final String JavaDoc ATTRIB_STATE_ID = "stateId";
62     public static final String JavaDoc TAG_REFERER = "Referer";
63
64     protected User m_User = null;
65     protected Profile m_UserProf = null;
66     protected String JavaDoc m_stringcontent = "";
67     protected File m_filecontent = null;
68     protected PublishFilter m_publishFilter = null;
69     protected AbstractDataStoreInterface m_dsi = null;
70     protected boolean m_bIsPopulated = false;
71     private static HashSet ignoreTags = new HashSet(89);
72     
73     static {
74         ignoreTags.add("show_xml");
75         ignoreTags.add("ignore_submit");
76         ignoreTags.add("ignore_submit.x");
77         ignoreTags.add("ignore_submit.y");
78         ignoreTags.add("ignore_filename");
79         ignoreTags.add("ignore_filepath");
80     }
81
82     /**
83      * Constructs State object from a W3C Document.
84      *
85      * @param document - The document to use
86      */

87     public State(AbstractDataStoreInterface dbintrf) throws StateException {
88         super();
89         m_dsi = dbintrf;
90         setBlankUserDetails();
91     }
92     
93     /**
94      * Constructs State object from a W3C Document.
95      *
96      * @param document - The document to use
97      */

98     public State(AbstractDataStoreInterface dbintrf, User usr) throws StateException {
99         super();
100         m_dsi = dbintrf;
101         m_User = usr;
102     }
103
104     /**
105      * Constructs State object from W3C Document.
106      *
107      * @param document - The document to use
108      */

109     public State(
110         org.w3c.dom.Document JavaDoc document,
111         AbstractDataStoreInterface dbintrf) throws StateException {
112         super(document);
113         m_dsi = dbintrf;
114         setBlankUserDetails();
115     }
116
117     /**
118      * Finds element in state which matches the given element
119      *
120      * @param el Element to match in state
121      * @param state XML representation of state
122      * @exception Exception
123      * @return Matching Element found in state
124      */

125     public Element findElement(Element el) {
126         Element foundEl = null;
127         String JavaDoc sTagName = el.getTagName();
128
129         NodeList nodes = getElementsByTagName(sTagName);
130
131         String JavaDoc sFindName = el.getAttribute(AbstractObject.ATTRIB_NAME);
132         String JavaDoc sFindId = el.getAttribute(AbstractObject.ATTRIB_ID);
133         String JavaDoc sFindStateId = el.getAttribute(ATTRIB_STATE_ID);
134
135         for (int i = 0; i < nodes.getLength(); i++) {
136             Element next = (Element) nodes.item(i);
137             String JavaDoc sNextName = next.getAttribute(AbstractObject.ATTRIB_NAME);
138             String JavaDoc sNextId = next.getAttribute(AbstractObject.ATTRIB_ID);
139             String JavaDoc sNextStateId = next.getAttribute(ATTRIB_STATE_ID);
140
141             boolean bFoundName = false;
142             boolean bFoundId = false;
143             boolean bFoundStateId = false;
144
145             if (!sFindName.equalsIgnoreCase("")
146                 && !sNextName.equalsIgnoreCase("")) {
147                 if (sFindName.equals(sNextName)) {
148                     bFoundName = true;
149                 }
150             } else {
151                 bFoundName = true;
152             }
153
154             if (!sFindId.equalsIgnoreCase("")
155                 && !sNextId.equalsIgnoreCase("")) {
156                 if (sFindId.equals(sNextId)) {
157                     bFoundId = true;
158                 }
159             } else {
160                 bFoundId = true;
161             }
162
163             if (!sFindStateId.equalsIgnoreCase("")
164                 && !sNextStateId.equalsIgnoreCase("")) {
165                 if (sFindStateId.equals(sNextStateId)) {
166                     bFoundStateId = true;
167                 }
168             } else {
169                 bFoundStateId = true;
170             }
171
172             if (bFoundId && bFoundName && bFoundStateId) {
173                 foundEl = next;
174             }
175         }
176
177         return foundEl;
178     }
179
180     /**
181      * Finds elements in state which matches the given element.
182      *
183      * @param el Element to match in state
184      * @param state XML representation of state
185      * @exception Exception
186      * @return Matching Element found in state
187      */

188     public List findElements(Element el) {
189         Element foundEl = null;
190         String JavaDoc sTagName = el.getTagName();
191         List vRetn = new ArrayList();
192
193         NodeList nodes = getElementsByTagName(sTagName);
194
195         String JavaDoc sFindName = el.getAttribute(AbstractObject.ATTRIB_NAME);
196         String JavaDoc sFindId = el.getAttribute(AbstractObject.ATTRIB_ID);
197         String JavaDoc sFindStateId = el.getAttribute(ATTRIB_STATE_ID);
198
199         for (int i = 0; i < nodes.getLength(); i++) {
200             Element next = (Element) nodes.item(i);
201             String JavaDoc sNextName = next.getAttribute(AbstractObject.ATTRIB_NAME);
202             String JavaDoc sNextId = next.getAttribute(AbstractObject.ATTRIB_ID);
203             String JavaDoc sNextStateId = next.getAttribute(ATTRIB_STATE_ID);
204
205             boolean bFoundName = false;
206             boolean bFoundId = false;
207             boolean bFoundStateId = false;
208
209             if (!sFindName.equalsIgnoreCase("")
210                 && !sNextName.equalsIgnoreCase("")) {
211                 if (sFindName.equals(sNextName)) {
212                     bFoundName = true;
213                 }
214             } else {
215                 bFoundName = true;
216             }
217
218             if (!sFindId.equalsIgnoreCase("")
219                 && !sNextId.equalsIgnoreCase("")) {
220                 if (sFindId.equals(sNextId)) {
221                     bFoundId = true;
222                 }
223             } else {
224                 bFoundId = true;
225             }
226
227             if (!sFindStateId.equalsIgnoreCase("")
228                 && !sNextStateId.equalsIgnoreCase("")) {
229                 if (sFindStateId.equals(sNextStateId)) {
230                     bFoundStateId = true;
231                 }
232             } else {
233                 bFoundStateId = true;
234             }
235
236             if (bFoundId && bFoundName && bFoundStateId) {
237                 vRetn.add(next);
238             }
239         }
240
241         return vRetn;
242     }
243
244
245     /**
246      * Resolves a relative path to an absolute one. Only copes
247      * with relative tokens at the beginning of a path.
248      *
249      * @param sClassName The tag name for the class that the path is in the context of
250      * @param sPath The path
251      * @return An absolute version of the path
252      * @throws Exception
253      */

254     public String JavaDoc resolveRelativePath(String JavaDoc sClassName, String JavaDoc sPath)
255         throws StateException {
256         String JavaDoc sReturn = null;
257
258         if (sPath.startsWith(".")) {
259             StringTokenizer tokenizer = new StringTokenizer(sPath, "/");
260             StringBuffer JavaDoc sNewPath = new StringBuffer JavaDoc();
261             AbstractChildObject obj =
262                 (AbstractChildObject) getHarmoniseObject(sClassName);
263
264             // if there is not an object of the required type, see if any
265
// children are in the state
266
if (obj == null) {
267                 Element el = createElement(sClassName);
268                 AbstractObject ohObj = null;
269                 try {
270                     ohObj = HarmoniseObjectFactory.instantiateHarmoniseObject(m_dsi, el, this);
271                 } catch (HarmoniseFactoryException e) {
272                     throw new StateException("Error getting object from factory",e);
273                 }
274
275                 if (ohObj instanceof AbstractParentObject) {
276                     AbstractParentObject parent = (AbstractParentObject) ohObj;
277                     
278                     List childClassNames = parent.getChildClassNames();
279                     
280                     Iterator iter = childClassNames.iterator();
281                     
282                     boolean bFound = false;
283                     
284                     while(iter.hasNext() == true && bFound == false) {
285                         sClassName = (String JavaDoc) iter.next();
286
287                         if (sClassName.indexOf('.') >= 0) {
288                             sClassName =
289                                 sClassName.substring(
290                                     sClassName.lastIndexOf('.') + 1);
291                         }
292                         
293                         obj = (AbstractChildObject) getHarmoniseObject(sClassName);
294                         
295                         bFound = (obj != null);
296                     }
297     
298                 } else {
299                     // must be a child object
300
sClassName =
301                         ((AbstractChildObject) ohObj)
302                             .getParentObjectClassName();
303
304                     if (sClassName.indexOf('.') >= 0) {
305                         sClassName =
306                             sClassName.substring(
307                                 sClassName.lastIndexOf('.') + 1);
308                     }
309
310                     obj = (AbstractChildObject) getHarmoniseObject(sClassName);
311                 }
312             }
313
314             if (obj != null) {
315                 String JavaDoc sNext = null;
316
317                 while (tokenizer.hasMoreTokens()) {
318                     sNext = tokenizer.nextToken();
319
320                     try {
321                         if (sNext.equals("..")) {
322                             if (sNewPath.length() > 0) {
323                                 sNewPath.append("/");
324                             }
325                         
326                             obj = (AbstractChildObject) obj.getRealParent();
327                             sNewPath = new StringBuffer JavaDoc(obj.getPath());
328                             sNewPath.append("/");
329                             sNewPath.append(obj.getName());
330                         } else if (sNext.equals(".")) {
331                             if (sNewPath.length() > 0) {
332                                 sNewPath.append("/");
333                             }
334                         
335                             sNewPath.append(obj.getPath());
336                             sNewPath.append("/");
337                             sNewPath.append(obj.getName());
338                         } else {
339                             if (sNewPath.length() > 0) {
340                                 sNewPath.append("/");
341                             }
342                         
343                             sNewPath.append(sNext);
344                         
345                             while (tokenizer.hasMoreTokens()) {
346                                 sNewPath.append("/");
347                                 sNext = tokenizer.nextToken();
348                                 sNewPath.append(sNext);
349                             }
350                         }
351                     } catch (DataAccessException e) {
352                         throw new StateException("Error occured accessing object data",e);
353                     }
354                 }
355
356                 sReturn = sNewPath.toString();
357             }
358         } else {
359             sReturn = sPath;
360         }
361
362         return sReturn;
363     }
364
365     /**
366      * Adds the file as extra contents to this representation of the state.
367      *
368      * @param fileContent
369      */

370     public void addFileContents(File fileContent) {
371         this.m_filecontent = fileContent;
372     }
373
374     /**
375      * Adds <code>sContent</code> as extra content to this state.
376      *
377      * @param stringContent
378      */

379     public void addStringContents(String JavaDoc sContent) {
380         this.m_stringcontent = sContent;
381     }
382
383     /**
384      * Returns the <code>File</code> contents of this state.
385      *
386      * @return
387      */

388     public File getFile() {
389         return m_filecontent;
390     }
391
392     /**
393      * Returns the <code>String</code> contents of this state.
394      *
395      * @return
396      */

397     public String JavaDoc getStringContent() {
398         return m_stringcontent;
399     }
400
401     /**
402      * Finds logged in User from Session in the state and returns their Profile.
403      *
404      * @param state XML state representation
405      * @exception Exception
406      * @return Profile of current logged in user
407      */

408     public Profile getLoggedInUserProfile() {
409
410         return m_UserProf;
411     }
412
413     /**
414      * Finds and returns the logged-in User found from Session in the state.
415      *
416      * @param state XML representation of the state
417      * @exception Exception
418      * @return User found in the state
419      */

420     public User getLoggedInUser() {
421
422         return m_User;
423     }
424     
425     /**
426      * Adds a user to this state representation.
427      *
428      * @param usr
429      */

430     public void setLoggedInUser(User usr) {
431         m_User = usr;
432     }
433
434     /**
435      * Returns the current Webpage id found in the state.
436      *
437      * @param state XML representation of the state
438      * @exception Exception
439      * @return Current Webpage id
440      */

441     public int getCurrentPageId() throws Exception JavaDoc {
442         Element pageEl =
443             XMLUtils.getFirstNamedChild(getDocumentElement(), WebPage.TAG_PAGE);
444
445         int nId = -1;
446
447         if (pageEl != null) {
448             nId =
449                 Integer.parseInt(pageEl.getAttribute(AbstractObject.ATTRIB_ID));
450         }
451
452         return nId;
453     }
454
455
456     /**
457      * Returns the page id from state.
458      *
459      * @return
460      */

461     public int getPageId() {
462         NodeList xnlPage = getElementsByTagName(WebPage.TAG_PAGE);
463         int nId = -1;
464
465         if (xnlPage.getLength() > 0) {
466             nId =
467                 Integer.parseInt(
468                     ((Element) xnlPage.item(0)).getAttribute(
469                         AbstractObject.ATTRIB_ID));
470         }
471
472         return nId;
473     }
474
475     /**
476      * Returns the session id from state.
477      *
478      * @return
479      */

480     public String JavaDoc getSessionId() {
481         NodeList xnlSession = getElementsByTagName(Session.TAG_SESSION);
482         String JavaDoc sSessionId = null;
483
484         if (xnlSession.getLength() > 0) {
485             sSessionId =
486                 ((Element) xnlSession.item(0)).getAttribute(
487                     AbstractObject.ATTRIB_ID);
488         }
489
490         return sSessionId;
491     }
492     
493     /**
494      * Returns the session associated with this state.
495      *
496      * @return
497      * @throws DataAccessException
498      */

499     public Session getSession() throws DataAccessException {
500         Session session = null;
501         try {
502             String JavaDoc sSessionId = getSessionId();
503             if(sSessionId != null) {
504                 session = SessionCache.getInstance(m_dsi).getSession(sSessionId);
505             }
506         } catch (CacheException e) {
507             throw new DataAccessException("Error getting session from cache",e);
508         }
509         
510         return session;
511     }
512
513     /**
514      * Returns a String that is this state converted to a list of HTTP params.
515      *
516      * @return The parameters
517      */

518     public String JavaDoc encodeAsHttpParams() {
519         NodeList nodes = getDocumentElement().getChildNodes();
520         StringBuffer JavaDoc sUrl = new StringBuffer JavaDoc();
521
522         for (int i = 0; i < nodes.getLength(); i++) {
523             if (nodes.item(i).getNodeType() != Node.ELEMENT_NODE) {
524                 continue;
525             }
526
527             if (sUrl.length() != 0) {
528                 sUrl.append("&");
529             }
530
531             Element elNext = (Element) nodes.item(i);
532             addHttpParams(sUrl, new StringBuffer JavaDoc(), elNext);
533         }
534
535         return sUrl.toString();
536     }
537
538     /**
539      * Adds HTTP parameters to a URL, recurses to grow the URL.
540      *
541      * @param sUrl The URL that is being built
542      * @param sCurrentFragment The current context
543      * @param el The Element to start at
544      */

545     protected void addHttpParams(
546         StringBuffer JavaDoc sUrl,
547         StringBuffer JavaDoc sCurrentFragment,
548         Element el) {
549
550         sCurrentFragment.append(el.getTagName());
551         String JavaDoc sId = el.getAttribute(AbstractObject.ATTRIB_ID);
552
553         StringBuffer JavaDoc sValue = new StringBuffer JavaDoc();
554         Vector elements = new Vector();
555         Vector names = new Vector();
556
557         NodeList nodes = el.getChildNodes();
558         for (int i = 0; i < nodes.getLength(); i++) {
559             if (nodes.item(i).getNodeType() == Node.TEXT_NODE) {
560                 String JavaDoc sText = nodes.item(i).getNodeValue();
561                 if (sText.trim().length() > 0) {
562                     sValue.append(sText);
563                 }
564             } else if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
565                 Element elNext = (Element) nodes.item(i);
566                 String JavaDoc sName = elNext.getTagName();
567                 if (sName.equals(Profile.TAG_PROFILE)
568                     || sName.equals(
569                         AbstractPropertyInstance.TAG_PROPERTYINSTANCE)) {
570                     sName = elNext.getAttribute(AbstractObject.ATTRIB_NAME);
571                 }
572                 if (names.contains(sName)) {
573                     if (elNext.getAttribute(AbstractObject.ATTRIB_ID)
574                         == null) {
575                         elNext.setAttribute(
576                             AbstractObject.ATTRIB_ID,
577                             Integer.toString(i));
578                     }
579                 } else {
580                     names.add(sName);
581                 }
582                 elements.add(elNext);
583             }
584         }
585
586         if (sValue.length() > 0) {
587             sUrl.append(sCurrentFragment);
588             sUrl.append("=");
589             sUrl.append(sValue);
590         } else if (elements.size() == 0) {
591             sUrl.append(sCurrentFragment);
592             sUrl.append("/");
593             sUrl.append("@id=");
594             sUrl.append(sId);
595         } else {
596             if (sId != null) {
597                 sCurrentFragment.append("[@id=");
598                 sCurrentFragment.append(sId);
599                 sCurrentFragment.append("]/");
600             }
601             for (int j = 0; j < elements.size(); j++) {
602                 addHttpParams(
603                     sUrl,
604                     sCurrentFragment,
605                     (Element) elements.elementAt(j));
606             }
607         }
608     }
609
610     /**
611      * Sets the <code>PublishFilter</code> for this state.
612      *
613      * @param filter
614      *
615      * @see PublishFilter
616      */

617     public void setPublishFilter(PublishFilter filter) {
618         m_publishFilter = filter;
619     }
620
621     /**
622      * Returns the <code>PublishFilter</code> for this state.
623      *
624      * @return
625      *
626      * @see PublishFilter
627      */

628     public PublishFilter getPublishFilter() {
629         return m_publishFilter;
630     }
631     
632     /**
633      * Returns the headers included in the HTTP request.
634      *
635      * @return
636      */

637     public Map getHeaders() {
638         return m_requestHeaders;
639     }
640     
641     /**
642      * Returns the remote address associated with the HTTP request.
643      *
644      * @return
645      */

646     public String JavaDoc getRemoteAddress() {
647         return m_requestRemoteAddress;
648     }
649     
650     /**
651      * Populates this object from the given <code>HttpRequestManager</code>.
652      *
653      * @param req_man
654      * @throws StateException
655      */

656     public void populate(HttpRequestManager req_man) throws StateException {
657         if(m_bIsPopulated == true) {
658             throw new StateException("Already populated!!");
659         }
660         
661         //hold on to request headers
662
m_requestHeaders = req_man.getHeaders();
663         
664         //hold on to remote address
665
m_requestRemoteAddress = req_man.getRemoteAddress();
666         
667         try {
668             if (req_man.hasUploadedFiles() == true) {
669                 if (req_man.isContentBinary() == true) {
670                     addFileContents(req_man.getUploadedFile());
671                 } else {
672                     
673                     addStringContents(req_man.getContentAsString(true));
674                 }
675             }
676             
677             if (req_man.containsXMLFeed() == true) {
678                 addStringContents(req_man.getContentAsString(true));
679             }
680         } catch (IOException e) {
681             throw new StateException("Error accessing file or string content from request",e);
682         }
683
684         
685         Element root = createElement(TAG_STATE);
686         appendChild(root);
687
688         Enumeration attribs = req_man.getParameterNames();
689         ArrayList tokanizedName = new ArrayList(89);
690
691         String JavaDoc sParamName = "";
692         String JavaDoc sTokElem = "";
693
694         Vector vAttNames = new Vector();
695         Vector vAttVals = new Vector();
696
697         String JavaDoc sTempAttName = "";
698         String JavaDoc sTempAttVal = "";
699         String JavaDoc sTempNodeName = "";
700
701         boolean isAttributeValue = false;
702
703         Element appendNode = null;
704         Element currentNode = null;
705         Element tempPropVal = null;
706         Element tempPropAV = null;
707         Element tempPropDesc = null;
708         Text textNode = null;
709
710         while (attribs.hasMoreElements()) {
711             appendNode = root;
712             isAttributeValue = false;
713
714             sParamName = ((String JavaDoc) attribs.nextElement()).trim();
715
716             if (ignoreTags.contains(sParamName) ||
717                     (sParamName.indexOf("ignore") >= 0)) {
718                 continue;
719             }
720
721             StringTokenizer sTok = new StringTokenizer(sParamName, "/");
722
723             while (sTok.hasMoreTokens()) {
724                 vAttNames.removeAllElements();
725                 vAttVals.removeAllElements();
726
727                 sTempNodeName = "";
728                 sTempAttName = "";
729                 sTempAttVal = "";
730
731                 sTokElem = sTok.nextToken().trim();
732                 sTempNodeName = sTokElem;
733
734                 if (sTokElem.indexOf("[") > -1) {
735                     try {
736                         sTempNodeName = sTokElem.substring(0,
737                                                            sTokElem.indexOf("["));
738                         boolean bEqualsSign=true;
739                         if( sTokElem.indexOf("=")==-1 ) {
740                           bEqualsSign=false;
741                           sTempAttName = sTokElem.substring(sTokElem.indexOf("@") + 1,
742                                                             sTokElem.indexOf("_eq_"));
743                         } else {
744                           sTempAttName = sTokElem.substring(sTokElem.indexOf("@") + 1,
745                                                             sTokElem.indexOf("="));
746                         }
747                         vAttNames.add(sTempAttName);
748
749                         if (sTokElem.indexOf("]") == -1) {
750                             if( bEqualsSign ) {
751                               sTempAttVal = sTokElem.substring(sTokElem.indexOf(
752                                                                        "=") + 1) +
753                                           "/";
754                             } else {
755                               sTempAttVal = sTokElem.substring(sTokElem.indexOf(
756                                                                        "_eq_") + 4) +
757                                           "/";
758                             }
759                             sTokElem = sTok.nextToken().trim();
760
761                             while (sTok.hasMoreTokens() &&
762                                    (sTokElem.indexOf("]") == -1)) {
763                                 sTempAttVal = sTempAttVal + sTokElem + "/";
764                                 sTokElem = sTok.nextToken().trim();
765                             }
766
767                             sTempAttVal = sTempAttVal +
768                                           sTokElem.substring(0,
769                                                              sTokElem.indexOf(
770                                                                      "]"));
771                         } else {
772                             if( bEqualsSign ) {
773                               sTempAttVal = sTokElem.substring(sTokElem.indexOf(
774                                                                        "=") + 1,
775                                                                sTokElem.indexOf(
776                                                                        "]"));
777                             } else {
778                               sTempAttVal = sTokElem.substring(sTokElem.indexOf(
779                                                                        "_eq_") + 4,
780                                                                sTokElem.indexOf(
781                                                                        "]"));
782                             }
783                         }
784
785                         vAttVals.add(sTempAttVal);
786                     } catch (Exception JavaDoc e) {
787                         throw new StateException("token=" + sTokElem);
788                     }
789
790                     
791                     currentNode = findNode(appendNode, sTempNodeName,
792                                                vAttNames, vAttVals);
793                     
794
795                     if (currentNode == null) {
796                         currentNode = createNode(appendNode,
797                                                  sTempNodeName, vAttNames,
798                                                  vAttVals);
799                     }
800                 } else if (sTokElem.indexOf("@") > -1) {
801                     isAttributeValue = true;
802                 } else {
803                     
804                     currentNode = findNode(appendNode, sTokElem, vAttNames,
805                                                vAttVals);
806                     
807
808                     if (currentNode == null) {
809                         currentNode = createNode(appendNode, sTokElem,
810                                                  vAttNames, vAttVals);
811                     }
812                 }
813
814                 appendNode = currentNode;
815             }
816
817             if (isAttributeValue) {
818                 if (req_man.getParameterValues(sParamName).length > 1) {
819                     String JavaDoc sTagName = currentNode.getNodeName();
820                     Element tempElem = null;
821
822                     for (int i = 1;
823                          i < req_man.getParameterValues(sParamName).length;
824                          i++) {
825                         tempElem = createElement(sTagName);
826                         tempElem.setAttribute(sTokElem.substring(1),
827                         req_man.getParameterValues(
828                                                       sParamName)[i]);
829                         currentNode.getParentNode().appendChild(tempElem);
830                     }
831
832                     ((Element) currentNode).setAttribute(sTokElem.substring(1),
833                     req_man.getParameterValues(sParamName)[0]);
834                 } else {
835                     ((Element) currentNode).setAttribute(sTokElem.substring(1),
836                     req_man.getParameterValues(sParamName)[0]);
837                 }
838
839                 
840             } else {
841                 if (((Element) currentNode).getTagName()
842                                          .equalsIgnoreCase(AbstractPropertyInstance.TAG_PROPERTYINSTANCE)) {
843                     if (req_man.getParameterValues(sParamName).length > 1) {
844                         for (int i = 0;
845                              i < req_man.getParameterValues(sParamName).length;
846                              i++) {
847                             if (req_man.getParameterValues(sParamName)[i].equals(
848                                          "XXXX") == false) {
849                                 
850
851                                 tempPropAV = createElement(
852                                                      AbstractPropertyInstance.TAG_AVAILABLEOPTIONS);
853                                 tempPropAV.setAttribute("selected", "1");
854                                 tempPropVal = createElement(
855                                                       Value.TAG_VALUE);
856                                 textNode = createTextNode(
857                                                     req_man.getParameterValues(
858                                                            sParamName)[i]);
859
860                                 tempPropVal.appendChild(textNode);
861                                 tempPropAV.appendChild(tempPropVal);
862                                 currentNode.appendChild(tempPropAV);
863                             }
864                         }
865                     } else {
866                         if (req_man.getParameterValues(sParamName)[0].equals(
867                                      "XXXX") == false) {
868                             
869
870                             tempPropVal = createElement(
871                                                   Profile.TAG_PROPERTY_VALUE);
872                             textNode = createTextNode(
873                                         req_man.getParameterValues(
874                                                        sParamName)[0]);
875                             tempPropVal.appendChild(textNode);
876                             currentNode.appendChild(tempPropVal);
877                         }
878                     }
879                 } else {
880
881                     String JavaDoc sFragment = req_man.getParameterValues(sParamName)[0];
882
883                     if ((sFragment != null) && (sFragment.length() > 0)) {
884                         XMLFragmentParser parser = new XMLFragmentParser(
885                                                            sFragment);
886                         try {
887                             parser.parse(currentNode);
888                         } catch (ParseException e) {
889                             throw new StateException("Error occured parsing fragment",e);
890                         }
891                     } else {
892                         textNode = createTextNode(sFragment);
893                         currentNode.appendChild(textNode);
894                     }
895
896                 }
897             }
898         }
899
900         String JavaDoc sReferer = (String JavaDoc) req_man.getHeaders().get("Referer");
901         String JavaDoc sRefererId = "";
902
903         if (sReferer != null) {
904             int nStart = sReferer.indexOf("Page/@id=") + 9;
905             int nEnd = sReferer.indexOf('&', nStart);
906
907             if (nEnd < 0) {
908                 sRefererId = sReferer.substring(nStart);
909             } else {
910                 sRefererId = sReferer.substring(nStart, nEnd);
911             }
912         } else {
913             try {
914                 sRefererId = ConfigSettings
915                                               .getProperty(PNAME_DEFAULT_PAGE, "1");
916             } catch (ConfigException e) {
917                 throw new StateException("Error occured getting default page number",e);
918             }
919         }
920
921         Element elReferer = createElement(TAG_REFERER);
922         Element elPage = createElement(WebPage.TAG_PAGE);
923
924         elPage.setAttribute(AbstractObject.ATTRIB_ID, sRefererId);
925         elReferer.appendChild(elPage);
926         getDocumentElement().appendChild(elReferer);
927         
928         m_bIsPopulated = true;
929     }
930     
931
932     /*--------------------------------------------------------------------------
933      
934      Private methods
935      -------------------------------------------------------------------------*/

936      
937
938     /**
939      * initialises the default user details.
940      */

941     private void setBlankUserDetails() throws StateException {
942         m_User = new User(m_dsi);
943
944         m_UserProf = new Profile(m_dsi);
945
946         try {
947             m_User = (User)HarmoniseObjectFactory.instantiatePublishableObject(m_dsi,User.class.getName(),"/root/public/guest");
948         } catch (HarmoniseFactoryException e) {
949             throw new StateException("Error getting default user from Database", e);
950         }
951     }
952
953     /**
954      * Returns an <code>AbstractObject</code> which matches the given element name and
955      * is represented in the state.
956      *
957      * @param sClassname
958      * @return
959      * @throws Exception
960      */

961     private AbstractObject getHarmoniseObject(String JavaDoc sTagName) throws StateException {
962         AbstractObject obj = null;
963         Element stateElement = findElement(createElement(sTagName));
964
965         if (stateElement != null) {
966             try {
967                 obj =
968                     HarmoniseObjectFactory.instantiateHarmoniseObject(
969                         m_dsi,
970                         stateElement,
971                         this);
972             } catch (HarmoniseFactoryException e) {
973                 throw new StateException("Error occured getting object from factory",e);
974             }
975         }
976
977         return obj;
978     }
979     
980     /**
981      * Finds node under <code>appendNode</code> which matches <code>sNodeName</code>. Returns
982      * <code>null</code> if there's no match.
983      *
984      * @param appendNode
985      * @param sNodeName
986      * @param vAttNames
987      * @param vAttVals
988      * @return
989      */

990     private Element findNode(Element appendNode, String JavaDoc sNodeName,
991                              Vector vAttNames, Vector vAttVals) {
992         Element foundNode = null;
993         boolean bAttsFound = true;
994
995         
996
997         NodeList nlNodes = appendNode.getChildNodes();
998
999         if (vAttNames.size() > 0) {
1000            for (int i = 0; i < nlNodes.getLength(); i++) {
1001                if ((nlNodes.item(i).getNodeType() == Node.ELEMENT_NODE) &&
1002                        nlNodes.item(i).getNodeName().equals(sNodeName)) {
1003                    bAttsFound = true;
1004
1005                    Element tempElem = (Element) nlNodes.item(i);
1006
1007                    for (int j = 0; j < vAttNames.size(); j++) {
1008                        if (!tempElem.getAttribute(
1009                                     (String JavaDoc) vAttNames.elementAt(j))
1010                                     .equals((String JavaDoc) vAttVals.elementAt(j))) {
1011                            bAttsFound = false;
1012                        }
1013                    }
1014
1015                    if (bAttsFound) {
1016                        foundNode = (Element) nlNodes.item(i);
1017                    }
1018                }
1019            }
1020        } else {
1021            if (nlNodes.getLength() > 0) {
1022                for (int j = 0; j < nlNodes.getLength(); j++) {
1023                    if ((nlNodes.item(j).getNodeType() == Node.ELEMENT_NODE) &&
1024                            nlNodes.item(j).getNodeName().equals(sNodeName)) {
1025                        foundNode = (Element) nlNodes.item(j);
1026                    }
1027                }
1028            }
1029        }
1030
1031       
1032
1033        return foundNode;
1034    }
1035    
1036    /**
1037     * Creates an <code>Element</code> with the name <code>sNodeName</code> and atttribute
1038     * values taken from the vectors <code>vAttNames</code> and <code>vAttVals</code>.
1039     *
1040     * @param appendNode
1041     * @param sNodeName
1042     * @param vAttNames
1043     * @param vAttVals
1044     * @return
1045     */

1046    private Element createNode( Element appendNode,
1047                               String JavaDoc sNodeName, Vector vAttNames,
1048                               Vector vAttVals) {
1049        Element newNode = createElement(sNodeName);
1050
1051        
1052
1053        if (vAttNames.size() > 0) {
1054            for (int i = 0; i < vAttNames.size(); i++) {
1055                newNode.setAttribute((String JavaDoc) vAttNames.elementAt(i),
1056                                     (String JavaDoc) vAttVals.elementAt(i));
1057
1058                
1059            }
1060        }
1061
1062        appendNode.appendChild(newNode);
1063
1064        return newNode;
1065    }
1066
1067    /**
1068     * Sets the session id associated to this object.
1069     *
1070     * @param sessionId the session id
1071     */

1072    public void setSessionId(String JavaDoc sessionId) {
1073        NodeList xnlSession = getElementsByTagName(Session.TAG_SESSION);
1074        
1075        Element sessEl = null;
1076        
1077        if (xnlSession.getLength() > 0) {
1078            sessEl = ((Element) xnlSession.item(0));
1079        } else {
1080            sessEl = createElement(Session.TAG_SESSION);
1081            Element rootEl = getDocumentElement();
1082            
1083            if(rootEl == null) {
1084                rootEl = createElement(TAG_STATE);
1085                appendChild(rootEl);
1086            }
1087            
1088            rootEl.appendChild(sessEl);
1089        }
1090        
1091        sessEl.setAttribute(
1092                AbstractObject.ATTRIB_ID,sessionId);
1093        
1094    }
1095}
1096
Popular Tags