source: main/trunk/greenstone3/src/java/org/greenstone/gsdl3/collection/Collection.java@ 32990

Last change on this file since 32990 was 32990, checked in by kjdon, 5 years ago

missing a }

  • Property svn:keywords set to Author Date Id Revision
File size: 29.2 KB
Line 
1/*
2 * Collection.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.collection;
20
21import java.io.BufferedReader;
22import java.io.BufferedWriter;
23import java.io.File;
24import java.io.FileReader;
25import java.io.FileWriter;
26import java.io.IOException;
27import java.io.PrintWriter;
28import java.io.StringWriter;
29import java.util.ArrayList;
30import java.util.HashMap;
31
32import org.apache.commons.lang3.StringUtils;
33import org.apache.log4j.Logger;
34import org.greenstone.gsdl3.core.ModuleInterface;
35import org.greenstone.gsdl3.service.Authentication;
36import org.greenstone.gsdl3.util.CustomClassLoader;
37import org.greenstone.gsdl3.util.Dictionary;
38import org.greenstone.gsdl3.util.GSFile;
39import org.greenstone.gsdl3.util.GSXML;
40import org.greenstone.gsdl3.util.GSXSLT;
41import org.greenstone.gsdl3.util.OAIXML;
42import org.greenstone.gsdl3.util.SimpleMacroResolver;
43import org.greenstone.gsdl3.util.UserContext;
44import org.greenstone.gsdl3.util.XMLConverter;
45import org.greenstone.gsdl3.util.XMLTransformer;
46import org.w3c.dom.Document;
47import org.w3c.dom.Element;
48import org.w3c.dom.Node;
49import org.w3c.dom.NodeList;
50
51/**
52 * Represents a collection in Greenstone. A collection is an extension of a
53 * ServiceCluster - it has local data that the services use.
54 *
55 * @author Katherine Don
56 * @see ModuleInterface
57 */
58public class Collection extends ServiceCluster
59{
60
61 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.collection.Collection.class.getName());
62
63 /** is this collection being tidied and therefore can support realistic book view? */
64 protected boolean useBook = false;
65 /**
66 * is this collection public or private - public collections will
67 * appear on the home page, whereas private collections won't
68 */
69 protected boolean is_public = true;
70 /** collection type : mg, mgpp or lucene */
71 protected String col_type = "";
72 /** database type : gdbm, jdbm or sqlite */
73 protected String db_type = "";
74 /** time when this collection was built Used by RSS */
75 protected long lastmodified = 0;
76 /** earliestDatestamp of this collection. Used by RSS. No longer used as fallback by OAI */
77 protected long earliestDatestamp = 0;
78
79 /** Stores the default accessibility of guest users */
80 protected boolean _publicAccess = true;
81 /** Stores the scope of any security rules (either collection or document) */
82 protected boolean _securityScopeCollection = true;
83 protected boolean _humanVerify = false;
84 protected boolean _useRecaptcha = false; // for human verify
85 protected String _siteKey = null; // for recaptcha
86 protected String _secretKey = null; // for recaptcha
87
88 protected HashMap<String, ArrayList<Element>> _documentSets = new HashMap<String, ArrayList<Element>>();
89 protected ArrayList<HashMap<String, ArrayList<String>>> _securityExceptions = new ArrayList<HashMap<String, ArrayList<String>>>();
90
91 protected XMLTransformer transformer = null;
92
93 /** same as setClusterName */
94 public void setCollectionName(String name)
95 {
96 setClusterName(name);
97 }
98
99 public Collection()
100 {
101 super();
102 this.description = this.desc_doc.createElement(GSXML.COLLECTION_ELEM);
103 }
104
105 /**
106 * Configures the collection.
107 *
108 * gsdlHome and collectionName must be set before configure is called.
109 *
110 * the file buildcfg.xml is located in gsdlHome/collect/collectionName
111 * collection metadata is obtained, and services loaded.
112 *
113 * @return true/false on success/fail
114 */
115 public boolean configure()
116 {
117 if (this.site_home == null || this.cluster_name == null)
118 {
119 logger.error("Collection: site_home and collection_name must be set before configure called!");
120 return false;
121 }
122 // set up the class loader
123 this.class_loader = new CustomClassLoader(this.getClass().getClassLoader(), GSFile.collectionResourceDir(this.site_home, this.cluster_name));
124
125 macro_resolver.addMacro("_httpcollection_", this.site_http_address + "/collect/" + this.cluster_name);
126
127 Element coll_config_xml = loadCollConfigFile();
128 if (coll_config_xml == null) {
129 logger.error("Collection: couldn't configure collection: " + this.cluster_name + ", " + "Couldn't load collection config file");
130
131 return false;
132 }
133 Element build_config_xml = loadBuildConfigFile();
134
135 if (build_config_xml == null)
136 {
137 logger.error("Collection: couldn't configure collection: " + this.cluster_name + ", " + "Couldn't load build config file");
138
139 return false;
140 }
141
142 GSXSLT.modifyCollectionConfigForDebug(coll_config_xml);
143 // get the collection type attribute
144 Element search = (Element) GSXML.getChildByTagName(coll_config_xml, GSXML.SEARCH_ELEM);
145 if (search != null)
146 {
147 col_type = search.getAttribute(GSXML.TYPE_ATT);
148 }
149
150 Element browse = (Element) GSXML.getChildByTagName(coll_config_xml, GSXML.INFODB_ELEM);
151 if (browse != null)
152 {
153 db_type = browse.getAttribute(GSXML.TYPE_ATT);
154 }
155 else
156 {
157 db_type = "gdbm"; //Default database type
158 }
159
160 this.description.setAttribute(GSXML.TYPE_ATT, col_type);
161 this.description.setAttribute(GSXML.DB_TYPE_ATT, db_type);
162
163 _globalFormat = (Element) GSXML.getChildByTagName(coll_config_xml, GSXML.FORMAT_ELEM);
164 // process the metadata and display items and default library params
165 super.configureLocalData(coll_config_xml);
166 super.configureLocalData(build_config_xml);
167 // get extra collection specific stuff
168 findAndLoadInfo(coll_config_xml, build_config_xml);
169
170 loadSecurityInformation(coll_config_xml);
171
172 // do we have archives folder?
173 File archives_folder = new File(GSFile.collectionArchiveDir(this.site_home, this.cluster_name));
174 if (!archives_folder.exists()) {
175 this.description.setAttribute(GSXML.NO_ARCHIVES_ATT, "true");
176 }
177 // now do the services
178 configureServiceRacks(coll_config_xml, build_config_xml);
179
180 return true;
181
182 }
183
184 public boolean useBook()
185 {
186 return useBook;
187 }
188
189 public boolean isPublic()
190 {
191 return is_public;
192 }
193
194 // Used by RSSRetrieve. No longer used by OAI Receptionist (as second fallback)
195 public long getLastmodified()
196 {
197 return lastmodified;
198 }
199
200 // used by RSSRetrieve, no longer used as fallback by the OAIReceptionist
201 public long getEarliestDatestamp()
202 {
203 return earliestDatestamp;
204 }
205
206 /**
207 * load in the collection config file into a DOM Element
208 */
209 protected Element loadCollConfigFile()
210 {
211
212 File coll_config_file = new File(GSFile.collectionConfigFile(this.site_home, this.cluster_name));
213
214 if (!coll_config_file.exists())
215 {
216 return null;
217 }
218 // get the xml
219 Document coll_config_doc = this.converter.getDOM(coll_config_file, CONFIG_ENCODING);
220 Element coll_config_elem = null;
221 if (coll_config_doc != null)
222 {
223 coll_config_elem = coll_config_doc.getDocumentElement();
224 }
225 return coll_config_elem;
226
227 }
228
229 /**
230 * load in the collection build config file into a DOM Element
231 */
232 protected Element loadBuildConfigFile()
233 {
234 File build_config_file = new File(GSFile.collectionBuildConfigFile(this.site_home, this.cluster_name));
235 if (!build_config_file.exists())
236 {
237 logger.error("Collection: couldn't configure collection: " + this.cluster_name + ", " + build_config_file + " does not exist");
238 return null;
239 }
240 Document build_config_doc = this.converter.getDOM(build_config_file, CONFIG_ENCODING);
241 Element build_config_elem = null;
242 if (build_config_doc != null)
243 {
244 build_config_elem = build_config_doc.getDocumentElement();
245 }
246
247 lastmodified = build_config_file.lastModified();
248
249 return build_config_elem;
250 }
251
252 /**
253 * find the metadata and display elems from the two config files and add it
254 * to the appropriate lists
255 */
256 protected boolean findAndLoadInfo(Element coll_config_xml, Element build_config_xml)
257 {
258 addMetadata("httpPath", this.site_http_address + "/collect/" + this.cluster_name);
259
260
261 //check whether the html are tidy or not
262 Element import_list = (Element) GSXML.getChildByTagName(coll_config_xml, GSXML.IMPORT_ELEM);
263 if (import_list != null)
264 {
265 Element plugin_list = (Element) GSXML.getChildByTagName(import_list, GSXML.PLUGIN_ELEM + GSXML.LIST_MODIFIER);
266 //addPlugins(plugin_list);
267 if (plugin_list != null)
268 {
269 Element plugin_elem = (Element) GSXML.getNamedElement(plugin_list, GSXML.PLUGIN_ELEM, GSXML.NAME_ATT, "HTMLPlugin");
270 if (plugin_elem != null)
271 {
272 //get the option
273 Element option_elem = (Element) GSXML.getNamedElement(plugin_elem, GSXML.PARAM_OPTION_ELEM, GSXML.NAME_ATT, "-use_realistic_book");
274 if (option_elem != null)
275 {
276 useBook = true;
277 }
278 }
279 }
280 }
281 String tidy = (useBook == true ? "tidy" : "untidy");
282 addMetadata("tidyoption", tidy);
283
284
285 if (this.metadata_list != null)
286 {
287 // check whether we are public or not
288 Element meta_elem = (Element) GSXML.getNamedElement(this.metadata_list, GSXML.METADATA_ELEM, GSXML.NAME_ATT, "public");
289 if (meta_elem != null)
290 {
291 String value = GSXML.getValue(meta_elem).toLowerCase().trim();
292 if (value.equals("false"))
293 {
294 is_public = false;
295 }
296 }
297 // earliest datestamp is the time the collection was created.
298 meta_elem = (Element) GSXML.getNamedElement(this.metadata_list, GSXML.METADATA_ELEM, GSXML.NAME_ATT, OAIXML.EARLIEST_DATESTAMP);
299 if (meta_elem != null) {
300 String earliestDatestampStr = GSXML.getValue(meta_elem);
301 if (!earliestDatestampStr.equals("")) {
302 earliestDatestamp = Long.parseLong(earliestDatestampStr) * 1000; // stored in seconds, convert to milliseconds
303 }
304 }
305
306 }
307 return true;
308 }
309
310 protected void loadSecurityInformation(Element coll_config_xml)
311 {
312 Element securityBlock = (Element) GSXML.getChildByTagName(coll_config_xml, GSXML.SECURITY_ELEM);
313
314 if (securityBlock == null)
315 {
316 return;
317 }
318
319 String disabled = securityBlock.getAttribute(GSXML.DISABLED_ATT);
320 if (!disabled.equals("")) {
321 // security block has been disabled.
322 logger.warn("Security block has been disabled. Not implementing any security for collection "+this.cluster_name);
323 return;
324 }
325 String scope = securityBlock.getAttribute(GSXML.SCOPE_ATT);
326 String defaultAccess = securityBlock.getAttribute(GSXML.DEFAULT_ACCESS_ATT);
327
328 if (defaultAccess.toLowerCase().equals("public"))
329 {
330 _publicAccess = true;
331 }
332 else if (defaultAccess.toLowerCase().equals("private"))
333 {
334 _publicAccess = false;
335 }
336 else
337 {
338 logger.warn("Default access for collection " + this.cluster_name + " is neither public or private, assuming public");
339 }
340
341 String humanVerify = securityBlock.getAttribute("humanVerify");
342 if (humanVerify.equals("true")) {
343 _humanVerify = true;
344 }
345
346 String useRecaptcha = securityBlock.getAttribute("useRecaptcha");
347 if (useRecaptcha.equals("true")) {
348
349 Authentication authen_services =(Authentication) this.router.getModuleMap().get(Authentication.AUTHENTICATION_SERVICE);
350 if (authen_services != null) {
351 String siteKey = authen_services.getRecaptchaSiteKey();
352 String secretKey = authen_services.getRecaptchaSecretKey();
353
354 if (siteKey != null && secretKey != null) {
355 _useRecaptcha = true;
356 _siteKey = siteKey;
357 _secretKey = secretKey;
358 } else {
359 logger.warn("use_recaptcha was set to true, but couldn't find recaptcha site and secret keys from the siteConfig Authentication service. Setting use_recaptcha to false!");
360 }
361 }
362 }
363 if (scope.toLowerCase().equals("collection"))
364 {
365 _securityScopeCollection = true;
366 }
367 else if (scope.toLowerCase().equals("documents") || scope.toLowerCase().equals("document"))
368 {
369 _securityScopeCollection = false;
370 }
371 else
372 {
373 logger.warn("Security scope is neither collection or document, assuming collection");
374 }
375
376 NodeList exceptions = GSXML.getChildrenByTagName(securityBlock, GSXML.EXCEPTION_ELEM);
377
378 if (exceptions.getLength() > 0)
379 {
380 if (!_securityScopeCollection)
381 {
382 NodeList documentSetElems = GSXML.getChildrenByTagName(securityBlock, GSXML.DOCUMENT_SET_ELEM);
383 for (int i = 0; i < documentSetElems.getLength(); i++)
384 {
385 Element documentSet = (Element) documentSetElems.item(i);
386 String setName = documentSet.getAttribute(GSXML.NAME_ATT);
387 NodeList matchStatements = GSXML.getChildrenByTagName(documentSet, GSXML.MATCH_ELEM);
388 ArrayList<Element> matchStatementList = new ArrayList<Element>();
389 for (int j = 0; j < matchStatements.getLength(); j++)
390 {
391 matchStatementList.add((Element) matchStatements.item(j));
392 }
393 _documentSets.put(setName, matchStatementList);
394 }
395 }
396
397 for (int i = 0; i < exceptions.getLength(); i++)
398 {
399 HashMap<String, ArrayList<String>> securityException = new HashMap<String, ArrayList<String>>();
400 ArrayList<String> exceptionGroups = new ArrayList<String>();
401 ArrayList<String> exceptionSets = new ArrayList<String>();
402
403 Element exception = (Element) exceptions.item(i);
404 NodeList groups = GSXML.getChildrenByTagName(exception, GSXML.GROUP_ELEM);
405 for (int j = 0; j < groups.getLength(); j++)
406 {
407 Element group = (Element) groups.item(j);
408 String groupName = group.getAttribute(GSXML.NAME_ATT);
409 exceptionGroups.add(groupName);
410 }
411 NodeList docSets = GSXML.getChildrenByTagName(exception, GSXML.DOCUMENT_SET_ELEM);
412 for (int j = 0; j < docSets.getLength(); j++)
413 {
414 Element docSet = (Element) docSets.item(j);
415 String docSetName = docSet.getAttribute(GSXML.NAME_ATT);
416 exceptionSets.add(docSetName);
417 }
418 if (_securityScopeCollection) {
419 // we don't add in any exceptions that have document sets
420 if (!exceptionSets.isEmpty()) {
421 continue;
422 }
423 }
424 securityException.put("groups", exceptionGroups);
425 securityException.put("sets", exceptionSets);
426 _securityExceptions.add(securityException);
427 }
428 }
429 }
430
431 protected boolean configureServiceRacks(Element coll_config_xml, Element build_config_xml)
432 {
433 clearServices();
434 Element service_list = (Element) GSXML.getChildByTagName(build_config_xml, GSXML.SERVICE_CLASS_ELEM + GSXML.LIST_MODIFIER);
435 if (service_list != null)
436 {
437 configureServiceRackList(service_list, coll_config_xml);
438 }
439 // collection Config may also contain manually added service racks
440 service_list = (Element) GSXML.getChildByTagName(coll_config_xml, GSXML.SERVICE_CLASS_ELEM + GSXML.LIST_MODIFIER);
441 if (service_list != null)
442 {
443 configureServiceRackList(service_list, build_config_xml);
444 }
445 return true;
446 }
447
448 /**
449 * do a configure on only part of the collection
450 */
451 protected boolean configureSubset(String subset)
452 {
453
454 // need the coll config files
455 Element coll_config_elem = loadCollConfigFile();
456 Element build_config_elem = loadBuildConfigFile();
457 if (coll_config_elem == null || build_config_elem == null)
458 {
459 // wont be able to do any of the requests
460 return false;
461 }
462
463 if (subset.equals(GSXML.SERVICE_ELEM + GSXML.LIST_MODIFIER))
464 {
465 return configureServiceRacks(coll_config_elem, build_config_elem);
466 }
467
468 if (subset.equals(GSXML.METADATA_ELEM + GSXML.LIST_MODIFIER) || subset.equals(GSXML.DISPLAY_TEXT_ELEM + GSXML.LIST_MODIFIER) || subset.equals(GSXML.LIBRARY_PARAM_ELEM+GSXML.LIST_MODIFIER))
469 {
470 configureLocalData(coll_config_elem);
471 configureLocalData(build_config_elem);
472 return findAndLoadInfo(coll_config_elem, build_config_elem);
473
474 }
475
476 logger.error("Collection: cant process system request, configure " + subset);
477 return false;
478 }
479
480 /**
481 * handles requests made to the ServiceCluster itself
482 *
483 * @param req
484 * - the request Element- <request>
485 * @return the result Element - should be <response>
486 */
487 protected Element processMessage(Document result_doc, Element request)
488 {
489 String type = request.getAttribute(GSXML.TYPE_ATT);
490 if (type.equals(GSXML.REQUEST_TYPE_FORMAT_STRING))
491 {
492 return processFormatStringRequest(result_doc, request);
493 }
494 else if (type.equals(GSXML.REQUEST_TYPE_SECURITY))
495 {
496 return processSecurityRequest(result_doc, request);
497 }
498 else if (type.equals(GSXML.REQUEST_TYPE_FORMAT))
499 {
500
501 Element response = result_doc.createElement(GSXML.RESPONSE_ELEM);
502 response.setAttribute(GSXML.FROM_ATT, this.cluster_name);
503 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_FORMAT);
504 if (_globalFormat != null)
505 {
506 response.appendChild(result_doc.importNode(_globalFormat, true));
507 }
508 return response;
509 }
510 // unknown type
511 return super.processMessage(result_doc, request);
512
513 }
514
515 protected Element processSecurityRequest(Document result_doc, Element request)
516 {
517 Element response = result_doc.createElement(GSXML.RESPONSE_ELEM);
518 response.setAttribute(GSXML.FROM_ATT, this.cluster_name);
519 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_SECURITY);
520
521 if (_humanVerify) {
522 response.setAttribute("humanVerify", "true");
523 if (_useRecaptcha) {
524 response.setAttribute("siteKey", _siteKey);
525 response.setAttribute("secretKey", _secretKey);
526 }
527 }
528 String oid = request.getAttribute("oid");
529 if (oid.contains("."))
530 {
531 oid = oid.substring(0, oid.indexOf("."));
532 }
533
534 ArrayList<String> groups = getPermittedGroups(oid);
535
536 Element groupList = result_doc.createElement(GSXML.GROUP_ELEM + GSXML.LIST_MODIFIER);
537 response.appendChild(groupList);
538
539 for (String groupName : groups)
540 {
541 Element group = result_doc.createElement(GSXML.GROUP_ELEM);
542 groupList.appendChild(group);
543 group.setAttribute(GSXML.NAME_ATT, groupName);
544 }
545 return response;
546 }
547
548 protected ArrayList<String> getPermittedGroups(String oid)
549 {
550 ArrayList<String> groups = new ArrayList<String>();
551
552 if (_securityScopeCollection)
553 {
554 if (_publicAccess)
555 {
556 groups.add("");
557 }
558 else
559 {
560 for (HashMap<String, ArrayList<String>> exception : _securityExceptions)
561 {
562 for (String group : exception.get("groups"))
563 {
564 groups.add(group);
565 }
566 }
567 }
568 }
569 else
570 {
571 if (oid != null && !oid.equals(""))
572 {
573 boolean inSet = false;
574 for (HashMap<String, ArrayList<String>> exception : _securityExceptions) {
575
576 ArrayList<String> exceptionSets = exception.get("sets");
577 if (exceptionSets.size() == 0) {
578 inSet = true;
579 for (String group : exception.get("groups"))
580 {
581 groups.add(group);
582 }
583 }
584 else {
585 for (String setName : exception.get("sets"))
586 {
587 if (documentIsInSet(oid, setName))
588 {
589 inSet = true;
590 for (String group : exception.get("groups"))
591 {
592 groups.add(group);
593 }
594 break;
595 }
596 }
597 }
598 }
599
600
601
602 if (!inSet && _publicAccess)
603 {// our doc was not part of any exception, so it must be public
604 groups.add("");
605 }
606 }
607 else // if we are not doing a request with an oid, then free to access
608 {
609 groups.add("");
610 }
611 }
612
613 return groups;
614 }
615
616 protected boolean documentIsInSet(String oid, String setName)
617 {
618 ArrayList<Element> matchStatements = _documentSets.get(setName);
619 if (matchStatements == null || matchStatements.size() == 0)
620 {
621 return false;
622 }
623
624 for (Element currentMatchStatement : matchStatements)
625 {
626 String fieldName = currentMatchStatement.getAttribute(GSXML.FIELD_ATT);
627 if (fieldName == null || fieldName.equals(""))
628 {
629 fieldName = "oid";
630 }
631
632 String type = currentMatchStatement.getAttribute(GSXML.TYPE_ATT);
633 if (type == null || type.equals(""))
634 {
635 type = "match";
636 }
637
638 String fieldValue = "";
639 if (!fieldName.equals("oid"))
640 {
641 fieldValue = getFieldValue(oid, fieldName);
642 if (fieldValue == null)
643 {
644 return false;
645 }
646 }
647 else
648 {
649 fieldValue = oid;
650 }
651
652 String matchValue = GSXML.getNodeText(currentMatchStatement);
653 if (type.equals("match"))
654 {
655 if (matchValue.equals(fieldValue))
656 {
657 return true;
658 }
659 }
660 else if (type.equals("regex"))
661 {
662 if (fieldValue.matches(matchValue))
663 {
664 return true;
665 }
666 }
667 else
668 {
669 logger.warn("Unknown type of match specified in security block of collection " + this.cluster_name + ".");
670 }
671 }
672
673 return false;
674 }
675
676 protected String getFieldValue(String oid, String fieldName)
677 {
678 Document msg_doc = XMLConverter.newDOM();
679 Element metadataMessage = msg_doc.createElement(GSXML.MESSAGE_ELEM);
680 Element metadataRequest = GSXML.createBasicRequest(msg_doc, GSXML.REQUEST_TYPE_PROCESS, this.cluster_name + "/DocumentMetadataRetrieve", new UserContext());
681 metadataMessage.appendChild(metadataRequest);
682
683 Element paramList = msg_doc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
684 metadataRequest.appendChild(paramList);
685
686 Element param = msg_doc.createElement(GSXML.PARAM_ELEM);
687 paramList.appendChild(param);
688
689 param.setAttribute(GSXML.NAME_ATT, "metadata");
690 param.setAttribute(GSXML.VALUE_ATT, fieldName);
691
692 Element docList = msg_doc.createElement(GSXML.DOC_NODE_ELEM + GSXML.LIST_MODIFIER);
693 metadataRequest.appendChild(docList);
694
695 Element doc = msg_doc.createElement(GSXML.DOC_NODE_ELEM);
696 docList.appendChild(doc);
697
698 doc.setAttribute(GSXML.NODE_ID_ATT, oid);
699
700 Element response = (Element) this.router.process(metadataMessage);
701 NodeList metadataElems = response.getElementsByTagName(GSXML.METADATA_ELEM);
702
703 if (metadataElems.getLength() > 0)
704 {
705 Element metadata = (Element) metadataElems.item(0);
706 return GSXML.getNodeText(metadata);
707 }
708
709 return null;
710 }
711
712 protected Element processFormatStringRequest(Document result_doc, Element request)
713 {
714 Element response = result_doc.createElement(GSXML.RESPONSE_ELEM);
715 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_FORMAT_STRING);
716 response.setAttribute(GSXML.FROM_ATT, this.cluster_name);
717
718 String subaction = request.getAttribute("subaction");
719 String service = request.getAttribute("service");
720
721 String classifier = null;
722 if (service.equals("ClassifierBrowse"))
723 {
724 classifier = request.getAttribute("classifier");
725 }
726
727 // check for version file
728 String directory = new File(GSFile.collectionConfigFile(this.site_home, this.cluster_name)).getParent() + File.separator;
729
730 String version_filename = "";
731 if (service.equals("ClassifierBrowse"))
732 version_filename = directory + "browse_" + classifier + "_format_statement_version.txt";
733 else
734 version_filename = directory + "query_format_statement_version.txt";
735
736 File version_file = new File(version_filename);
737
738 if (subaction.equals("update"))
739 {
740 Element format_element = (Element) GSXML.getChildByTagName(request, GSXML.FORMAT_STRING_ELEM);
741 //String format_string = GSXML.getNodeText(format_element);
742 Element format_statement = (Element) format_element.getFirstChild();
743
744 String version_number = "1";
745 BufferedWriter writer;
746
747 try
748 {
749
750 if (version_file.exists())
751 {
752 // Read version
753 BufferedReader reader = new BufferedReader(new FileReader(version_filename));
754 version_number = reader.readLine();
755 int aInt = Integer.parseInt(version_number) + 1;
756 version_number = Integer.toString(aInt);
757 reader.close();
758 }
759 else
760 {
761 // Create
762 version_file.createNewFile();
763 writer = new BufferedWriter(new FileWriter(version_filename));
764 writer.write(version_number);
765 writer.close();
766 }
767
768 // Write version file
769 String format_statement_filename = "";
770
771 if (service.equals("ClassifierBrowse"))
772 format_statement_filename = directory + "browse_" + classifier + "_format_statement_v" + version_number + ".txt";
773 else
774 format_statement_filename = directory + "query_format_statement_v" + version_number + ".txt";
775
776 // Write format statement
777 String format_string = this.converter.getString(format_statement); //GSXML.xmlNodeToString(format_statement);
778 writer = new BufferedWriter(new FileWriter(format_statement_filename));
779 writer.write(format_string);
780 writer.close();
781
782 // Update version number
783 writer = new BufferedWriter(new FileWriter(version_filename));
784 writer.write(version_number);
785 writer.close();
786
787 }
788 catch (IOException e)
789 {
790 logger.error("IO Exception " + e);
791 }
792 }
793
794 if (subaction.equals("saveDocument"))
795 {
796 Element format_element = (Element) GSXML.getChildByTagName(request, GSXML.FORMAT_STRING_ELEM);
797 //String format_string = GSXML.getNodeText(format_element);
798 // Get display tag
799 Element display_format = (Element) format_element.getFirstChild();
800
801 String collection_config = directory + "collectionConfig.xml";
802 Document config = this.converter.getDOM(new File(collection_config), "UTF-8");
803
804 Node current_node = GSXML.getChildByTagName(config, "CollectionConfig");
805
806 // Get display child
807 if (GSXML.getChildByTagName(current_node, "display") == null)
808 {
809 // well then create a format tag
810 Element display_tag = config.createElement("display");
811 current_node = (Node) current_node.appendChild(display_tag);
812 }
813 else
814 {
815 current_node = GSXML.getChildByTagName(current_node, "display");
816 }
817
818 if (GSXML.getChildByTagName(current_node, "format") == null)
819 {
820 // well then create a format tag
821 Element format_tag = config.createElement("format");
822 current_node.appendChild(format_tag);
823 }
824
825 current_node.replaceChild(config.importNode(display_format, true), GSXML.getChildByTagName(current_node, "format"));
826
827 String new_config = this.converter.getString(config);
828
829 new_config = StringUtils.replace(new_config, "&lt;", "<");
830 new_config = StringUtils.replace(new_config, "&gt;", ">");
831 new_config = StringUtils.replace(new_config, "&quot;", "\"");
832
833 try
834 {
835 // Write to file (not original! for now)
836 BufferedWriter writer = new BufferedWriter(new FileWriter(collection_config + ".new"));
837 writer.write(new_config);
838 writer.close();
839 }
840 catch (IOException e)
841 {
842 logger.error("IO Exception " + e);
843 }
844 }
845
846 if (subaction.equals("save"))
847 {
848 Element format_element = (Element) GSXML.getChildByTagName(request, GSXML.FORMAT_STRING_ELEM);
849 Element format_statement = (Element) format_element.getFirstChild();
850
851 try
852 {
853 // open collectionConfig.xml and read in to w3 Document
854 String collection_config = directory + "collectionConfig.xml";
855 Document config = this.converter.getDOM(new File(collection_config), "UTF-8");
856
857 //String tag_name = "";
858 int k;
859 int index;
860 Element elem;
861 Node current_node = GSXML.getChildByTagName(config, "CollectionConfig");
862 NodeList current_node_list;
863
864 if (service.equals("ClassifierBrowse"))
865 {
866 //tag_name = "browse";
867 // if CLX then need to look in <classifier> X then <format>
868 // default is <browse><format>
869
870 current_node = GSXML.getChildByTagName(current_node, "browse");
871
872 // find CLX
873 if (classifier != null)
874 {
875 current_node_list = GSXML.getChildrenByTagName(current_node, "classifier");
876 index = Integer.parseInt(classifier.substring(2)) - 1;
877
878 // index should be given by X-1
879 current_node = current_node_list.item(index);
880 // what if classifier does not have a format tag?
881 if (GSXML.getChildByTagName(current_node, "format") == null)
882 {
883 // well then create a format tag
884 Element format_tag = config.createElement("format");
885 current_node.appendChild(format_tag);
886 }
887 }
888 else
889 {
890 // To support all classifiers, set classifier to null? There is the chance here that the format tag does not exist
891 if (GSXML.getChildByTagName(current_node, "format") == null)
892 {
893 // well then create a format tag
894 Element format_tag = config.createElement("format");
895 current_node.appendChild(format_tag);
896 }
897 }
898 }
899 else if (service.equals("AllClassifierBrowse"))
900 {
901 current_node = GSXML.getChildByTagName(current_node, "browse");
902 if (GSXML.getChildByTagName(current_node, "format") == null)
903 {
904 // well then create a format tag
905 Element format_tag = config.createElement("format");
906 current_node.appendChild(format_tag);
907 }
908 }
909 else
910 {
911 // look in <format> with no attributes
912 current_node_list = GSXML.getChildrenByTagName(current_node, "search");
913 for (k = 0; k < current_node_list.getLength(); k++)
914 {
915 current_node = current_node_list.item(k);
916 // if current_node has no attributes then break
917 elem = (Element) current_node;
918 if (elem.hasAttribute("name") == false)
919 break;
920 }
921 }
922
923 current_node.replaceChild(config.importNode(format_statement, true), GSXML.getChildByTagName(current_node, "format"));
924
925 // Now convert config document to string for writing to file
926 String new_config = this.converter.getString(config);
927
928 new_config = StringUtils.replace(new_config, "&lt;", "<");
929 new_config = StringUtils.replace(new_config, "&gt;", ">");
930 new_config = StringUtils.replace(new_config, "&quot;", "\"");
931
932 // Write to file (not original! for now)
933 BufferedWriter writer = new BufferedWriter(new FileWriter(collection_config + ".new"));
934 writer.write(new_config);
935 writer.close();
936
937 }
938 catch (Exception ex)
939 {
940 logger.error("There was an exception " + ex);
941
942 StringWriter sw = new StringWriter();
943 PrintWriter pw = new PrintWriter(sw, true);
944 ex.printStackTrace(pw);
945 pw.flush();
946 sw.flush();
947 logger.error(sw.toString());
948 }
949
950 }
951
952 return response;
953 }
954
955
956}
Note: See TracBrowser for help on using the repository browser.