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

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

mods to store new humanverify settings. in collectionConfig security element, set humanVerify=true to trigger the verify page. set useRecaptcha=true if you want a recaptcha on the verify page. The Authentication servicerack must be active in siteConfig, and recaptcha site and secret key elements must be present with valid keys.

  • Property svn:keywords set to Author Date Id Revision
File size: 29.0 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 }
359 }
360 }
361 if (scope.toLowerCase().equals("collection"))
362 {
363 _securityScopeCollection = true;
364 }
365 else if (scope.toLowerCase().equals("documents") || scope.toLowerCase().equals("document"))
366 {
367 _securityScopeCollection = false;
368 }
369 else
370 {
371 logger.warn("Security scope is neither collection or document, assuming collection");
372 }
373
374 NodeList exceptions = GSXML.getChildrenByTagName(securityBlock, GSXML.EXCEPTION_ELEM);
375
376 if (exceptions.getLength() > 0)
377 {
378 if (!_securityScopeCollection)
379 {
380 NodeList documentSetElems = GSXML.getChildrenByTagName(securityBlock, GSXML.DOCUMENT_SET_ELEM);
381 for (int i = 0; i < documentSetElems.getLength(); i++)
382 {
383 Element documentSet = (Element) documentSetElems.item(i);
384 String setName = documentSet.getAttribute(GSXML.NAME_ATT);
385 NodeList matchStatements = GSXML.getChildrenByTagName(documentSet, GSXML.MATCH_ELEM);
386 ArrayList<Element> matchStatementList = new ArrayList<Element>();
387 for (int j = 0; j < matchStatements.getLength(); j++)
388 {
389 matchStatementList.add((Element) matchStatements.item(j));
390 }
391 _documentSets.put(setName, matchStatementList);
392 }
393 }
394
395 for (int i = 0; i < exceptions.getLength(); i++)
396 {
397 HashMap<String, ArrayList<String>> securityException = new HashMap<String, ArrayList<String>>();
398 ArrayList<String> exceptionGroups = new ArrayList<String>();
399 ArrayList<String> exceptionSets = new ArrayList<String>();
400
401 Element exception = (Element) exceptions.item(i);
402 NodeList groups = GSXML.getChildrenByTagName(exception, GSXML.GROUP_ELEM);
403 for (int j = 0; j < groups.getLength(); j++)
404 {
405 Element group = (Element) groups.item(j);
406 String groupName = group.getAttribute(GSXML.NAME_ATT);
407 exceptionGroups.add(groupName);
408 }
409 NodeList docSets = GSXML.getChildrenByTagName(exception, GSXML.DOCUMENT_SET_ELEM);
410 for (int j = 0; j < docSets.getLength(); j++)
411 {
412 Element docSet = (Element) docSets.item(j);
413 String docSetName = docSet.getAttribute(GSXML.NAME_ATT);
414 exceptionSets.add(docSetName);
415 }
416 if (_securityScopeCollection) {
417 // we don't add in any exceptions that have document sets
418 if (!exceptionSets.isEmpty()) {
419 continue;
420 }
421 }
422 securityException.put("groups", exceptionGroups);
423 securityException.put("sets", exceptionSets);
424 _securityExceptions.add(securityException);
425 }
426 }
427 }
428
429 protected boolean configureServiceRacks(Element coll_config_xml, Element build_config_xml)
430 {
431 clearServices();
432 Element service_list = (Element) GSXML.getChildByTagName(build_config_xml, GSXML.SERVICE_CLASS_ELEM + GSXML.LIST_MODIFIER);
433 if (service_list != null)
434 {
435 configureServiceRackList(service_list, coll_config_xml);
436 }
437 // collection Config may also contain manually added service racks
438 service_list = (Element) GSXML.getChildByTagName(coll_config_xml, GSXML.SERVICE_CLASS_ELEM + GSXML.LIST_MODIFIER);
439 if (service_list != null)
440 {
441 configureServiceRackList(service_list, build_config_xml);
442 }
443 return true;
444 }
445
446 /**
447 * do a configure on only part of the collection
448 */
449 protected boolean configureSubset(String subset)
450 {
451
452 // need the coll config files
453 Element coll_config_elem = loadCollConfigFile();
454 Element build_config_elem = loadBuildConfigFile();
455 if (coll_config_elem == null || build_config_elem == null)
456 {
457 // wont be able to do any of the requests
458 return false;
459 }
460
461 if (subset.equals(GSXML.SERVICE_ELEM + GSXML.LIST_MODIFIER))
462 {
463 return configureServiceRacks(coll_config_elem, build_config_elem);
464 }
465
466 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))
467 {
468 configureLocalData(coll_config_elem);
469 configureLocalData(build_config_elem);
470 return findAndLoadInfo(coll_config_elem, build_config_elem);
471
472 }
473
474 logger.error("Collection: cant process system request, configure " + subset);
475 return false;
476 }
477
478 /**
479 * handles requests made to the ServiceCluster itself
480 *
481 * @param req
482 * - the request Element- <request>
483 * @return the result Element - should be <response>
484 */
485 protected Element processMessage(Document result_doc, Element request)
486 {
487 String type = request.getAttribute(GSXML.TYPE_ATT);
488 if (type.equals(GSXML.REQUEST_TYPE_FORMAT_STRING))
489 {
490 return processFormatStringRequest(result_doc, request);
491 }
492 else if (type.equals(GSXML.REQUEST_TYPE_SECURITY))
493 {
494 return processSecurityRequest(result_doc, request);
495 }
496 else if (type.equals(GSXML.REQUEST_TYPE_FORMAT))
497 {
498
499 Element response = result_doc.createElement(GSXML.RESPONSE_ELEM);
500 response.setAttribute(GSXML.FROM_ATT, this.cluster_name);
501 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_FORMAT);
502 if (_globalFormat != null)
503 {
504 response.appendChild(result_doc.importNode(_globalFormat, true));
505 }
506 return response;
507 }
508 // unknown type
509 return super.processMessage(result_doc, request);
510
511 }
512
513 protected Element processSecurityRequest(Document result_doc, Element request)
514 {
515 Element response = result_doc.createElement(GSXML.RESPONSE_ELEM);
516 response.setAttribute(GSXML.FROM_ATT, this.cluster_name);
517 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_SECURITY);
518
519 if (_humanVerify) {
520 response.setAttribute("humanVerify", "true");
521 if (_useRecaptcha) {
522 response.setAttribute("siteKey", _siteKey);
523 response.setAttribute("secretKey", _secretKey);
524 }
525 }
526 String oid = request.getAttribute("oid");
527 if (oid.contains("."))
528 {
529 oid = oid.substring(0, oid.indexOf("."));
530 }
531
532 ArrayList<String> groups = getPermittedGroups(oid);
533
534 Element groupList = result_doc.createElement(GSXML.GROUP_ELEM + GSXML.LIST_MODIFIER);
535 response.appendChild(groupList);
536
537 for (String groupName : groups)
538 {
539 Element group = result_doc.createElement(GSXML.GROUP_ELEM);
540 groupList.appendChild(group);
541 group.setAttribute(GSXML.NAME_ATT, groupName);
542 }
543 return response;
544 }
545
546 protected ArrayList<String> getPermittedGroups(String oid)
547 {
548 ArrayList<String> groups = new ArrayList<String>();
549
550 if (_securityScopeCollection)
551 {
552 if (_publicAccess)
553 {
554 groups.add("");
555 }
556 else
557 {
558 for (HashMap<String, ArrayList<String>> exception : _securityExceptions)
559 {
560 for (String group : exception.get("groups"))
561 {
562 groups.add(group);
563 }
564 }
565 }
566 }
567 else
568 {
569 if (oid != null && !oid.equals(""))
570 {
571 boolean inSet = false;
572 for (HashMap<String, ArrayList<String>> exception : _securityExceptions) {
573
574 ArrayList<String> exceptionSets = exception.get("sets");
575 if (exceptionSets.size() == 0) {
576 inSet = true;
577 for (String group : exception.get("groups"))
578 {
579 groups.add(group);
580 }
581 }
582 else {
583 for (String setName : exception.get("sets"))
584 {
585 if (documentIsInSet(oid, setName))
586 {
587 inSet = true;
588 for (String group : exception.get("groups"))
589 {
590 groups.add(group);
591 }
592 break;
593 }
594 }
595 }
596 }
597
598
599
600 if (!inSet && _publicAccess)
601 {// our doc was not part of any exception, so it must be public
602 groups.add("");
603 }
604 }
605 else // if we are not doing a request with an oid, then free to access
606 {
607 groups.add("");
608 }
609 }
610
611 return groups;
612 }
613
614 protected boolean documentIsInSet(String oid, String setName)
615 {
616 ArrayList<Element> matchStatements = _documentSets.get(setName);
617 if (matchStatements == null || matchStatements.size() == 0)
618 {
619 return false;
620 }
621
622 for (Element currentMatchStatement : matchStatements)
623 {
624 String fieldName = currentMatchStatement.getAttribute(GSXML.FIELD_ATT);
625 if (fieldName == null || fieldName.equals(""))
626 {
627 fieldName = "oid";
628 }
629
630 String type = currentMatchStatement.getAttribute(GSXML.TYPE_ATT);
631 if (type == null || type.equals(""))
632 {
633 type = "match";
634 }
635
636 String fieldValue = "";
637 if (!fieldName.equals("oid"))
638 {
639 fieldValue = getFieldValue(oid, fieldName);
640 if (fieldValue == null)
641 {
642 return false;
643 }
644 }
645 else
646 {
647 fieldValue = oid;
648 }
649
650 String matchValue = GSXML.getNodeText(currentMatchStatement);
651 if (type.equals("match"))
652 {
653 if (matchValue.equals(fieldValue))
654 {
655 return true;
656 }
657 }
658 else if (type.equals("regex"))
659 {
660 if (fieldValue.matches(matchValue))
661 {
662 return true;
663 }
664 }
665 else
666 {
667 logger.warn("Unknown type of match specified in security block of collection " + this.cluster_name + ".");
668 }
669 }
670
671 return false;
672 }
673
674 protected String getFieldValue(String oid, String fieldName)
675 {
676 Document msg_doc = XMLConverter.newDOM();
677 Element metadataMessage = msg_doc.createElement(GSXML.MESSAGE_ELEM);
678 Element metadataRequest = GSXML.createBasicRequest(msg_doc, GSXML.REQUEST_TYPE_PROCESS, this.cluster_name + "/DocumentMetadataRetrieve", new UserContext());
679 metadataMessage.appendChild(metadataRequest);
680
681 Element paramList = msg_doc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
682 metadataRequest.appendChild(paramList);
683
684 Element param = msg_doc.createElement(GSXML.PARAM_ELEM);
685 paramList.appendChild(param);
686
687 param.setAttribute(GSXML.NAME_ATT, "metadata");
688 param.setAttribute(GSXML.VALUE_ATT, fieldName);
689
690 Element docList = msg_doc.createElement(GSXML.DOC_NODE_ELEM + GSXML.LIST_MODIFIER);
691 metadataRequest.appendChild(docList);
692
693 Element doc = msg_doc.createElement(GSXML.DOC_NODE_ELEM);
694 docList.appendChild(doc);
695
696 doc.setAttribute(GSXML.NODE_ID_ATT, oid);
697
698 Element response = (Element) this.router.process(metadataMessage);
699 NodeList metadataElems = response.getElementsByTagName(GSXML.METADATA_ELEM);
700
701 if (metadataElems.getLength() > 0)
702 {
703 Element metadata = (Element) metadataElems.item(0);
704 return GSXML.getNodeText(metadata);
705 }
706
707 return null;
708 }
709
710 protected Element processFormatStringRequest(Document result_doc, Element request)
711 {
712 Element response = result_doc.createElement(GSXML.RESPONSE_ELEM);
713 response.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_FORMAT_STRING);
714 response.setAttribute(GSXML.FROM_ATT, this.cluster_name);
715
716 String subaction = request.getAttribute("subaction");
717 String service = request.getAttribute("service");
718
719 String classifier = null;
720 if (service.equals("ClassifierBrowse"))
721 {
722 classifier = request.getAttribute("classifier");
723 }
724
725 // check for version file
726 String directory = new File(GSFile.collectionConfigFile(this.site_home, this.cluster_name)).getParent() + File.separator;
727
728 String version_filename = "";
729 if (service.equals("ClassifierBrowse"))
730 version_filename = directory + "browse_" + classifier + "_format_statement_version.txt";
731 else
732 version_filename = directory + "query_format_statement_version.txt";
733
734 File version_file = new File(version_filename);
735
736 if (subaction.equals("update"))
737 {
738 Element format_element = (Element) GSXML.getChildByTagName(request, GSXML.FORMAT_STRING_ELEM);
739 //String format_string = GSXML.getNodeText(format_element);
740 Element format_statement = (Element) format_element.getFirstChild();
741
742 String version_number = "1";
743 BufferedWriter writer;
744
745 try
746 {
747
748 if (version_file.exists())
749 {
750 // Read version
751 BufferedReader reader = new BufferedReader(new FileReader(version_filename));
752 version_number = reader.readLine();
753 int aInt = Integer.parseInt(version_number) + 1;
754 version_number = Integer.toString(aInt);
755 reader.close();
756 }
757 else
758 {
759 // Create
760 version_file.createNewFile();
761 writer = new BufferedWriter(new FileWriter(version_filename));
762 writer.write(version_number);
763 writer.close();
764 }
765
766 // Write version file
767 String format_statement_filename = "";
768
769 if (service.equals("ClassifierBrowse"))
770 format_statement_filename = directory + "browse_" + classifier + "_format_statement_v" + version_number + ".txt";
771 else
772 format_statement_filename = directory + "query_format_statement_v" + version_number + ".txt";
773
774 // Write format statement
775 String format_string = this.converter.getString(format_statement); //GSXML.xmlNodeToString(format_statement);
776 writer = new BufferedWriter(new FileWriter(format_statement_filename));
777 writer.write(format_string);
778 writer.close();
779
780 // Update version number
781 writer = new BufferedWriter(new FileWriter(version_filename));
782 writer.write(version_number);
783 writer.close();
784
785 }
786 catch (IOException e)
787 {
788 logger.error("IO Exception " + e);
789 }
790 }
791
792 if (subaction.equals("saveDocument"))
793 {
794 Element format_element = (Element) GSXML.getChildByTagName(request, GSXML.FORMAT_STRING_ELEM);
795 //String format_string = GSXML.getNodeText(format_element);
796 // Get display tag
797 Element display_format = (Element) format_element.getFirstChild();
798
799 String collection_config = directory + "collectionConfig.xml";
800 Document config = this.converter.getDOM(new File(collection_config), "UTF-8");
801
802 Node current_node = GSXML.getChildByTagName(config, "CollectionConfig");
803
804 // Get display child
805 if (GSXML.getChildByTagName(current_node, "display") == null)
806 {
807 // well then create a format tag
808 Element display_tag = config.createElement("display");
809 current_node = (Node) current_node.appendChild(display_tag);
810 }
811 else
812 {
813 current_node = GSXML.getChildByTagName(current_node, "display");
814 }
815
816 if (GSXML.getChildByTagName(current_node, "format") == null)
817 {
818 // well then create a format tag
819 Element format_tag = config.createElement("format");
820 current_node.appendChild(format_tag);
821 }
822
823 current_node.replaceChild(config.importNode(display_format, true), GSXML.getChildByTagName(current_node, "format"));
824
825 String new_config = this.converter.getString(config);
826
827 new_config = StringUtils.replace(new_config, "&lt;", "<");
828 new_config = StringUtils.replace(new_config, "&gt;", ">");
829 new_config = StringUtils.replace(new_config, "&quot;", "\"");
830
831 try
832 {
833 // Write to file (not original! for now)
834 BufferedWriter writer = new BufferedWriter(new FileWriter(collection_config + ".new"));
835 writer.write(new_config);
836 writer.close();
837 }
838 catch (IOException e)
839 {
840 logger.error("IO Exception " + e);
841 }
842 }
843
844 if (subaction.equals("save"))
845 {
846 Element format_element = (Element) GSXML.getChildByTagName(request, GSXML.FORMAT_STRING_ELEM);
847 Element format_statement = (Element) format_element.getFirstChild();
848
849 try
850 {
851 // open collectionConfig.xml and read in to w3 Document
852 String collection_config = directory + "collectionConfig.xml";
853 Document config = this.converter.getDOM(new File(collection_config), "UTF-8");
854
855 //String tag_name = "";
856 int k;
857 int index;
858 Element elem;
859 Node current_node = GSXML.getChildByTagName(config, "CollectionConfig");
860 NodeList current_node_list;
861
862 if (service.equals("ClassifierBrowse"))
863 {
864 //tag_name = "browse";
865 // if CLX then need to look in <classifier> X then <format>
866 // default is <browse><format>
867
868 current_node = GSXML.getChildByTagName(current_node, "browse");
869
870 // find CLX
871 if (classifier != null)
872 {
873 current_node_list = GSXML.getChildrenByTagName(current_node, "classifier");
874 index = Integer.parseInt(classifier.substring(2)) - 1;
875
876 // index should be given by X-1
877 current_node = current_node_list.item(index);
878 // what if classifier does not have a format tag?
879 if (GSXML.getChildByTagName(current_node, "format") == null)
880 {
881 // well then create a format tag
882 Element format_tag = config.createElement("format");
883 current_node.appendChild(format_tag);
884 }
885 }
886 else
887 {
888 // To support all classifiers, set classifier to null? There is the chance here that the format tag does not exist
889 if (GSXML.getChildByTagName(current_node, "format") == null)
890 {
891 // well then create a format tag
892 Element format_tag = config.createElement("format");
893 current_node.appendChild(format_tag);
894 }
895 }
896 }
897 else if (service.equals("AllClassifierBrowse"))
898 {
899 current_node = GSXML.getChildByTagName(current_node, "browse");
900 if (GSXML.getChildByTagName(current_node, "format") == null)
901 {
902 // well then create a format tag
903 Element format_tag = config.createElement("format");
904 current_node.appendChild(format_tag);
905 }
906 }
907 else
908 {
909 // look in <format> with no attributes
910 current_node_list = GSXML.getChildrenByTagName(current_node, "search");
911 for (k = 0; k < current_node_list.getLength(); k++)
912 {
913 current_node = current_node_list.item(k);
914 // if current_node has no attributes then break
915 elem = (Element) current_node;
916 if (elem.hasAttribute("name") == false)
917 break;
918 }
919 }
920
921 current_node.replaceChild(config.importNode(format_statement, true), GSXML.getChildByTagName(current_node, "format"));
922
923 // Now convert config document to string for writing to file
924 String new_config = this.converter.getString(config);
925
926 new_config = StringUtils.replace(new_config, "&lt;", "<");
927 new_config = StringUtils.replace(new_config, "&gt;", ">");
928 new_config = StringUtils.replace(new_config, "&quot;", "\"");
929
930 // Write to file (not original! for now)
931 BufferedWriter writer = new BufferedWriter(new FileWriter(collection_config + ".new"));
932 writer.write(new_config);
933 writer.close();
934
935 }
936 catch (Exception ex)
937 {
938 logger.error("There was an exception " + ex);
939
940 StringWriter sw = new StringWriter();
941 PrintWriter pw = new PrintWriter(sw, true);
942 ex.printStackTrace(pw);
943 pw.flush();
944 sw.flush();
945 logger.error(sw.toString());
946 }
947
948 }
949
950 return response;
951 }
952
953
954}
Note: See TracBrowser for help on using the repository browser.