-
Notifications
You must be signed in to change notification settings - Fork 364
/
Configuration.java
1422 lines (1368 loc) · 48.2 KB
/
Configuration.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2021 Bosch.IO GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors:
* Bosch IO.GmbH - initial creation (derived from former NetworkConfig
* in org.eclipse.californium.core.network.config)
******************************************************************************/
package org.eclipse.californium.elements.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import org.eclipse.californium.elements.Definitions;
import org.eclipse.californium.elements.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The configuration for a Californium's components.
*
* In Californium the configuration is considered to be used via 3 interfaces:
* <ul>
* <li>The modules of Californium are consuming their configuration values using
* the get functions.</li>
* <li>The configuration values of the used modules are presented in a
* properties file in order to enable a end-user to provide values according the
* specific usage.</li>
* <li>The applications using Californium may use the set functions in order to
* provide application specific values.</li>
* </ul>
* <p>
*
* Example parts of "Californium3.properties":
*
* <pre>
* <code>
* # Californium CoAP Properties file for client
* # Tue Oct 19 10:21:43 CEST 2021
* #
* # Random factor for initial CoAP acknowledge timeout.
* # Default: 1.5
* COAP.ACK_INIT_RANDOM=1.5
* # Initial CoAP acknowledge timeout.
* # Default: 2[s]
* COAP.ACK_TIMEOUT=2[s]
* # Scale factor for CoAP acknowledge backoff-timeout.
* # Default: 2.0
* COAP.ACK_TIMEOUT_SCALE=2.0
* # Enable automatic failover on "entity too large" response.
* # Default: true
* COAP.BLOCKWISE_ENTITY_TOO_LARGE_AUTO_FAILOVER=true
* ...
* </code>
* </pre>
*
* If an application uses the properties file, an user may adapt the values
* according the specific requirements by editing this file.
* <p>
* If you want to implement an application, you need to decide which modules you
* want to use. Currently the following modules are available:
*
* <dl>
* <dt>UdpConfig</dt>
* <dd>Configuration options for plain UDP communication</dd>
* <dt>TcpConfig</dt>
* <dd>Configuration options for TCP and TLS communication</dd>
* <dt>DtlsConfig</dt>
* <dd>Configuration options for DTLS communication</dd>
* <dt>CoapConfig</dt>
* <dd>Configuration options for CoAP processing</dd>
* <dt>Proxy2Config</dt>
* <dd>Configuration options for CoAP proxy processing</dd>
* </dl>
*
* Register the required modules ahead using
*
* <pre>
* <code>
* ...
* static {
* DtlsConfig.register();
* CoapConfig.register();
* }
* ...
* public static void main(String[] args) {
* Configuration.getStandard();
* ...
* }
* </code>
* </pre>
*
* You will need to add the modules also to your maven {@code pom.xml} in order
* to use them. Please refer to that specific {@code ???fConfig.xml} to see,
* which values are supported.
* <p>
* The configuration may be changed via the API.
*
* <pre>
* <code>
* Configuration config = Configuration.getStandard()
* .set(CoapConfig.PREFERRED_BLOCK_SIZE, 1_024)
* .set(CoapConfig.EXCHANGE_LIFETIME, 2, TimeUnit.MINUTES)
* .set(CoapConfig.MAX_RESOURCE_BODY_SIZE, 1_000_000);
* </code>
* </pre>
* <p>
*
* <b>Note:</b> an application, which uses this API, doesn't allow a end user to
* configure these value using the properties file. If the application doesn't
* support to use a properties file at all, the end user must use the mechanism
* defined by that application.
* <p>
* In order to simplify the consumption by Californium itself, the data-model is
* kept (mostly) simple and usually already defines the defaults. That prevents
* to apply several different defaults when accessing them.
* <p>
* If custom logic is required for properties files, please consider to
* {@link #setTransient(DocumentedDefinition)} such a value and replace it by a
* custom definition (with different name and detailed documentation!). It's
* then the responsibility of that custom code to determine the value for the
* original Californium configuration value and set that before passing the
* configuration to Californium's functions.
*
* <pre>
* <code>
* public static final TimeDefinition APPL_HEALTH_STATUS_INTERVAL = new TimeDefinition(
* "APPL_HEALTH_STATUS_INTERVAL", "Application Health status interval. 0 to disable the health status. Default depends on CLI parameter.");
* ...
* Configuration config = Configuration.getStandard();
* config.setTransient(NetworkConfig.HEALTH_STATUS_INTERVAL);
* config.set(APPL_HEALTH_STATUS_INTERVAL, null, TimeUnit.SECONDS);
* ...
* config.save();
* config.load();
* ...
* Long time = config.get(APPL_HEALTH_STATUS_INTERVAL, TimeUnit.SECONDS);
* if (time == null) {
* time = cli.healthInterval;
* }
* config.set(SystemConfig.HEALTH_STATUS_INTERVAL, time, TimeUnit.SECONDS);
* ...
* </code>
* </pre>
*
* <p>
* If both, the file-based provider and the setter-API, provides values for one
* configuration topic, the value of the setter has precedence over the one from
* the file. CLI parameters may be passed in with that. For other overwrites,
* please consider to document them in order to make it transparent for users.
* In cases, where the configuration value is always overwritten by a CLI
* parameter, consider to mark the value as transient.
* <p>
* Depending on the environment, the configuration is stored and loaded from
* properties files. When that file does not exist, Californium generates a
* properties file. If file access is not possible, there are variants, which
* are marked as "WithoutFile" or variants, which use a {@link InputStream} to
* read the properties. Please use such a variant, e.g.
* {@link #createStandardWithoutFile()}, if you want Californium to stop
* generating a properties file. In order to still use the properties file to
* provide specific values, such a file may be generate on a system, where files
* are possible to write. Take that generated file as template, edit it
* accordingly and then use it as "read-only" source.
* <p>
* <b>Note</b>: For Android it's recommended to use the AssetManager and pass in
* the InputStream to the variants using that as parameter. Alternatively you
* may chose to use the "WithoutFile" variant and, if required, adjust the
* defaults in your code. If the "File" variants are used, ensure, that you have
* the android-os-permission to do so.
* <p>
* In order to use this {@link Configuration} with modules (sets of
* {@link DocumentedDefinition}),
* {@link #addDefaultModule(ModuleDefinitionsProvider)} is used to register a
* {@link ModuleDefinitionsProvider}. When creating a new {@link Configuration},
* all registered {@link ModuleDefinitionsProvider} are applied and will fill
* the map of {@link DocumentedDefinition}s and values. In order to ensure, that
* the modules are register in a early stage, a application should call e.g.
* {@link SystemConfig#register()} of the used modules at the begin. See
* {@link SystemConfig} as example.
*
* <p>
* Alternatively
* {@link Configuration#Configuration(ModuleDefinitionsProvider...)} may be used
* to provide the set of modules the {@link Configuration} is based of.
* <p>
* In some case an application may adapt the default definitions by providing an
* {@link DefinitionsProvider} to
* {@link #createFromStream(InputStream, DefinitionsProvider)} or
* {@link #createWithFile(File, String, DefinitionsProvider)}.
*
* <pre>
* <code>
* private static DefinitionsProvider DEFAULTS = new DefinitionsProvider() {
*
* @Override
* public void applyDefinitions(Configuration config) {
* config.set(CoapConfig.MAX_ACTIVE_PEERS, 100);
* config.set(CoapConfig.PROTOCOL_STAGE_THREAD_COUNT, 2);
* config.set(DtlsConfig.DTLS_RECEIVER_THREAD_COUNT, 1);
* }
* };
*
* Configuration config = Configuration.createWithFile(new File("My3.properties"), "My properties", DEFAULTS);
* </code>
* </pre>
* <p>
* Especially if Californium is used with a set of applications instead of a
* single one, ensure, that it's either clear, which file is used by which
* application, or use the same modules for all files, regardless, if a specific
* application of that set is using a module or not. The same applies, if single
* values are marked with {@link #setTransient(DocumentedDefinition)}.
* <p>
* To access the values always using the original {@link DocumentedDefinition}s
* of a module, e.g. {@link SystemConfig#HEALTH_STATUS_INTERVAL}.
*
* <pre>
* <code>
* Configuration config = Configuration.getStandard();
* config.set(SystemConfig.HEALTH_STATUS_INTERVAL, 30, TimeUnit.SECONDS);
* ...
* long timeMillis = config.get(SystemConfig.HEALTH_STATUS_INTERVAL, TimeUnit.MILLISECONDS);
* </code>
* </pre>
* <p>
* When primitive types (e.g. {@code int}) are used to process configuration
* values, care must be taken to define a proper default value instead of
* returning {@code null}. The {@link DocumentedDefinition}s therefore offer
* variants, where such a default could be provided, e.g.
* {@link IntegerDefinition#IntegerDefinition(String, String, Integer)}.
* <p>
* For definitions a optional minimum value may be provided. That doesn't grant,
* that the resulting configuration is proper, neither general nor for specific
* conditions. If a minimum value is too high for your use-case, please create
* an issue in the
* <a href="https://github.com/eclipse-californium/californium" target=
* "_blank">Californium github repository</a>.
*
* @see SystemConfig
* @see TcpConfig
* @see UdpConfig
*
* @since 3.0 (derived from the former NetworkConfig in
* org.eclipse.californium.core.network.config)
*/
public final class Configuration {
/**
* The default name for the configuration.
*/
public static final String DEFAULT_FILE_NAME = "Californium3.properties";
/**
* The default file for the configuration.
*/
public static final File DEFAULT_FILE = new File(DEFAULT_FILE_NAME);
/**
* The default header for a configuration file.
*/
public static final String DEFAULT_HEADER = "Californium3 CoAP Properties file";
/**
* Handler for (custom) setup of configuration
* {@link DocumentedDefinition}s.
*/
public interface DefinitionsProvider {
/**
* Apply definitions.
*
* <pre>
* <code>
* private static DefinitionsProvider DEFAULTS = new DefinitionsProvider() {
*
* @Override
* public void applyDefinitions(Configuration config) {
* config.set(CoapConfig.MAX_ACTIVE_PEERS, 100);
* config.set(CoapConfig.PROTOCOL_STAGE_THREAD_COUNT, 2);
* config.set(DtlsConfig.DTLS_RECEIVER_THREAD_COUNT, 1);
* }
* };
*
* Configuration config = Configuration.createWithFile(new File("My3.properties"), "My properties", DEFAULTS);
* </code>
* </pre>
*
* Use {@link Configuration#set(BasicDefinition, Object)},
* {@link Configuration#set(TimeDefinition, int, TimeUnit)} or
* {@link Configuration#set(TimeDefinition, Long, TimeUnit)} to apply
* the definitions.
*
* @param config configuration to be apply the definitions.
*/
void applyDefinitions(Configuration config);
}
/**
* Handler for (custom) setup of configuration
* {@link DocumentedDefinition}s.
*/
public interface ModuleDefinitionsProvider extends DefinitionsProvider {
/**
* Get module name
*
* @return module name
*/
String getModule();
}
private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class);
/**
* The map of registered default modules.
*/
private static final ConcurrentMap<String, DefinitionsProvider> DEFAULT_MODULES = new ConcurrentHashMap<>();
/**
* The default properties definitions.
*/
private static final Definitions<DocumentedDefinition<?>> DEFAULT_DEFINITIONS = new Definitions<>("Configuration");
/**
* The standard configuration that is used if none is defined.
*/
private static Configuration standard;
/**
* Modules.
*/
private final ConcurrentMap<String, DefinitionsProvider> modules;
/**
* Definitions.
*/
private final Definitions<DocumentedDefinition<?>> definitions;
/**
* The typed properties.
*/
private final Map<String, Object> values = new HashMap<>();
/**
* The transient property names.
*/
private final Set<String> transientValues = new HashSet<>();
/**
* The deprecated property names.
*
* @since 3.5
*/
private final Map<String, String> deprecatedValues = new HashMap<>();
/**
* Add definitions provider for module.
*
* @param modules available modules to add the module
* @param definitionsProvider definitions provider of module
* @return {@code true}, if module is added, {@code false}, if modules was
* already added.
* @throws NullPointerException if any parameter is {@code null}
* @throws IllegalArgumentException if the module name is {@code null} or
* empty or a different definitions provider is already
* registered with that module name.
*/
private static boolean addModule(ConcurrentMap<String, DefinitionsProvider> modules,
ModuleDefinitionsProvider definitionsProvider) {
if (modules == null) {
throw new NullPointerException("Modules must not be null!");
}
if (definitionsProvider == null) {
throw new NullPointerException("DefinitionsProvider must not be null!");
}
String module = definitionsProvider.getModule();
if (module == null) {
throw new IllegalArgumentException("DefinitionsProvider's module must not be null!");
}
if (module.isEmpty()) {
throw new IllegalArgumentException("DefinitionsProvider's module name must not be empty!");
}
DefinitionsProvider previous = modules.putIfAbsent(module, definitionsProvider);
if (previous != null && previous != definitionsProvider) {
throw new IllegalArgumentException("Module " + module + " already registered with different provider!");
}
return previous == null;
}
/**
* Add definitions provider for module.
*
* @param definitionsProvider definitions provider of module
* @throws NullPointerException if any parameter is {@code null}
* @throws IllegalArgumentException if the module name is {@code null} or
* empty or a different definitions provider is already
* registered with that module name.
*/
public static void addDefaultModule(ModuleDefinitionsProvider definitionsProvider) {
if (addModule(DEFAULT_MODULES, definitionsProvider)) {
LOGGER.info("defaults added {}", definitionsProvider.getModule());
}
}
/**
* Gives access to the standard configuration.
*
* When a new endpoint or server is created without a specific
* configuration, it will use this standard configuration.
*
* Apply all {@link ModuleDefinitionsProvider} of registered modules.
*
* For Android, please ensure, that either
* {@link Configuration#setStandard(Configuration)},
* {@link Configuration#createStandardWithoutFile()}, or
* {@link Configuration#createStandardFromStream(InputStream)} is called
* before!
*
* <pre>
* <code>
* CoapConfig.register();
* DtlsConfig.register();
* ...
* Configuration.getStandard();
* </code>
* </pre>
*
* @return the standard configuration
* @throws IllegalStateException if configuration has no definitions.
* @see #addDefaultModule(ModuleDefinitionsProvider)
*/
public static Configuration getStandard() {
synchronized (Configuration.class) {
if (standard == null)
createStandardWithFile(DEFAULT_FILE);
}
return standard;
}
/**
* Sets the standard configuration.
*
* @param standard the new standard configuration
*/
public static void setStandard(Configuration standard) {
Configuration.standard = standard;
}
/**
* Creates the standard configuration without reading it or writing it to a
* file.
*
* Applies all {@link ModuleDefinitionsProvider} of registered modules. A
* previous standard configuration will be replaced by this.
*
* <pre>
* <code>
* CoapConfig.register();
* DtlsConfig.register();
* ...
* Configuration.createStandardWithoutFile();
* </code>
* </pre>
*
* @return the standard configuration
* @see #addDefaultModule(ModuleDefinitionsProvider)
*/
public static Configuration createStandardWithoutFile() {
LOGGER.info("Creating standard configuration properties without a file");
standard = new Configuration();
return standard;
}
/**
* Creates the standard configuration from stream.
*
* Support environments without file access.
*
* Applies all {@link ModuleDefinitionsProvider} of registered modules. A
* previous standard configuration will be replaced by this.
*
* <pre>
* <code>
* CoapConfig.register();
* DtlsConfig.register();
* ...
* Configuration.createStandardFromStream(in);
* </code>
* </pre>
*
* @param inStream input stream to read properties.
* @return the standard configuration
* @throws NullPointerException if the in stream is {@code null}.
* @throws IllegalStateException if configuration has no definitions.
* @see #addDefaultModule(ModuleDefinitionsProvider)
*/
public static Configuration createStandardFromStream(InputStream inStream) {
standard = createFromStream(inStream, null);
return standard;
}
/**
* Creates a configuration from stream.
*
* Support environments without file access.
*
* Applies all {@link ModuleDefinitionsProvider} of registered modules.
*
* <pre>
* <code>
* CoapConfig.register();
* ...
* Configuration.createStandardWithoutFile();
* </code>
* </pre>
*
* @param inStream input stream to read properties.
* @param customProvider custom definitions handler. May be {@code null}.
* @return the configuration
* @throws NullPointerException if the in stream is {@code null}.
* @throws IllegalStateException if configuration has no definitions.
* @see #addDefaultModule(ModuleDefinitionsProvider)
*/
public static Configuration createFromStream(InputStream inStream, DefinitionsProvider customProvider) {
LOGGER.info("Creating configuration properties from stream");
Configuration configuration = new Configuration();
configuration.apply(customProvider);
try {
configuration.load(inStream);
} catch (IOException e) {
LOGGER.warn("cannot load properties from stream: {}", e.getMessage());
}
return configuration;
}
/**
* Creates the standard configuration with a file.
*
* If the provided file exists, the configuration reads the properties from
* this file. Otherwise it creates the file.
*
* Applies all {@link ModuleDefinitionsProvider} of registered modules. A
* previous standard configuration will be replaced by this.
*
* For Android, please use
* {@link Configuration#createStandardWithoutFile()}, or
* {@link Configuration#createStandardFromStream(InputStream)}.
*
* <pre>
* <code>
* CoapConfig.register();
* DtlsConfig.register();
* ...
* Configuration.createStandardWithFile(file);
* </code>
* </pre>
*
* @param file the configuration file
* @return the standard configuration
* @throws NullPointerException if the file is {@code null}.
* @throws IllegalStateException if configuration has no definitions.
* @see #addDefaultModule(ModuleDefinitionsProvider)
*/
public static Configuration createStandardWithFile(File file) {
standard = createWithFile(file, DEFAULT_HEADER, null);
return standard;
}
/**
* Creates a configuration with a file.
*
* If the provided file exists, the configuration reads the properties from
* this file. Otherwise it creates the file with the provided header.
*
* Applies all {@link ModuleDefinitionsProvider} of registered modules.
*
* For Android, please use {@link Configuration#Configuration()}, and load
* the values using {@link Configuration#load(InputStream)} or adjust the in
* your code.
*
* <pre>
* <code>
* CoapConfig.register();
* DtlsConfig.register();
* ...
* Configuration.createWithFile(...);
* </code>
* </pre>
*
* @param file the configuration file
* @param header The header to write to the top of the file.
* @param customProvider custom definitions handler. May be {@code null}.
* @return the configuration
* @throws NullPointerException if the file or header is {@code null}.
* @throws IllegalStateException if configuration has no definitions.
* @see #addDefaultModule(ModuleDefinitionsProvider)
*/
public static Configuration createWithFile(File file, String header, DefinitionsProvider customProvider) {
if (file == null) {
throw new NullPointerException("file must not be null!");
}
Configuration configuration = new Configuration();
configuration.apply(customProvider);
if (file.exists()) {
configuration.load(file);
} else {
configuration.store(file, header);
}
return configuration;
}
/**
* Instantiates a new configuration and sets the value definitions using the
* registered module's {@link ModuleDefinitionsProvider}s.
*
* @see #addDefaultModule(ModuleDefinitionsProvider)
*/
public Configuration() {
this.definitions = DEFAULT_DEFINITIONS;
this.modules = DEFAULT_MODULES;
applyModules();
}
/**
* Instantiates a new configuration and sets the values and from the
* provided configuration.
*
* @param config configuration to copy
*/
public Configuration(Configuration config) {
this.definitions = DEFAULT_DEFINITIONS == config.definitions ? DEFAULT_DEFINITIONS
: new Definitions<DocumentedDefinition<?>>(config.definitions);
this.modules = DEFAULT_MODULES == config.modules ? DEFAULT_MODULES
: new ConcurrentHashMap<String, Configuration.DefinitionsProvider>(config.modules);
this.transientValues.addAll(config.transientValues);
this.values.putAll(config.values);
}
/**
* Instantiates a new configuration and sets the value definitions using the
* provided {@link ModuleDefinitionsProvider}s.
*
* @param providers module definitions provider
*/
public Configuration(ModuleDefinitionsProvider... providers) {
this.definitions = new Definitions<>("Configuration");
this.modules = new ConcurrentHashMap<>();
for (ModuleDefinitionsProvider provider : providers) {
if (addModule(modules, provider)) {
LOGGER.trace("added {}", provider.getModule());
}
}
applyModules();
}
/**
* Apply module's definitions.
*
* Add default values and definitions.
*/
private void applyModules() {
for (DefinitionsProvider handler : modules.values()) {
handler.applyDefinitions(this);
}
}
/**
* Apply custom provider.
*
* @param customProvider custom provider. May be {@code null}.
*/
private void apply(DefinitionsProvider customProvider) {
if (customProvider != null) {
Set<String> before = new HashSet<>(modules.keySet());
customProvider.applyDefinitions(this);
if (before.size() < modules.size()) {
Set<String> set = modules.keySet();
set.removeAll(before);
for (String newModule : set) {
LOGGER.warn("Add missing module {}", newModule);
modules.get(newModule).applyDefinitions(this);
}
customProvider.applyDefinitions(this);
}
}
}
/**
* Loads properties from a file.
*
* Requires to add the {@link DocumentedDefinition}s of the modules or
* custom definitions using a setter ahead.
*
* Unknown, transient or invalid values are ignored and the
* {@link DocumentedDefinition#getDefaultValue()} will be used instead.
*
* For Android, please use {@link Configuration#load(InputStream)}.
*
* @param file the file
* @throws NullPointerException if the file is {@code null}.
* @throws IllegalStateException if configuration has no definitions.
* @see #addDefaultModule(ModuleDefinitionsProvider)
* @see #Configuration(ModuleDefinitionsProvider...)
* @see #set(BasicDefinition, Object)
* @see #set(TimeDefinition, int, TimeUnit)
* @see #set(TimeDefinition, Long, TimeUnit)
* @see #setFromText(DocumentedDefinition, String)
*/
public void load(final File file) {
if (file == null) {
throw new NullPointerException("file must not be null");
} else {
LOGGER.info("loading properties from file {}", file.getAbsolutePath());
try (InputStream inStream = new FileInputStream(file)) {
load(inStream);
} catch (IOException e) {
LOGGER.warn("cannot load properties from file {}: {}", file.getAbsolutePath(), e.getMessage());
}
}
}
/**
* Loads properties from a input stream.
*
* Requires to add the {@link DocumentedDefinition}s of the modules or
* custom definitions using a setter ahead.
*
* Unknown, transient or invalid values are ignored and the
* {@link DocumentedDefinition#getDefaultValue()} will be used instead.
*
* @param inStream the input stream
* @throws NullPointerException if the inStream is {@code null}.
* @throws IOException if an error occurred when reading from the input
* stream
* @throws IllegalStateException if configuration has no definitions.
* @see #addDefaultModule(ModuleDefinitionsProvider)
* @see #Configuration(ModuleDefinitionsProvider...)
* @see #set(BasicDefinition, Object)
* @see #set(TimeDefinition, int, TimeUnit)
* @see #set(TimeDefinition, Long, TimeUnit)
* @see #setFromText(DocumentedDefinition, String)
*/
public void load(final InputStream inStream) throws IOException {
if (inStream == null) {
throw new NullPointerException("input stream must not be null");
}
Properties properties = new Properties();
properties.load(inStream);
add(properties);
}
/**
* Add properties.
*
* Requires to add the {@link DocumentedDefinition}s of the modules or
* custom definitions using a setter ahead.
*
* Unknown, transient or invalid values are ignored and the
* {@link DocumentedDefinition#getDefaultValue()} will be used instead.
*
* Applies conversion defined by that {@link DocumentedDefinition}s to the
* textual values.
*
* @param properties properties to convert and add
* @throws NullPointerException if properties is {@code null}.
* @throws IllegalStateException if configuration has no definitions.
* @see #addDefaultModule(ModuleDefinitionsProvider)
* @see #Configuration(ModuleDefinitionsProvider...)
* @see #set(BasicDefinition, Object)
* @see #set(TimeDefinition, int, TimeUnit)
* @see #set(TimeDefinition, Long, TimeUnit)
* @see #setFromText(DocumentedDefinition, String)
*/
public void add(Properties properties) {
if (properties == null) {
throw new NullPointerException("properties must not be null!");
}
if (definitions.isEmpty()) {
throw new IllegalStateException("Configuration contains no definitions!");
}
for (Object k : properties.keySet()) {
if (k instanceof String) {
String key = (String) k;
DocumentedDefinition<?> definition = definitions.get(key);
if (definition == null) {
LOGGER.warn("Ignore {}, no configuration definition available!", key);
} else if (useLoad(key)) {
String text = properties.getProperty(key);
Object value = loadValue(definition, text);
values.put(key, value);
}
}
}
}
/**
* Add dictionary.
*
* Requires to add the {@link DocumentedDefinition}s of the modules or
* custom definitions using a setter ahead.
*
* Unknown, transient or invalid values are ignored and the
* {@link DocumentedDefinition#getDefaultValue()} will be used instead.
*
* Applies conversion defined by that {@link DocumentedDefinition}s to
* String entries. Entries of other types are added, if
* {@link DocumentedDefinition#isAssignableFrom(Object)} returns
* {@code true}.
*
* @param dictionary dictionary to convert and add
* @throws NullPointerException if dictionary is {@code null}.
* @throws IllegalStateException if configuration has no definitions.
* @see #addDefaultModule(ModuleDefinitionsProvider)
* @see #Configuration(ModuleDefinitionsProvider...)
* @see #set(BasicDefinition, Object)
* @see #set(TimeDefinition, int, TimeUnit)
* @see #set(TimeDefinition, Long, TimeUnit)
* @see #setFromText(DocumentedDefinition, String)
*/
public void add(Dictionary<String, ?> dictionary) {
if (dictionary == null) {
throw new NullPointerException("dictionary must not be null!");
}
if (definitions.isEmpty()) {
throw new IllegalStateException("Configuration contains no definitions!");
}
for (Enumeration<String> allKeys = dictionary.keys(); allKeys.hasMoreElements();) {
String key = allKeys.nextElement();
Object value = dictionary.get(key);
DocumentedDefinition<?> definition = definitions.get(key);
if (definition == null) {
LOGGER.warn("Ignore {}, no configuration definition available!", key);
} else if (useLoad(key)) {
if (value instanceof String) {
String text = (String) value;
value = loadValue(definition, text);
} else if (value != null) {
if (!definition.isAssignableFrom(value)) {
LOGGER.warn("{} is not a {}!", value.getClass().getSimpleName(), definition.getTypeName());
value = null;
}
try {
value = definition.checkRawValue(value);
} catch (ValueException e) {
value = null;
}
}
values.put(key, value);
}
}
}
/**
* Check, if value is to be loaded.
*
* Transient values are not loaded. For both, transient and deprecated
* values, a warning message is written to the logging.
*
* @param key key to check
* @return {@code true}, to load the value, {@code false}, to ignore it.
* @see #setTransient(DocumentedDefinition)
* @see #setDeprecated(DocumentedDefinition, DocumentedDefinition)
* @since 3.5
*/
private boolean useLoad(String key) {
if (transientValues.contains(key)) {
LOGGER.warn("Ignore {}, definition set transient!", key);
return false;
} else {
if (deprecatedValues.containsKey(key)) {
String replace = deprecatedValues.get(key);
if (replace != null) {
LOGGER.warn("Deprecated {}, please replace it by {}!", key, replace);
} else {
LOGGER.warn("Deprecated {}, please remove it!", key);
}
} else {
LOGGER.debug("Load {}", key);
}
return true;
}
}
/**
* Load value from text.
*
* @param definition value's definition
* @param text textual value
* @return value, or {@code null}, if textual value is empty or could not be
* read.
*/
private Object loadValue(DocumentedDefinition<?> definition, String text) {
Object value = null;
if (text != null) {
text = text.trim();
if (!text.isEmpty()) {
try {
value = definition.readValue(text);
} catch (RuntimeException ex) {
LOGGER.warn("{}", ex.getMessage());
value = null;
}
}
}
return value;
}
/**
* Stores the configuration to a file.
*
* Not intended for Android!
*
* @param file The file to write to.
* @throws NullPointerException if the file is {@code null}.
* @throws IllegalStateException if configuration has no definitions.
*/
public void store(final File file) {
store(file, DEFAULT_HEADER);
}
/**
* Stores the configuration to a file using a given header.
*
* Not intended for Android!
*
* @param file The file to write to.
* @param header The header to write to the top of the file.
* @throws NullPointerException if the file or header is {@code null}.
* @throws IllegalStateException if configuration has no definitions.
*/
public void store(File file, String header) {
if (file == null) {
throw new NullPointerException("file must not be null");
} else {
try (FileOutputStream out = new FileOutputStream(file)) {
store(out, header, file.getAbsolutePath());
} catch (IOException e) {
LOGGER.warn("cannot write properties to {}: {}", file.getAbsolutePath(), e.getMessage());
}
}
}
/**
* Stores the configuration to a stream using a given header.
*
* @param out stream to store
* @param header header to use
* @param resourceName resource name of store for logging, if available. May
* be {@code null}, if not.
* @throws NullPointerException if out stream or header is {@code null}
* @throws IllegalStateException if configuration has no definitions.
*/
public void store(OutputStream out, String header, String resourceName) {
if (out == null) {
throw new NullPointerException("output stream must not be null!");
}
if (header == null) {
throw new NullPointerException("header must not be null!");
}
if (resourceName != null) {
LOGGER.info("writing properties to {}", resourceName);
}
if (values.isEmpty()) {
throw new IllegalStateException("Configuration contains no values!");
}
try {
Set<String> modules = this.modules.keySet();
List<String> generalKeys = new ArrayList<>();
List<String> moduleKeys = new ArrayList<>();
for (String key : values.keySet()) {
if (transientValues.contains(key) || deprecatedValues.containsKey(key)) {
continue;
}
boolean add = true;
for (String head : modules) {
if (key.startsWith(head)) {
moduleKeys.add(key);