source: main/trunk/greenstone3/src/java/org/greenstone/gsdl3/service/ServiceRack.java

Last change on this file was 36985, checked in by kjdon, 17 months ago

the custom class loader now uses site resources file if no cluster_name is set - ie its a site-wide service, not a collection-specific service.

  • Property svn:keywords set to Author Date Id Revision
File size: 17.3 KB
Line 
1/*
2 * ServiceRack.java
3 * Copyright (C) 2002 New Zealand Digital Library, http://www.nzdl.org
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19package org.greenstone.gsdl3.service;
20
21// greenstone classes
22import java.lang.reflect.Method;
23import java.util.ArrayList;
24import java.util.HashMap;
25
26import org.apache.log4j.Logger;
27import org.greenstone.gsdl3.collection.ServiceCluster;
28import org.greenstone.gsdl3.core.MessageRouter;
29import org.greenstone.gsdl3.core.ModuleInterface;
30import org.greenstone.gsdl3.util.CustomClassLoader;
31import org.greenstone.gsdl3.util.Dictionary;
32import org.greenstone.gsdl3.util.GSFile;
33import org.greenstone.gsdl3.util.GSParams;
34import org.greenstone.gsdl3.util.GSPath;
35import org.greenstone.gsdl3.util.GSXML;
36import org.greenstone.gsdl3.util.XMLConverter;
37import org.w3c.dom.Document;
38import org.w3c.dom.Element;
39import org.w3c.dom.Node;
40import org.w3c.dom.NodeList;
41
42import java.io.StringWriter;
43import java.io.PrintWriter;
44
45/**
46 * ServiceRack - abstract base class for services
47 *
48 * A ServiceRack provides one or more Services. This base class implements the
49 * process method. Each service is invoked by a method called process<service
50 * name> which takes one parameter - the xml request Element, and returns an XML
51 * response Element. for example, the TextQuery service would be invoked by
52 * processTextQuery(Element request)
53 *
54 * @author Katherine Don
55 */
56public abstract class ServiceRack implements ModuleInterface
57{
58
59 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.service.ServiceRack.class.getName());
60
61 /** the absolute address of the site home */
62 protected String site_home = null;
63 /** the http address of the site home */
64 protected String site_http_address = null;
65
66 protected String library_name = null;
67 /**
68 * the name of the cluster (or collection) that this service belongs to - if
69 * any
70 */
71 protected String cluster_name = null;
72
73 /** some services can talk back to the message router */
74 protected MessageRouter router = null;
75
76 /** Access to the collection/serviceCluster object for service subclasses */
77 protected ServiceCluster serviceCluster = null;
78
79 /** a converter class to create Documents etc */
80 protected XMLConverter converter = null;
81
82 /** the original config info - if need to store it */
83 protected Element config_info = null;
84
85 /** XML element for stored description XML */
86 protected Document desc_doc = null;
87
88 /**
89 * XML element for describe requests - list of supported services - this is
90 * static
91 */
92 protected Element short_service_info = null;
93
94 /**
95 * XML element for stylesheet requests - map of service name to format elem
96 */
97 protected HashMap<String, Node> format_info_map = null;
98
99 /** the list of cgi params that this services are looking for, that need saving in the session */
100 protected ArrayList<String> save_params = null;
101 protected ArrayList<String> sensitive_params = null;
102 protected Element _globalFormat = null;
103
104 /**
105 * A class loader that knows about the collection resources directory can
106 * put properties files, dtds etc in here
107 */
108 CustomClassLoader class_loader = null;
109
110 /** sets the cluster name */
111 public void setClusterName(String cluster_name)
112 {
113 this.cluster_name = cluster_name;
114 }
115
116 /** sets the serviceCluster/Collection object */
117 public void setServiceCluster(ServiceCluster serviceCluster)
118 {
119 this.serviceCluster = serviceCluster;
120 }
121
122 /** sets the collect name */
123 public void setCollectionName(String coll_name)
124 {
125 setClusterName(coll_name);
126 }
127
128 public void cleanUp()
129 {
130 }
131
132 public void setGlobalFormat(Element globalFormat)
133 {
134 _globalFormat = GSXML.duplicateWithNewName(this.desc_doc, globalFormat, GSXML.GLOBAL_FORMAT_ELEM, false);
135 }
136
137 /** sets the site home */
138 public void setSiteHome(String site_home)
139 {
140 this.site_home = site_home;
141 }
142
143 /** sets the site http address */
144 public void setSiteAddress(String site_address)
145 {
146 this.site_http_address = site_address;
147 }
148
149 public void setLibraryName(String library_name)
150 {
151 this.library_name = library_name;
152 }
153
154 public String getLibraryName()
155 {
156 return this.library_name;
157 }
158
159 /** sets the message router */
160 public void setMessageRouter(MessageRouter m)
161 {
162 this.router = m;
163 setLibraryName(m.getLibraryName());
164 }
165
166 public boolean addServiceParameters(GSParams params) {
167
168 if (params == null) {
169 logger.error("params is null!!!");
170 return false;
171 }
172
173 for (int i=0; i<save_params.size(); i++) {
174 params.addServiceParameter(save_params.get(i), "", true, false);
175 }
176 for (int i=0; i<sensitive_params.size(); i++) {
177 params.addServiceParameter(sensitive_params.get(i), "", false, true);
178 }
179 return true;
180
181 }
182 /** the no-args constructor */
183 public ServiceRack()
184 {
185 this.converter = new XMLConverter();
186 this.desc_doc = XMLConverter.newDOM();
187 this.short_service_info = this.desc_doc.createElement(GSXML.SERVICE_ELEM + GSXML.LIST_MODIFIER);
188 this.format_info_map = new HashMap<String, Node>();
189 this.save_params = new ArrayList<String>();
190 this.sensitive_params = new ArrayList<String>();
191 }
192
193 /**
194 * configure the service module
195 *
196 * @param info
197 * the XML node <serviceRack name="XXX"/> with name equal to the
198 * class name (of the subclass)
199 *
200 * must configure short_service_info_ and service_info_map_
201 * @return true if configured ok must be implemented in subclasses
202 */
203 public boolean configure(Element info)
204 {
205 return configure(info, null);
206 }
207
208 public boolean configure(Element info, Element extra_info)
209 {
210 // set up the class loader
211 // are we in a collection?
212 if (this.cluster_name != null) {
213 this.class_loader = new CustomClassLoader(this.getClass().getClassLoader(), GSFile.collectionResourceDir(this.site_home, this.cluster_name));
214 return true;
215 }
216 // we are at site level
217 this.class_loader = new CustomClassLoader(this.getClass().getClassLoader(), GSFile.siteResourceDir(this.site_home));
218 return true;
219 }
220
221 /**
222 * Process an XML document - convenience method that uses Strings rather
223 * than Elements. just calls process(Element).
224 *
225 * @param xml_in
226 * the Document to process - a string
227 * @return the resultant document as a string - contains any error messages
228 * @see String
229 */
230 public String process(String xml_in)
231 {
232
233 Document doc = this.converter.getDOM(xml_in);
234 if (doc == null)
235 {
236 logger.error("Couldn't parse request");
237 logger.error(xml_in);
238 return null;
239 }
240 Node res = process(doc);
241 return this.converter.getString(res);
242
243 }
244
245 /**
246 * process an XML request in DOM form
247 *
248 * @param message
249 * the Node node containing the request should be <message>
250 * @return an Node with the result XML
251 * @see Node/Element
252 */
253 public Node process(Node message_node)
254 {
255 Element message = GSXML.nodeToElement(message_node);
256
257 NodeList requests = message.getElementsByTagName(GSXML.REQUEST_ELEM);
258 Document result_doc = XMLConverter.newDOM();
259 Element mainResult = result_doc.createElement(GSXML.MESSAGE_ELEM);
260 if (requests.getLength() == 0)
261 {
262 // no requests
263 return mainResult; // empty message for now
264 }
265
266 for (int i = 0; i < requests.getLength(); i++)
267 {
268 Element request = (Element) requests.item(i);
269
270 String type = request.getAttribute(GSXML.TYPE_ATT);
271 if (type.equals(GSXML.REQUEST_TYPE_DESCRIBE))
272 {
273 Element response = processDescribe(request);
274 if (response != null)
275 {
276 mainResult.appendChild(result_doc.importNode(response, true));
277 }
278
279 }
280 else if (type.equals(GSXML.REQUEST_TYPE_FORMAT))
281 {
282 Element response = processFormat(request);
283 mainResult.appendChild(result_doc.importNode(response, true));
284 }
285 else
286 {
287 // other type of request, must be processed by the subclass -
288 // send to the service method
289 StringBuffer error_string = new StringBuffer();
290 String to = GSPath.getFirstLink(request.getAttribute(GSXML.TO_ATT));
291 Element response = null;
292 try
293 {
294 Class c = this.getClass();
295 Class[] params = { Class.forName("org.w3c.dom.Element") };
296
297 String method_name = "process" + to;
298 Method m = null;
299 while (c != null)
300 {
301
302 try
303 {
304 m = c.getDeclaredMethod(method_name, params);
305 // if this has worked, break
306 break;
307 }
308 catch (NoSuchMethodException e)
309 {
310 c = c.getSuperclass();
311 }
312 catch (SecurityException e)
313 {
314 logger.error("security exception for finding method " + method_name);
315 error_string.append("ServiceRack.process: security exception for finding method " + method_name);
316 }
317 } // while
318 if (m != null)
319 {
320 Object[] args = { request };
321 try
322 {
323 response = (Element) m.invoke(this, args);
324
325 }
326 catch (Exception e)
327 {
328 logger.error("Trying to call a processService type method (process" + to + ") on a subclass(" + this.getClass().getName() + "), but an exception happened:" + e.toString(), e);
329 // for debugging, it's useful to see what's really causing this supposed "invocationTargetException"
330 // When the error message is displayed in the "Net" tab in the browser's web inspector, scroll down to "Caused by"
331 StringWriter errors = new StringWriter();
332 e.printStackTrace(new PrintWriter(errors));
333 String errStr = errors.toString();
334 errStr += XMLConverter.getString(request);
335
336
337 error_string.append("Trying to call a processService type method (process" + to + ") on a subclass(" + this.getClass().getName() + "), but an exception happened:" + e.toString() + "\n" + errStr );
338 }
339 }
340 else
341 {
342 logger.error("method " + method_name + " not found for class " + this.getClass().getName());
343 error_string.append("ServiceRack.process: method " + method_name + " not found for class " + this.getClass().getName());
344 }
345
346 }
347 catch (ClassNotFoundException e)
348 {
349 logger.error("Element class not found");
350 error_string.append("Element class not found");
351 }
352 if (response != null)
353 {
354 mainResult.appendChild(result_doc.importNode(response, true));
355 }
356 else
357 {
358 // add in a dummy response
359 logger.error("adding in an error element\n");
360 response = result_doc.createElement(GSXML.RESPONSE_ELEM);
361 GSXML.addError(response, error_string.toString());
362 mainResult.appendChild(response);
363
364 }
365
366 } // else process request
367 } // for each request
368
369 return mainResult;
370
371 }
372
373 /**
374 * process method for describe requests
375 */
376 protected Element processDescribe(Element request)
377 {
378 Document result_doc = XMLConverter.newDOM();
379 Element response = result_doc.createElement(GSXML.RESPONSE_ELEM);
380 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_DESCRIBE);
381
382 String lang = request.getAttribute(GSXML.LANG_ATT);
383 String to = GSPath.getFirstLink(request.getAttribute(GSXML.TO_ATT));
384 if (to.equals(""))
385 { // return the service list
386 response.appendChild(result_doc.importNode(getServiceList(result_doc, lang), true));
387 return response;
388 }
389 response.setAttribute(GSXML.FROM_ATT, to);
390 Element param_list = (Element) GSXML.getChildByTagName(request, GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
391 Element description = null;
392 if (param_list == null)
393 {
394 description = getServiceDescription(result_doc, to, lang, null);
395 }
396 else
397 {
398 NodeList params = param_list.getElementsByTagName(GSXML.PARAM_ELEM);
399 for (int i = 0; i < params.getLength(); i++)
400 {
401
402 Element param = (Element) params.item(i);
403 // Identify the structure information desired
404 if (param.getAttribute(GSXML.NAME_ATT).equals(GSXML.SUBSET_PARAM))
405 {
406 String info = param.getAttribute(GSXML.VALUE_ATT);
407 if (description == null)
408 {
409 description = getServiceDescription(result_doc, to, lang, info);
410 }
411 else
412 {
413 Element temp = getServiceDescription(result_doc, to, lang, info);
414 GSXML.mergeElements(description, temp);
415 }
416 }
417 }
418 }
419 if (description != null)
420 { // may be null if non-existant service
421 response.appendChild(description);
422 }
423 return response;
424
425 }
426
427 /**
428 * process method for stylesheet requests
429 */
430 protected Element processFormat(Element request)
431 {
432 Document result_doc = XMLConverter.newDOM();
433 Element response = result_doc.createElement(GSXML.RESPONSE_ELEM);
434 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_FORMAT);
435
436 String to = GSPath.getFirstLink(request.getAttribute(GSXML.TO_ATT));
437
438 if (to.equals(""))
439 { // serviceRack query - is this appropriate??
440 return response;
441 }
442
443 // describe a particular service
444 if (this.format_info_map.containsKey(to))
445 {
446 response.appendChild(getServiceFormat(result_doc, to));
447 if (_globalFormat != null)
448 {
449 response.appendChild(result_doc.importNode(this._globalFormat, true));
450 }
451 response.setAttribute(GSXML.FROM_ATT, to);
452 return response;
453 }
454
455 // else no format info
456 logger.error("ServiceRack describe request: no format info for " + to + ".");
457 return response;
458 }
459
460 /** returns the service list for the subclass */
461 protected Element getServiceList(Document doc, String lang)
462 {
463 // for now, it is static and has no language stuff
464 return (Element)doc.importNode(this.short_service_info, true);
465 }
466
467 /** returns a specific service description */
468 abstract protected Element getServiceDescription(Document doc, String service, String lang, String subset);
469
470 protected Element getServiceFormat(Document doc, String service)
471 {
472 Element format = (Element) this.format_info_map.get(service);
473 if (format != null) {
474 return (Element)doc.importNode(format, true);
475 }
476 return null;
477 }
478
479
480 /**
481 * Returns the appropriate language element from a display elem, display is
482 * the containing element, name is the name of the element to look for, lang
483 * is the preferred language, lang_default is the fall back lang, if neither
484 * lang is found will return the first one it finds
485 */
486 public String getDisplayText(Element display, String name, String lang, String lang_default) {
487 return getDisplayText(display, name, lang, lang_default, null);
488 }
489
490 public String getDisplayText(Element display, String name, String lang, String lang_default, String default_dictionary) {
491
492
493 String def = null;
494 String first = null;
495 String key = null;
496 String dictionary_name = default_dictionary;
497 NodeList elems = display.getElementsByTagName(GSXML.DISPLAY_TEXT_ELEM);
498 if (elems.getLength() == 0)
499 return "";
500 for (int i = 0; i < elems.getLength(); i++)
501 {
502 Element e = (Element) elems.item(i);
503 String n = e.getAttribute(GSXML.NAME_ATT);
504 if (name.equals(n))
505 {
506 String l = e.getAttribute(GSXML.LANG_ATT);
507 String k = e.getAttribute(GSXML.KEY_ATT);
508 // if we have a specific lang value, return that
509 if (!l.equals("") && lang.equals(l))
510 {
511 return GSXML.getNodeText(e);
512 }
513 else if (!l.equals("") && lang_default.equals(l))
514 {
515 def = GSXML.getNodeText(e);
516 }
517 else if (!k.equals("")) {
518 if ( key == null) {
519 // a key specified. only allowed one spec with key
520 key = k;
521 String d = e.getAttribute(GSXML.DICTIONARY_ATT);
522 if (!d.equals("")) {
523 dictionary_name = d;
524 }
525 }
526 }
527 // we have no key and we don't match the languages
528 else if (first == null)
529 {
530 // but we are the first one, so we remember the value
531 first = GSXML.getNodeText(e);
532 }
533 }
534 else
535 {
536 continue;
537 }
538 }
539
540
541 if (key != null) {
542 String s = getTextString(key, lang, dictionary_name);
543 // only use this one if a value was actually found
544 if (s!= null) {
545 return s;
546 }
547 //if (!s.equals( "_"+key +"_")) {
548 // return s;
549 //}
550 }
551
552 if (def != null)
553 {
554 return def;
555 }
556 if (first != null)
557 {
558 return first;
559 }
560 return "";
561 }
562
563 /** overloaded version for no args case */
564 protected String getTextString(String key, String lang)
565 {
566 return getTextString(key, lang, null, null);
567 }
568
569 protected String getTextString(String key, String lang, String dictionary)
570 {
571 return getTextString(key, lang, dictionary, null);
572 }
573
574 protected String getTextString(String key, String lang, String[] args)
575 {
576 return getTextString(key, lang, null, args);
577 }
578
579 /**
580 * getTextString - retrieves a language specific text string for the given
581 * key and locale, from the specified resource_bundle (dictionary)
582 * dictionary may be null, in which case it will use class names
583 */
584 protected String getTextString(String key, String lang, String dictionary, String[] args)
585 {
586
587 return Dictionary.getTextString(key, lang, args, dictionary, this.getClass(), "ServiceRack", this.class_loader);
588 }
589
590 protected String getMetadataNameText(String key, String lang)
591 {
592 return Dictionary.getTextString(key, lang, null, "metadata_names", null, null, this.class_loader);
593 }
594}
Note: See TracBrowser for help on using the repository browser.