/
XmlConfiguration.java
1935 lines (1749 loc) · 73 KB
/
XmlConfiguration.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
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.xml;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Queue;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jetty.util.LazyList;
import org.eclipse.jetty.util.Loader;
import org.eclipse.jetty.util.MultiException;
import org.eclipse.jetty.util.Pool;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.annotation.Name;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.resource.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
/**
* <p>Configures objects from XML.</p>
* <p>This class reads an XML file conforming to the configure.dtd DTD
* and uses it to configure and object by calling set, put or other methods on the object.</p>
* <p>The actual XML file format may be changed (eg to spring XML) by implementing the
* {@link ConfigurationProcessorFactory} interface to be found by the
* {@link ServiceLoader} by using the DTD and first tag element in the file.
* Note that DTD will be null if validation is off.</p>
* <p>The configuration can be parameterised with properties that are looked up via the
* Property XML element and set on the configuration via the map returned from
* {@link #getProperties()}</p>
* <p>The configuration can create and lookup beans by ID. If multiple configurations are used, then it
* is good practise to copy the entries from the {@link #getIdMap()} of a configuration to the next
* configuration so that they can share an ID space for beans.</p>
*/
public class XmlConfiguration
{
private static final Logger LOG = LoggerFactory.getLogger(XmlConfiguration.class);
private static final Class<?>[] PRIMITIVES =
{
Boolean.TYPE, Character.TYPE, Byte.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE, Void.TYPE
};
private static final Class<?>[] BOXED_PRIMITIVES =
{
Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class,
Void.class
};
private static final Class<?>[] SUPPORTED_COLLECTIONS =
{
ArrayList.class, HashSet.class, Queue.class, List.class, Set.class, Collection.class
};
private static final List<ConfigurationProcessorFactory> PROCESSOR_FACTORIES = TypeUtil.serviceProviderStream(ServiceLoader.load(ConfigurationProcessorFactory.class))
.flatMap(p -> Stream.of(p.get()))
.collect(Collectors.toList());
private static final Pool<ConfigurationParser> __parsers =
new Pool<>(Pool.StrategyType.THREAD_ID, Math.min(8, Runtime.getRuntime().availableProcessors()));
public static final Comparator<Executable> EXECUTABLE_COMPARATOR = (e1, e2) ->
{
// Favour methods with less parameters
int count = e1.getParameterCount();
int compare = Integer.compare(count, e2.getParameterCount());
if (compare == 0 && count > 0)
{
Parameter[] p1 = e1.getParameters();
Parameter[] p2 = e2.getParameters();
// Favour methods without varargs
compare = Boolean.compare(p1[count - 1].isVarArgs(), p2[count - 1].isVarArgs());
if (compare == 0)
{
// Rank by differences in the parameters
for (int i = 0; i < count; i++)
{
Class<?> t1 = p1[i].getType();
Class<?> t2 = p2[i].getType();
if (t1 != t2)
{
// Favour derived type over base type
compare = Boolean.compare(t1.isAssignableFrom(t2), t2.isAssignableFrom(t1));
if (compare == 0)
{
// favour primitive type over reference
compare = Boolean.compare(!t1.isPrimitive(), !t2.isPrimitive());
if (compare == 0)
// Use name to avoid non determinant sorting
compare = t1.getName().compareTo(t2.getName());
}
// break on the first different parameter (should always be true)
if (compare != 0)
break;
}
}
}
compare = Math.min(1, Math.max(compare, -1));
}
return compare;
};
/**
* Set the standard IDs and properties expected in a jetty XML file:
* <ul>
* <li>RefId Server</li>
* <li>Property jetty.home</li>
* <li>Property jetty.home.uri</li>
* <li>Property jetty.base</li>
* <li>Property jetty.base.uri</li>
* <li>Property jetty.webapps</li>
* <li>Property jetty.webapps.uri</li>
* </ul>
*
* @param server The Server object to set
* @param webapp The webapps Resource
*/
public void setJettyStandardIdsAndProperties(Object server, Resource webapp)
{
try
{
if (server != null)
getIdMap().put("Server", server);
Path home = Paths.get(System.getProperty("jetty.home", "."));
getProperties().put("jetty.home", home.toString());
getProperties().put("jetty.home.uri", normalizeURI(home.toUri().toASCIIString()));
Path base = Paths.get(System.getProperty("jetty.base", home.toString()));
getProperties().put("jetty.base", base.toString());
getProperties().put("jetty.base.uri", normalizeURI(base.toUri().toASCIIString()));
if (webapp != null)
{
Path webappPath = webapp.getFile().toPath().toAbsolutePath();
getProperties().put("jetty.webapp", webappPath.toString());
getProperties().put("jetty.webapps", webappPath.getParent().toString());
getProperties().put("jetty.webapps.uri", normalizeURI(webappPath.getParent().toUri().toString()));
}
}
catch (Exception e)
{
LOG.warn("Unable to get webapp file reference", e);
}
}
public static String normalizeURI(String uri)
{
if (uri.endsWith("/"))
return uri.substring(0, uri.length() - 1);
return uri;
}
private final Map<String, Object> _idMap = new HashMap<>();
private final Map<String, String> _propertyMap = new HashMap<>();
private final Resource _location;
private final String _dtd;
private ConfigurationProcessor _processor;
ConfigurationParser getParser()
{
Pool<ConfigurationParser>.Entry entry = __parsers.acquire(ConfigurationParser::new);
if (entry == null)
return new ConfigurationParser(null);
return entry.getPooled();
}
/**
* Reads and parses the XML configuration file.
*
* @param resource the Resource to the XML configuration
* @throws IOException if the configuration could not be read
* @throws SAXException if the configuration could not be parsed
*/
public XmlConfiguration(Resource resource) throws SAXException, IOException
{
try (ConfigurationParser parser = getParser(); InputStream inputStream = resource.getInputStream())
{
_location = resource;
setConfig(parser.parse(inputStream));
_dtd = parser.getDTD();
}
}
@Override
public String toString()
{
if (_location == null)
{
return "UNKNOWN-LOCATION";
}
return _location.toString();
}
private void setConfig(XmlParser.Node config)
{
if ("Configure".equals(config.getTag()))
{
_processor = new JettyXmlConfiguration();
}
else if (PROCESSOR_FACTORIES != null)
{
for (ConfigurationProcessorFactory factory : PROCESSOR_FACTORIES)
{
_processor = factory.getConfigurationProcessor(_dtd, config.getTag());
if (_processor != null)
break;
}
if (_processor == null)
throw new IllegalStateException("Unknown configuration type: " + config.getTag() + " in " + this);
}
else
{
throw new IllegalArgumentException("Unknown XML tag:" + config.getTag());
}
_processor.init(_location, config, this);
}
/**
* Get the map of ID String to Objects that is used to hold
* and lookup any objects by ID.
* <p>
* A New, Get or Call XML element may have an
* id attribute which will cause the resulting object to be placed into
* this map. A Ref XML element will lookup an object from this map.</p>
* <p>
* When chaining configuration files, it is good practise to copy the
* ID entries from the ID map to the map of the next configuration, so
* that they may share an ID space
* </p>
*
* @return A modifiable map of ID strings to Objects
*/
public Map<String, Object> getIdMap()
{
return _idMap;
}
/**
* Get the map of properties used by the Property XML element
* to parametrize configuration.
*
* @return A modifiable map of properties.
*/
public Map<String, String> getProperties()
{
return _propertyMap;
}
/**
* Applies the XML configuration script to the given object.
*
* @param obj The object to be configured, which must be of a type or super type
* of the class attribute of the <Configure> element.
* @return the configured object
* @throws Exception if the configuration fails
*/
public Object configure(Object obj) throws Exception
{
return _processor.configure(obj);
}
/**
* Applies the XML configuration script.
* If the root element of the configuration has an ID, an object is looked up by ID and its type checked
* against the root element's type.
* Otherwise a new object of the type specified by the root element is created.
*
* @return The newly created configured object.
* @throws Exception if the configuration fails
*/
public Object configure() throws Exception
{
if (LOG.isDebugEnabled())
LOG.debug("Configure {}", _location);
return _processor.configure();
}
/**
* Initialize a new Object defaults.
* <p>This method must be called by any {@link ConfigurationProcessor} when it
* creates a new instance of an object before configuring it, so that a derived
* XmlConfiguration class may inject default values.
*
* @param object the object to initialize defaults on
*/
public void initializeDefaults(Object object)
{
}
/**
* Utility method to resolve a provided path against a directory.
*
* @param dir the directory (should be a directory reference, does not have to exist)
* @param destPath the destination path (can be relative or absolute, syntax depends on OS + FileSystem in use,
* and does not need to exist)
* @return String to resolved and normalized path, or null if dir or destPath is empty.
*/
public static String resolvePath(String dir, String destPath)
{
if (StringUtil.isEmpty(dir) || StringUtil.isEmpty(destPath))
return null;
return Paths.get(dir).resolve(destPath).normalize().toString();
}
private static class JettyXmlConfiguration implements ConfigurationProcessor
{
XmlParser.Node _root;
XmlConfiguration _configuration;
@Override
public void init(Resource resource, XmlParser.Node root, XmlConfiguration configuration)
{
_root = root;
_configuration = configuration;
}
@Override
public Object configure(Object obj) throws Exception
{
// Check the class of the object
Class<?> oClass = nodeClass(_root);
if (oClass != null && !oClass.isInstance(obj))
{
String loaders = (oClass.getClassLoader() == obj.getClass().getClassLoader()) ? "" : "Object Class and type Class are from different loaders.";
throw new IllegalArgumentException("Object of class '" + obj.getClass().getCanonicalName() + "' is not of type '" + oClass.getCanonicalName() + "'. " + loaders + " in " + _configuration);
}
String id = _root.getAttribute("id");
if (id != null)
_configuration.getIdMap().put(id, obj);
AttrOrElementNode aoeNode = new AttrOrElementNode(obj, _root, "Id", "Class", "Arg");
// The Object already existed, if it has <Arg> nodes, warn about them not being used.
aoeNode.getNodes("Arg")
.forEach((node) -> LOG.warn("Ignored arg {} in {}", node, this._configuration._location));
configure(obj, _root, aoeNode.getNext());
return obj;
}
@Override
public Object configure() throws Exception
{
AttrOrElementNode aoeNode = new AttrOrElementNode(_root, "Id", "Class", "Arg");
String id = aoeNode.getString("Id");
String clazz = aoeNode.getString("Class");
Object obj = id == null ? null : _configuration.getIdMap().get(id);
Class<?> oClass = clazz != null ? Loader.loadClass(clazz) : obj == null ? null : obj.getClass();
if (LOG.isDebugEnabled())
LOG.debug("Configure {} {}", oClass, obj);
if (obj == null && oClass != null)
{
try
{
obj = construct(oClass, new Args(null, oClass, aoeNode.getNodes("Arg")));
if (id != null)
_configuration.getIdMap().put(id, obj);
}
catch (NoSuchMethodException x)
{
throw new IllegalStateException(String.format("No matching constructor %s in %s", oClass, _configuration));
}
}
else
{
// The Object already existed, if it has <Arg> nodes, warn about them not being used.
aoeNode.getNodes("Arg")
.forEach((node) -> LOG.warn("Ignored arg {} in {}", node, this._configuration._location));
}
_configuration.initializeDefaults(obj);
configure(obj, _root, aoeNode.getNext());
return obj;
}
private static Class<?> nodeClass(XmlParser.Node node) throws ClassNotFoundException
{
String className = node.getAttribute("class");
if (className == null)
return null;
return Loader.loadClass(className);
}
/**
* Recursive configuration routine.
* This method applies the nested Set, Put, Call, etc. elements to the given object.
*
* @param obj the object to configure
* @param cfg the XML nodes of the configuration
* @param i the index of the XML nodes
* @throws Exception if the configuration fails
*/
public void configure(Object obj, XmlParser.Node cfg, int i) throws Exception
{
// Process real arguments
for (; i < cfg.size(); i++)
{
Object o = cfg.get(i);
if (o instanceof String)
continue;
XmlParser.Node node = (XmlParser.Node)o;
try
{
String tag = node.getTag();
switch (tag)
{
case "Arg":
case "Class":
case "Id":
throw new IllegalStateException("Element '" + tag + "' not skipped");
case "Set":
set(obj, node);
break;
case "Put":
put(obj, node);
break;
case "Call":
call(obj, node);
break;
case "Get":
get(obj, node);
break;
case "New":
newObj(obj, node);
break;
case "Array":
newArray(obj, node);
break;
case "Map":
newMap(obj, node);
break;
case "Ref":
refObj(node);
break;
case "Property":
propertyObj(node);
break;
case "SystemProperty":
systemPropertyObj(node);
break;
case "Env":
envObj(node);
break;
default:
throw new IllegalStateException("Unknown tag: " + tag + " in " + _configuration);
}
}
catch (Exception e)
{
LOG.warn("Config error {} at {} in {}", e.toString(), node, _configuration);
throw e;
}
}
}
/**
* <p>Call a setter method.</p>
* <p>This method makes a best effort to find a matching set method.
* The type of the value is used to find a suitable set method by:</p>
* <ol>
* <li>Trying for a trivial type match</li>
* <li>Looking for a native type match</li>
* <li>Trying all correctly named methods for an auto conversion</li>
* <li>Attempting to construct a suitable value from original value</li>
* </ol>
*
* @param obj the enclosing object
* @param node the <Set> XML node
*/
private void set(Object obj, XmlParser.Node node) throws Exception
{
String attr = node.getAttribute("name");
String name = "set" + attr.substring(0, 1).toUpperCase(Locale.ENGLISH) + attr.substring(1);
String id = node.getAttribute("id");
String property = node.getAttribute("property");
String propertyValue = null;
Class<?> oClass = nodeClass(node);
if (oClass != null)
obj = null;
else
oClass = obj.getClass();
// Look for a property value
if (property != null)
{
Map<String, String> properties = _configuration.getProperties();
propertyValue = properties.get(property);
// If no property value, then do not set
if (propertyValue == null)
{
// check that there is at least one setter that could have matched
if (Arrays.stream(oClass.getMethods()).noneMatch(m -> m.getName().equals(name)))
throw new NoSuchMethodException(String.format("No '%s' on %s", name, oClass.getName()));
// otherwise it is a noop
return;
}
}
Object value = value(obj, node);
if (value == null)
value = propertyValue;
Object[] arg = {value};
Class<?>[] vClass = {Object.class};
if (value != null)
vClass[0] = value.getClass();
if (LOG.isDebugEnabled())
LOG.debug("XML {}.{} ({})", (obj != null ? obj.toString() : oClass.getName()), name, value);
MultiException me = new MultiException();
String types = null;
Object setValue = value;
try
{
// Try for trivial match
try
{
Method set = oClass.getMethod(name, vClass);
invokeMethod(set, obj, arg);
return;
}
catch (IllegalArgumentException | IllegalAccessException | NoSuchMethodException e)
{
LOG.trace("IGNORED", e);
me.add(e);
}
// Try for native match
try
{
Field type = vClass[0].getField("TYPE");
vClass[0] = (Class<?>)type.get(null);
Method set = oClass.getMethod(name, vClass);
invokeMethod(set, obj, arg);
return;
}
catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException e)
{
LOG.trace("IGNORED", e);
me.add(e);
}
// Try a field
try
{
Field field = oClass.getField(attr);
if (Modifier.isPublic(field.getModifiers()))
{
try
{
setField(field, obj, value);
return;
}
catch (IllegalArgumentException e)
{
// try to convert String value to field value
if (value instanceof String)
{
try
{
value = TypeUtil.valueOf(field.getType(), ((String)value).trim());
setField(field, obj, value);
return;
}
catch (Exception e2)
{
e.addSuppressed(e2);
throw e;
}
}
}
}
}
catch (NoSuchFieldException e)
{
LOG.trace("IGNORED", e);
me.add(e);
}
// Search for a match by trying all the set methods
Method[] sets = oClass.getMethods();
Method set = null;
for (Method setter : sets)
{
if (setter.getParameterCount() != 1)
continue;
Class<?>[] paramTypes = setter.getParameterTypes();
if (name.equals(setter.getName()))
{
types = types == null ? paramTypes[0].getName() : (types + "," + paramTypes[0].getName());
// lets try it
try
{
set = setter;
invokeMethod(set, obj, arg);
return;
}
catch (IllegalArgumentException | IllegalAccessException e)
{
LOG.trace("IGNORED", e);
me.add(e);
}
try
{
for (Class<?> c : SUPPORTED_COLLECTIONS)
{
if (paramTypes[0].isAssignableFrom(c))
{
setValue = convertArrayToCollection(value, c);
invokeMethod(setter, obj, setValue);
return;
}
}
}
catch (IllegalAccessException e)
{
LOG.trace("IGNORED", e);
me.add(e);
}
}
}
// Try converting the arg to the last set found.
if (set != null)
{
try
{
Class<?> sClass = set.getParameterTypes()[0];
if (sClass.isPrimitive())
{
for (int t = 0; t < PRIMITIVES.length; t++)
{
if (sClass.equals(PRIMITIVES[t]))
{
sClass = BOXED_PRIMITIVES[t];
break;
}
}
}
Constructor<?> cons = sClass.getConstructor(vClass);
arg[0] = cons.newInstance(arg);
_configuration.initializeDefaults(arg[0]);
invokeMethod(set, obj, arg);
setValue = arg[0];
return;
}
catch (NoSuchMethodException | IllegalAccessException | InstantiationException e)
{
LOG.trace("IGNORED", e);
me.add(e);
}
}
setValue = null;
}
finally
{
if (id != null && setValue != null)
_configuration.getIdMap().put(id, setValue);
}
// No Joy
String message = oClass + "." + name + "(" + vClass[0] + ")";
if (types != null)
message += ". Found setters for " + types;
NoSuchMethodException failure = new NoSuchMethodException(message);
for (int i = 0; i < me.size(); i++)
{
failure.addSuppressed(me.getThrowable(i));
}
throw failure;
}
private Object invokeConstructor(Constructor<?> constructor, Object... args) throws IllegalAccessException, InvocationTargetException, InstantiationException
{
Object result = constructor.newInstance(args);
if (constructor.getAnnotation(Deprecated.class) != null)
LOG.warn("Deprecated constructor {} in {}", constructor, _configuration);
return result;
}
private Object invokeMethod(Method method, Object obj, Object... args) throws IllegalAccessException, InvocationTargetException
{
Object result = method.invoke(obj, args);
if (method.getAnnotation(Deprecated.class) != null)
LOG.warn("Deprecated method {} in {}", method, _configuration);
return result;
}
private Object getField(Field field, Object object) throws IllegalAccessException
{
Object result = field.get(object);
if (field.getAnnotation(Deprecated.class) != null)
LOG.warn("Deprecated field {} in {}", field, _configuration);
return result;
}
private void setField(Field field, Object obj, Object arg) throws IllegalAccessException
{
field.set(obj, arg);
if (field.getAnnotation(Deprecated.class) != null)
LOG.warn("Deprecated field {} in {}", field, _configuration);
}
/**
* @param array the array to convert
* @param collectionType the desired collection type
* @return a collection of the desired type if the array can be converted
*/
private static Collection<?> convertArrayToCollection(Object array, Class<?> collectionType)
{
if (array == null)
return null;
Collection<?> collection = null;
if (array.getClass().isArray())
{
if (collectionType.isAssignableFrom(ArrayList.class))
collection = convertArrayToArrayList(array);
else if (collectionType.isAssignableFrom(HashSet.class))
collection = new HashSet<>(convertArrayToArrayList(array));
}
if (collection == null)
throw new IllegalArgumentException("Can't convert \"" + array.getClass() + "\" to " + collectionType);
return collection;
}
private static ArrayList<Object> convertArrayToArrayList(Object array)
{
int length = Array.getLength(array);
ArrayList<Object> list = new ArrayList<>(length);
for (int i = 0; i < length; i++)
{
list.add(Array.get(array, i));
}
return list;
}
/**
* <p>Calls a put method.</p>
*
* @param obj the enclosing map object
* @param node the <Put> XML node
*/
private void put(Object obj, XmlParser.Node node) throws Exception
{
if (!(obj instanceof Map))
throw new IllegalArgumentException("Object for put is not a Map: " + obj);
@SuppressWarnings("unchecked")
Map<Object, Object> map = (Map<Object, Object>)obj;
String name = node.getAttribute("name");
Object value = value(obj, node);
map.put(name, value);
if (LOG.isDebugEnabled())
LOG.debug("XML {}.put({},{})", obj, name, value);
}
/**
* <p>Calls a getter method.</p>
* <p>Any object returned from the call is passed to the configure method to consume the remaining elements.</p>
* <p>If the "class" attribute is present and its value is "class", then the class instance itself is returned.</p>
*
* @param obj the enclosing object
* @param node the <Get> XML node
* @return the result of the getter invocation
*/
private Object get(Object obj, XmlParser.Node node) throws Exception
{
AttrOrElementNode aoeNode = new AttrOrElementNode(obj, node, "Id", "Name", "Class");
String id = aoeNode.getString("Id");
String name = aoeNode.getString("Name");
String clazz = aoeNode.getString("Class");
Class<?> oClass;
if (clazz != null)
{
// static call
oClass = Loader.loadClass(clazz);
obj = null;
}
else if (obj != null)
{
oClass = obj.getClass();
}
else
{
throw new IllegalArgumentException(node.toString());
}
if (LOG.isDebugEnabled())
LOG.debug("XML get {}", name);
try
{
// Handle getClass() explicitly.
if ("class".equalsIgnoreCase(name))
{
obj = oClass;
}
else
{
// Try calling a getXxx method.
Method method = oClass.getMethod("get" + name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1));
obj = invokeMethod(method, obj);
}
if (id != null)
_configuration.getIdMap().put(id, obj);
configure(obj, node, aoeNode.getNext());
}
catch (NoSuchMethodException nsme1)
{
try
{
// Try calling a isXxx() method.
Method method = oClass.getMethod("is" + name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1));
obj = invokeMethod(method, obj);
if (id != null)
_configuration.getIdMap().put(id, obj);
configure(obj, node, aoeNode.getNext());
}
catch (NoSuchMethodException nsme2)
{
// Try the field.
Field field = oClass.getField(name);
obj = getField(field, obj);
if (id != null)
_configuration.getIdMap().put(id, obj);
configure(obj, node, aoeNode.getNext());
}
}
return obj;
}
/**
* <p>Calls a method.</p>
* <p>A method is selected by trying all methods with matching names and number of arguments.
* Any object returned from the call is passed to the configure method to consume the remaining elements.
* Note that if this is a static call we consider only methods declared directly in the given class,
* i.e. we ignore any static methods in superclasses.
*
* @param obj the enclosing object
* @param node the <Call> XML node
* @return the result of the method invocation
*/
private Object call(Object obj, XmlParser.Node node) throws Exception
{
AttrOrElementNode aoeNode = new AttrOrElementNode(obj, node, "Id", "Name", "Class", "Arg");
String id = aoeNode.getString("Id");
String name = aoeNode.getString("Name");
String clazz = aoeNode.getString("Class");
Class<?> oClass;
if (clazz != null)
{
// static call
oClass = Loader.loadClass(clazz);
obj = null;
}
else if (obj != null)
{
oClass = obj.getClass();
}
else
{
throw new IllegalArgumentException(node.toString());
}
if (LOG.isDebugEnabled())
LOG.debug("XML call {}", name);
try
{
Object nobj = call(oClass, name, obj, new Args(obj, oClass, aoeNode.getNodes("Arg")));
if (id != null)
_configuration.getIdMap().put(id, nobj);
configure(nobj, node, aoeNode.getNext());
return nobj;
}
catch (NoSuchMethodException e)
{
throw new IllegalStateException("No Method: " + node + " on " + oClass, e);
}
}
private Object call(Class<?> oClass, String methodName, Object obj, Args args) throws InvocationTargetException, NoSuchMethodException
{
Objects.requireNonNull(oClass, "Class cannot be null");
Objects.requireNonNull(methodName, "Method name cannot be null");
if (StringUtil.isBlank(methodName))
throw new IllegalArgumentException("Method name cannot be blank");
// Lets just try all methods for now
Method[] methods = oClass.getMethods();
Arrays.sort(methods, EXECUTABLE_COMPARATOR);
for (Method method : methods)
{
if (!method.getName().equals(methodName))
continue;
Object[] arguments = args.applyTo(method);
if (arguments == null)
continue;
if (Modifier.isStatic(method.getModifiers()) != (obj == null))
continue;
if ((obj == null) && method.getDeclaringClass() != oClass)
continue;
try
{
return invokeMethod(method, obj, arguments);
}
catch (IllegalAccessException | IllegalArgumentException e)
{
LOG.trace("IGNORED", e);
}
}
throw new NoSuchMethodException(methodName);
}
/**
* <p>Creates a new value object.</p>
*
* @param obj the enclosing object
* @param node the <New> XML node
* @return the result of the constructor invocation
*/
private Object newObj(Object obj, XmlParser.Node node) throws Exception
{
AttrOrElementNode aoeNode = new AttrOrElementNode(obj, node, "Id", "Class", "Arg");
String id = aoeNode.getString("Id");
String clazz = aoeNode.getString("Class");
if (LOG.isDebugEnabled())
LOG.debug("XML new {}", clazz);
Class<?> oClass = Loader.loadClass(clazz);
Object nobj;
try
{
nobj = construct(oClass, new Args(obj, oClass, aoeNode.getNodes("Arg")));
}
catch (NoSuchMethodException e)
{
throw new IllegalStateException("No suitable constructor: " + node + " on " + obj);
}
if (id != null)
_configuration.getIdMap().put(id, nobj);