aboutsummaryrefslogtreecommitdiffstats
path: root/app-c/appc/appc-common/src/main/java/org/openecomp/appc/configuration/DefaultConfiguration.java
blob: 7af4917249ac1ee868e1281aa32a8583c2064dde (plain)
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
/*-
 * ============LICENSE_START=======================================================
 * openECOMP : APP-C
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights
 * 						reserved.
 * ================================================================================
 * Licensed 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.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.appc.configuration;



import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.security.Provider;
import java.security.Provider.Service;
import java.security.Security;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openecomp.appc.encryption.EncryptionTool;
import org.openecomp.appc.util.UnmodifiableProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class provides the implementation of the <code>Configuration</code> interface. It is created by the
 * ConfigurationFactory and initialized with the configuration values for the process.
 * 
 * @since Mar 18, 2014
 * @version $Id$
 */
public final class DefaultConfiguration implements Configuration, Cloneable {

    private static final Logger logger = LoggerFactory.getLogger(DefaultConfiguration.class);

    /**
     * The framework configuration properties.
     */
    private Properties properties = new Properties();

    /**
     * Construct the configuration object.
     */
    public DefaultConfiguration() {
    }

    /**
     * Clears all properties
     */
    public void clear() {
        properties.clear();
    }

    /**
     * @see java.lang.Object#clone()
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        DefaultConfiguration clone = (DefaultConfiguration) super.clone();

        clone.properties = new Properties(this.properties);
        clone.properties.putAll(this.properties);

        return clone;
    }

    /**
     * Decrypts an encrypted value, if it is encrypted, and returns the clear text. Performs no operation on the string
     * if it is not encrypted.
     * 
     * @param value
     *            The value to (optionally) be decrypted
     * @return The clear text
     */
    @SuppressWarnings("nls")
    private static String decrypt(String value) {
        if (value != null) {
            if (value.startsWith(EncryptionTool.ENCRYPTED_VALUE_PREFIX)) {
                try {
                    return EncryptionTool.getInstance().decrypt(value);
                } catch (Throwable e) {
                    String out = "";
                    for (Provider p : Security.getProviders()) {
                        for (Service s : p.getServices()) {
                            String algo = s.getAlgorithm();
                            out +=
                                String.format("\n==Found Algorithm [ %s ] in provider [ %s ] and service [ %s ]", algo,
                                    p.getName(), s.getClassName());
                        }
                    }
                    logger.debug(out);
                    logger.warn(String.format("Could not decrypt the configuration value [%s]", value), e);
                }
            }
        }
        return value;
    }

    /**
     * Decrypts all elements in the properties object
     */
    private void decryptAllProperties() {
        if (properties != null) {
            for (Entry<Object, Object> e : properties.entrySet()) {
                if (e.getValue() != null) {
                    e.setValue(decrypt(e.getValue().toString()));
                }
            }
        }
    }

    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        DefaultConfiguration other = (DefaultConfiguration) obj;

        if ((this.properties.size() == other.properties.size())
            && (this.properties.entrySet().containsAll(other.properties.entrySet()))
            && (other.properties.entrySet().containsAll(this.properties.entrySet()))) {
            return true;
        }

        return false;
    }

    /**
     * This method will use the properties object to expand any variables that may be present in the template provided.
     * Variables are represented by the string "${name}", where "name" is the name of a property defined in either the
     * current configuration object, or system properties if undefined. If the value cannot be found, the variable is
     * removed and an empty string is used to replace the variable.
     * 
     * @param template
     *            The template to be expanded
     * @return The expanded template where each variable is replaced with its value
     */
    @SuppressWarnings("nls")
    private String expandVariables(String template) {
        if (template == null) {
            return template;
        }

        // Decrypt the template if needed
        // template = decrypt(template); DH: Do not assign values to parameters, bad form! Also, Sonar complains
        // bitterly

        StringBuffer buffer = new StringBuffer(decrypt(template));
        Pattern pattern = Pattern.compile("\\$\\{([^\\}]+)\\}");
        Matcher matcher = pattern.matcher(buffer);
        while (matcher.find()) {
            String variable = matcher.group(1);
            String value = properties.getProperty(variable);
            if (value == null) {
                value = System.getProperty(variable);
            }
            if (value == null) {
                value = "";
            }
            buffer.replace(matcher.start(), matcher.end(), value);

            matcher.reset();
        }
        return buffer.toString().trim();
    }

    /**
     * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for
     * Boolean.parseBoolean() are used.
     * 
     * @param key
     *            The property key
     * @return The value of the property expressed as a boolean, or false if it does not exist.
     */
    @SuppressWarnings("nls")
    @Override
    public boolean getBooleanProperty(String key) {
        return Boolean.valueOf(getProperty(key, "false")).booleanValue();
    }

    /**
     * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for
     * Boolean.valueOf(String) are used.
     * 
     * @param key
     *            The property key
     * @param defaultValue
     *            The default value to be returned if the property does not exist
     * @return The value of the property expressed as a boolean, or false if it does not exist.
     * @see org.openecomp.appc.configuration.Configuration#getBooleanProperty(java.lang.String, boolean)
     */
    @Override
    public boolean getBooleanProperty(String key, boolean defaultValue) {
        if (isPropertyDefined(key)) {
            return getBooleanProperty(key);
        }
        return defaultValue;
    }

    /**
     * Returns the indicated property value expressed as a floating point double-precision value (double).
     * 
     * @param key
     *            The property to retrieve
     * @return The value of the property, or 0.0 if not found
     * @see org.openecomp.appc.configuration.Configuration#getDoubleProperty(java.lang.String)
     */
    @SuppressWarnings("nls")
    @Override
    public double getDoubleProperty(String key) {
        try {
            return Double.valueOf(getProperty(key, "0.0")).doubleValue();
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }

    /**
     * This method is called to obtain a property as a string value
     * 
     * @param key
     *            The key of the property
     * @param defaultValue
     *            The default value to be returned if the property does not exist
     * @return The string value, or null if it does not exist.
     * @see org.openecomp.appc.configuration.Configuration#getDoubleProperty(java.lang.String, double)
     */
    @Override
    public double getDoubleProperty(String key, double defaultValue) {
        if (isPropertyDefined(key)) {
            return getDoubleProperty(key);
        }
        return defaultValue;
    }

    /**
     * Returns the property indicated expressed as an integer. The standard rules for
     * {@link Integer#parseInt(String, int)} using a radix of 10 are used.
     * 
     * @param key
     *            The property name to retrieve.
     * @returns The value of the property, or 0 if it does not exist or is invalid.
     * @see org.openecomp.appc.configuration.Configuration#getIntegerProperty(java.lang.String)
     */
    @SuppressWarnings("nls")
    @Override
    public int getIntegerProperty(String key) {
        try {
            return Integer.parseInt(getProperty(key, "0"), 10);
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    /**
     * Returns the property indicated expressed as an integer. The standard rules for Integer.parseInt(String, int)
     * using a radix of 10 are used.
     * 
     * @param key
     *            The property name to retrieve.
     * @param defaultValue
     *            The default value to be returned if the property does not exist
     * @return The value of the property, or 0 if it does not exist or is invalid.
     * @see org.openecomp.appc.configuration.Configuration#getIntegerProperty(java.lang.String, int)
     */
    @Override
    public int getIntegerProperty(String key, int defaultValue) {
        if (isPropertyDefined(key)) {
            return getIntegerProperty(key);
        }
        return defaultValue;
    }

    /**
     * Returns the specified property as a long integer value, if it exists, or zero if it does not.
     * 
     * @param key
     *            The key of the property desired.
     * @return The value of the property expressed as an integer long value, or zero if the property does not exist or
     *         is not a valid integer long.
     * @see org.openecomp.appc.configuration.Configuration#getLongProperty(java.lang.String)
     */
    @SuppressWarnings("nls")
    @Override
    public long getLongProperty(String key) {
        try {
            return Long.parseLong(getProperty(key, "0"), 10);
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    /**
     * Returns the specified property as a long integer value, if it exists, or the default value if it does not exist
     * or is invalid.
     * 
     * @param key
     *            The key of the property desired.
     * @param defaultValue
     *            the value to be returned if the property is not valid or does not exist.
     * @return The value of the property expressed as an integer long value, or the default value if the property does
     *         not exist or is not a valid integer long.
     * @see org.openecomp.appc.configuration.Configuration#getLongProperty(java.lang.String, long)
     */
    @Override
    public long getLongProperty(String key, long defaultValue) {
        if (isPropertyDefined(key)) {
            return getLongProperty(key);
        }
        return defaultValue;
    }

    /**
     * This method can be called to retrieve a properties object that is immutable. Any attempt to modify the properties
     * object returned will result in an exception. This allows a caller to view the current configuration as a set of
     * properties.
     * 
     * @return An unmodifiable properties object.
     * @see org.openecomp.appc.configuration.Configuration#getProperties()
     */
    @Override
    public Properties getProperties() {
        return new UnmodifiableProperties(properties);
    }

    /**
     * This method is called to obtain a property as a string value
     * 
     * @param key
     *            The key of the property
     * @return The string value, or null if it does not exist.
     */
    @Override
    public String getProperty(String key) {
        String value = properties.getProperty(key);
        if (value == null) {
            return null;
        }
        return expandVariables(value.trim());
    }

    /**
     * This method is called to obtain a property as a string value
     * 
     * @param key
     *            The key of the property
     * @param defaultValue
     *            The default value to be returned if the property does not exist
     * @return The string value, or null if it does not exist.
     * @see org.openecomp.appc.configuration.Configuration#getProperty(java.lang.String, java.lang.String)
     */
    @Override
    public String getProperty(String key, String defaultValue) {
        if (isPropertyDefined(key)) {
            return getProperty(key);
        }

        if (defaultValue == null) {
            return null;
        }

        return expandVariables(defaultValue.trim());
    }

    /**
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        return (properties == null ? 0 : properties.hashCode());
    }

    /**
     * Returns true if the named property is defined, false otherwise.
     * 
     * @param key
     *            The key of the property we are interested in
     * @return True if the property exists.
     */
    @Override
    public boolean isPropertyDefined(String key) {
        return properties.containsKey(key);
    }

    /**
     * Returns an indication of the validity of the boolean property. A boolean property is considered to be valid only
     * if it has the value "true" or "false" (ignoring case).
     * 
     * @param key
     *            The property to be checked
     * @returns True if the value is a boolean constant, or false if it does not exist or is not a correct string
     * @see org.openecomp.appc.configuration.Configuration#isValidBoolean(java.lang.String)
     */
    @SuppressWarnings("nls")
    @Override
    public boolean isValidBoolean(String key) {
        String value = getProperty(key);
        if (value != null) {
            value = value.toLowerCase();
            return value.matches("true|false");
        }
        return false;
    }

    /**
     * Returns an indication if the indicated property represents a valid double-precision floating point number.
     * 
     * @param key
     *            The property to be examined
     * @returns True if the property is a valid representation of a double, or false if it does not exist or contains
     *          illegal characters.
     * @see org.openecomp.appc.configuration.Configuration#isValidDouble(java.lang.String)
     */
    @Override
    public boolean isValidDouble(String key) {
        String value = getProperty(key);
        if (value != null) {
            try {
                Double.valueOf(value);
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }
        return false;
    }

    /**
     * Returns an indication if the property is a valid integer value or not.
     * 
     * @param key
     *            The key of the property to check
     * @returns True if the value is a valid integer string, or false if it does not exist or contains illegal
     *          characters.
     * @see org.openecomp.appc.configuration.Configuration#isValidInteger(java.lang.String)
     */
    @Override
    public boolean isValidInteger(String key) {
        String value = getProperty(key);
        if (value != null) {
            try {
                Integer.parseInt(value.trim(), 10);
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }
        return false;
    }

    /**
     * Determines is the specified property exists and is a valid representation of an integer long value.
     * 
     * @param key
     *            The property to be checked
     * @return True if the property is a valid representation of an integer long value, and false if it either does not
     *         exist or is not valid.
     * @see org.openecomp.appc.configuration.Configuration#isValidLong(java.lang.String)
     */
    @Override
    public boolean isValidLong(String key) {
        String value = getProperty(key);
        if (value != null) {
            try {
                Long.parseLong(value.trim(), 10);
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }
        return false;
    }

    /**
     * This method allows an implementation to load configuration properties that may override default values.
     * 
     * @param is
     *            An input stream that contains the properties to be loaded
     */
    public void setProperties(InputStream is) {
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * This method allows an implementation to load configuration properties that may override default values.
     * 
     * @param props
     *            An optional Properties object to be merged into the configuration, replacing any same-named
     *            properties.
     * @see org.openecomp.appc.configuration.Configuration#setProperties(java.util.Properties)
     */
    @Override
    public void setProperties(Properties props) {
        properties.putAll(props);
        decryptAllProperties();
    }

    /**
     * This method allows a caller to insert a new property definition into the configuration object. This allows the
     * application to adjust or add to the current configuration. If the property already exists, it is replaced with
     * the new value.
     * 
     * @param key
     *            The key of the property to be defined
     * @param value
     *            The value of the property to be defined
     * @see org.openecomp.appc.configuration.Configuration#setProperty(java.lang.String, java.lang.String)
     */
    @Override
    public void setProperty(String key, String value) {
        properties.setProperty(key, decrypt(value));
    }

    /**
     * @see java.lang.Object#toString()
     */
    @SuppressWarnings("nls")
    @Override
    public String toString() {
        return String.format("Configuration: %d properties, keys:[%s]", properties.size(), properties.keySet()
            .toString());
    }

    /**
     * This is a helper method to read the manifest of the jar file that this class was loaded from. Note that this will
     * only work if the code is packaged in a jar file. If it is an open deployment, such as under eclipse, this will
     * not work and there is code added to detect that case.
     * 
     * @return The manifest object from the jar file, or null if the code is not packaged in a jar file.
     */
    @SuppressWarnings({
        "unused", "nls"
    })
    private Manifest getManifest() {
        ProtectionDomain domain = getClass().getProtectionDomain();
        CodeSource source = domain.getCodeSource();
        URL location = source.getLocation();
        String path = location.getPath();
        int index = path.indexOf('!');
        if (index != -1) {
            path = path.substring(0, index);
        }
        if (path.endsWith(".jar")) {
            try (JarFile jar = new JarFile(location.getFile())) {
                return jar.getManifest();
            } catch (IOException e) {
                logger.error("getManifest", e);
            }
        }

        return null;
    }
}