This repository has been archived by the owner on Feb 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 158
/
Configuration.java
1463 lines (1355 loc) · 46.8 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
/**
* 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.hadoop.conf;
import java.io.BufferedInputStream;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.WeakHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
/**
* Provides access to configuration parameters.
*
* <h4 id="Resources">Resources</h4>
*
* <p>Configurations are specified by resources. A resource contains a set of
* name/value pairs as XML data. Each resource is named by either a
* <code>String</code> or by a {@link Path}. If named by a <code>String</code>,
* then the classpath is examined for a file with that name. If named by a
* <code>Path</code>, then the local filesystem is examined directly, without
* referring to the classpath.
*
* <p>Unless explicitly turned off, Hadoop by default specifies two
* resources, loaded in-order from the classpath: <ol>
* <li><tt><a href="{@docRoot}/../core-default.html">core-default.xml</a>
* </tt>: Read-only defaults for hadoop.</li>
* <li><tt>core-site.xml</tt>: Site-specific configuration for a given hadoop
* installation.</li>
* </ol>
* Applications may add additional resources, which are loaded
* subsequent to these resources in the order they are added.
*
* <h4 id="FinalParams">Final Parameters</h4>
*
* <p>Configuration parameters may be declared <i>final</i>.
* Once a resource declares a value final, no subsequently-loaded
* resource can alter that value.
* For example, one might define a final parameter with:
* <tt><pre>
* <property>
* <name>dfs.client.buffer.dir</name>
* <value>/tmp/hadoop/dfs/client</value>
* <b><final>true</final></b>
* </property></pre></tt>
*
* Administrators typically define parameters as final in
* <tt>core-site.xml</tt> for values that user applications may not alter.
*
* <h4 id="VariableExpansion">Variable Expansion</h4>
*
* <p>Value strings are first processed for <i>variable expansion</i>. The
* available properties are:<ol>
* <li>Other properties defined in this Configuration; and, if a name is
* undefined here,</li>
* <li>Properties in {@link System#getProperties()}.</li>
* </ol>
*
* <p>For example, if a configuration resource contains the following property
* definitions:
* <tt><pre>
* <property>
* <name>basedir</name>
* <value>/user/${<i>user.name</i>}</value>
* </property>
*
* <property>
* <name>tempdir</name>
* <value>${<i>basedir</i>}/tmp</value>
* </property></pre></tt>
*
* When <tt>conf.get("tempdir")</tt> is called, then <tt>${<i>basedir</i>}</tt>
* will be resolved to another property in this Configuration, while
* <tt>${<i>user.name</i>}</tt> would then ordinarily be resolved to the value
* of the System property with that name.
*/
public class Configuration implements Iterable<Map.Entry<String,String>>,
Writable {
private static final Log LOG =
LogFactory.getLog(Configuration.class);
private boolean quietmode = true;
/**
* List of configuration resources.
*/
private ArrayList<Object> resources = new ArrayList<Object>();
/**
* List of configuration parameters marked <b>final</b>.
*/
private Set<String> finalParameters = new HashSet<String>();
private boolean loadDefaults = true;
/**
* Configuration objects
*/
private static final WeakHashMap<Configuration,Object> REGISTRY =
new WeakHashMap<Configuration,Object>();
/**
* List of default Resources. Resources are loaded in the order of the list
* entries
*/
private static final CopyOnWriteArrayList<String> defaultResources =
new CopyOnWriteArrayList<String>();
/**
* The value reported as the setting resource when a key is set
* by code rather than a file resource.
*/
static final String UNKNOWN_RESOURCE = "Unknown";
/**
* Stores the mapping of key to the resource which modifies or loads
* the key most recently
*/
private HashMap<String, String> updatingResource;
static{
//print deprecation warning if hadoop-site.xml is found in classpath
ClassLoader cL = Thread.currentThread().getContextClassLoader();
if (cL == null) {
cL = Configuration.class.getClassLoader();
}
if(cL.getResource("hadoop-site.xml")!=null) {
LOG.warn("DEPRECATED: hadoop-site.xml found in the classpath. " +
"Usage of hadoop-site.xml is deprecated. Instead use core-site.xml, "
+ "mapred-site.xml and hdfs-site.xml to override properties of " +
"core-default.xml, mapred-default.xml and hdfs-default.xml " +
"respectively");
}
addDefaultResource("core-default.xml");
addDefaultResource("core-site.xml");
}
private Properties properties;
private Properties overlay;
private ClassLoader classLoader;
{
classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = Configuration.class.getClassLoader();
}
}
/** A new configuration. */
public Configuration() {
this(true);
}
/** A new configuration where the behavior of reading from the default
* resources can be turned off.
*
* If the parameter {@code loadDefaults} is false, the new instance
* will not load resources from the default files.
* @param loadDefaults specifies whether to load from the default files
*/
public Configuration(boolean loadDefaults) {
this.loadDefaults = loadDefaults;
updatingResource = new HashMap<String, String>();
synchronized(Configuration.class) {
REGISTRY.put(this, null);
}
}
/**
* A new configuration with the same settings cloned from another.
*
* @param other the configuration from which to clone settings.
*/
@SuppressWarnings("unchecked")
public Configuration(Configuration other) {
this.resources = (ArrayList) other.resources.clone();
synchronized (other) {
if (other.properties != null) {
this.properties = (Properties) other.properties.clone();
}
if (other.overlay != null) {
this.overlay = (Properties) other.overlay.clone();
}
this.updatingResource = new HashMap<String, String>(
other.updatingResource);
}
this.finalParameters = new HashSet<String>(other.finalParameters);
synchronized (Configuration.class) {
REGISTRY.put(this, null);
}
}
/**
* Add a default resource. Resources are loaded in the order of the resources
* added.
* @param name file name. File should be present in the classpath.
*/
public static synchronized void addDefaultResource(String name) {
if(!defaultResources.contains(name)) {
defaultResources.add(name);
for(Configuration conf : REGISTRY.keySet()) {
if(conf.loadDefaults) {
conf.reloadConfiguration();
}
}
}
}
/**
* Add a configuration resource.
*
* The properties of this resource will override properties of previously
* added resources, unless they were marked <a href="#Final">final</a>.
*
* @param name resource to be added, the classpath is examined for a file
* with that name.
*/
public void addResource(String name) {
addResourceObject(name);
}
/**
* Add a configuration resource.
*
* The properties of this resource will override properties of previously
* added resources, unless they were marked <a href="#Final">final</a>.
*
* @param url url of the resource to be added, the local filesystem is
* examined directly to find the resource, without referring to
* the classpath.
*/
public void addResource(URL url) {
addResourceObject(url);
}
/**
* Add a configuration resource.
*
* The properties of this resource will override properties of previously
* added resources, unless they were marked <a href="#Final">final</a>.
*
* @param file file-path of resource to be added, the local filesystem is
* examined directly to find the resource, without referring to
* the classpath.
*/
public void addResource(Path file) {
addResourceObject(file);
}
/**
* Add a configuration resource.
*
* The properties of this resource will override properties of previously
* added resources, unless they were marked <a href="#Final">final</a>.
*
* @param in InputStream to deserialize the object from.
*/
public void addResource(InputStream in) {
addResourceObject(in);
}
/**
* Reload configuration from previously added resources.
*
* This method will clear all the configuration read from the added
* resources, and final parameters. This will make the resources to
* be read again before accessing the values. Values that are added
* via set methods will overlay values read from the resources.
*/
public synchronized void reloadConfiguration() {
properties = null; // trigger reload
finalParameters.clear(); // clear site-limits
}
private synchronized void addResourceObject(Object resource) {
resources.add(resource); // add to resources
reloadConfiguration();
}
private static Pattern varPat = Pattern.compile("\\$\\{[^\\}\\$\u0020]+\\}");
private static int MAX_SUBST = 20;
private String substituteVars(String expr) {
if (expr == null) {
return null;
}
Matcher match = varPat.matcher("");
String eval = expr;
for(int s=0; s<MAX_SUBST; s++) {
match.reset(eval);
if (!match.find()) {
return eval;
}
String var = match.group();
var = var.substring(2, var.length()-1); // remove ${ .. }
String val = null;
try {
val = System.getProperty(var);
} catch(SecurityException se) {
LOG.warn("Unexpected SecurityException in Configuration", se);
}
if (val == null) {
val = getRaw(var);
}
if (val == null) {
return eval; // return literal ${var}: var is unbound
}
// substitute
eval = eval.substring(0, match.start())+val+eval.substring(match.end());
}
throw new IllegalStateException("Variable substitution depth too large: "
+ MAX_SUBST + " " + expr);
}
/**
* Get the value of the <code>name</code> property, <code>null</code> if
* no such property exists.
*
* Values are processed for <a href="#VariableExpansion">variable expansion</a>
* before being returned.
*
* @param name the property name.
* @return the value of the <code>name</code> property,
* or null if no such property exists.
*/
public String get(String name) {
return substituteVars(getProps().getProperty(name));
}
/**
* Get the value of the <code>name</code> property, without doing
* <a href="#VariableExpansion">variable expansion</a>.
*
* @param name the property name.
* @return the value of the <code>name</code> property,
* or null if no such property exists.
*/
public String getRaw(String name) {
return getProps().getProperty(name);
}
/**
* Set the <code>value</code> of the <code>name</code> property.
*
* @param name property name.
* @param value property value.
*/
public void set(String name, String value) {
getOverlay().setProperty(name, value);
getProps().setProperty(name, value);
this.updatingResource.put(name, UNKNOWN_RESOURCE);
}
/**
* Sets a property if it is currently unset.
* @param name the property name
* @param value the new value
*/
public void setIfUnset(String name, String value) {
if (get(name) == null) {
set(name, value);
}
}
private synchronized Properties getOverlay() {
if (overlay==null){
overlay=new Properties();
}
return overlay;
}
/**
* Get the value of the <code>name</code> property. If no such property
* exists, then <code>defaultValue</code> is returned.
*
* @param name property name.
* @param defaultValue default value.
* @return property value, or <code>defaultValue</code> if the property
* doesn't exist.
*/
public String get(String name, String defaultValue) {
return substituteVars(getProps().getProperty(name, defaultValue));
}
/**
* Get the value of the <code>name</code> property as an <code>int</code>.
*
* If no such property exists, or if the specified value is not a valid
* <code>int</code>, then <code>defaultValue</code> is returned.
*
* @param name property name.
* @param defaultValue default value.
* @return property value as an <code>int</code>,
* or <code>defaultValue</code>.
*/
public int getInt(String name, int defaultValue) {
String valueString = get(name);
if (valueString == null)
return defaultValue;
try {
String hexString = getHexDigits(valueString);
if (hexString != null) {
return Integer.parseInt(hexString, 16);
}
return Integer.parseInt(valueString);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/**
* Set the value of the <code>name</code> property to an <code>int</code>.
*
* @param name property name.
* @param value <code>int</code> value of the property.
*/
public void setInt(String name, int value) {
set(name, Integer.toString(value));
}
/**
* Get the value of the <code>name</code> property as a <code>long</code>.
* If no such property is specified, or if the specified value is not a valid
* <code>long</code>, then <code>defaultValue</code> is returned.
*
* @param name property name.
* @param defaultValue default value.
* @return property value as a <code>long</code>,
* or <code>defaultValue</code>.
*/
public long getLong(String name, long defaultValue) {
String valueString = get(name);
if (valueString == null)
return defaultValue;
try {
String hexString = getHexDigits(valueString);
if (hexString != null) {
return Long.parseLong(hexString, 16);
}
return Long.parseLong(valueString);
} catch (NumberFormatException e) {
return defaultValue;
}
}
private String getHexDigits(String value) {
boolean negative = false;
String str = value;
String hexString = null;
if (value.startsWith("-")) {
negative = true;
str = value.substring(1);
}
if (str.startsWith("0x") || str.startsWith("0X")) {
hexString = str.substring(2);
if (negative) {
hexString = "-" + hexString;
}
return hexString;
}
return null;
}
/**
* Set the value of the <code>name</code> property to a <code>long</code>.
*
* @param name property name.
* @param value <code>long</code> value of the property.
*/
public void setLong(String name, long value) {
set(name, Long.toString(value));
}
/**
* Get the value of the <code>name</code> property as a <code>float</code>.
* If no such property is specified, or if the specified value is not a valid
* <code>float</code>, then <code>defaultValue</code> is returned.
*
* @param name property name.
* @param defaultValue default value.
* @return property value as a <code>float</code>,
* or <code>defaultValue</code>.
*/
public float getFloat(String name, float defaultValue) {
String valueString = get(name);
if (valueString == null)
return defaultValue;
try {
return Float.parseFloat(valueString);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/**
* Set the value of the <code>name</code> property to a <code>float</code>.
*
* @param name property name.
* @param value property value.
*/
public void setFloat(String name, float value) {
set(name,Float.toString(value));
}
/**
* Get the value of the <code>name</code> property as a <code>boolean</code>.
* If no such property is specified, or if the specified value is not a valid
* <code>boolean</code>, then <code>defaultValue</code> is returned.
*
* @param name property name.
* @param defaultValue default value.
* @return property value as a <code>boolean</code>,
* or <code>defaultValue</code>.
*/
public boolean getBoolean(String name, boolean defaultValue) {
String valueString = get(name);
if ("true".equals(valueString))
return true;
else if ("false".equals(valueString))
return false;
else return defaultValue;
}
/**
* Set the value of the <code>name</code> property to a <code>boolean</code>.
*
* @param name property name.
* @param value <code>boolean</code> value of the property.
*/
public void setBoolean(String name, boolean value) {
set(name, Boolean.toString(value));
}
/**
* Set the given property, if it is currently unset.
* @param name property name
* @param value new value
*/
public void setBooleanIfUnset(String name, boolean value) {
setIfUnset(name, Boolean.toString(value));
}
/**
* Set the value of the <code>name</code> property to the given type. This
* is equivalent to <code>set(<name>, value.toString())</code>.
* @param name property name
* @param value new value
*/
public <T extends Enum<T>> void setEnum(String name, T value) {
set(name, value.toString());
}
/**
* Return value matching this enumerated type.
* @param name Property name
* @param defaultValue Value returned if no mapping exists
* @throws IllegalArgumentException If mapping is illegal for the type
* provided
*/
public <T extends Enum<T>> T getEnum(String name, T defaultValue) {
final String val = get(name);
return null == val
? defaultValue
: Enum.valueOf(defaultValue.getDeclaringClass(), val);
}
/**
* A class that represents a set of positive integer ranges. It parses
* strings of the form: "2-3,5,7-" where ranges are separated by comma and
* the lower/upper bounds are separated by dash. Either the lower or upper
* bound may be omitted meaning all values up to or over. So the string
* above means 2, 3, 5, and 7, 8, 9, ...
*/
public static class IntegerRanges {
private static class Range {
int start;
int end;
}
List<Range> ranges = new ArrayList<Range>();
public IntegerRanges() {
}
public IntegerRanges(String newValue) {
StringTokenizer itr = new StringTokenizer(newValue, ",");
while (itr.hasMoreTokens()) {
String rng = itr.nextToken().trim();
String[] parts = rng.split("-", 3);
if (parts.length < 1 || parts.length > 2) {
throw new IllegalArgumentException("integer range badly formed: " +
rng);
}
Range r = new Range();
r.start = convertToInt(parts[0], 0);
if (parts.length == 2) {
r.end = convertToInt(parts[1], Integer.MAX_VALUE);
} else {
r.end = r.start;
}
if (r.start > r.end) {
throw new IllegalArgumentException("IntegerRange from " + r.start +
" to " + r.end + " is invalid");
}
ranges.add(r);
}
}
/**
* Convert a string to an int treating empty strings as the default value.
* @param value the string value
* @param defaultValue the value for if the string is empty
* @return the desired integer
*/
private static int convertToInt(String value, int defaultValue) {
String trim = value.trim();
if (trim.length() == 0) {
return defaultValue;
}
return Integer.parseInt(trim);
}
/**
* Is the given value in the set of ranges
* @param value the value to check
* @return is the value in the ranges?
*/
public boolean isIncluded(int value) {
for(Range r: ranges) {
if (r.start <= value && value <= r.end) {
return true;
}
}
return false;
}
@Override
public String toString() {
StringBuffer result = new StringBuffer();
boolean first = true;
for(Range r: ranges) {
if (first) {
first = false;
} else {
result.append(',');
}
result.append(r.start);
result.append('-');
result.append(r.end);
}
return result.toString();
}
}
/**
* Parse the given attribute as a set of integer ranges
* @param name the attribute name
* @param defaultValue the default value if it is not set
* @return a new set of ranges from the configured value
*/
public IntegerRanges getRange(String name, String defaultValue) {
return new IntegerRanges(get(name, defaultValue));
}
/**
* Get the comma delimited values of the <code>name</code> property as
* a collection of <code>String</code>s.
* If no such property is specified then empty collection is returned.
* <p>
* This is an optimized version of {@link #getStrings(String)}
*
* @param name property name.
* @return property value as a collection of <code>String</code>s.
*/
public Collection<String> getStringCollection(String name) {
String valueString = get(name);
return StringUtils.getStringCollection(valueString);
}
/**
* Get the comma delimited values of the <code>name</code> property as
* an array of <code>String</code>s.
* If no such property is specified then <code>null</code> is returned.
*
* @param name property name.
* @return property value as an array of <code>String</code>s,
* or <code>null</code>.
*/
public String[] getStrings(String name) {
String valueString = get(name);
return StringUtils.getStrings(valueString);
}
/**
* Get the comma delimited values of the <code>name</code> property as
* an array of <code>String</code>s.
* If no such property is specified then default value is returned.
*
* @param name property name.
* @param defaultValue The default value
* @return property value as an array of <code>String</code>s,
* or default value.
*/
public String[] getStrings(String name, String... defaultValue) {
String valueString = get(name);
if (valueString == null) {
return defaultValue;
} else {
return StringUtils.getStrings(valueString);
}
}
/**
* Set the array of string values for the <code>name</code> property as
* as comma delimited values.
*
* @param name property name.
* @param values The values
*/
public void setStrings(String name, String... values) {
set(name, StringUtils.arrayToString(values));
}
/**
* Load a class by name.
*
* @param name the class name.
* @return the class object.
* @throws ClassNotFoundException if the class is not found.
*/
public Class<?> getClassByName(String name) throws ClassNotFoundException {
return Class.forName(name, true, classLoader);
}
/**
* Get the value of the <code>name</code> property
* as an array of <code>Class</code>.
* The value of the property specifies a list of comma separated class names.
* If no such property is specified, then <code>defaultValue</code> is
* returned.
*
* @param name the property name.
* @param defaultValue default value.
* @return property value as a <code>Class[]</code>,
* or <code>defaultValue</code>.
*/
public Class<?>[] getClasses(String name, Class<?> ... defaultValue) {
String[] classnames = getStrings(name);
if (classnames == null)
return defaultValue;
try {
Class<?>[] classes = new Class<?>[classnames.length];
for(int i = 0; i < classnames.length; i++) {
classes[i] = getClassByName(classnames[i]);
}
return classes;
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* Get the value of the <code>name</code> property as a <code>Class</code>.
* If no such property is specified, then <code>defaultValue</code> is
* returned.
*
* @param name the class name.
* @param defaultValue default value.
* @return property value as a <code>Class</code>,
* or <code>defaultValue</code>.
*/
public Class<?> getClass(String name, Class<?> defaultValue) {
String valueString = get(name);
if (valueString == null)
return defaultValue;
try {
return getClassByName(valueString);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* Get the value of the <code>name</code> property as a <code>Class</code>
* implementing the interface specified by <code>xface</code>.
*
* If no such property is specified, then <code>defaultValue</code> is
* returned.
*
* An exception is thrown if the returned class does not implement the named
* interface.
*
* @param name the class name.
* @param defaultValue default value.
* @param xface the interface implemented by the named class.
* @return property value as a <code>Class</code>,
* or <code>defaultValue</code>.
*/
public <U> Class<? extends U> getClass(String name,
Class<? extends U> defaultValue,
Class<U> xface) {
try {
Class<?> theClass = getClass(name, defaultValue);
if (theClass != null && !xface.isAssignableFrom(theClass))
throw new RuntimeException(theClass+" not "+xface.getName());
else if (theClass != null)
return theClass.asSubclass(xface);
else
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Get the value of the <code>name</code> property as a <code>List</code>
* of objects implementing the interface specified by <code>xface</code>.
*
* An exception is thrown if any of the classes does not exist, or if it does
* not implement the named interface.
*
* @param name the property name.
* @param xface the interface implemented by the classes named by
* <code>name</code>.
* @return a <code>List</code> of objects implementing <code>xface</code>.
*/
@SuppressWarnings("unchecked")
public <U> List<U> getInstances(String name, Class<U> xface) {
List<U> ret = new ArrayList<U>();
Class<?>[] classes = getClasses(name);
for (Class<?> cl: classes) {
if (!xface.isAssignableFrom(cl)) {
throw new RuntimeException(cl + " does not implement " + xface);
}
ret.add((U)ReflectionUtils.newInstance(cl, this));
}
return ret;
}
/**
* Set the value of the <code>name</code> property to the name of a
* <code>theClass</code> implementing the given interface <code>xface</code>.
*
* An exception is thrown if <code>theClass</code> does not implement the
* interface <code>xface</code>.
*
* @param name property name.
* @param theClass property value.
* @param xface the interface implemented by the named class.
*/
public void setClass(String name, Class<?> theClass, Class<?> xface) {
if (!xface.isAssignableFrom(theClass))
throw new RuntimeException(theClass+" not "+xface.getName());
set(name, theClass.getName());
}
/**
* Get a local file under a directory named by <i>dirsProp</i> with
* the given <i>path</i>. If <i>dirsProp</i> contains multiple directories,
* then one is chosen based on <i>path</i>'s hash code. If the selected
* directory does not exist, an attempt is made to create it.
*
* @param dirsProp directory in which to locate the file.
* @param path file-path.
* @return local file under the directory with the given path.
*/
public Path getLocalPath(String dirsProp, String path)
throws IOException {
String[] dirs = getStrings(dirsProp);
int hashCode = path.hashCode();
FileSystem fs = FileSystem.getLocal(this);
for (int i = 0; i < dirs.length; i++) { // try each local dir
int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length;
Path file = new Path(dirs[index], path);
Path dir = file.getParent();
if (fs.mkdirs(dir) || fs.exists(dir)) {
return file;
}
}
LOG.warn("Could not make " + path +
" in local directories from " + dirsProp);
for(int i=0; i < dirs.length; i++) {
int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length;
LOG.warn(dirsProp + "[" + index + "]=" + dirs[index]);
}
throw new IOException("No valid local directories in property: "+dirsProp);
}
/**
* Get a local file name under a directory named in <i>dirsProp</i> with
* the given <i>path</i>. If <i>dirsProp</i> contains multiple directories,
* then one is chosen based on <i>path</i>'s hash code. If the selected
* directory does not exist, an attempt is made to create it.
*
* @param dirsProp directory in which to locate the file.
* @param path file-path.
* @return local file under the directory with the given path.
*/
public File getFile(String dirsProp, String path)
throws IOException {
String[] dirs = getStrings(dirsProp);
int hashCode = path.hashCode();
for (int i = 0; i < dirs.length; i++) { // try each local dir
int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length;
File file = new File(dirs[index], path);
File dir = file.getParentFile();
if (dir.exists() || dir.mkdirs()) {
return file;
}
}
throw new IOException("No valid local directories in property: "+dirsProp);
}
/**
* Get the {@link URL} for the named resource.
*
* @param name resource name.
* @return the url for the named resource.
*/
public URL getResource(String name) {
return classLoader.getResource(name);
}
/**
* Get an input stream attached to the configuration resource with the
* given <code>name</code>.
*
* @param name configuration resource name.
* @return an input stream attached to the resource.
*/