/
BaseHierarchicalConfiguration.java
1050 lines (976 loc) · 38.6 KB
/
BaseHierarchicalConfiguration.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.configuration2;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.configuration2.event.ConfigurationEvent;
import org.apache.commons.configuration2.event.EventListener;
import org.apache.commons.configuration2.ex.ConfigurationRuntimeException;
import org.apache.commons.configuration2.interpol.ConfigurationInterpolator;
import org.apache.commons.configuration2.tree.ConfigurationNodeVisitorAdapter;
import org.apache.commons.configuration2.tree.ImmutableNode;
import org.apache.commons.configuration2.tree.InMemoryNodeModel;
import org.apache.commons.configuration2.tree.InMemoryNodeModelSupport;
import org.apache.commons.configuration2.tree.NodeHandler;
import org.apache.commons.configuration2.tree.NodeModel;
import org.apache.commons.configuration2.tree.NodeSelector;
import org.apache.commons.configuration2.tree.NodeTreeWalker;
import org.apache.commons.configuration2.tree.QueryResult;
import org.apache.commons.configuration2.tree.ReferenceNodeHandler;
import org.apache.commons.configuration2.tree.TrackedNodeModel;
import org.apache.commons.lang3.ObjectUtils;
/**
* <p>
* A specialized hierarchical configuration implementation that is based on a
* structure of {@link ImmutableNode} objects.
* </p>
*
*/
public class BaseHierarchicalConfiguration extends AbstractHierarchicalConfiguration<ImmutableNode>
implements InMemoryNodeModelSupport
{
/** A listener for reacting on changes caused by sub configurations. */
private final EventListener<ConfigurationEvent> changeListener;
/**
* Creates a new instance of {@code BaseHierarchicalConfiguration}.
*/
public BaseHierarchicalConfiguration()
{
this((HierarchicalConfiguration<ImmutableNode>) null);
}
/**
* Creates a new instance of {@code BaseHierarchicalConfiguration} and
* copies all data contained in the specified configuration into the new
* one.
*
* @param c the configuration that is to be copied (if <b>null</b>, this
* constructor will behave like the standard constructor)
* @since 1.4
*/
public BaseHierarchicalConfiguration(final HierarchicalConfiguration<ImmutableNode> c)
{
this(createNodeModel(c));
}
/**
* Creates a new instance of {@code BaseHierarchicalConfiguration} and
* initializes it with the given {@code NodeModel}.
*
* @param model the {@code NodeModel}
*/
protected BaseHierarchicalConfiguration(final NodeModel<ImmutableNode> model)
{
super(model);
changeListener = createChangeListener();
}
/**
* {@inheritDoc} This implementation returns the {@code InMemoryNodeModel}
* used by this configuration.
*/
@Override
public InMemoryNodeModel getNodeModel()
{
return (InMemoryNodeModel) super.getNodeModel();
}
/**
* Creates a new {@code Configuration} object containing all keys
* that start with the specified prefix. This implementation will return a
* {@code BaseHierarchicalConfiguration} object so that the structure of
* the keys will be saved. The nodes selected by the prefix (it is possible
* that multiple nodes are selected) are mapped to the root node of the
* returned configuration, i.e. their children and attributes will become
* children and attributes of the new root node. However, a value of the root
* node is only set if exactly one of the selected nodes contain a value (if
* multiple nodes have a value, there is simply no way to decide how these
* values are merged together). Note that the returned
* {@code Configuration} object is not connected to its source
* configuration: updates on the source configuration are not reflected in
* the subset and vice versa. The returned configuration uses the same
* {@code Synchronizer} as this configuration.
*
* @param prefix the prefix of the keys for the subset
* @return a new configuration object representing the selected subset
*/
@Override
public Configuration subset(final String prefix)
{
beginRead(false);
try
{
final List<QueryResult<ImmutableNode>> results = fetchNodeList(prefix);
if (results.isEmpty())
{
return new BaseHierarchicalConfiguration();
}
final BaseHierarchicalConfiguration parent = this;
final BaseHierarchicalConfiguration result =
new BaseHierarchicalConfiguration()
{
// Override interpolate to always interpolate on the parent
@Override
protected Object interpolate(final Object value)
{
return parent.interpolate(value);
}
@Override
public ConfigurationInterpolator getInterpolator()
{
return parent.getInterpolator();
}
};
result.getModel().setRootNode(createSubsetRootNode(results));
if (result.isEmpty())
{
return new BaseHierarchicalConfiguration();
}
result.setSynchronizer(getSynchronizer());
return result;
}
finally
{
endRead();
}
}
/**
* Creates a root node for a subset configuration based on the passed in
* query results. This method creates a new root node and adds the children
* and attributes of all result nodes to it. If only a single node value is
* defined, it is assigned as value of the new root node.
*
* @param results the collection of query results
* @return the root node for the subset configuration
*/
private ImmutableNode createSubsetRootNode(
final Collection<QueryResult<ImmutableNode>> results)
{
final ImmutableNode.Builder builder = new ImmutableNode.Builder();
Object value = null;
int valueCount = 0;
for (final QueryResult<ImmutableNode> result : results)
{
if (result.isAttributeResult())
{
builder.addAttribute(result.getAttributeName(),
result.getAttributeValue(getModel().getNodeHandler()));
}
else
{
if (result.getNode().getValue() != null)
{
value = result.getNode().getValue();
valueCount++;
}
builder.addChildren(result.getNode().getChildren());
builder.addAttributes(result.getNode().getAttributes());
}
}
if (valueCount == 1)
{
builder.value(value);
}
return builder.create();
}
/**
* {@inheritDoc} The result of this implementation depends on the
* {@code supportUpdates} flag: If it is <b>false</b>, a plain
* {@code BaseHierarchicalConfiguration} is returned using the selected node
* as root node. This is suitable for read-only access to properties.
* Because the configuration returned in this case is not connected to the
* parent configuration, updates on properties made by one configuration are
* not reflected by the other one. A value of <b>true</b> for this parameter
* causes a tracked node to be created, and result is a
* {@link SubnodeConfiguration} based on this tracked node. This
* configuration is really connected to its parent, so that updated
* properties are visible on both.
*
* @see SubnodeConfiguration
* @throws ConfigurationRuntimeException if the key does not select a single
* node
*/
@Override
public HierarchicalConfiguration<ImmutableNode> configurationAt(final String key,
final boolean supportUpdates)
{
beginRead(false);
try
{
return supportUpdates ? createConnectedSubConfiguration(key)
: createIndependentSubConfiguration(key);
}
finally
{
endRead();
}
}
/**
* Returns the {@code InMemoryNodeModel} to be used as parent model for a
* new sub configuration. This method is called whenever a sub configuration
* is to be created. This base implementation returns the model of this
* configuration. Sub classes with different requirements for the parent
* models of sub configurations have to override it.
*
* @return the parent model for a new sub configuration
*/
protected InMemoryNodeModel getSubConfigurationParentModel()
{
return (InMemoryNodeModel) getModel();
}
/**
* Returns the {@code NodeSelector} to be used for a sub configuration based
* on the passed in key. This method is called whenever a sub configuration
* is to be created. This base implementation returns a new
* {@code NodeSelector} initialized with the passed in key. Sub classes may
* override this method if they have a different strategy for creating a
* selector.
*
* @param key the key of the sub configuration
* @return a {@code NodeSelector} for initializing a sub configuration
* @since 2.0
*/
protected NodeSelector getSubConfigurationNodeSelector(final String key)
{
return new NodeSelector(key);
}
/**
* Creates a connected sub configuration based on a selector for a tracked
* node.
*
* @param selector the {@code NodeSelector}
* @param parentModelSupport the {@code InMemoryNodeModelSupport} object for
* the parent node model
* @return the newly created sub configuration
* @since 2.0
*/
protected SubnodeConfiguration createSubConfigurationForTrackedNode(
final NodeSelector selector, final InMemoryNodeModelSupport parentModelSupport)
{
final SubnodeConfiguration subConfig =
new SubnodeConfiguration(this, new TrackedNodeModel(
parentModelSupport, selector, true));
initSubConfigurationForThisParent(subConfig);
return subConfig;
}
/**
* Initializes a {@code SubnodeConfiguration} object. This method should be
* called for each sub configuration created for this configuration. It
* ensures that the sub configuration is correctly connected to its parent
* instance and that update events are correctly propagated.
*
* @param subConfig the sub configuration to be initialized
* @since 2.0
*/
protected void initSubConfigurationForThisParent(final SubnodeConfiguration subConfig)
{
initSubConfiguration(subConfig);
subConfig.addEventListener(ConfigurationEvent.ANY, changeListener);
}
/**
* Creates a sub configuration from the specified key which is connected to
* this configuration. This implementation creates a
* {@link SubnodeConfiguration} with a tracked node identified by the passed
* in key.
*
* @param key the key of the sub configuration
* @return the new sub configuration
*/
private BaseHierarchicalConfiguration createConnectedSubConfiguration(
final String key)
{
final NodeSelector selector = getSubConfigurationNodeSelector(key);
getSubConfigurationParentModel().trackNode(selector, this);
return createSubConfigurationForTrackedNode(selector, this);
}
/**
* Creates a list of connected sub configurations based on a passed in list
* of node selectors.
*
* @param parentModelSupport the parent node model support object
* @param selectors the list of {@code NodeSelector} objects
* @return the list with sub configurations
*/
private List<HierarchicalConfiguration<ImmutableNode>> createConnectedSubConfigurations(
final InMemoryNodeModelSupport parentModelSupport,
final Collection<NodeSelector> selectors)
{
final List<HierarchicalConfiguration<ImmutableNode>> configs =
new ArrayList<>(
selectors.size());
for (final NodeSelector selector : selectors)
{
configs.add(createSubConfigurationForTrackedNode(selector,
parentModelSupport));
}
return configs;
}
/**
* Creates a sub configuration from the specified key which is independent
* on this configuration. This means that the sub configuration operates on
* a separate node model (although the nodes are initially shared).
*
* @param key the key of the sub configuration
* @return the new sub configuration
*/
private BaseHierarchicalConfiguration createIndependentSubConfiguration(
final String key)
{
final List<ImmutableNode> targetNodes = fetchFilteredNodeResults(key);
final int size = targetNodes.size();
if (size != 1)
{
throw new ConfigurationRuntimeException(
"Passed in key must select exactly one node (found %,d): %s", size, key);
}
final BaseHierarchicalConfiguration sub =
new BaseHierarchicalConfiguration(new InMemoryNodeModel(
targetNodes.get(0)));
initSubConfiguration(sub);
return sub;
}
/**
* Returns an initialized sub configuration for this configuration that is
* based on another {@code BaseHierarchicalConfiguration}. Thus, it is
* independent from this configuration.
*
* @param node the root node for the sub configuration
* @return the initialized sub configuration
*/
private BaseHierarchicalConfiguration createIndependentSubConfigurationForNode(
final ImmutableNode node)
{
final BaseHierarchicalConfiguration sub =
new BaseHierarchicalConfiguration(new InMemoryNodeModel(node));
initSubConfiguration(sub);
return sub;
}
/**
* Executes a query on the specified key and filters it for node results.
*
* @param key the key
* @return the filtered list with result nodes
*/
private List<ImmutableNode> fetchFilteredNodeResults(final String key)
{
final NodeHandler<ImmutableNode> handler = getModel().getNodeHandler();
return resolveNodeKey(handler.getRootNode(), key, handler);
}
/**
* {@inheritDoc} This implementation creates a {@code SubnodeConfiguration}
* by delegating to {@code configurationAt()}. Then an immutable wrapper
* is created and returned.
*/
@Override
public ImmutableHierarchicalConfiguration immutableConfigurationAt(
final String key, final boolean supportUpdates)
{
return ConfigurationUtils.unmodifiableConfiguration(configurationAt(
key, supportUpdates));
}
/**
* {@inheritDoc} This is a short form for {@code configurationAt(key,
* <b>false</b>)}.
* @throws ConfigurationRuntimeException if the key does not select a single node
*/
@Override
public HierarchicalConfiguration<ImmutableNode> configurationAt(final String key)
{
return configurationAt(key, false);
}
/**
* {@inheritDoc} This implementation creates a {@code SubnodeConfiguration}
* by delegating to {@code configurationAt()}. Then an immutable wrapper
* is created and returned.
* @throws ConfigurationRuntimeException if the key does not select a single node
*/
@Override
public ImmutableHierarchicalConfiguration immutableConfigurationAt(
final String key)
{
return ConfigurationUtils.unmodifiableConfiguration(configurationAt(
key));
}
/**
* {@inheritDoc} This implementation creates sub configurations in the same
* way as described for {@link #configurationAt(String)}.
*/
@Override
public List<HierarchicalConfiguration<ImmutableNode>> configurationsAt(
final String key)
{
List<ImmutableNode> nodes;
beginRead(false);
try
{
nodes = fetchFilteredNodeResults(key);
}
finally
{
endRead();
}
final List<HierarchicalConfiguration<ImmutableNode>> results =
new ArrayList<>(
nodes.size());
for (final ImmutableNode node : nodes)
{
final BaseHierarchicalConfiguration sub =
createIndependentSubConfigurationForNode(node);
results.add(sub);
}
return results;
}
/**
* {@inheritDoc} This implementation creates tracked nodes for the specified
* key. Then sub configurations for these nodes are created and returned.
*/
@Override
public List<HierarchicalConfiguration<ImmutableNode>> configurationsAt(
final String key, final boolean supportUpdates)
{
if (!supportUpdates)
{
return configurationsAt(key);
}
InMemoryNodeModel parentModel;
beginRead(false);
try
{
parentModel = getSubConfigurationParentModel();
}
finally
{
endRead();
}
final Collection<NodeSelector> selectors =
parentModel.selectAndTrackNodes(key, this);
return createConnectedSubConfigurations(this, selectors);
}
/**
* {@inheritDoc} This implementation first delegates to
* {@code configurationsAt()} to create a list of
* {@code SubnodeConfiguration} objects. Then for each element of this list
* an unmodifiable wrapper is created.
*/
@Override
public List<ImmutableHierarchicalConfiguration> immutableConfigurationsAt(
final String key)
{
return toImmutable(configurationsAt(key));
}
/**
* {@inheritDoc} This implementation resolves the node(s) selected by the
* given key. If not a single node is selected, an empty list is returned.
* Otherwise, sub configurations for each child of the node are created.
*/
@Override
public List<HierarchicalConfiguration<ImmutableNode>> childConfigurationsAt(
final String key)
{
List<ImmutableNode> nodes;
beginRead(false);
try
{
nodes = fetchFilteredNodeResults(key);
}
finally
{
endRead();
}
if (nodes.size() != 1)
{
return Collections.emptyList();
}
final ImmutableNode parent = nodes.get(0);
final List<HierarchicalConfiguration<ImmutableNode>> subs =
new ArrayList<>(parent
.getChildren().size());
for (final ImmutableNode node : parent)
{
subs.add(createIndependentSubConfigurationForNode(node));
}
return subs;
}
/**
* {@inheritDoc} This method works like
* {@link #childConfigurationsAt(String)}; however, depending on the value
* of the {@code supportUpdates} flag, connected sub configurations may be
* created.
*/
@Override
public List<HierarchicalConfiguration<ImmutableNode>> childConfigurationsAt(
final String key, final boolean supportUpdates)
{
if (!supportUpdates)
{
return childConfigurationsAt(key);
}
final InMemoryNodeModel parentModel = getSubConfigurationParentModel();
return createConnectedSubConfigurations(this,
parentModel.trackChildNodes(key, this));
}
/**
* {@inheritDoc} This implementation first delegates to
* {@code childConfigurationsAt()} to create a list of mutable child
* configurations. Then a list with immutable wrapper configurations is
* created.
*/
@Override
public List<ImmutableHierarchicalConfiguration> immutableChildConfigurationsAt(
final String key)
{
return toImmutable(childConfigurationsAt(key));
}
/**
* This method is always called when a subnode configuration created from
* this configuration has been modified. This implementation transforms the
* received event into an event of type {@code SUBNODE_CHANGED}
* and notifies the registered listeners.
*
* @param event the event describing the change
* @since 1.5
*/
protected void subnodeConfigurationChanged(final ConfigurationEvent event)
{
fireEvent(ConfigurationEvent.SUBNODE_CHANGED, null, event, event.isBeforeUpdate());
}
/**
* Initializes properties of a sub configuration. A sub configuration
* inherits some settings from its parent, e.g. the expression engine or the
* synchronizer. The corresponding values are copied by this method.
*
* @param sub the sub configuration to be initialized
*/
private void initSubConfiguration(final BaseHierarchicalConfiguration sub)
{
sub.setSynchronizer(getSynchronizer());
sub.setExpressionEngine(getExpressionEngine());
sub.setListDelimiterHandler(getListDelimiterHandler());
sub.setThrowExceptionOnMissing(isThrowExceptionOnMissing());
sub.getInterpolator().setParentInterpolator(getInterpolator());
}
/**
* Creates a listener which reacts on all changes on this configuration or
* one of its {@code SubnodeConfiguration} instances. If such a change is
* detected, some updates have to be performed.
*
* @return the newly created change listener
*/
private EventListener<ConfigurationEvent> createChangeListener()
{
return this::subnodeConfigurationChanged;
}
/**
* Returns a configuration with the same content as this configuration, but
* with all variables replaced by their actual values. This implementation
* is specific for hierarchical configurations. It clones the current
* configuration and runs a specialized visitor on the clone, which performs
* interpolation on the single configuration nodes.
*
* @return a configuration with all variables interpolated
* @since 1.5
*/
@Override
public Configuration interpolatedConfiguration()
{
final InterpolatedVisitor visitor = new InterpolatedVisitor();
final NodeHandler<ImmutableNode> handler = getModel().getNodeHandler();
NodeTreeWalker.INSTANCE
.walkDFS(handler.getRootNode(), visitor, handler);
final BaseHierarchicalConfiguration c =
(BaseHierarchicalConfiguration) clone();
c.getNodeModel().setRootNode(visitor.getInterpolatedRoot());
return c;
}
/**
* {@inheritDoc} This implementation creates a new instance of
* {@link InMemoryNodeModel}, initialized with this configuration's root
* node. This has the effect that although the same nodes are used, the
* original and copied configurations are independent on each other.
*/
@Override
protected NodeModel<ImmutableNode> cloneNodeModel()
{
return new InMemoryNodeModel(getModel().getNodeHandler().getRootNode());
}
/**
* Creates a list with immutable configurations from the given input list.
*
* @param subs a list with mutable configurations
* @return a list with corresponding immutable configurations
*/
private static List<ImmutableHierarchicalConfiguration> toImmutable(
final List<? extends HierarchicalConfiguration<?>> subs)
{
final List<ImmutableHierarchicalConfiguration> res =
new ArrayList<>(subs.size());
for (final HierarchicalConfiguration<?> sub : subs)
{
res.add(ConfigurationUtils.unmodifiableConfiguration(sub));
}
return res;
}
/**
* Creates the {@code NodeModel} for this configuration based on a passed in
* source configuration. This implementation creates an
* {@link InMemoryNodeModel}. If the passed in source configuration is
* defined, its root node also becomes the root node of this configuration.
* Otherwise, a new, empty root node is used.
*
* @param c the configuration that is to be copied
* @return the {@code NodeModel} for the new configuration
*/
private static NodeModel<ImmutableNode> createNodeModel(
final HierarchicalConfiguration<ImmutableNode> c)
{
final ImmutableNode root = c != null ? obtainRootNode(c) : null;
return new InMemoryNodeModel(root);
}
/**
* Obtains the root node from a configuration whose data is to be copied. It
* has to be ensured that the synchronizer is called correctly.
*
* @param c the configuration that is to be copied
* @return the root node of this configuration
*/
private static ImmutableNode obtainRootNode(
final HierarchicalConfiguration<ImmutableNode> c)
{
return c.getNodeModel().getNodeHandler().getRootNode();
}
/**
* A specialized visitor base class that can be used for storing the tree of
* configuration nodes. The basic idea is that each node can be associated
* with a reference object. This reference object has a concrete meaning in
* a derived class, e.g. an entry in a JNDI context or an XML element. When
* the configuration tree is set up, the {@code load()} method is
* responsible for setting the reference objects. When the configuration
* tree is later modified, new nodes do not have a defined reference object.
* This visitor class processes all nodes and finds the ones without a
* defined reference object. For those nodes the {@code insert()}
* method is called, which must be defined in concrete sub classes. This
* method can perform all steps to integrate the new node into the original
* structure.
*/
protected abstract static class BuilderVisitor extends
ConfigurationNodeVisitorAdapter<ImmutableNode>
{
@Override
public void visitBeforeChildren(final ImmutableNode node, final NodeHandler<ImmutableNode> handler)
{
final ReferenceNodeHandler refHandler = (ReferenceNodeHandler) handler;
updateNode(node, refHandler);
insertNewChildNodes(node, refHandler);
}
/**
* Inserts a new node into the structure constructed by this builder.
* This method is called for each node that has been added to the
* configuration tree after the configuration has been loaded from its
* source. These new nodes have to be inserted into the original
* structure. The passed in nodes define the position of the node to be
* inserted: its parent and the siblings between to insert.
*
* @param newNode the node to be inserted
* @param parent the parent node
* @param sibling1 the sibling after which the node is to be inserted;
* can be <b>null</b> if the new node is going to be the first
* child node
* @param sibling2 the sibling before which the node is to be inserted;
* can be <b>null</b> if the new node is going to be the last
* child node
* @param refHandler the {@code ReferenceNodeHandler}
*/
protected abstract void insert(ImmutableNode newNode,
ImmutableNode parent, ImmutableNode sibling1,
ImmutableNode sibling2, ReferenceNodeHandler refHandler);
/**
* Updates a node that already existed in the original hierarchy. This
* method is called for each node that has an assigned reference object.
* A concrete implementation should update the reference according to
* the node's current value.
*
* @param node the current node to be processed
* @param reference the reference object for this node
* @param refHandler the {@code ReferenceNodeHandler}
*/
protected abstract void update(ImmutableNode node, Object reference,
ReferenceNodeHandler refHandler);
/**
* Updates the value of a node. If this node is associated with a
* reference object, the {@code update()} method is called.
*
* @param node the current node to be processed
* @param refHandler the {@code ReferenceNodeHandler}
*/
private void updateNode(final ImmutableNode node,
final ReferenceNodeHandler refHandler)
{
final Object reference = refHandler.getReference(node);
if (reference != null)
{
update(node, reference, refHandler);
}
}
/**
* Inserts new children that have been added to the specified node.
*
* @param node the current node to be processed
* @param refHandler the {@code ReferenceNodeHandler}
*/
private void insertNewChildNodes(final ImmutableNode node,
final ReferenceNodeHandler refHandler)
{
final Collection<ImmutableNode> subNodes =
new LinkedList<>(refHandler.getChildren(node));
final Iterator<ImmutableNode> children = subNodes.iterator();
ImmutableNode sibling1;
ImmutableNode nd = null;
while (children.hasNext())
{
// find the next new node
do
{
sibling1 = nd;
nd = children.next();
} while (refHandler.getReference(nd) != null
&& children.hasNext());
if (refHandler.getReference(nd) == null)
{
// find all following new nodes
final List<ImmutableNode> newNodes =
new LinkedList<>();
newNodes.add(nd);
while (children.hasNext())
{
nd = children.next();
if (refHandler.getReference(nd) != null) {
break;
}
newNodes.add(nd);
}
// Insert all new nodes
final ImmutableNode sibling2 =
refHandler.getReference(nd) == null ? null : nd;
for (final ImmutableNode insertNode : newNodes)
{
if (refHandler.getReference(insertNode) == null)
{
insert(insertNode, node, sibling1, sibling2,
refHandler);
sibling1 = insertNode;
}
}
}
}
}
}
/**
* A specialized visitor implementation which constructs the root node of a
* configuration with all variables replaced by their interpolated values.
*/
private class InterpolatedVisitor extends
ConfigurationNodeVisitorAdapter<ImmutableNode>
{
/** A stack for managing node builder instances. */
private final List<ImmutableNode.Builder> builderStack;
/** The resulting root node. */
private ImmutableNode interpolatedRoot;
/**
* Creates a new instance of {@code InterpolatedVisitor}.
*/
public InterpolatedVisitor()
{
builderStack = new LinkedList<>();
}
/**
* Returns the result of this builder: the root node of the interpolated
* nodes hierarchy.
*
* @return the resulting root node
*/
public ImmutableNode getInterpolatedRoot()
{
return interpolatedRoot;
}
@Override
public void visitBeforeChildren(final ImmutableNode node,
final NodeHandler<ImmutableNode> handler)
{
if (isLeafNode(node, handler))
{
handleLeafNode(node, handler);
}
else
{
final ImmutableNode.Builder builder =
new ImmutableNode.Builder(handler.getChildrenCount(
node, null))
.name(handler.nodeName(node))
.value(interpolate(handler.getValue(node)))
.addAttributes(
interpolateAttributes(node, handler));
push(builder);
}
}
@Override
public void visitAfterChildren(final ImmutableNode node,
final NodeHandler<ImmutableNode> handler)
{
if (!isLeafNode(node, handler))
{
final ImmutableNode newNode = pop().create();
storeInterpolatedNode(newNode);
}
}
/**
* Pushes a new builder on the stack.
*
* @param builder the builder
*/
private void push(final ImmutableNode.Builder builder)
{
builderStack.add(0, builder);
}
/**
* Pops the top-level element from the stack.
*
* @return the element popped from the stack
*/
private ImmutableNode.Builder pop()
{
return builderStack.remove(0);
}
/**
* Returns the top-level element from the stack without removing it.
*
* @return the top-level element from the stack
*/
private ImmutableNode.Builder peek()
{
return builderStack.get(0);
}
/**
* Returns a flag whether the given node is a leaf. This is the case if
* it does not have children.
*
* @param node the node in question
* @param handler the {@code NodeHandler}
* @return a flag whether this is a leaf node
*/
private boolean isLeafNode(final ImmutableNode node,
final NodeHandler<ImmutableNode> handler)
{
return handler.getChildren(node).isEmpty();
}
/**
* Handles interpolation for a node with no children. If interpolation
* does not change this node, it is copied as is to the resulting
* structure. Otherwise, a new node is created with the interpolated
* values.
*
* @param node the current node to be processed
* @param handler the {@code NodeHandler}
*/
private void handleLeafNode(final ImmutableNode node,
final NodeHandler<ImmutableNode> handler)
{
final Object value = interpolate(node.getValue());
final Map<String, Object> interpolatedAttributes =
new HashMap<>();
final boolean attributeChanged =
interpolateAttributes(node, handler, interpolatedAttributes);
final ImmutableNode newNode =
valueChanged(value, handler.getValue(node)) || attributeChanged ? new ImmutableNode.Builder()
.name(handler.nodeName(node)).value(value)
.addAttributes(interpolatedAttributes).create()
: node;
storeInterpolatedNode(newNode);
}
/**
* Stores a processed node. Per default, the node is added to the
* current builder on the stack. If no such builder exists, this is the
* result node.
*
* @param node the node to be stored
*/
private void storeInterpolatedNode(final ImmutableNode node)
{
if (builderStack.isEmpty())
{
interpolatedRoot = node;
}
else
{
peek().addChild(node);
}
}
/**
* Populates a map with interpolated attributes of the passed in node.
*
* @param node the current node to be processed
* @param handler the {@code NodeHandler}
* @param interpolatedAttributes a map for storing the results