View Javadoc

1   package org.astrogrid.portal.registry;
2   
3   import org.apache.avalon.framework.parameters.Parameters;
4   import org.apache.cocoon.acting.AbstractAction;
5   import org.apache.cocoon.environment.Request;
6   import org.apache.cocoon.environment.Session;
7   import org.apache.cocoon.environment.Redirector;
8   import org.apache.cocoon.environment.SourceResolver;
9   import org.apache.cocoon.environment.ObjectModelHelper;
10  import java.util.Map;
11  import java.util.HashMap;
12  import java.util.ArrayList;
13  import java.util.LinkedHashMap;
14  import java.util.TreeMap;
15  import java.util.Set;
16  import java.util.Iterator;
17  import java.io.File;
18  import java.io.IOException;
19  import org.astrogrid.registry.client.admin.RegistryAdminDocumentHelper;
20  import org.w3c.dom.Document;
21  import org.w3c.dom.NodeList;
22  import org.w3c.dom.Node;
23  import org.w3c.dom.Element;
24  import org.w3c.dom.DocumentFragment;
25  import javax.xml.parsers.DocumentBuilderFactory;
26  import javax.xml.parsers.DocumentBuilder;
27  import javax.xml.parsers.ParserConfigurationException;
28  import org.xml.sax.SAXException;
29  import org.apache.axis.utils.XMLUtils;
30  import org.astrogrid.registry.client.RegistryDelegateFactory;
31  import org.astrogrid.registry.client.query.RegistryService;
32  
33  import org.astrogrid.registry.NoResourcesFoundException;
34  import org.astrogrid.registry.RegistryException;
35  
36  import org.astrogrid.config.Config;
37  
38  import org.astrogrid.util.DomHelper;
39  import org.astrogrid.registry.common.WSDLBasicInformation;
40  import org.astrogrid.store.Ivorn;
41  
42  import org.exolab.castor.xml.*;
43  import java.io.InputStream;
44  
45  
46  
47  /***
48   *
49   *
50   */
51  public class RegistryQueryAction extends AbstractAction
52  {
53     /***
54      * Switch for our debug statements.
55      *
56      */
57     public static boolean DEBUG_FLAG = true;
58     
59     private static final String PARAM_MAIN_ELEMENT = "mainelement";   
60     
61     /***
62      * Cocoon param for the user param in the session.
63      *
64      */
65     private static final String PARAM_ACTION = "action";
66     
67     private static final String PARAM_CRITERIA_NUMBER = "criteria_number";      
68     
69     private static final Integer DEFAULT_CRITERIA_NUMBER = new Integer(1);
70     
71     private static final String QUERY_ACTION = "selectquery";
72  
73     private static final String ADD_CRITERIA_ACTION = "addcriteria";   
74     
75     private static final String SEARCH_REGISTRY_NAME = "searchregistryname";
76        
77     private static final String PUBLISH_REGISTRY_NAME = "publishregistryname";
78     
79     private static final String ERROR_MESSAGE = "errormessage";
80     
81     public static Config conf = null;   
82     
83     private static final String RESOURCE_XML_URL_TEMPLATE_PROPERTY =
84                                                 "QueryXMLPaths.xml";   
85    
86     static {
87        if(conf == null) {
88           conf = org.astrogrid.config.SimpleConfig.getSingleton();
89        }      
90     }
91   
92  
93     /***
94      * Action page to do a query.
95      *
96      */
97     public Map act(
98        Redirector redirector, 
99        SourceResolver resolver, 
100       Map objectModel, 
101       String source, 
102       Parameters params)
103       {
104       
105       //
106       // Get our current request and session.
107       Request request = ObjectModelHelper.getRequest(objectModel);
108       Session session = request.getSession();
109       String errorMessage = null;
110       int crit_number = 0;
111       Document registryDocument = null;
112       LinkedHashMap compareTypeList = new LinkedHashMap();            
113       ArrayList joinTypes = new ArrayList();
114       ArrayList resultXML = null;      
115       String result = null;
116             
117       String action = (String)request.getParameter(PARAM_ACTION);
118       String mainElem = request.getParameter(PARAM_MAIN_ELEMENT);
119       String method = "Registry Query Action";               
120       
121       if(DEBUG_FLAG) {
122          printDebug(method, "the action is = " + action);      
123          printDebug(method, "the mainElem = " + mainElem);
124       }            
125 
126          //Create the Document object and throw it to createMap
127          try {
128            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
129            //dbf.setNamespaceAware(true);
130            
131            DocumentBuilder regBuilder = dbf.newDocumentBuilder();
132            registryDocument = getDocumentTemplate();           
133          } catch (ParserConfigurationException e) {
134            e.printStackTrace();
135          }
136          // now get the unique last text nodes of the map.
137          // should be able to do an indexOf and see if their is an "attr"
138          // which you put in "@" in front of the string.
139          RegistryAdminDocumentHelper rad = new RegistryAdminDocumentHelper();
140          Map mp = rad.createMap(registryDocument);
141          Set st = mp.keySet();
142          Iterator iter = st.iterator();
143          //TreeMap selectItems = new TreeMap();
144          //Go through the Map and put it in a TreeMap which is
145          //an alphabetical list.
146          //And cut off everything but the last node which is the text or
147          //attribute node.
148          /*
149          while(iter.hasNext()) {
150             String key = (String)iter.next();
151             String []split = key.split("///");
152             
153             key = split[(split.length-1)];
154             if(Character.isDigit(key.charAt(key.length()-1)))
155                key = key.substring(0,key.length()-1);
156             if(Character.isDigit(key.charAt(key.length()-1)))
157                key = key.substring(0,key.length()-1);
158             if(Character.isDigit(key.charAt(key.length()-1)))
159                key = key.substring(0,key.length()-1);
160             
161             if("attr".indexOf(key) != -1) {
162                selectItems.put("@" + key,null);
163             }else {            
164                selectItems.put(key,null);
165             }//else
166          }//while
167          */
168          //request.setAttribute("selectitems",selectItems);
169          request.setAttribute("selectitems",mp);
170          
171          
172          if(DEBUG_FLAG) {
173             printDebug(method, "selectitems size = " + mp.size());
174          }            
175    
176          
177          //Create a Linked Hashmap of all the possible types.
178          //LinkedHashmap preservest the order of the list.
179          compareTypeList.put("Contains","CONTAINS");
180          compareTypeList.put("equal","EQ");
181          compareTypeList.put("not equal","NE");
182          compareTypeList.put("Less Than","LT");
183          compareTypeList.put("Greater Than","GT");
184          compareTypeList.put("After (for dates)","AFTER");
185          request.setAttribute("Comparisons",compareTypeList);
186    
187          if(DEBUG_FLAG) {
188             printDebug( method, "comparetypelist size = " +
189                                 compareTypeList.size() );
190          }            
191    
192          //Put in the join types.
193 
194          joinTypes.add("AND");
195          joinTypes.add("OR");
196          request.setAttribute("JoinTypes",joinTypes);
197    
198 
199          //What is the current criteria number count.
200          String crit_number_str = request.getParameter(PARAM_CRITERIA_NUMBER);
201          if(crit_number_str != null && crit_number_str.length() > 0) {
202             crit_number = Integer.parseInt(crit_number_str);
203          }      
204             
205          if(crit_number <= 0) {
206             crit_number = 1;      
207          }
208          //What is the action if any.
209          if(ADD_CRITERIA_ACTION.equals(action)) {
210             //user wants to add more criteria's.
211             crit_number++;
212          } else if(QUERY_ACTION.equals(action)) {
213             //Need to query.  So lets build up the XML for a query.
214             String selItem = null;
215             String selItemOperation = null;
216             String selItemValue = null;
217             String selJoinType = null;
218             String query = "<query><selectionSequence>" +
219             "<selection item='searchElements' itemOp='EQ' value='Resource'/>";
220             query += "<selectionOp op='$and$'/>";
221             selItem = request.getParameter("selectitem0");
222             selItemOperation = request.getParameter("selectitemop0");
223             selItemValue = request.getParameter("selectitemvalue0");
224                
225             query += "<selection item='" + selItem + "' itemOp='" +
226                        selItemOperation + "' value='" + selItemValue + "'/>";
227             for(int i = 1;i < crit_number;i++) {
228                selJoinType = request.getParameter(("selectjointype" + i));
229                query += "<selectionOp op='" + selJoinType + "'/>";
230    
231                selItem = request.getParameter("selectitem" + i);
232                selItemOperation = request.getParameter("selectitemop" + i);
233                selItemValue = request.getParameter("selectitemvalue" + i);
234                
235                query += "<selection item='" + selItem + "' itemOp='" +
236                           selItemOperation + "' value='" + selItemValue + "'/>";
237             }
238             query += "</selectionSequence></query>";
239             if ( DEBUG_FLAG) printDebug( method, "Query = " + query);
240             try {
241                //Now lets query.
242                String url = null;               
243                RegistryService rs = RegistryDelegateFactory.createQuery();
244                if (DEBUG_FLAG) printDebug( method, "Service = " + rs);
245 //               VODescription vo = rs.submitQueryString(query);
246 //               if (DEBUG_FLAG) printDebug( method, "VO Description = " + vo);
247                //Document doc = rs.submitQuery( query );
248                Document doc = rs.submitQuery( query );
249                if ( DEBUG_FLAG) printDebug( method, "doc = " + doc );
250                 //                     XMLUtils.DocumentToString(doc) );
251                //if ( doc == null )
252                    //throw new NoResourcesFoundException("Null Query");
253 //               errorMessage = getResultMessage(doc);
254                   //create the results and put it in the request.
255                   if (DEBUG_FLAG)
256                      printDebug(method, "the Elementtostring in queryaction = " +
257                            XMLUtils.ElementToString(doc.getDocumentElement()) );
258                   ArrayList resultNodes = new ArrayList();
259                   NodeList nl = doc.getElementsByTagNameNS("*","Resource");
260                   for(int i = 0;i < nl.getLength();i++) {
261                       resultNodes.add(nl.item(i));
262                   }
263                   request.setAttribute("resultNodes",resultNodes);
264                   if(nl.getLength() <= 0) {
265                       errorMessage = "Your query produced no results";
266                   }
267                   
268                   //Here are the managed authorities.
269                   //Which determine which AuthorityID
270                   //the registry owns and hence can do an update for.
271                   /*
272                   if(resultXML.size() > 0) {
273                      HashMap hm = (HashMap)session.getAttribute(
274                                       "ManageAuthorities" );
275                      if(hm == null || hm.size() <= 0) {
276                         hm = rs.managedAuthorities();
277                         session.setAttribute("ManageAuthorities",hm);
278                      }//if              
279                   }//if
280                   */
281             }catch(NoResourcesFoundException nrfe) {
282                //nrfe.printStackTrace();
283                errorMessage = "Your query produced no results";
284             }catch(RegistryException re) {
285                //re.printStackTrace();
286                errorMessage = "A error occurred in processing your query " +
287                               "with the Registry.";
288             }catch(Exception e) {
289                e.printStackTrace();
290             }
291          }//else doing a query
292          request.setAttribute( PARAM_CRITERIA_NUMBER,
293                                String.valueOf(crit_number) );         
294       
295       //
296       //Create a new HashMap for our results.  Will be used to
297       //pass to the transformer (xsl page)
298       Map results = new HashMap() ;
299       results.put(PARAM_MAIN_ELEMENT,mainElem);
300       results.put(PARAM_CRITERIA_NUMBER,String.valueOf(crit_number));
301       //results.put(SEARCH_REGISTRY_NAME,searchRegName);
302       //results.put(PUBLISH_REGISTRY_NAME,publishRegName);
303       results.put(ERROR_MESSAGE,errorMessage);
304       if(result != null && result.length() > 0) {
305          results.put("queryresult",result);
306       }
307       return results;
308       
309    }
310    
311    private String getResultMessage(Document doc) {
312       String message = null;
313       NodeList nl = doc.getElementsByTagName("error");      
314       if(nl != null && nl.getLength() > 0) {
315          message = nl.item(0).getFirstChild().getNodeValue();
316       }//if
317       return message;  
318    }
319    
320    /***
321       * Small convenience method to print DEBUG Messages.
322       * @param method The java function
323       * @param message The Debug message
324       */   
325    
326    private void printDebug (String method, String message) {
327       if( DEBUG_FLAG ) System.out.println( method + " : " + message );      
328    }
329    private void printMessage (String message) {
330       System.out.println( message );      
331    }
332    
333    public Document getDocumentTemplate() {
334       ClassLoader loader = this.getClass().getClassLoader();
335       InputStream is = null;
336       
337       is = loader.getResourceAsStream(RESOURCE_XML_URL_TEMPLATE_PROPERTY);
338       
339       if(is != null) {
340          try {
341             Document doc = DomHelper.newDocument(is);
342             return doc;            
343          }catch(Exception e) {
344             e.printStackTrace();
345          }
346       }//if
347       return null;
348    }
349    
350    
351    
352 }