forked from eXist-db/exist
/
Configuration.java
1725 lines (1355 loc) · 73.2 KB
/
Configuration.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* eXist Open Source Native XML Database
* Copyright (C) 2001-2016 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.backup.SystemExport;
import org.exist.repo.Deployment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.exist.Indexer;
import org.exist.indexing.IndexManager;
import org.exist.dom.memtree.SAXAdapter;
import org.exist.scheduler.JobConfig;
import org.exist.scheduler.JobException;
import org.exist.security.internal.RealmImpl;
import org.exist.storage.BrokerFactory;
import org.exist.storage.BrokerPool;
import org.exist.storage.CollectionCacheManager;
import org.exist.storage.DBBroker;
import org.exist.storage.DefaultCacheManager;
import org.exist.storage.IndexSpec;
import org.exist.storage.NativeBroker;
import org.exist.storage.NativeValueIndex;
import org.exist.storage.XQueryPool;
import org.exist.storage.journal.Journal;
import org.exist.storage.serializers.CustomMatchListenerFactory;
import org.exist.storage.serializers.Serializer;
import org.exist.storage.txn.TransactionManager;
import org.exist.validation.GrammarPool;
import org.exist.validation.resolver.eXistXMLCatalogResolver;
import org.exist.xmldb.DatabaseImpl;
import org.exist.xquery.FunctionFactory;
import org.exist.xquery.PerformanceStats;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.XQueryWatchDog;
import org.exist.xslt.TransformerFactoryAllocator;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.Map.Entry;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.exist.Namespaces;
import org.exist.scheduler.JobType;
import org.exist.xquery.Module;
public class Configuration implements ErrorHandler
{
private final static Logger LOG = LogManager.getLogger(Configuration.class); //Logger
protected Optional<Path> configFilePath = Optional.empty();
protected Optional<Path> existHome = Optional.empty();
protected DocumentBuilder builder = null;
protected HashMap<String, Object> config = new HashMap<>(); //Configuration
private static final String XQUERY_CONFIGURATION_ELEMENT_NAME = "xquery";
private static final String XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULES_ELEMENT_NAME = "builtin-modules";
private static final String XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULE_ELEMENT_NAME = "module";
public final static String BINARY_CACHE_CLASS_PROPERTY = "binary.cache.class";
public Configuration() throws DatabaseConfigurationException {
this(DatabaseImpl.CONF_XML, Optional.empty());
}
public Configuration(final String configFilename) throws DatabaseConfigurationException {
this(configFilename, Optional.empty());
}
public Configuration(String configFilename, Optional<Path> existHomeDirname) throws DatabaseConfigurationException {
InputStream is = null;
try {
if(configFilename == null) {
// Default file name
configFilename = DatabaseImpl.CONF_XML;
}
// firstly, try to read the configuration from a file within the
// classpath
try {
is = Configuration.class.getClassLoader().getResourceAsStream(configFilename);
if(is != null) {
LOG.info("Reading configuration from classloader");
}
} catch(final Exception e) {
// EB: ignore and go forward, e.g. in case there is an absolute
// file name for configFileName
LOG.debug( e );
}
// otherwise, secondly try to read configuration from file. Guess the
// location if necessary
if(is == null) {
existHome = existHomeDirname.map(Optional::of).orElse(ConfigurationHelper.getExistHome(configFilename));
if(!existHome.isPresent()) {
// EB: try to create existHome based on location of config file
// when config file points to absolute file location
final Path absoluteConfigFile = Paths.get(configFilename);
if(absoluteConfigFile.isAbsolute() && Files.exists(absoluteConfigFile) && Files.isReadable(absoluteConfigFile)) {
existHome = Optional.of(absoluteConfigFile.getParent());
configFilename = FileUtils.fileName(absoluteConfigFile);
}
}
Path configFile = Paths.get(configFilename);
if(!configFile.isAbsolute() && existHome.isPresent()) {
// try the passed or constructed existHome first
configFile = existHome.get().resolve(configFilename);
}
//if( configFile == null ) {
// configFile = ConfigurationHelper.lookup( configFilename );
//}
if(!Files.exists(configFile) || !Files.isReadable(configFile)) {
throw new DatabaseConfigurationException("Unable to read configuration file at " + configFile);
}
configFilePath = Optional.of(configFile.toAbsolutePath());
is = Files.newInputStream(configFile);
// set dbHome to parent of the conf file found, to resolve relative
// path from conf file
existHomeDirname = Optional.of(configFile.getParent());
LOG.info("Reading configuration from file " + configFile);
}
// initialize xml parser
// we use eXist's in-memory DOM implementation to work
// around a bug in Xerces
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware( true );
// factory.setFeature("http://apache.org/xml/features/validation/schema", true);
// factory.setFeature("http://apache.org/xml/features/validation/dynamic", true);
final InputSource src = new InputSource(is);
final SAXParser parser = factory.newSAXParser();
final XMLReader reader = parser.getXMLReader();
final SAXAdapter adapter = new SAXAdapter();
reader.setContentHandler(adapter);
reader.parse(src);
final Document doc = adapter.getDocument();
//indexer settings
final NodeList indexers = doc.getElementsByTagName(Indexer.CONFIGURATION_ELEMENT_NAME);
if(indexers.getLength() > 0) {
configureIndexer( existHomeDirname, doc, (Element)indexers.item( 0 ) );
}
//scheduler settings
final NodeList schedulers = doc.getElementsByTagName(JobConfig.CONFIGURATION_ELEMENT_NAME);
if(schedulers.getLength() > 0) {
configureScheduler((Element)schedulers.item(0));
}
//db connection settings
final NodeList dbcon = doc.getElementsByTagName(BrokerPool.CONFIGURATION_CONNECTION_ELEMENT_NAME);
if(dbcon.getLength() > 0) {
configureBackend(existHomeDirname, (Element)dbcon.item(0));
}
final NodeList repository = doc.getElementsByTagName("repository");
if(repository.getLength() > 0) {
configureRepository((Element) repository.item(0));
}
final NodeList binaryManager = doc.getElementsByTagName("binary-manager");
if(binaryManager.getLength() > 0) {
configureBinaryManager((Element)binaryManager.item(0));
}
//transformer settings
final NodeList transformers = doc.getElementsByTagName(TransformerFactoryAllocator.CONFIGURATION_ELEMENT_NAME);
if( transformers.getLength() > 0 ) {
configureTransformer((Element)transformers.item(0));
}
//parser settings
final NodeList parsers = doc.getElementsByTagName(HtmlToXmlParser.PARSER_ELEMENT_NAME);
if(parsers.getLength() > 0) {
configureParser((Element)parsers.item(0));
}
//serializer settings
final NodeList serializers = doc.getElementsByTagName(Serializer.CONFIGURATION_ELEMENT_NAME);
if(serializers.getLength() > 0) {
configureSerializer((Element)serializers.item(0));
}
//XUpdate settings
final NodeList xupdates = doc.getElementsByTagName(DBBroker.CONFIGURATION_ELEMENT_NAME);
if(xupdates.getLength() > 0) {
configureXUpdate((Element)xupdates.item(0));
}
//XQuery settings
final NodeList xquery = doc.getElementsByTagName(XQUERY_CONFIGURATION_ELEMENT_NAME);
if(xquery.getLength() > 0) {
configureXQuery((Element)xquery.item(0));
}
//Validation
final NodeList validations = doc.getElementsByTagName(XMLReaderObjectFactory.CONFIGURATION_ELEMENT_NAME);
if(validations.getLength() > 0) {
configureValidation(existHomeDirname, doc, (Element)validations.item(0));
}
}
catch(final SAXException | IOException | ParserConfigurationException e) {
LOG.error("error while reading config file: " + configFilename, e);
throw new DatabaseConfigurationException(e.getMessage(), e);
} finally {
if(is != null) {
try {
is.close();
} catch(final IOException ioe) {
LOG.error(ioe);
}
}
}
}
private void configureRepository(Element element) {
String root = element.getAttribute("root");
if (root != null && root.length() > 0) {
if (!root.endsWith("/"))
{root += "/";}
config.put(Deployment.PROPERTY_APP_ROOT, root);
}
}
private void configureBinaryManager(Element binaryManager) throws DatabaseConfigurationException {
final NodeList nlCache = binaryManager.getElementsByTagName("cache");
if(nlCache.getLength() > 0) {
final Element cache = (Element)nlCache.item(0);
final String binaryCacheClass = cache.getAttribute("class");
config.put(BINARY_CACHE_CLASS_PROPERTY, binaryCacheClass);
LOG.debug(BINARY_CACHE_CLASS_PROPERTY + ": " + config.get(BINARY_CACHE_CLASS_PROPERTY));
}
}
private void configureXQuery( Element xquery ) throws DatabaseConfigurationException
{
//java binding
final String javabinding = getConfigAttributeValue( xquery, FunctionFactory.ENABLE_JAVA_BINDING_ATTRIBUTE );
if( javabinding != null ) {
config.put( FunctionFactory.PROPERTY_ENABLE_JAVA_BINDING, javabinding );
LOG.debug( FunctionFactory.PROPERTY_ENABLE_JAVA_BINDING + ": " + config.get( FunctionFactory.PROPERTY_ENABLE_JAVA_BINDING ) );
}
final String disableDeprecated = getConfigAttributeValue( xquery, FunctionFactory.DISABLE_DEPRECATED_FUNCTIONS_ATTRIBUTE );
config.put( FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS, Configuration.parseBoolean( disableDeprecated, FunctionFactory.DISABLE_DEPRECATED_FUNCTIONS_BY_DEFAULT ) );
LOG.debug( FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS + ": " + config.get( FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS ) );
final String optimize = getConfigAttributeValue( xquery, XQueryContext.ENABLE_QUERY_REWRITING_ATTRIBUTE );
if( ( optimize != null ) && ( optimize.length() > 0 ) ) {
config.put( XQueryContext.PROPERTY_ENABLE_QUERY_REWRITING, optimize );
LOG.debug( XQueryContext.PROPERTY_ENABLE_QUERY_REWRITING + ": " + config.get( XQueryContext.PROPERTY_ENABLE_QUERY_REWRITING ) );
}
final String enforceIndexUse = getConfigAttributeValue( xquery, XQueryContext.ENFORCE_INDEX_USE_ATTRIBUTE );
if (enforceIndexUse != null) {
config.put( XQueryContext.PROPERTY_ENFORCE_INDEX_USE, enforceIndexUse );
}
final String backwardCompatible = getConfigAttributeValue( xquery, XQueryContext.XQUERY_BACKWARD_COMPATIBLE_ATTRIBUTE );
if( ( backwardCompatible != null ) && ( backwardCompatible.length() > 0 ) ) {
config.put( XQueryContext.PROPERTY_XQUERY_BACKWARD_COMPATIBLE, backwardCompatible );
LOG.debug( XQueryContext.PROPERTY_XQUERY_BACKWARD_COMPATIBLE + ": " + config.get( XQueryContext.PROPERTY_XQUERY_BACKWARD_COMPATIBLE ) );
}
final String raiseErrorOnFailedRetrieval = getConfigAttributeValue( xquery, XQueryContext.XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL_ATTRIBUTE );
config.put( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL, Configuration.parseBoolean( raiseErrorOnFailedRetrieval, XQueryContext.XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL_DEFAULT ) );
LOG.debug( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL + ": " + config.get( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL ) );
final String trace = getConfigAttributeValue( xquery, PerformanceStats.CONFIG_ATTR_TRACE );
config.put( PerformanceStats.CONFIG_PROPERTY_TRACE, trace );
// built-in-modules
final Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
final Map<String, String> knownMappings = new HashMap<String, String>();
final Map<String, Map<String, List<? extends Object>>> moduleParameters = new HashMap<String, Map<String, List<? extends Object>>>();
loadModuleClasses(xquery, classMap, knownMappings, moduleParameters);
config.put( XQueryContext.PROPERTY_BUILT_IN_MODULES, classMap);
config.put( XQueryContext.PROPERTY_STATIC_MODULE_MAP, knownMappings);
config.put( XQueryContext.PROPERTY_MODULE_PARAMETERS, moduleParameters);
}
/**
* Read list of built-in modules from the configuration. This method will only make sure
* that the specified module class exists and is a subclass of {@link org.exist.xquery.Module}.
*
* @param xquery configuration root
* @param modulesClassMap map containing all classes of modules
* @param modulesSourceMap map containing all source uris to external resources
*
* @throws DatabaseConfigurationException
*/
private void loadModuleClasses( Element xquery, Map<String, Class<?>> modulesClassMap, Map<String, String> modulesSourceMap, Map<String, Map<String, List<? extends Object>>> moduleParameters) throws DatabaseConfigurationException {
// add the standard function module
modulesClassMap.put(Namespaces.XPATH_FUNCTIONS_NS, org.exist.xquery.functions.fn.FnModule.class);
// add other modules specified in configuration
final NodeList builtins = xquery.getElementsByTagName(XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULES_ELEMENT_NAME);
// search under <builtin-modules>
if(builtins.getLength() > 0) {
Element elem = (Element)builtins.item(0);
final NodeList modules = elem.getElementsByTagName(XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULE_ELEMENT_NAME);
if(modules.getLength() > 0) {
// iterate over all <module src= uri= class=> entries
for(int i = 0; i < modules.getLength(); i++) {
// Get element.
elem = (Element)modules.item(i);
// Get attributes uri class and src
final String uri = elem.getAttribute(XQueryContext.BUILT_IN_MODULE_URI_ATTRIBUTE);
final String clazz = elem.getAttribute(XQueryContext.BUILT_IN_MODULE_CLASS_ATTRIBUTE);
final String source = elem.getAttribute(XQueryContext.BUILT_IN_MODULE_SOURCE_ATTRIBUTE);
// uri attribute is the identifier and is always required
if(uri == null) {
throw(new DatabaseConfigurationException("element 'module' requires an attribute 'uri'" ));
}
// either class or source attribute must be present
if((clazz == null) && (source == null)) {
throw(new DatabaseConfigurationException("element 'module' requires either an attribute " + "'class' or 'src'" ));
}
if(source != null) {
// Store src attribute info
modulesSourceMap.put(uri, source);
if(LOG.isDebugEnabled()) {
LOG.debug( "Registered mapping for module '" + uri + "' to '" + source + "'");
}
} else {
// source class attribute info
// Get class of module
final Class<?> moduleClass = lookupModuleClass(uri, clazz);
// Store class if thw module class actually exists
if( moduleClass != null) {
modulesClassMap.put(uri, moduleClass);
}
if(LOG.isDebugEnabled()) {
LOG.debug("Configured module '" + uri + "' implemented in '" + clazz + "'");
}
}
//parse any module parameters
moduleParameters.put(uri, ParametersExtractor.extract(elem.getElementsByTagName(ParametersExtractor.PARAMETER_ELEMENT_NAME)));
}
}
}
}
/**
* Returns the Class object associated with the with the given module class name. All
* important exceptions are caught. @see org.exist.xquery.Module
*
* @param uri namespace of class. For logging purposes only.
* @param clazz the fully qualified name of the desired module class.
* @return the module Class object for the module with the specified name.
* @throws DatabaseConfigurationException if the given module class is not an instance
* of org.exist.xquery.Module
*/
private Class<?> lookupModuleClass(String uri, String clazz) throws DatabaseConfigurationException
{
Class<?> mClass = null;
try {
mClass = Class.forName( clazz );
if( !( Module.class.isAssignableFrom( mClass ) ) ) {
throw( new DatabaseConfigurationException( "Failed to load module: " + uri
+ ". Class " + clazz + " is not an instance of org.exist.xquery.Module." ) );
}
} catch( final ClassNotFoundException e ) {
// Note: can't throw an exception here since this would create
// problems with test cases and jar dependencies
LOG.error( "Configuration problem: class not found for module '" + uri
+ "' (ClassNotFoundException); class:'" + clazz
+ "'; message:'" + e.getMessage() + "'");
} catch( final NoClassDefFoundError e ) {
LOG.error( "Module " + uri + " could not be initialized due to a missing "
+ "dependancy (NoClassDefFoundError): " + e.getMessage(), e );
}
return mClass;
}
/**
* DOCUMENT ME!
*
* @param xupdate
*
* @throws NumberFormatException
*/
private void configureXUpdate( Element xupdate ) throws NumberFormatException
{
final String fragmentation = getConfigAttributeValue( xupdate, DBBroker.XUPDATE_FRAGMENTATION_FACTOR_ATTRIBUTE );
if( fragmentation != null ) {
config.put( DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR, Integer.valueOf(fragmentation) );
LOG.debug( DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR + ": " + config.get( DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR ) );
}
final String consistencyCheck = getConfigAttributeValue( xupdate, DBBroker.XUPDATE_CONSISTENCY_CHECKS_ATTRIBUTE );
if( consistencyCheck != null ) {
config.put( DBBroker.PROPERTY_XUPDATE_CONSISTENCY_CHECKS, parseBoolean( consistencyCheck, false ) );
LOG.debug( DBBroker.PROPERTY_XUPDATE_CONSISTENCY_CHECKS + ": " + config.get( DBBroker.PROPERTY_XUPDATE_CONSISTENCY_CHECKS ) );
}
}
private void configureTransformer( Element transformer )
{
final String className = getConfigAttributeValue( transformer, TransformerFactoryAllocator.TRANSFORMER_CLASS_ATTRIBUTE );
if( className != null ) {
config.put( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_CLASS, className );
LOG.debug( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_CLASS + ": " + config.get( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_CLASS ) );
// Process any specified attributes that should be passed to the transformer factory
final NodeList attrs = transformer.getElementsByTagName( TransformerFactoryAllocator.CONFIGURATION_TRANSFORMER_ATTRIBUTE_ELEMENT_NAME );
final Hashtable<Object, Object> attributes = new Properties();
for( int a = 0; a < attrs.getLength(); a++ ) {
final Element attr = (Element)attrs.item( a );
final String name = attr.getAttribute( "name" );
final String value = attr.getAttribute( "value" );
final String type = attr.getAttribute( "type" );
if( ( name == null ) || ( name.length() == 0 ) ) {
LOG.warn( "Discarded invalid attribute for TransformerFactory: '" + className + "', name not specified" );
} else if( ( type == null ) || ( type.length() == 0 ) || type.equalsIgnoreCase( "string" ) ) {
attributes.put( name, value );
} else if( type.equalsIgnoreCase( "boolean" ) ) {
attributes.put( name, Boolean.valueOf( value ) );
} else if( type.equalsIgnoreCase( "integer" ) ) {
try {
attributes.put( name, Integer.valueOf( value ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Discarded invalid attribute for TransformerFactory: '" + className + "', name: " + name + ", value not integer: " + value, nfe);
}
} else {
// Assume string type
attributes.put( name, value );
}
}
config.put( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_ATTRIBUTES, attributes );
}
final String cachingValue = getConfigAttributeValue( transformer, TransformerFactoryAllocator.TRANSFORMER_CACHING_ATTRIBUTE );
if( cachingValue != null ) {
config.put( TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE, parseBoolean( cachingValue, false ) );
LOG.debug( TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE + ": " + config.get( TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE ) );
}
}
private void configureParser(final Element parser) {
configureXmlParser(parser);
configureHtmlToXmlParser(parser);
}
private void configureXmlParser(final Element parser) {
final NodeList nlXml = parser.getElementsByTagName(XMLReaderPool.XmlParser.XML_PARSER_ELEMENT);
if(nlXml.getLength() > 0) {
final Element xml = (Element)nlXml.item(0);
final NodeList nlFeatures = xml.getElementsByTagName(XMLReaderPool.XmlParser.XML_PARSER_FEATURES_ELEMENT);
if(nlFeatures.getLength() > 0) {
final Properties pFeatures = ParametersExtractor.parseFeatures(nlFeatures.item(0));
if(pFeatures != null) {
final Map<String, Boolean> features = new HashMap<>();
pFeatures.forEach((k,v) -> features.put(k.toString(), Boolean.valueOf(v.toString())));
config.put(XMLReaderPool.XmlParser.XML_PARSER_FEATURES_PROPERTY, features);
}
}
}
}
private void configureHtmlToXmlParser(final Element parser) {
final NodeList nlHtmlToXml = parser.getElementsByTagName(HtmlToXmlParser.HTML_TO_XML_PARSER_ELEMENT);
if(nlHtmlToXml.getLength() > 0) {
final Element htmlToXml = (Element)nlHtmlToXml.item(0);
final String htmlToXmlParserClass = getConfigAttributeValue(htmlToXml, HtmlToXmlParser.HTML_TO_XML_PARSER_CLASS_ATTRIBUTE);
config.put(HtmlToXmlParser.HTML_TO_XML_PARSER_PROPERTY, htmlToXmlParserClass);
final NodeList nlProperties = htmlToXml.getElementsByTagName(HtmlToXmlParser.HTML_TO_XML_PARSER_PROPERTIES_ELEMENT);
if(nlProperties.getLength() > 0) {
final Properties pProperties = ParametersExtractor.parseProperties(nlProperties.item(0));
if(pProperties != null) {
final Map<String, Object> properties = new HashMap<>();
pProperties.forEach((k,v) -> properties.put(k.toString(), v));
config.put(HtmlToXmlParser.HTML_TO_XML_PARSER_PROPERTIES_PROPERTY, properties);
}
}
final NodeList nlFeatures = htmlToXml.getElementsByTagName(HtmlToXmlParser.HTML_TO_XML_PARSER_FEATURES_ELEMENT);
if(nlFeatures.getLength() > 0) {
final Properties pFeatures = ParametersExtractor.parseFeatures(nlFeatures.item(0));
if(pFeatures != null) {
final Map<String, Boolean> features = new HashMap<>();
pFeatures.forEach((k,v) -> features.put(k.toString(), Boolean.valueOf(v.toString())));
config.put(HtmlToXmlParser.HTML_TO_XML_PARSER_FEATURES_PROPERTY, features);
}
}
}
}
/**
* DOCUMENT ME!
*
* @param serializer
*/
private void configureSerializer( Element serializer )
{
final String xinclude = getConfigAttributeValue( serializer, Serializer.ENABLE_XINCLUDE_ATTRIBUTE );
if( xinclude != null ) {
config.put( Serializer.PROPERTY_ENABLE_XINCLUDE, xinclude );
LOG.debug( Serializer.PROPERTY_ENABLE_XINCLUDE + ": " + config.get( Serializer.PROPERTY_ENABLE_XINCLUDE ) );
}
final String xsl = getConfigAttributeValue( serializer, Serializer.ENABLE_XSL_ATTRIBUTE );
if( xsl != null ) {
config.put( Serializer.PROPERTY_ENABLE_XSL, xsl );
LOG.debug( Serializer.PROPERTY_ENABLE_XSL + ": " + config.get( Serializer.PROPERTY_ENABLE_XSL ) );
}
final String indent = getConfigAttributeValue( serializer, Serializer.INDENT_ATTRIBUTE );
if( indent != null ) {
config.put( Serializer.PROPERTY_INDENT, indent );
LOG.debug( Serializer.PROPERTY_INDENT + ": " + config.get( Serializer.PROPERTY_INDENT ) );
}
final String compress = getConfigAttributeValue( serializer, Serializer.COMPRESS_OUTPUT_ATTRIBUTE );
if( compress != null ) {
config.put( Serializer.PROPERTY_COMPRESS_OUTPUT, compress );
LOG.debug( Serializer.PROPERTY_COMPRESS_OUTPUT + ": " + config.get( Serializer.PROPERTY_COMPRESS_OUTPUT ) );
}
final String internalId = getConfigAttributeValue( serializer, Serializer.ADD_EXIST_ID_ATTRIBUTE );
if( internalId != null ) {
config.put( Serializer.PROPERTY_ADD_EXIST_ID, internalId );
LOG.debug( Serializer.PROPERTY_ADD_EXIST_ID + ": " + config.get( Serializer.PROPERTY_ADD_EXIST_ID ) );
}
final String tagElementMatches = getConfigAttributeValue( serializer, Serializer.TAG_MATCHING_ELEMENTS_ATTRIBUTE );
if( tagElementMatches != null ) {
config.put( Serializer.PROPERTY_TAG_MATCHING_ELEMENTS, tagElementMatches );
LOG.debug( Serializer.PROPERTY_TAG_MATCHING_ELEMENTS + ": " + config.get( Serializer.PROPERTY_TAG_MATCHING_ELEMENTS ) );
}
final String tagAttributeMatches = getConfigAttributeValue( serializer, Serializer.TAG_MATCHING_ATTRIBUTES_ATTRIBUTE );
if( tagAttributeMatches != null ) {
config.put( Serializer.PROPERTY_TAG_MATCHING_ATTRIBUTES, tagAttributeMatches );
LOG.debug( Serializer.PROPERTY_TAG_MATCHING_ATTRIBUTES + ": " + config.get( Serializer.PROPERTY_TAG_MATCHING_ATTRIBUTES ) );
}
final NodeList nlFilters = serializer.getElementsByTagName( CustomMatchListenerFactory.CONFIGURATION_ELEMENT );
if( nlFilters != null ) {
final List<String> filters = new ArrayList<>(nlFilters.getLength());
for (int i = 0; i < nlFilters.getLength(); i++) {
final Element filterElem = (Element) nlFilters.item(i);
final String filterClass = filterElem.getAttribute(CustomMatchListenerFactory.CONFIGURATION_ATTR_CLASS);
if (filterClass != null) {
filters.add(filterClass);
LOG.debug(CustomMatchListenerFactory.CONFIG_MATCH_LISTENERS + ": " + filterClass);
} else {
LOG.warn("Configuration element " + CustomMatchListenerFactory.CONFIGURATION_ELEMENT + " needs an attribute 'class'");
}
}
config.put(CustomMatchListenerFactory.CONFIG_MATCH_LISTENERS, filters);
}
final NodeList backupFilters = serializer.getElementsByTagName( SystemExport.CONFIGURATION_ELEMENT );
if( backupFilters != null ) {
final List<String> filters = new ArrayList<>(backupFilters.getLength());
for (int i = 0; i < backupFilters.getLength(); i++) {
final Element filterElem = (Element) backupFilters.item(i);
final String filterClass = filterElem.getAttribute(CustomMatchListenerFactory.CONFIGURATION_ATTR_CLASS);
if (filterClass != null) {
filters.add(filterClass);
LOG.debug(CustomMatchListenerFactory.CONFIG_MATCH_LISTENERS + ": " + filterClass);
} else {
LOG.warn("Configuration element " + SystemExport.CONFIGURATION_ELEMENT + " needs an attribute 'class'");
}
}
if (!filters.isEmpty()) config.put(SystemExport.CONFIG_FILTERS, filters);
}
}
/**
* Reads the scheduler configuration.
*
* @param scheduler DOCUMENT ME!
*/
private void configureScheduler(final Element scheduler)
{
final NodeList nlJobs = scheduler.getElementsByTagName(JobConfig.CONFIGURATION_JOB_ELEMENT_NAME);
if(nlJobs == null) {
return;
}
final List<JobConfig> jobList = new ArrayList<JobConfig>();
for(int i = 0; i < nlJobs.getLength(); i++) {
final Element job = (Element)nlJobs.item( i );
//get the job type
final String strJobType = getConfigAttributeValue(job, JobConfig.JOB_TYPE_ATTRIBUTE);
final JobType jobType;
if(strJobType == null) {
jobType = JobType.USER; //default to user if unspecified
} else {
jobType = JobType.valueOf(strJobType.toUpperCase(Locale.ENGLISH));
}
final String jobName = getConfigAttributeValue(job, JobConfig.JOB_NAME_ATTRIBUTE);
//get the job resource
String jobResource = getConfigAttributeValue(job, JobConfig.JOB_CLASS_ATTRIBUTE);
if(jobResource == null) {
jobResource = getConfigAttributeValue(job, JobConfig.JOB_XQUERY_ATTRIBUTE);
}
//get the job schedule
String jobSchedule = getConfigAttributeValue(job, JobConfig.JOB_CRON_TRIGGER_ATTRIBUTE);
if(jobSchedule == null) {
jobSchedule = getConfigAttributeValue(job, JobConfig.JOB_PERIOD_ATTRIBUTE);
}
final String jobUnschedule = getConfigAttributeValue(job, JobConfig.JOB_UNSCHEDULE_ON_EXCEPTION);
//create the job config
try {
final JobConfig jobConfig = new JobConfig(jobType, jobName, jobResource, jobSchedule, jobUnschedule);
//get and set the job delay
final String jobDelay = getConfigAttributeValue(job, JobConfig.JOB_DELAY_ATTRIBUTE);
if((jobDelay != null) && (jobDelay.length() > 0)) {
jobConfig.setDelay(Long.parseLong(jobDelay));
}
//get and set the job repeat
final String jobRepeat = getConfigAttributeValue(job, JobConfig.JOB_REPEAT_ATTRIBUTE);
if((jobRepeat != null) && (jobRepeat.length() > 0)) {
jobConfig.setRepeat(Integer.parseInt(jobRepeat));
}
final NodeList nlParam = job.getElementsByTagName(ParametersExtractor.PARAMETER_ELEMENT_NAME);
final Map<String, List<? extends Object>> params = ParametersExtractor.extract(nlParam);
for(final Entry<String, List<? extends Object>> param : params.entrySet()) {
final List<? extends Object> values = param.getValue();
if(values != null && values.size() > 0) {
jobConfig.addParameter(param.getKey(), values.get(0).toString());
if(values.size() > 1) {
LOG.warn("Parameter '" + param.getKey() + "' for job '" + jobName + "' has more than one value, ignoring further values.");
}
}
}
jobList.add(jobConfig);
LOG.debug("Configured scheduled '" + jobType + "' job '" + jobResource + ((jobSchedule == null) ? "" : ("' with trigger '" + jobSchedule)) + ((jobDelay == null) ? "" : ("' with delay '" + jobDelay)) + ((jobRepeat == null) ? "" : ("' repetitions '" + jobRepeat)) + "'");
} catch(final JobException je) {
LOG.error(je);
}
}
if(jobList.size() > 0 ) {
final JobConfig[] configs = new JobConfig[jobList.size()];
for(int i = 0; i < jobList.size(); i++) {
configs[i] = (JobConfig)jobList.get(i);
}
config.put(JobConfig.PROPERTY_SCHEDULER_JOBS, configs);
}
}
/**
* DOCUMENT ME!
*
* @param dbHome
* @param con
*
* @throws DatabaseConfigurationException
*/
private void configureBackend( final Optional<Path> dbHome, Element con ) throws DatabaseConfigurationException
{
final String mysql = getConfigAttributeValue( con, BrokerFactory.PROPERTY_DATABASE );
if( mysql != null ) {
config.put( BrokerFactory.PROPERTY_DATABASE, mysql );
LOG.debug( BrokerFactory.PROPERTY_DATABASE + ": " + config.get( BrokerFactory.PROPERTY_DATABASE ) );
}
// directory for database files
final String dataFiles = getConfigAttributeValue( con, BrokerPool.DATA_DIR_ATTRIBUTE );
if (dataFiles != null) {
final Path df = ConfigurationHelper.lookup( dataFiles, dbHome );
if (!Files.isReadable(df)) {
try {
Files.createDirectories(df);
} catch (final IOException ioe) {
throw new DatabaseConfigurationException("cannot read data directory: " + df.toAbsolutePath().toString(), ioe);
}
}
config.put(BrokerPool.PROPERTY_DATA_DIR, df.toAbsolutePath());
LOG.debug(BrokerPool.PROPERTY_DATA_DIR + ": " + config.get(BrokerPool.PROPERTY_DATA_DIR));
}
String cacheMem = getConfigAttributeValue( con, DefaultCacheManager.CACHE_SIZE_ATTRIBUTE );
if( cacheMem != null ) {
if( cacheMem.endsWith( "M" ) || cacheMem.endsWith( "m" ) ) {
cacheMem = cacheMem.substring( 0, cacheMem.length() - 1 );
}
try {
config.put( DefaultCacheManager.PROPERTY_CACHE_SIZE, Integer.valueOf(cacheMem) );
LOG.debug( DefaultCacheManager.PROPERTY_CACHE_SIZE + ": " + config.get( DefaultCacheManager.PROPERTY_CACHE_SIZE ) + "m" );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + DefaultCacheManager.PROPERTY_CACHE_SIZE + " value to integer: " + cacheMem, nfe);
}
}
// Process the Check Max Cache value
String checkMaxCache = getConfigAttributeValue( con, DefaultCacheManager.CACHE_CHECK_MAX_SIZE_ATTRIBUTE );
if( checkMaxCache == null ) {
checkMaxCache = DefaultCacheManager.DEFAULT_CACHE_CHECK_MAX_SIZE_STRING;
}
config.put( DefaultCacheManager.PROPERTY_CACHE_CHECK_MAX_SIZE, parseBoolean( checkMaxCache, true ) );
LOG.debug( DefaultCacheManager.PROPERTY_CACHE_CHECK_MAX_SIZE + ": " + config.get( DefaultCacheManager.PROPERTY_CACHE_CHECK_MAX_SIZE ) );
String cacheShrinkThreshold = getConfigAttributeValue( con, DefaultCacheManager.SHRINK_THRESHOLD_ATTRIBUTE );
if( cacheShrinkThreshold == null ) {
cacheShrinkThreshold = DefaultCacheManager.DEFAULT_SHRINK_THRESHOLD_STRING;
}
try {
config.put(DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY, Integer.valueOf(cacheShrinkThreshold));
LOG.debug(DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY + ": " + config.get(DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY));
} catch(final NumberFormatException nfe) {
LOG.warn("Cannot convert " + DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY + " value to integer: " + cacheShrinkThreshold, nfe);
}
String collectionCache = getConfigAttributeValue(con, CollectionCacheManager.CACHE_SIZE_ATTRIBUTE);
if(collectionCache != null) {
collectionCache = collectionCache.toLowerCase();
try {
final int collectionCacheBytes;
if(collectionCache.endsWith("k")) {
collectionCacheBytes = 1024 * Integer.valueOf(collectionCache.substring(0, collectionCache.length() - 1));
} else if(collectionCache.endsWith("kb")) {
collectionCacheBytes = 1024 * Integer.valueOf(collectionCache.substring(0, collectionCache.length() - 2));
} else if(collectionCache.endsWith("m")) {
collectionCacheBytes = 1024 * 1024 * Integer.valueOf(collectionCache.substring(0, collectionCache.length() - 1));
} else if(collectionCache.endsWith("mb")) {
collectionCacheBytes = 1024 * 1024 * Integer.valueOf(collectionCache.substring(0, collectionCache.length() - 2));
} else if(collectionCache.endsWith("g")) {
collectionCacheBytes = 1024 * 1024 * 1024 * Integer.valueOf(collectionCache.substring(0, collectionCache.length() - 1));
} else if(collectionCache.endsWith("gb")) {
collectionCacheBytes = 1024 * 1024 * 1024 * Integer.valueOf(collectionCache.substring(0, collectionCache.length() - 2));
} else {
collectionCacheBytes = Integer.valueOf(collectionCache);
}
config.put(CollectionCacheManager.PROPERTY_CACHE_SIZE_BYTES, collectionCacheBytes);
if(LOG.isDebugEnabled()) {
LOG.debug("Set config {} = {}", CollectionCacheManager.PROPERTY_CACHE_SIZE_BYTES, config.get(CollectionCacheManager.PROPERTY_CACHE_SIZE_BYTES));
}
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + CollectionCacheManager.PROPERTY_CACHE_SIZE_BYTES + " value to integer: " + collectionCache, nfe);
}
}
final String pageSize = getConfigAttributeValue( con, NativeBroker.PAGE_SIZE_ATTRIBUTE );
if( pageSize != null ) {
try {
config.put( BrokerPool.PROPERTY_PAGE_SIZE, Integer.valueOf(pageSize) );
LOG.debug( BrokerPool.PROPERTY_PAGE_SIZE + ": " + config.get( BrokerPool.PROPERTY_PAGE_SIZE ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + BrokerPool.PROPERTY_PAGE_SIZE + " value to integer: " + pageSize, nfe);
}
}
//Not clear : rather looks like a buffers count
final String collCacheSize = getConfigAttributeValue( con, BrokerPool.COLLECTION_CACHE_SIZE_ATTRIBUTE );
if( collCacheSize != null ) {
try {
config.put( BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE, Integer.valueOf(collCacheSize) );
LOG.debug( BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE + ": " + config.get( BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE + " value to integer: " + collCacheSize, nfe);
}
}
final String nodesBuffer = getConfigAttributeValue( con, BrokerPool.NODES_BUFFER_ATTRIBUTE );
if( nodesBuffer != null ) {
try {
config.put( BrokerPool.PROPERTY_NODES_BUFFER, Integer.valueOf(nodesBuffer) );
LOG.debug( BrokerPool.PROPERTY_NODES_BUFFER + ": " + config.get( BrokerPool.PROPERTY_NODES_BUFFER ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + BrokerPool.PROPERTY_NODES_BUFFER + " value to integer: " + nodesBuffer, nfe);
}
}
final String docIds = con.getAttribute(BrokerPool.DOC_ID_MODE_ATTRIBUTE);
if (docIds != null) {
config.put(BrokerPool.DOC_ID_MODE_PROPERTY, docIds);
}
//Unused !
final String buffers = getConfigAttributeValue( con, "buffers" );
if( buffers != null ) {
try {
config.put( "db-connection.buffers", Integer.valueOf(buffers) );
LOG.debug( "db-connection.buffers: " + config.get( "db-connection.buffers" ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + "db-connection.buffers" + " value to integer: " + buffers, nfe);
}
}
//Unused !
final String collBuffers = getConfigAttributeValue( con, "collection_buffers" );
if( collBuffers != null ) {
try {
config.put( "db-connection.collections.buffers", Integer.valueOf(collBuffers) );
LOG.debug( "db-connection.collections.buffers: " + config.get( "db-connection.collections.buffers" ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + "db-connection.collections.buffers" + " value to integer: " + collBuffers, nfe);
}
}
//Unused !
final String wordBuffers = getConfigAttributeValue( con, "words_buffers" );
if( wordBuffers != null ) {
try {
config.put( "db-connection.words.buffers", Integer.valueOf(wordBuffers) );
LOG.debug( "db-connection.words.buffers: " + config.get( "db-connection.words.buffers" ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + "db-connection.words.buffers" + " value to integer: " + wordBuffers, nfe);
}
}
//Unused !
final String elementBuffers = getConfigAttributeValue( con, "elements_buffers" );
if( elementBuffers != null ) {
try {
config.put( "db-connection.elements.buffers", Integer.valueOf(elementBuffers) );
LOG.debug( "db-connection.elements.buffers: " + config.get( "db-connection.elements.buffers" ) );
}
catch( final NumberFormatException nfe ) {
LOG.warn("Cannot convert " + "db-connection.elements.buffers" + " value to integer: " + elementBuffers, nfe);
}
}
String diskSpace = getConfigAttributeValue(con, BrokerPool.DISK_SPACE_MIN_ATTRIBUTE);
if( diskSpace != null ) {
if( diskSpace.endsWith( "M" ) || diskSpace.endsWith( "m" ) ) {