diff options
author | Skip Wonnell <skip@att.com> | 2017-12-16 18:48:27 -0600 |
---|---|---|
committer | Patrick Brady <pb071s@att.com> | 2017-12-19 04:39:25 +0000 |
commit | 17c2c59a3301cdc969fe53a9de8e0d84d4163b9e (patch) | |
tree | ee21556245fa45e9cab78b5ef52e7655b33e45d1 /appc-common/src/main | |
parent | 3d77400558365d716f567248d189a474d0bc8fae (diff) |
Platform hardening for common bundle
General code clean up code
Additional test cases
Support for APPC-348, APPC-349
Issue-ID: APPC-305
Change-Id: I341c960bb33794c681aea86f2bd1b415294ec03f
Signed-off-by: Skip Wonnell <skip@att.com>
Diffstat (limited to 'appc-common/src/main')
14 files changed, 887 insertions, 466 deletions
diff --git a/appc-common/src/main/java/org/onap/appc/Constants.java b/appc-common/src/main/java/org/onap/appc/Constants.java index e030b647d..0e838395b 100644 --- a/appc-common/src/main/java/org/onap/appc/Constants.java +++ b/appc-common/src/main/java/org/onap/appc/Constants.java @@ -174,7 +174,6 @@ public final class Constants { /** * The name for the status vm attribute to be set in the context when executing a vmstatuscheck. */ - @SuppressWarnings("nls") public static final String STATUS_OF_VM = "status-vm"; @@ -203,10 +202,9 @@ public final class Constants { public static final String YANG_VNF_CONFIG = "vnf-config"; /** - * Private default constructor prevents instantiation + * default constructor prevents instantiation */ - - private Constants() { - + Constants() { + throw new IllegalAccessError("Constants"); } } diff --git a/appc-common/src/main/java/org/onap/appc/cache/impl/MetadataCacheImpl.java b/appc-common/src/main/java/org/onap/appc/cache/impl/MetadataCacheImpl.java index ca225adfe..e660e6ba0 100644 --- a/appc-common/src/main/java/org/onap/appc/cache/impl/MetadataCacheImpl.java +++ b/appc-common/src/main/java/org/onap/appc/cache/impl/MetadataCacheImpl.java @@ -64,6 +64,6 @@ public class MetadataCacheImpl<K,V> implements MetadataCache<K,V> { @Override public void putObject(K key, V value) { - strategy.putObject(key,value); + strategy.putObject(key, value); } } diff --git a/appc-common/src/main/java/org/onap/appc/configuration/ConfigurationFactory.java b/appc-common/src/main/java/org/onap/appc/configuration/ConfigurationFactory.java index 47ffca7e4..a0fda4033 100644 --- a/appc-common/src/main/java/org/onap/appc/configuration/ConfigurationFactory.java +++ b/appc-common/src/main/java/org/onap/appc/configuration/ConfigurationFactory.java @@ -36,41 +36,44 @@ import java.util.Properties; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; - import org.onap.appc.i18n.Msg; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import com.att.eelf.i18n.EELFResourceManager; /** - * The configuration factory is used to obtain access to an already created and initialized singleton configuration - * object as well as to create and initialize the singleton if not already set up. + * The configuration factory is used to obtain access to an already created and initialized + * singleton configuration object as well as to create and initialize the singleton if not already + * set up. * <p> - * This class is responsible for the creation of the configuration object used to manage the configuration of the - * application. The configuration object implementation must implement the <code>Configuration</code> interface. This - * allows for the factory to create different specializations in the future if needed and not break any application - * code. + * This class is responsible for the creation of the configuration object used to manage the + * configuration of the application. The configuration object implementation must implement the + * <code>Configuration</code> interface. This allows for the factory to create different + * specializations in the future if needed and not break any application code. * </p> * <p> - * The configuration object is basically a wrapper around a properties object. The configuration is therefore specified - * as a set of properties that are loaded and processed from different sources with different precedences. It is - * important that the configuration object always be able to supply default values for any configuration properties that - * must be supplied, and not rely on the user always supplying these values. This also relieves the application itself - * from having to interpret missing or invalid properties and applying defaults. By having all of the defaults in one - * place, the application code can be simpler (not having to worry about defaults or invalid properties), and the - * defaults can be changed much easier (they are all in one place and not distributed throughout the codebase). + * The configuration object is basically a wrapper around a properties object. The configuration is + * therefore specified as a set of properties that are loaded and processed from different sources + * with different precedences. It is important that the configuration object always be able to + * supply default values for any configuration properties that must be supplied, and not rely on the + * user always supplying these values. This also relieves the application itself from having to + * interpret missing or invalid properties and applying defaults. By having all of the defaults in + * one place, the application code can be simpler (not having to worry about defaults or invalid + * properties), and the defaults can be changed much easier (they are all in one place and not + * distributed throughout the codebase). * </p> * <p> - * Since the configuration is managed as a property object, we can use a characteristic of the <code>Properties</code> - * class to our advantage. Namely, if we put a property into a <code>Properties</code> object that already exists, the - * <code>Properties</code> object replaces it with the new value. This does not affect any other properties that may - * already be defined in the properties object. This gives us the ability to initialize the properties with default - * values for all of the application settings, then override just those that we need to override, possibly from multiple - * sources and in increasing order of precedence. + * Since the configuration is managed as a property object, we can use a characteristic of the + * <code>Properties</code> class to our advantage. Namely, if we put a property into a + * <code>Properties</code> object that already exists, the <code>Properties</code> object replaces + * it with the new value. This does not affect any other properties that may already be defined in + * the properties object. This gives us the ability to initialize the properties with default values + * for all of the application settings, then override just those that we need to override, possibly + * from multiple sources and in increasing order of precedence. * </p> * <p> - * This means that properties are in effect "merged" together from multiple sources in a prescribed precedence order. In - * fact, the precedence order that this factory implements is defined as: + * This means that properties are in effect "merged" together from multiple sources in a prescribed + * precedence order. In fact, the precedence order that this factory implements is defined as: * </p> * <ol> * <li>Default values from a system resource file.</li> @@ -79,20 +82,21 @@ import com.att.eelf.i18n.EELFResourceManager; * <li>Command-line properties (if any)</li> * </ol> * <p> - * The name and location of the properties file that is loaded can also be set, either in the defaults, overridden by - * the system command line via -D, or as a system environment variable. There are two properties that can be specified - * to define the name and path. These are: + * The name and location of the properties file that is loaded can also be set, either in the + * defaults, overridden by the system command line via -D, or as a system environment variable. + * There are two properties that can be specified to define the name and path. These are: * </p> * <dl> * <dt>org.onap.appc.bootstrap.file</dt> - * <dd>This property defines the name of the file that will be loaded. If not specified, the default value is - * "appc.properties". This can be specified in either (or both) the default properties or the command line. The command - * line specification will always override.</dd> + * <dd>This property defines the name of the file that will be loaded. If not specified, the default + * value is "appc.properties". This can be specified in either (or both) the default properties or + * the command line. The command line specification will always override.</dd> * <dt>org.onap.appc.bootstrap.path</dt> - * <dd>This is a comma-delimited (,) path of directories to be searched to locate the specified file. The first - * occurrence of the file is the one loaded, and no additional searching is performed. The path can be specified in - * either, or both, the default values and the command line specification. If specified on the command line, the value - * overrides the default values. If omitted, the default path is <code>$/opt/onap/appc/data/properties,${user.home},.</code></dd> + * <dd>This is a comma-delimited (,) path of directories to be searched to locate the specified + * file. The first occurrence of the file is the one loaded, and no additional searching is + * performed. The path can be specified in either, or both, the default values and the command line + * specification. If specified on the command line, the value overrides the default values. If + * omitted, the default path is <code>$/opt/onap/appc/data/properties,${user.home},.</code></dd> * </dl> * * @since Mar 18, 2014 @@ -100,16 +104,17 @@ import com.att.eelf.i18n.EELFResourceManager; */ public final class ConfigurationFactory { - private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); /** - * This is a string constant for the comma character. It's intended to be used a common string delimiter. + * This is a string constant for the comma character. It's intended to be used a common string + * delimiter. */ private static final String COMMA = ","; /** - * The default Configuration object that implements the <code>Configuration</code> interface and represents our - * system configuration settings. + * The default Configuration object that implements the <code>Configuration</code> interface and + * represents our system configuration settings. */ private static DefaultConfiguration config = null; @@ -119,9 +124,9 @@ public final class ConfigurationFactory { private static final String DEFAULT_PROPERTIES = "org/onap/appc/default.properties"; /** - * This collection allows for special configurations to be created and maintained, organized by some identification - * (such as an object reference to the StackBuilder to which they apply), and then obtained from the configuration - * factory when needed. + * This collection allows for special configurations to be created and maintained, organized by + * some identification (such as an object reference to the StackBuilder to which they apply), + * and then obtained from the configuration factory when needed. */ private static HashMap<Object, Configuration> localConfigs = new HashMap<>(); @@ -129,22 +134,22 @@ public final class ConfigurationFactory { * The reentrant shared lock used to serialize access to the properties. */ private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - + /** - * This is a constant array of special property names that will be copied from the configuration back to the System - * properties object if they are defined in the configuration AND they do not already exist in the System properties - * object. These are intended as a convenience for setting the AFT properties for the Discovery client where it may - * be difficult or impossible to set VM arguments for the container. + * This is a constant array of special property names that will be copied from the configuration + * back to the System properties object if they are defined in the configuration AND they do not + * already exist in the System properties object. These are intended as a convenience for + * setting the AFT properties for the Discovery client where it may be difficult or impossible + * to set VM arguments for the container. */ - private static final String[] specialProperties = { - "AFT_LATITUDE", "AFT_LONGITUDE", "AFT_ENVIRONMENT", "SCLD_PLATFORM" - }; + private static final String[] specialProperties = + {"AFT_LATITUDE", "AFT_LONGITUDE", "AFT_ENVIRONMENT", "SCLD_PLATFORM"}; - private ConfigurationFactory() { - } + private ConfigurationFactory() {} /** - * This method is used to obtain the common configuration object (as well as set it up if not already). + * This method is used to obtain the common configuration object (as well as set it up if not + * already). * * @return The configuration object implementation */ @@ -158,10 +163,10 @@ public final class ConfigurationFactory { try { /* - * If the properties don't exist, release the read lock and acquire the write lock. Once we get the write - * lock, we need to re-check to see that the configuration needs to be set up (because another thread may - * have beat us to it). After we get a configuration set up, release the write lock and re-obtain the read - * lock to access the properties. + * If the properties don't exist, release the read lock and acquire the write lock. Once + * we get the write lock, we need to re-check to see that the configuration needs to be + * set up (because another thread may have beat us to it). After we get a configuration + * set up, release the write lock and re-obtain the read lock to access the properties. */ if (config == null) { readLock.unlock(); @@ -186,14 +191,14 @@ public final class ConfigurationFactory { } /** - * This method will obtain the local configuration for the specified object if it exists, or will create it from the - * current global configuration. This allows the configuration to be tailored for a specific process or operation, - * and uniquely identified by some value (such as the object that represents the special use of the configuration). + * This method will obtain the local configuration for the specified object if it exists, or + * will create it from the current global configuration. This allows the configuration to be + * tailored for a specific process or operation, and uniquely identified by some value (such as + * the object that represents the special use of the configuration). * - * @param owner - * The owner or identification of the owner of the special configuration - * @return The special configuration object, or a clone of the global configuration so that it can be altered if - * needed. + * @param owner The owner or identification of the owner of the special configuration + * @return The special configuration object, or a clone of the global configuration so that it + * can be altered if needed. */ public static Configuration getConfiguration(final Object owner) { ReadLock readLock = lock.readLock(); @@ -227,20 +232,20 @@ public final class ConfigurationFactory { } /** - * This method allows the caller to alter the configuration, supplying the specified configuration properties which - * override the application default values. + * This method allows the caller to alter the configuration, supplying the specified + * configuration properties which override the application default values. * <p> - * The configuration is re-constructed (if already constructed) or created new (if not already created) and the - * default properties are loaded into the configuration. + * The configuration is re-constructed (if already constructed) or created new (if not already + * created) and the default properties are loaded into the configuration. * </p> * <p> - * The primary purpose of this method is to allow the application configuration properties to be reset or refreshed - * after the application has already been initialized. This method will lock the configuration for the duration - * while it is being re-built, and should not be called on a regular basis. + * The primary purpose of this method is to allow the application configuration properties to be + * reset or refreshed after the application has already been initialized. This method will lock + * the configuration for the duration while it is being re-built, and should not be called on a + * regular basis. * </p> * - * @param props - * The properties used to configure the application. + * @param props The properties used to configure the application. * @return Access to the configuration implementation */ public static Configuration getConfiguration(final Properties props) { @@ -256,25 +261,26 @@ public final class ConfigurationFactory { } /** - * This method will clear the current configuration and then re-initialize it with the default values, - * application-specific configuration file, user-supplied properties (if any), and then command-line settings. + * This method will clear the current configuration and then re-initialize it with the default + * values, application-specific configuration file, user-supplied properties (if any), and then + * command-line settings. * <p> * This method <strong><em>MUST</em></strong> be called holding the configuration lock! * </p> * <p> - * This method is a little special in that logging messages generated during the method must be cached and delayed - * until after the logging framework has been initialized. After that, the delayed logging buffer can be dumped to - * the log file and cleared. + * This method is a little special in that logging messages generated during the method must be + * cached and delayed until after the logging framework has been initialized. After that, the + * delayed logging buffer can be dumped to the log file and cleared. * </p> * - * @param props - * Application-supplied configuration values, if any + * @param props Application-supplied configuration values, if any */ private static void initialize(final Properties props) { DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); Date now = new Date(); - logger.info("------------------------------------------------------------------------------"); - + logger.info( + "------------------------------------------------------------------------------"); + logger.info(Msg.CONFIGURATION_STARTED, format.format(now)); /* @@ -286,7 +292,8 @@ public final class ConfigurationFactory { /* * Load the defaults (if any are present) */ - InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_PROPERTIES); + InputStream in = Thread.currentThread().getContextClassLoader() + .getResourceAsStream(DEFAULT_PROPERTIES); if (in != null) { logger.info(Msg.LOADING_DEFAULTS, DEFAULT_PROPERTIES); try { @@ -307,24 +314,25 @@ public final class ConfigurationFactory { } /* - * Look for application configuration property file. By default, we will look for the file "cdp.properties" on - * the user home path, then on "./etc" (relative to current path), then on "../etc" (relative to current path). - * If we do not find any property file, then we continue. Otherwise, we load the first property file we find and - * then continue. In order to allow default values for the filename and paths to be searched, we first attempt - * to obtain these from our configuration object (which should be primed with default values and/or overridden - * with application-specified values). We then use the values obtained from that to get any user supplied values - * on the command line. + * Look for application configuration property file. By default, we will look for the file + * "cdp.properties" on the user home path, then on "./etc" (relative to current path), then + * on "../etc" (relative to current path). If we do not find any property file, then we + * continue. Otherwise, we load the first property file we find and then continue. In order + * to allow default values for the filename and paths to be searched, we first attempt to + * obtain these from our configuration object (which should be primed with default values + * and/or overridden with application-specified values). We then use the values obtained + * from that to get any user supplied values on the command line. */ - String filename = - config.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME, Configuration.DEFAULT_BOOTSTRAP_FILE_NAME); + String filename = config.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME, + Configuration.DEFAULT_BOOTSTRAP_FILE_NAME); filename = System.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME, filename); String env = System.getenv(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME); if (env != null && env.trim().length() > 0) { filename = env; } - String path = - config.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH, Configuration.DEFAULT_BOOTSTRAP_FILE_PATH); + String path = config.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH, + Configuration.DEFAULT_BOOTSTRAP_FILE_PATH); path = System.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH, path); env = System.getenv(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH); if (env != null && env.trim().length() > 0) { @@ -391,8 +399,8 @@ public final class ConfigurationFactory { config.setProperties(System.getProperties()); /* - * As a convenience, copy the "specialProperties" that are not defined in System.properties from the - * configuration back to the system properties object. + * As a convenience, copy the "specialProperties" that are not defined in System.properties + * from the configuration back to the system properties object. */ for (String key : config.getProperties().stringPropertyNames()) { for (String specialProperty : specialProperties) { @@ -404,14 +412,15 @@ public final class ConfigurationFactory { } /* - * Initialize the resource manager by loading the requested bundles, if any are defined. Resource bundles may be - * specified as a comma-delimited list of names. These resource names are base names of resource bundles, do not - * include the language or country code, or the ".properties" extension. The actual loading of the resource - * bundles is done lazily when requested the first time. If the bundle does not exist, or cannot be loaded, it - * is ignored. + * Initialize the resource manager by loading the requested bundles, if any are defined. + * Resource bundles may be specified as a comma-delimited list of names. These resource + * names are base names of resource bundles, do not include the language or country code, or + * the ".properties" extension. The actual loading of the resource bundles is done lazily + * when requested the first time. If the bundle does not exist, or cannot be loaded, it is + * ignored. */ - String resourcesList = - config.getProperty(Configuration.PROPERTY_RESOURCE_BUNDLES, Configuration.DEFAULT_RESOURCE_BUNDLES); + String resourcesList = config.getProperty(Configuration.PROPERTY_RESOURCE_BUNDLES, + Configuration.DEFAULT_RESOURCE_BUNDLES); String[] resources = resourcesList.split(","); for (String resource : resources) { logger.info(Msg.LOADING_RESOURCE_BUNDLE, resource.trim()); diff --git a/appc-common/src/main/java/org/onap/appc/configuration/DefaultConfiguration.java b/appc-common/src/main/java/org/onap/appc/configuration/DefaultConfiguration.java index 3e86c0788..f6e482b25 100644 --- a/appc-common/src/main/java/org/onap/appc/configuration/DefaultConfiguration.java +++ b/appc-common/src/main/java/org/onap/appc/configuration/DefaultConfiguration.java @@ -38,17 +38,15 @@ import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; - import org.onap.appc.encryption.EncryptionTool; import org.onap.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. + * 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. * - * @version $Id$ * @since Mar 18, 2014 */ public final class DefaultConfiguration implements Configuration, Cloneable { @@ -63,9 +61,7 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * Construct the configuration object. */ - DefaultConfiguration() { - // do nothing - } + DefaultConfiguration() {} /** * Clears all properties @@ -88,8 +84,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * Decrypts an encrypted value, if it is encrypted, and returns the clear text. Performs no operation on the string - * if it is not encrypted. + * 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 @@ -104,12 +100,14 @@ public final class DefaultConfiguration implements Configuration, Cloneable { for (Provider p : Security.getProviders()) { for (Service s : p.getServices()) { String algo = s.getAlgorithm(); - out.append(String.format("\n==Found Algorithm [ %s ] in provider [ %s ] and service [ %s ]", + out.append(String.format( + "\n==Found Algorithm [ %s ] in provider [ %s ] and service [ %s ]", algo, p.getName(), s.getClassName())); } } logger.debug(out.toString()); - logger.warn(String.format("Could not decrypt the configuration value [%s]", value), e); + logger.warn(String.format("Could not decrypt the configuration value [%s]", value), + e); } } return value; @@ -151,10 +149,11 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * 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. + * 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 @@ -166,7 +165,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } // Decrypt the template if needed - // template = decrypt(template); DH: Do not assign values to parameters, bad form! Also, Sonar complains + // template = decrypt(template); DH: Do not assign values to parameters, bad form! Also, + // Sonar complains // bitterly StringBuilder builder = new StringBuilder(decrypt(template)); @@ -189,8 +189,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * This method is called to obtain a property expressed as a boolean value (true or false). The standard rules for - * Boolean.parseBoolean() are used. + * 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. @@ -202,10 +202,10 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * 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. + * 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 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.onap.appc.configuration.Configuration#getBooleanProperty(java.lang.String, boolean) @@ -219,7 +219,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * Returns the indicated property value expressed as a floating point double-precision value (double). + * 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 @@ -238,7 +239,7 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * This method is called to obtain a property as a string value * - * @param key The key of the property + * @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.onap.appc.configuration.Configuration#getDoubleProperty(java.lang.String, double) @@ -270,10 +271,10 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * Returns the property indicated expressed as an integer. The standard rules for Integer.parseInt(String, int) - * using a radix of 10 are used. + * 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 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.onap.appc.configuration.Configuration#getIntegerProperty(java.lang.String, int) @@ -290,8 +291,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { * 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. + * @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.onap.appc.configuration.Configuration#getLongProperty(java.lang.String) */ @SuppressWarnings("nls") @@ -305,13 +306,13 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * Returns the specified property as a long integer value, if it exists, or the default value if it does not exist - * or is invalid. + * 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 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. + * @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.onap.appc.configuration.Configuration#getLongProperty(java.lang.String, long) */ @Override @@ -323,9 +324,9 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * 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. + * 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.onap.appc.configuration.Configuration#getProperties() @@ -353,10 +354,11 @@ public final class DefaultConfiguration implements Configuration, Cloneable { /** * This method is called to obtain a property as a string value * - * @param key The key of the property + * @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.onap.appc.configuration.Configuration#getProperty(java.lang.String, java.lang.String) + * @see org.onap.appc.configuration.Configuration#getProperty(java.lang.String, + * java.lang.String) */ @Override public String getProperty(String key, String defaultValue) { @@ -391,11 +393,12 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * 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). + * 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 - * @return True if the value is a boolean constant, or false if it does not exist or is not a correct string + * @return True if the value is a boolean constant, or false if it does not exist or is not a + * correct string * @see org.onap.appc.configuration.Configuration#isValidBoolean(java.lang.String) */ @SuppressWarnings("nls") @@ -410,11 +413,12 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * Returns an indication if the indicated property represents a valid double-precision floating point number. + * Returns an indication if the indicated property represents a valid double-precision floating + * point number. * * @param key The property to be examined - * @return True if the property is a valid representation of a double, or false if it does not exist or contains - * illegal characters. + * @return True if the property is a valid representation of a double, or false if it does not + * exist or contains illegal characters. * @see org.onap.appc.configuration.Configuration#isValidDouble(java.lang.String) */ @Override @@ -435,8 +439,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { * Returns an indication if the property is a valid integer value or not. * * @param key The key of the property to check - * @return True if the value is a valid integer string, or false if it does not exist or contains illegal - * characters. + * @return True if the value is a valid integer string, or false if it does not exist or + * contains illegal characters. * @see org.onap.appc.configuration.Configuration#isValidInteger(java.lang.String) */ @Override @@ -454,11 +458,12 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * Determines is the specified property exists and is a valid representation of an integer long value. + * 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. + * @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.onap.appc.configuration.Configuration#isValidLong(java.lang.String) */ @Override @@ -476,7 +481,8 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * This method allows an implementation to load configuration properties that may override default values. + * 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 */ @@ -489,10 +495,11 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * This method allows an implementation to load configuration properties that may override default values. + * 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. + * @param props An optional Properties object to be merged into the configuration, replacing any + * same-named properties. * @see org.onap.appc.configuration.Configuration#setProperties(java.util.Properties) */ @Override @@ -502,13 +509,14 @@ public final class DefaultConfiguration implements Configuration, Cloneable { } /** - * 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. + * 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 key The key of the property to be defined * @param value The value of the property to be defined - * @see org.onap.appc.configuration.Configuration#setProperty(java.lang.String, java.lang.String) + * @see org.onap.appc.configuration.Configuration#setProperty(java.lang.String, + * java.lang.String) */ @Override public void setProperty(String key, String value) { @@ -521,20 +529,20 @@ public final class DefaultConfiguration implements Configuration, Cloneable { @SuppressWarnings("nls") @Override public String toString() { - return String.format("Configuration: %d properties, keys:[%s]", - properties.size(), properties.keySet().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. + * 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. + * @return The manifest object from the jar file, or null if the code is not packaged in a jar + * file. */ - @SuppressWarnings({ - "unused", "nls" - }) + @SuppressWarnings({"unused", "nls"}) private Manifest getManifest() { ProtectionDomain domain = getClass().getProtectionDomain(); CodeSource source = domain.getCodeSource(); diff --git a/appc-common/src/main/java/org/onap/appc/i18n/Msg.java b/appc-common/src/main/java/org/onap/appc/i18n/Msg.java index b6a0657a0..2f22a692a 100644 --- a/appc-common/src/main/java/org/onap/appc/i18n/Msg.java +++ b/appc-common/src/main/java/org/onap/appc/i18n/Msg.java @@ -807,7 +807,11 @@ public enum Msg implements EELFResolvableErrorEnum { /** * {0} */ - OAM_OPERATION_INVALID_INPUT, + OAM_OPERATION_INVALID_INPUT, + + ATTACHINGVOLUME_SERVER, + + DETTACHINGVOLUME_SERVER, /** * Unsupported identity service version, unable to retrieve ServiceCatalog diff --git a/appc-common/src/main/java/org/onap/appc/logging/LoggingUtils.java b/appc-common/src/main/java/org/onap/appc/logging/LoggingUtils.java index 1e4156e02..5e0b2fa93 100644 --- a/appc-common/src/main/java/org/onap/appc/logging/LoggingUtils.java +++ b/appc-common/src/main/java/org/onap/appc/logging/LoggingUtils.java @@ -30,10 +30,8 @@ import com.att.eelf.configuration.EELFManager; import com.att.eelf.i18n.EELFResolvableErrorEnum; import com.att.eelf.i18n.EELFResourceManager; import org.slf4j.MDC; - import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; - import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.Instant; @@ -46,76 +44,76 @@ import java.util.TimeZone; */ public class LoggingUtils { - private final static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); - private final static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); - private final static EELFLogger metricLogger = EELFManager.getInstance().getMetricsLogger(); + private static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + private static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + private static final EELFLogger metricLogger = EELFManager.getInstance().getMetricsLogger(); private LoggingUtils() { throw new IllegalAccessError("LoggingUtils"); } - public static void logErrorMessage(String errorCode, String errorDescription, String targetEntity, - String targetServiceName, String additionalMessage, String className) { - logError(errorCode, errorDescription, targetEntity, targetServiceName, additionalMessage, className); + public static void logErrorMessage(String errorCode, String errorDescription, + String targetEntity, String targetServiceName, String additionalMessage, + String className) { + logError(errorCode, errorDescription, targetEntity, targetServiceName, additionalMessage, + className); } - public static void logErrorMessage(String targetEntity, String targetServiceName, String additionalMessage, - String className) { + public static void logErrorMessage(String targetEntity, String targetServiceName, + String additionalMessage, String className) { logError("", "", targetEntity, targetServiceName, additionalMessage, className); } - public static void logErrorMessage(String targetServiceName, String additionalMessage, String className) { - logError("", "", LoggingConstants.TargetNames.APPC, targetServiceName, - additionalMessage, className); + public static void logErrorMessage(String targetServiceName, String additionalMessage, + String className) { + logError("", "", LoggingConstants.TargetNames.APPC, targetServiceName, additionalMessage, + className); } private static void logError(String errorCode, String errorDescription, String targetEntity, - String targetServiceName, String additionalMessage, String className) { - populateErrorLogContext(errorCode, errorDescription, targetEntity, targetServiceName, className); + String targetServiceName, String additionalMessage, String className) { + populateErrorLogContext(errorCode, errorDescription, targetEntity, targetServiceName, + className); errorLogger.error(additionalMessage == null ? "" : additionalMessage); cleanErrorLogContext(); } public static void logAuditMessage(Instant beginTimeStamp, Instant endTimeStamp, String code, - String responseDescription, String className) { + String responseDescription, String className) { populateAuditLogContext(beginTimeStamp, endTimeStamp, code, responseDescription, className); - auditLogger.info(EELFResourceManager.format(Msg.APPC_AUDIT_MSG, - MDC.get(MDC_SERVICE_NAME), + auditLogger.info(EELFResourceManager.format(Msg.APPC_AUDIT_MSG, MDC.get(MDC_SERVICE_NAME), MDC.get(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY), - MDC.get(LoggingConstants.MDCKeys.PARTNER_NAME), - MDC.get(MDC_KEY_REQUEST_ID), + MDC.get(LoggingConstants.MDCKeys.PARTNER_NAME), MDC.get(MDC_KEY_REQUEST_ID), MDC.get(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP), MDC.get(LoggingConstants.MDCKeys.END_TIMESTAMP), MDC.get(LoggingConstants.MDCKeys.RESPONSE_CODE))); cleanAuditErrorContext(); } - public static void auditInfo(Instant beginTimeStamp, Instant endTimeStamp, String code, String responseDescription, - String className,EELFResolvableErrorEnum resourceId, String... arguments) { + public static void auditInfo(Instant beginTimeStamp, Instant endTimeStamp, String code, + String responseDescription, String className, EELFResolvableErrorEnum resourceId, + String... arguments) { populateAuditLogContext(beginTimeStamp, endTimeStamp, code, responseDescription, className); - auditLogger.info(resourceId,arguments); + auditLogger.info(resourceId, arguments); cleanAuditErrorContext(); } - public static void auditWarn(Instant beginTimeStamp, Instant endTimeStamp, String code, String responseDescription, - String className,EELFResolvableErrorEnum resourceId, String... arguments) { + public static void auditWarn(Instant beginTimeStamp, Instant endTimeStamp, String code, + String responseDescription, String className, EELFResolvableErrorEnum resourceId, + String... arguments) { populateAuditLogContext(beginTimeStamp, endTimeStamp, code, responseDescription, className); - auditLogger.warn(resourceId,arguments); + auditLogger.warn(resourceId, arguments); cleanAuditErrorContext(); } - - - public static void logMetricsMessage(Instant beginTimeStamp, Instant endTimeStamp, String targetEntity, - String targetServiceName, String statusCode, String responseCode, - String responseDescription, String className) { - populateMetricLogContext(beginTimeStamp, endTimeStamp, targetEntity, targetServiceName, statusCode, - responseCode, responseDescription, className); - metricLogger.info(EELFResourceManager.format(Msg.APPC_METRIC_MSG, - MDC.get(MDC_SERVICE_NAME), + public static void logMetricsMessage(Instant beginTimeStamp, Instant endTimeStamp, + String targetEntity, String targetServiceName, String statusCode, String responseCode, + String responseDescription, String className) { + populateMetricLogContext(beginTimeStamp, endTimeStamp, targetEntity, targetServiceName, + statusCode, responseCode, responseDescription, className); + metricLogger.info(EELFResourceManager.format(Msg.APPC_METRIC_MSG, MDC.get(MDC_SERVICE_NAME), MDC.get(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY), - MDC.get(LoggingConstants.MDCKeys.PARTNER_NAME), - MDC.get(MDC_KEY_REQUEST_ID), + MDC.get(LoggingConstants.MDCKeys.PARTNER_NAME), MDC.get(MDC_KEY_REQUEST_ID), MDC.get(LoggingConstants.MDCKeys.TARGET_ENTITY), MDC.get(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME), MDC.get(LoggingConstants.MDCKeys.ELAPSED_TIME), @@ -123,15 +121,15 @@ public class LoggingUtils { cleanMetricContext(); } - private static void populateAuditLogContext(Instant beginTimeStamp, Instant endTimeStamp, String code, - String responseDescription, String className) { + private static void populateAuditLogContext(Instant beginTimeStamp, Instant endTimeStamp, + String code, String responseDescription, String className) { populateTimeContext(beginTimeStamp, endTimeStamp); MDC.put(LoggingConstants.MDCKeys.RESPONSE_CODE, code); - MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, "100".equals(code) || "400".equals(code) ? - LoggingConstants.StatusCodes.COMPLETE : - LoggingConstants.StatusCodes.ERROR); - MDC.put(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION, responseDescription!=null?responseDescription:""); - MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, className!=null?className:""); + MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, "100".equals(code) || "400".equals(code) + ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR); + MDC.put(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION, + responseDescription != null ? responseDescription : ""); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, className != null ? className : ""); } private static void cleanAuditErrorContext() { @@ -142,11 +140,11 @@ public class LoggingUtils { MDC.remove(LoggingConstants.MDCKeys.CLASS_NAME); } - private static void populateErrorLogContext(String errorCode, String errorDescription, String targetEntity, - String targetServiceName, String className) { + private static void populateErrorLogContext(String errorCode, String errorDescription, + String targetEntity, String targetServiceName, String className) { populateErrorContext(errorCode, errorDescription); - populateTargetContext(targetEntity, targetServiceName!=null?targetServiceName:""); - MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, className!=null?className:""); + populateTargetContext(targetEntity, targetServiceName != null ? targetServiceName : ""); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, className != null ? className : ""); } private static void cleanErrorLogContext() { @@ -155,13 +153,13 @@ public class LoggingUtils { MDC.remove(LoggingConstants.MDCKeys.CLASS_NAME); } - private static void populateMetricLogContext(Instant beginTimeStamp, Instant endTimeStamp, String targetEntity, - String targetServiceName, String statusCode, String responseCode, - String responseDescription, String className) { + private static void populateMetricLogContext(Instant beginTimeStamp, Instant endTimeStamp, + String targetEntity, String targetServiceName, String statusCode, String responseCode, + String responseDescription, String className) { populateTimeContext(beginTimeStamp, endTimeStamp); populateTargetContext(targetEntity, targetServiceName); populateResponseContext(statusCode, responseCode, responseDescription); - MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, className!=null?className:""); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, className != null ? className : ""); } private static void cleanMetricContext() { @@ -172,8 +170,9 @@ public class LoggingUtils { } private static void populateTargetContext(String targetEntity, String targetServiceName) { - MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, targetEntity!=null?targetEntity:""); - MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, targetServiceName!=null?targetServiceName:""); + MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, targetEntity != null ? targetEntity : ""); + MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, + targetServiceName != null ? targetServiceName : ""); } private static void cleanTargetContext() { @@ -187,7 +186,7 @@ public class LoggingUtils { String elapsedTime = ""; if (beginTimeStamp != null && endTimeStamp != null) { - elapsedTime = String.valueOf(ChronoUnit.MILLIS.between(beginTimeStamp, endTimeStamp)); + elapsedTime = String.valueOf(ChronoUnit.MILLIS.between(beginTimeStamp, endTimeStamp)); beginTime = generateTimestampStr(beginTimeStamp); endTime = generateTimestampStr(endTimeStamp); } @@ -210,10 +209,12 @@ public class LoggingUtils { MDC.remove(LoggingConstants.MDCKeys.ELAPSED_TIME); } - private static void populateResponseContext(String statusCode, String responseCode, String responseDescription) { - MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, statusCode!=null?statusCode:""); + private static void populateResponseContext(String statusCode, String responseCode, + String responseDescription) { + MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, statusCode != null ? statusCode : ""); MDC.put(LoggingConstants.MDCKeys.RESPONSE_CODE, responseCode); - MDC.put(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION, responseDescription!=null?responseDescription:""); + MDC.put(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION, + responseDescription != null ? responseDescription : ""); } private static void cleanResponseContext() { diff --git a/appc-common/src/main/java/org/onap/appc/metadata/objects/DependencyModelIdentifier.java b/appc-common/src/main/java/org/onap/appc/metadata/objects/DependencyModelIdentifier.java index ddd035644..6593c27ec 100644 --- a/appc-common/src/main/java/org/onap/appc/metadata/objects/DependencyModelIdentifier.java +++ b/appc-common/src/main/java/org/onap/appc/metadata/objects/DependencyModelIdentifier.java @@ -25,11 +25,11 @@ package org.onap.appc.metadata.objects; /** - * Object of identifier for dependency model. - * Currently uses VNF type and catalog version + * Object of identifier for dependency model. Currently uses VNF type and catalog version */ public class DependencyModelIdentifier { - static final String TO_STRING_FORMAT = "DependencyModelIdentifier : vnfType = %s , catalogVersion = %s"; + static final String TO_STRING_FORMAT = + "DependencyModelIdentifier : vnfType = %s , catalogVersion = %s"; static final int prime = 31; private String vnfType; @@ -37,6 +37,7 @@ public class DependencyModelIdentifier { /** * Constructor + * * @param vnfType String of the VNF type * @param catalogVersion String of the catalog version */ @@ -48,23 +49,24 @@ public class DependencyModelIdentifier { @Override public int hashCode() { int result = 1; - result = result * prime + (this.vnfType == null ? 0 :this.vnfType.hashCode()); - result = result * prime + (this.catalogVersion == null ? 0 :this.catalogVersion.hashCode()); + result = result * prime + (this.vnfType == null ? 0 : this.vnfType.hashCode()); + result = result * prime + + (this.catalogVersion == null ? 0 : this.catalogVersion.hashCode()); return result; } @Override public boolean equals(Object obj) { - if (obj ==null) { + if (obj == null) { return false; } if (!(obj instanceof DependencyModelIdentifier)) { return false; } - DependencyModelIdentifier modelIdentifier = (DependencyModelIdentifier)obj; + DependencyModelIdentifier modelIdentifier = (DependencyModelIdentifier) obj; if (this.vnfType == null) { - if (modelIdentifier.vnfType !=null) { + if (modelIdentifier.vnfType != null) { return false; } } else if (!this.vnfType.equals(modelIdentifier.vnfType)) { @@ -72,13 +74,12 @@ public class DependencyModelIdentifier { } if (this.catalogVersion == null) { - if (modelIdentifier.catalogVersion !=null) { + if (modelIdentifier.catalogVersion != null) { return false; } } else if (!this.catalogVersion.equals(modelIdentifier.catalogVersion)) { return false; } - return true; } diff --git a/appc-common/src/main/java/org/onap/appc/pool/CachedElement.java b/appc-common/src/main/java/org/onap/appc/pool/CachedElement.java index d7d243d4f..b37156f9a 100644 --- a/appc-common/src/main/java/org/onap/appc/pool/CachedElement.java +++ b/appc-common/src/main/java/org/onap/appc/pool/CachedElement.java @@ -22,8 +22,6 @@ * ============LICENSE_END========================================================= */ - - package org.onap.appc.pool; import java.io.Closeable; @@ -34,15 +32,17 @@ import java.lang.reflect.Proxy; import java.util.concurrent.atomic.AtomicBoolean; /** - * This class is used as a "wrapper" for any closeable elements that are cached in a pool. It is implemented as a - * dynamic proxy, so that it appears to be the same class of object to the client as the interface being cached. The - * generic type being cached MUST be an interface. - * @param <T> - * The generic type that we create a cached element for. This type is used to wrap instances of this type and - * expose access to the {@link java.io.Closeable} interface by using a dynamic proxy. + * This class is used as a "wrapper" for any closeable elements that are cached in a pool. It is + * implemented as a dynamic proxy, so that it appears to be the same class of object to the client + * as the interface being cached. The generic type being cached MUST be an interface. + * + * @param <T> The generic type that we create a cached element for. This type is used to wrap + * instances of this type and expose access to the {@link java.io.Closeable} interface by + * using a dynamic proxy. */ -public class CachedElement<T extends Closeable> implements Closeable, InvocationHandler, CacheManagement { +public class CachedElement<T extends Closeable> + implements Closeable, InvocationHandler, CacheManagement { /** * The pool that is managing this cached element @@ -55,33 +55,33 @@ public class CachedElement<T extends Closeable> implements Closeable, Invocation private T element; /** - * A thread-safe atomic indicator that tells us that the wrapped element has been released to the pool already, and - * not to do it again. + * A thread-safe atomic indicator that tells us that the wrapped element has been released to + * the pool already, and not to do it again. */ private AtomicBoolean released = new AtomicBoolean(false); /** * Create a new instance of a cached element dynamic proxy for use in the pool. * <p> - * This returns an instance of the proxy to the caller that appears to be the same interface(s) as the object being - * cached. The dynamic proxy then intercepts all open and close semantics and directs that element to the pool. + * This returns an instance of the proxy to the caller that appears to be the same interface(s) + * as the object being cached. The dynamic proxy then intercepts all open and close semantics + * and directs that element to the pool. * </p> * <p> - * If the object being proxied does not implement the {@link CacheManagement} interface, then that interface is - * added to the dynamic proxy being created. This interface is actually implemented by the invocation handler (this - * object) for the proxy and allows direct access to the wrapped object inside the proxy. + * If the object being proxied does not implement the {@link CacheManagement} interface, then + * that interface is added to the dynamic proxy being created. This interface is actually + * implemented by the invocation handler (this object) for the proxy and allows direct access to + * the wrapped object inside the proxy. * </p> * - * @param pool - * The pool that we are caching these elements within - * @param element - * The element actually being cached - * @param interfaces - * The interface list of interfaces the element must implement (usually one) + * @param pool The pool that we are caching these elements within + * @param element The element actually being cached + * @param interfaces The interface list of interfaces the element must implement (usually one) * @return The dynamic proxy */ @SuppressWarnings("unchecked") - public static <T extends Closeable> T newInstance(Pool<T> pool, T element, Class<?>[] interfaces) { + public static <T extends Closeable> T newInstance(Pool<T> pool, T element, + Class<?>[] interfaces) { ClassLoader cl = element.getClass().getClassLoader(); CachedElement<T> ce = new CachedElement<>(pool, element); boolean found = false; @@ -106,10 +106,8 @@ public class CachedElement<T extends Closeable> implements Closeable, Invocation /** * Construct a cached element and assign it to the pool as a free element * - * @param pool - * The pool that the element will be managed within - * @param element - * The element we are caching + * @param pool The pool that the element will be managed within + * @param element The element we are caching */ @SuppressWarnings("unchecked") public CachedElement(Pool<T> pool, T element) { @@ -126,9 +124,10 @@ public class CachedElement<T extends Closeable> implements Closeable, Invocation /** * This method delegates the close call to the actual wrapped element. * <p> - * NOTE: This is not the same method that is called by the dynamic proxy. This method is in place to satisfy the - * signature of the {@link java.io.Closeable} interface. If it were to be called directly, then we will delegate the - * close to the underlying context. However, when the cached element is called as a synamic proxy, entry is in the + * NOTE: This is not the same method that is called by the dynamic proxy. This method is in + * place to satisfy the signature of the {@link java.io.Closeable} interface. If it were to be + * called directly, then we will delegate the close to the underlying context. However, when the + * cached element is called as a synamic proxy, entry is in the * {@link #invoke(Object, Method, Object[])} method. * </p> * @@ -140,36 +139,37 @@ public class CachedElement<T extends Closeable> implements Closeable, Invocation } /** - * This method is the magic part of dynamic proxies. When the caller makes a method call based on the interface - * being proxied, this method is given control. This informs us of the method and arguments of the call. The object - * reference is that of the dynamic proxy itself, which is us. + * This method is the magic part of dynamic proxies. When the caller makes a method call based + * on the interface being proxied, this method is given control. This informs us of the method + * and arguments of the call. The object reference is that of the dynamic proxy itself, which is + * us. * <p> - * Here we will check to see if the user is trying to close the "element" (the dynamic proxy acts like the wrapped - * element). If he is, then we don't really close it, but instead release the element that we are wrapping back to - * the free pool. Once this has happened, we mark the element as "closed" (from the perspective of this dynamic - * proxy) so that we wont try to release it again. + * Here we will check to see if the user is trying to close the "element" (the dynamic proxy + * acts like the wrapped element). If he is, then we don't really close it, but instead release + * the element that we are wrapping back to the free pool. Once this has happened, we mark the + * element as "closed" (from the perspective of this dynamic proxy) so that we wont try to + * release it again. * </p> * <p> - * If the method is the <code>equals</code> method then we assume that we are comparing the cached element in one - * dynamic proxy to the cached element in another. We execute the comparison between the cached elements, and not - * the dynamic proxies themselves. This preserves the allusion to the caller that the dynamic proxy is the object - * being wrapped. + * If the method is the <code>equals</code> method then we assume that we are comparing the + * cached element in one dynamic proxy to the cached element in another. We execute the + * comparison between the cached elements, and not the dynamic proxies themselves. This + * preserves the allusion to the caller that the dynamic proxy is the object being wrapped. * </p> * <p> - * For convenience, we also implement the <code>getWrappedObject</code> method so that the dynamic proxy can be - * called to obtain the actual wrapped object if desired. Note, to use this method, the caller would have to invoke - * it through reflection. + * For convenience, we also implement the <code>getWrappedObject</code> method so that the + * dynamic proxy can be called to obtain the actual wrapped object if desired. Note, to use this + * method, the caller would have to invoke it through reflection. * </p> * <p> - * If the method being invoked is not one that we intercept, then we simply delegate that method onto the wrapped - * object. + * If the method being invoked is not one that we intercept, then we simply delegate that method + * onto the wrapped object. * </p> * - * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) + * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, + * java.lang.Object[]) */ - @SuppressWarnings({ - "unchecked", "nls" - }) + @SuppressWarnings({"unchecked", "nls"}) @Override public Object invoke(Object proxy, Method method, Object[] args) throws Exception { Object result = null; diff --git a/appc-common/src/main/java/org/onap/appc/rest/client/RestClientInvoker.java b/appc-common/src/main/java/org/onap/appc/rest/client/RestClientInvoker.java new file mode 100644 index 000000000..f2bec45ca --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/rest/client/RestClientInvoker.java @@ -0,0 +1,257 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.rest.client; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; +import org.onap.appc.exceptions.APPCException; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URL; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +public class RestClientInvoker { + + public RestClientInvoker(URL url){ + this.url=url; + } + private RestClientInvoker(){} + + private URL url=null; + private String basicAuth=null; + + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(RestClientInvoker.class); + private static final String OPERATION_HTTPS="https"; + private static final String OPERATION_APPLICATION_JSON= " application/json"; + + + /** + * Sets the basic authentication header for the given user and password. If either entry is null then does not set basic auth + * + * @param user The user with optional domain name (for AAF) + * @param password The password for the user + */ + public void setAuthentication(String user, String password) { + if (user != null && password != null) { + String authStr = user + ":" + password; + basicAuth = new String(Base64.encodeBase64(authStr.getBytes())); + } + } + + public HttpResponse doPost (String path , String body) throws APPCException { + HttpPost post; + + try { + + URL postUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); + post = new HttpPost(postUrl.toExternalForm()); + post.setHeader(HttpHeaders.CONTENT_TYPE, OPERATION_APPLICATION_JSON); + post.setHeader(HttpHeaders.ACCEPT, OPERATION_APPLICATION_JSON); + + if (basicAuth != null) { + post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); + } + + StringEntity entity = new StringEntity(body); + entity.setContentType(OPERATION_APPLICATION_JSON); + post.setEntity(new StringEntity(body)); + } catch (MalformedURLException | UnsupportedEncodingException e) { + throw new APPCException(e); + } + HttpClient client = getHttpClient(); + + try { + return client.execute(post); + } catch (IOException e) { + throw new APPCException(e); + } + } + + /** + * This is Generic method that can be used to perform REST Put operation + * @param path - path for put + * @param body - payload for put action which will be sent as request body. + * @return - HttpResponse object which is returned from put REST call. + * @throws APPCException when error occurs + */ + public HttpResponse doPut (String path, String body) throws APPCException { + HttpPut put; + try { + URL putUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); + put = new HttpPut(putUrl.toExternalForm()); + put.setHeader(HttpHeaders.CONTENT_TYPE, OPERATION_APPLICATION_JSON); + put.setHeader(HttpHeaders.ACCEPT, OPERATION_APPLICATION_JSON); + + if (basicAuth != null) { + put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); + } + + StringEntity entity = new StringEntity(body); + entity.setContentType(OPERATION_APPLICATION_JSON); + put.setEntity(new StringEntity(body)); + } catch (UnsupportedEncodingException | MalformedURLException e) { + throw new APPCException(e); + } + + HttpClient client = getHttpClient(); + + try { + return client.execute(put); + } catch (IOException e) { + throw new APPCException(e); + } + } + + public HttpResponse doGet (String path) throws APPCException { + HttpGet get; + try { + URL getUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); + get = new HttpGet(getUrl.toExternalForm()); + get.setHeader(HttpHeaders.CONTENT_TYPE, OPERATION_APPLICATION_JSON); + get.setHeader(HttpHeaders.ACCEPT, OPERATION_APPLICATION_JSON); + + if (basicAuth != null) { + get.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth); + } + + } catch (Exception e) { + throw new APPCException(e); + } + HttpClient client = getHttpClient(); + try { + return client.execute(get); + } catch (IOException e) { + throw new APPCException(e); + } + } + + @SuppressWarnings("deprecation") + private HttpClient getHttpClient() throws APPCException { + HttpClient client; + switch (url.getProtocol()) { + case OPERATION_HTTPS: + try { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); + sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme(OPERATION_HTTPS, sf, 443)); + registry.register(new Scheme(OPERATION_HTTPS, sf, 8443)); + registry.register(new Scheme("http", sf, 8181)); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + client = new DefaultHttpClient(ccm, params); + } catch (Exception e) { + LOG.error("Error creating HTTP Client. Creating default client.", e); + client = new DefaultHttpClient(); + } + break; + case "http": + client = new DefaultHttpClient(); + break; + default: + throw new APPCException( + "The url did not start with http[s]"); + } + return client; + } + @SuppressWarnings("deprecation") + private static class MySSLSocketFactory extends SSLSocketFactory { + private SSLContext sslContext = SSLContext.getInstance("TLS"); + + private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, + KeyStoreException, UnrecoverableKeyException { + super(truststore); + + TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + LOG.debug("Inside checkClientTrusted"); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + LOG.debug("Inside checkServerTrusted"); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[1]; + } + }; + + sslContext.init(null, new TrustManager[]{ + tm + }, null); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } + + @Override + public Socket createSocket() throws IOException { + return sslContext.getSocketFactory().createSocket(); + } + } + +} diff --git a/appc-common/src/main/java/org/onap/appc/util/JsonUtil.java b/appc-common/src/main/java/org/onap/appc/util/JsonUtil.java index c1906362e..7e6f5ef8d 100644 --- a/appc-common/src/main/java/org/onap/appc/util/JsonUtil.java +++ b/appc-common/src/main/java/org/onap/appc/util/JsonUtil.java @@ -24,24 +24,104 @@ package org.onap.appc.util; -import com.fasterxml.jackson.databind.ObjectMapper; - +import java.io.FileNotFoundException; import java.io.IOException; +import java.io.InputStream; import java.util.Map; - +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; public class JsonUtil { + + static ObjectMapper MAPPER = null; + static { + MAPPER = new ObjectMapper(); + MAPPER.enable(SerializationFeature.INDENT_OUTPUT); + MAPPER.configure(JsonParser.Feature.ALLOW_COMMENTS, true); + MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL); + MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // allow translation even + // if extra attrs exist + // in the json + MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + // Uncomment below when Jackson is upgraded to version 2.7 or above + // MAPPER.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE); + } + /** * @param valueAsString a valid json Map represented as String - * @return a flat map that each entry key derived from hierarchy path in the json object and flatted to a dotted separated string. - * e.g. "{\"A\":\"A-value\",\"B\":{\"C\":\"B.C-value\",\"D\":\"B.D-value\"}}"; will be represented as {A=A-value, B.C=B.C-value, B.D=B.D-value} - * when it required that the input will not be flatted the json string should be formatted as below example: - * e.g. "{\"A\":\"A-value\",\"B\":\"{\\\"C\\\":\\\"C-value\\\",\\\"D\\\":\\\"D-value\\\"}\"}" will be represented as {A=A-value, B={"C":"C-value","D":"D-value"}} + * @return a flat map that each entry key derived from hierarchy path in the json object and + * flatted to a dotted separated string. e.g. + * "{\"A\":\"A-value\",\"B\":{\"C\":\"B.C-value\",\"D\":\"B.D-value\"}}"; will be + * represented as {A=A-value, B.C=B.C-value, B.D=B.D-value} when it required that the + * input will not be flatted the json string should be formatted as below example: e.g. + * "{\"A\":\"A-value\",\"B\":\"{\\\"C\\\":\\\"C-value\\\",\\\"D\\\":\\\"D-value\\\"}\"}" + * will be represented as {A=A-value, B={"C":"C-value","D":"D-value"}} * @throws IOException when the object is not valid json Map */ - public static Map<String, String> convertJsonStringToFlatMap(String valueAsString) throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - Map readValueMap = objectMapper.readValue(valueAsString,Map.class); + public static Map<String, String> convertJsonStringToFlatMap(String valueAsString) + throws IOException { + Map readValueMap = MAPPER.readValue(valueAsString, Map.class); return org.onap.appc.util.ObjectMapper.map(readValueMap); } + + /** + * 0 is the getStackTrace method 1 is the current method 2 is the parent method, 3 is the + * grandparent method or the parent class in this case. + */ + private static final int PARENT_CLASS_INDEX = 3; + + + /** + * @see #readInputJson(String, Class, Class) + */ + public static <T> T readInputJson(String location, Class<T> returnClass) throws IOException { + return readInputJson(location, returnClass, getCallingClass(PARENT_CLASS_INDEX)); + } + + /** + * @param location The location or name of the file we are trying to read e.g. JsonBody.json + * @param returnClass The class *this* Json is suppose to represent. + * @param locationClass The starting point for json lookup. the value specified by location is + * relative to this class. + * @return The object being returned + * @throws IOException Can't find the specified json file at Location. + */ + public static <T> T readInputJson(String location, Class<T> returnClass, Class<?> locationClass) + throws IOException { + try (InputStream is = locationClass.getResourceAsStream(location)) { + validateInput(is, location); + return MAPPER.readValue(is, returnClass); + } + } + + /** + * Note that this method is sensitive to the depth of the call stack. For example if a public + * method calls a private method, that calls this method likely the desired classIndex value is + * 4 rather than 3. However, it's convenient to reduce the input required by callers of this + * class. + * + * @param classIndex How far up the stack trace to find the class we want. + * @return The class that called one of the public methods of this class. + */ + private static Class<?> getCallingClass(int classIndex) { + String className = Thread.currentThread().getStackTrace()[classIndex].getClassName(); + try { + return Class.forName(className); + } catch (ClassNotFoundException e) { + // Theoretically impossible. + throw new IllegalStateException( + "Could not do class lookup for class in our stack trace?!?"); + } + } + + private static void validateInput(InputStream is, String location) + throws FileNotFoundException { + if (is == null) { + throw new FileNotFoundException(String.format("Could not find file at '%s'", location)); + } + } + } diff --git a/appc-common/src/main/java/org/onap/appc/util/MessageFormatter.java b/appc-common/src/main/java/org/onap/appc/util/MessageFormatter.java index 44095fb71..71ef40641 100644 --- a/appc-common/src/main/java/org/onap/appc/util/MessageFormatter.java +++ b/appc-common/src/main/java/org/onap/appc/util/MessageFormatter.java @@ -25,7 +25,6 @@ package org.onap.appc.util; import org.apache.commons.lang3.StringUtils; - import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -33,10 +32,15 @@ import java.util.regex.Pattern; public class MessageFormatter { private final static String paramNameRegexGroupName = "paramName"; - private final static String paramRegex = "\\$\\{(?<paramName>[^}$]+)\\}"; //start with ${ and after there is one or more characters that are not $ and not } and ended with } + private final static String paramRegex = "\\$\\{(?<paramName>[^}$]+)\\}"; // start with ${ and + // after there is one + // or more characters + // that are not $ and + // not } and ended + // with } - public static String format(String messageTemplate, Map<String,Object> params) { + public static String format(String messageTemplate, Map<String, Object> params) { if (StringUtils.isEmpty(messageTemplate)) return ""; if (params == null || params.isEmpty()) @@ -45,16 +49,26 @@ public class MessageFormatter { String formattedMessage = messageTemplate; if (formattedMessage.contains("$")) { for (Map.Entry<String, Object> entry : params.entrySet()) { - formattedMessage = formattedMessage.replaceAll("\\$\\{" + entry.getKey() + "\\}", String.valueOf(entry.getValue())); + formattedMessage = formattedMessage.replaceAll("\\$\\{" + entry.getKey() + "\\}", + escapeDollarChar(String.valueOf(entry.getValue()))); } } return formattedMessage; } + private static String escapeDollarChar(String msg) { + String formatedMsg = msg; + if (formatedMsg.contains("$")) { + formatedMsg = formatedMsg.replaceAll("\\$", "\\\\\\$"); + + } + return formatedMsg; + } + public static List<String> getParamsNamesList(String messageTemplate) { List<String> paramsNames = null; - if(!StringUtils.isEmpty(messageTemplate)){ + if (!StringUtils.isEmpty(messageTemplate)) { paramsNames = new ArrayList<String>(); Matcher m = Pattern.compile(paramRegex).matcher(messageTemplate); while (m.find()) { @@ -64,12 +78,13 @@ public class MessageFormatter { } return paramsNames; } + public static Set<String> getParamsNamesSet(String messageTemplate) { List<String> paramsNamesList = getParamsNamesList(messageTemplate); Set<String> paramsNamesSet = null; - if(paramsNamesList != null && !paramsNamesList.isEmpty()){ + if (paramsNamesList != null && !paramsNamesList.isEmpty()) { paramsNamesSet = new HashSet<String>(); - for(String paramName : paramsNamesList){ + for (String paramName : paramsNamesList) { paramsNamesSet.add(paramName); } } diff --git a/appc-common/src/main/java/org/onap/appc/util/StreamHelper.java b/appc-common/src/main/java/org/onap/appc/util/StreamHelper.java new file mode 100644 index 000000000..4f9510655 --- /dev/null +++ b/appc-common/src/main/java/org/onap/appc/util/StreamHelper.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.appc.util; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; + +public class StreamHelper { + + /** + * private default constructor prevents instantiation + */ + private StreamHelper() { + } + + /** + * @param inputStream + * @return Input stream converted to string + */ + public static String getStringFromInputStream(InputStream inputStream) { + StringBuffer buffer = new StringBuffer(); + byte[] array = new byte[4096]; + + if (inputStream != null) { + try { + int len = inputStream.read(array); + while (len != -1) { + buffer.append(new String(array, 0, len, Charset.forName("UTF-8"))); + len = inputStream.read(array); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + return buffer.toString(); + } + +} diff --git a/appc-common/src/main/java/org/onap/appc/util/Time.java b/appc-common/src/main/java/org/onap/appc/util/Time.java index ce2babdc3..af42ebdaa 100644 --- a/appc-common/src/main/java/org/onap/appc/util/Time.java +++ b/appc-common/src/main/java/org/onap/appc/util/Time.java @@ -38,11 +38,9 @@ import java.util.List; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.TimeZone; - import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -82,24 +80,19 @@ public final class Time { } /** - * Increments a date by the indicated months, days, hours, minutes, and seconds, and returns the updated date. + * Increments a date by the indicated months, days, hours, minutes, and seconds, and returns the + * updated date. * - * @param date - * The date to be manipulated - * @param months - * The number of months to be added to the date - * @param days - * The number of days to be added to the date - * @param hours - * The number of hours to be added to the date - * @param minutes - * The number of minutes to be added to the date - * @param seconds - * The number of seconds to be added to the date + * @param date The date to be manipulated + * @param months The number of months to be added to the date + * @param days The number of days to be added to the date + * @param hours The number of hours to be added to the date + * @param minutes The number of minutes to be added to the date + * @param seconds The number of seconds to be added to the date * @return The updated date. */ - public static Date addTime(final Date date, final int months, final int days, final int hours, final int minutes, - final int seconds) { + public static Date addTime(final Date date, final int months, final int days, final int hours, + final int minutes, final int seconds) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.MONTH, months); @@ -113,8 +106,7 @@ public final class Time { /** * Clears the time components of a calendar to zero, leaving the date components unchanged. * - * @param cal - * the calendar to be updated + * @param cal the calendar to be updated * @return The updated calendar object */ public static Calendar dateOnly(final Calendar cal) { @@ -135,11 +127,10 @@ public final class Time { } /** - * This method returns the last moment of the day for the supplied local time. This is defined as the millisecond - * before midnight of the current date represented by the local time. + * This method returns the last moment of the day for the supplied local time. This is defined + * as the millisecond before midnight of the current date represented by the local time. * - * @param localTime - * The local time for which the last moment of the day is desired. + * @param localTime The local time for which the last moment of the day is desired. * @return The millisecond prior to midnight, local time. */ public static Date endOfDayLocal(final Date localTime) { @@ -166,26 +157,27 @@ public final class Time { } /** - * Returns the UTC time that corresponds to the end of the day for the local time specified, using the current - * (default) time zone. + * Returns the UTC time that corresponds to the end of the day for the local time specified, + * using the current (default) time zone. * - * @param localTime - * The local time for which we are requesting the UTC time that corresponds to the end of the day - * @return The UTC time that corresponds to the end of the local day specified by the local time. + * @param localTime The local time for which we are requesting the UTC time that corresponds to + * the end of the day + * @return The UTC time that corresponds to the end of the local day specified by the local + * time. */ public static Date endOfDayUTC(final Date localTime) { return endOfDayUTC(localTime, TimeZone.getDefault()); } /** - * Returns the time expressed in UTC time of the end of the day specified in local time and within the local time - * zone. + * Returns the time expressed in UTC time of the end of the day specified in local time and + * within the local time zone. * - * @param localTime - * The local time for which we will compute the end of the local day, and then convert to UTC time. - * @param localTimeZone - * The time zone that the local time is within. - * @return The UTC date that corresponds to the end of the day local time and in the local time zone. + * @param localTime The local time for which we will compute the end of the local day, and then + * convert to UTC time. + * @param localTimeZone The time zone that the local time is within. + * @return The UTC date that corresponds to the end of the day local time and in the local time + * zone. */ public static Date endOfDayUTC(final Date localTime, final TimeZone localTimeZone) { Date endOfDay = endOfDayLocal(localTime); @@ -200,7 +192,8 @@ public final class Time { @SuppressWarnings("nls") public static Date getCurrentUTCDate() { - // This code incorrectly changes the default timezone for the entire JVM in order to compute the UTC + // This code incorrectly changes the default timezone for the entire JVM in order to compute + // the UTC // date for the current time. GregorianCalendar calendar = new GregorianCalendar(); @@ -228,17 +221,16 @@ public final class Time { /** * Gives the date-time String based on given Locale and Timezone * - * @param date - * The date to be formatted - * @param locale - * The locale that we want to format the value for - * @param timezone - * The time zone that the date is within + * @param date The date to be formatted + * @param locale The locale that we want to format the value for + * @param timezone The time zone that the date is within * @return The formatted value */ - public static String getDateByLocaleAndTimeZone(final Date date, final Locale locale, final TimeZone timezone) { + public static String getDateByLocaleAndTimeZone(final Date date, final Locale locale, + final TimeZone timezone) { String strDate = null; - DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale); + DateFormat df = + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale); df.setTimeZone(timezone); synchronized (df) { strDate = df.format(date); @@ -261,10 +253,11 @@ public final class Time { } /** - * This method returns the local time that corresponds to a given UTC time in the current time zone. + * This method returns the local time that corresponds to a given UTC time in the current time + * zone. * - * @param utcTime - * The UTC time for which we desire the equivalent local time in the current time zone. + * @param utcTime The UTC time for which we desire the equivalent local time in the current time + * zone. * @return The local time that is equivalent to the given UTC time for the current time zone */ public static long localTime(final long utcTime) { @@ -274,16 +267,14 @@ public final class Time { /** * This method can be used to get the local time that corresponds to a specific UTC time. * <p> - * This method has a problem since the offset can only be determined by having a local time. So, we take the UTC - * time and add the raw offset to it to come up with an approximation of the local time. This gives us a local time - * that we can use to determine what the offset should be, which is what we actually add to the UTC time to get the - * local time. + * This method has a problem since the offset can only be determined by having a local time. So, + * we take the UTC time and add the raw offset to it to come up with an approximation of the + * local time. This gives us a local time that we can use to determine what the offset should + * be, which is what we actually add to the UTC time to get the local time. * </p> * - * @param utcTime - * The UTC time for which we want to obtain the equivalent local time - * @param localTZ - * The time zone that we want the local time to be within + * @param utcTime The UTC time for which we want to obtain the equivalent local time + * @param localTZ The time zone that we want the local time to be within * @return The local time for the specified time zone and the given UTC time */ public static long localTime(final long utcTime, final TimeZone localTZ) { @@ -294,19 +285,17 @@ public final class Time { } /** - * Sets the date components of a calendar to the specified values, leaving the time components unchanged. + * Sets the date components of a calendar to the specified values, leaving the time components + * unchanged. * - * @param cal - * The calendar to be updated - * @param year - * The year to be set - * @param month - * The month to be set - * @param day - * The day to be set + * @param cal The calendar to be updated + * @param year The year to be set + * @param month The month to be set + * @param day The day to be set * @return The updated calendar object */ - public static Calendar setDate(final Calendar cal, final int year, final int month, final int day) { + public static Calendar setDate(final Calendar cal, final int year, final int month, + final int day) { cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_MONTH, day); @@ -323,12 +312,12 @@ public final class Time { } /** - * This method returns the date that corresponds to the start of the day local time. The date returned represents - * midnight of the previous day represented in local time. If the UTC time is desired, use the methods - * {@link #startOfDayUTC(Date, TimeZone)}, {@link #startOfDayUTC(Date)}, or {@link #startOfDayUTC()} + * This method returns the date that corresponds to the start of the day local time. The date + * returned represents midnight of the previous day represented in local time. If the UTC time + * is desired, use the methods {@link #startOfDayUTC(Date, TimeZone)}, + * {@link #startOfDayUTC(Date)}, or {@link #startOfDayUTC()} * - * @param localTime - * The local date that we wish to compute the start of day for. + * @param localTime The local date that we wish to compute the start of day for. * @return The date that corresponds to the start of the local day */ public static Date startOfDayLocal(final Date localTime) { @@ -344,8 +333,8 @@ public final class Time { } /** - * This method returns the UTC date that corresponds to the start of the local day based on the current time and the - * default time zone (the time zone we are running in). + * This method returns the UTC date that corresponds to the start of the local day based on the + * current time and the default time zone (the time zone we are running in). * * @return The start of the local day expressed as a UTC time. */ @@ -354,11 +343,10 @@ public final class Time { } /** - * This method returns the UTC date that corresponds to the start of the local day specified in the current time - * zone. + * This method returns the UTC date that corresponds to the start of the local day specified in + * the current time zone. * - * @param localTime - * The local time to be used to compute the start of the day + * @param localTime The local time to be used to compute the start of the day * @return The start of the local day expressed as a UTC time. */ public static Date startOfDayUTC(final Date localTime) { @@ -366,12 +354,11 @@ public final class Time { } /** - * This method returns the UTC date that corresponds to the start of the local day specified in the local timezone. + * This method returns the UTC date that corresponds to the start of the local day specified in + * the local timezone. * - * @param localTime - * The local time to be used to compute start of day - * @param localTimeZone - * The time zone that the local time was recorded within + * @param localTime The local time to be used to compute start of day + * @param localTimeZone The time zone that the local time was recorded within * @return The corresponding UTC date */ public static Date startOfDayUTC(final Date localTime, final TimeZone localTimeZone) { @@ -380,9 +367,9 @@ public final class Time { } /** - * This method creates and returns an XML timestamp expressed as the current UTC value for the system. The caller - * does not specify the time value or time zone using this method. This ensures that the timestamp value is always - * expressed as UTC time. + * This method creates and returns an XML timestamp expressed as the current UTC value for the + * system. The caller does not specify the time value or time zone using this method. This + * ensures that the timestamp value is always expressed as UTC time. * * @return The XMLGregorianCalendar that can be used to record the timestamp */ @@ -407,8 +394,7 @@ public final class Time { /** * Converts XMLGregorianCalendar to java.util.Date in Java * - * @param calendar - * the calendar object to be converted + * @param calendar the calendar object to be converted * @return The equivalent Date object */ public static Date toDate(final XMLGregorianCalendar calendar) { @@ -421,8 +407,7 @@ public final class Time { /** * Converts java Date to XMLGregorianCalendar. * - * @param date - * The date to convert + * @param date The date to convert * @return The XMLGregorianCalendar for the specified date */ @SuppressWarnings("nls") @@ -440,11 +425,10 @@ public final class Time { } /** - * Truncates the provided date so that only the date, hours, and minutes portions are significant. This method - * returns the date with the seconds and milliseconds forced to zero. + * Truncates the provided date so that only the date, hours, and minutes portions are + * significant. This method returns the date with the seconds and milliseconds forced to zero. * - * @param date - * The date to truncate + * @param date The date to truncate * @return The date with only the year, month, day, hours, and minutes significant. */ public static Date truncDate(final Date date) { @@ -467,8 +451,7 @@ public final class Time { /** * The UTC date for the specified date in the current (default) time zone. * - * @param date - * The local date for which the UTC date is desired. + * @param date The local date for which the UTC date is desired. * @return The UTC date that corresponds to the date in the current time zone. */ public static Date utcDate(final Date date) { @@ -479,10 +462,8 @@ public final class Time { /** * Returns the UTC date for the specified date in the specified time zone. * - * @param date - * The date for which the UTC date is desired in the specified zone - * @param tz - * The time zone that corresponds to the date to be converted to UTC + * @param date The date for which the UTC date is desired in the specified zone + * @param tz The time zone that corresponds to the date to be converted to UTC * @return The UTC date that corresponds to the local date in the local time zone. */ public static Date utcDate(final Date date, final TimeZone tz) { @@ -492,8 +473,7 @@ public final class Time { /** * Format incoming date as string in GMT or UTC. * - * @param dt - * The date to be formatted + * @param dt The date to be formatted * @return The date formatted for UTC timezone */ public static String utcFormat(final Date dt) { @@ -508,26 +488,24 @@ public final class Time { /** * Parse previously formated Date object back to a Date object. * - * @param dateStr - * The representation of a UTC date as a string - * @return The date object containing the parsed representation, or null if the representation cannot be parsed + * @param dateStr The representation of a UTC date as a string + * @return The date object containing the parsed representation, or null if the representation + * cannot be parsed */ @SuppressWarnings("nls") public static Date utcParse(final String dateStr) { - String[] adtl = { - "yyyy-MM-dd" - }; + String[] adtl = {"yyyy-MM-dd"}; return utcParse(dateStr, adtl); } /** * Parse previously formated Date object back to a Date object. * - * @param dateStr - * The representation of a UTC date as a string - * @param adtlFormatStrings - * A list of strings that represent additional date format representations to try and parse. - * @return The date object containing the parsed representation, or null if the representation cannot be parsed + * @param dateStr The representation of a UTC date as a string + * @param adtlFormatStrings A list of strings that represent additional date format + * representations to try and parse. + * @return The date object containing the parsed representation, or null if the representation + * cannot be parsed */ @SuppressWarnings("nls") public static Date utcParse(final String dateStr, String... adtlFormatStrings) { @@ -548,8 +526,8 @@ public final class Time { try { return df.parse(dateStr); } catch (ParseException e) { - LOG.debug(String.format("IGNORE - Date string [%s] does not fit pattern [%s]", dateStr, - df.toString())); + LOG.debug(String.format("IGNORE - Date string [%s] does not fit pattern [%s]", + dateStr, df.toString())); } } } @@ -566,10 +544,10 @@ public final class Time { } /** - * Get the UTC time that corresponds to the given time in the default time zone (current time zone for the system). + * Get the UTC time that corresponds to the given time in the default time zone (current time + * zone for the system). * - * @param localTime - * The time in the current time zone for which the UTC time is desired. + * @param localTime The time in the current time zone for which the UTC time is desired. * @return The UTC time */ public static long utcTime(final long localTime) { @@ -580,15 +558,14 @@ public final class Time { /** * Get the UTC time that corresponds to the given time in the specified timezone. * <p> - * Note that the java <code>getOffset()</code> method works a little counter-intuitive. It returns the offset that - * would be added to the current UTC time to get the LOCAL time represented by the local time zone. That means to - * get the UTC time, we need to SUBTRACT this offset from the local time. + * Note that the java <code>getOffset()</code> method works a little counter-intuitive. It + * returns the offset that would be added to the current UTC time to get the LOCAL time + * represented by the local time zone. That means to get the UTC time, we need to SUBTRACT this + * offset from the local time. * </p> * - * @param localTime - * The time in the specified time zone for which the UTC time is desired. - * @param localTZ - * The time zone which the local time is in. + * @param localTime The time in the specified time zone for which the UTC time is desired. + * @param localTZ The time zone which the local time is in. * @return The UTC time for the specified local time in the specified local time zone. */ public static long utcTime(final long localTime, final TimeZone localTZ) { @@ -600,12 +577,24 @@ public final class Time { /** * Creates a timestamp value from a time * - * @param utcTime - * The UTC time to convert to a timestamp + * @param utcTime The UTC time to convert to a timestamp * @return The timestamp */ public static Timestamp utcTimestamp(final long utcTime) { TimeZone tz = TimeZone.getDefault(); return new Timestamp(utcTime(utcTime, tz)); } + + public static String dateToStringConverterMillis(Date date) { + SimpleDateFormat customDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); + if (date != null) { + return customDate.format(date); + } + return null; + } + + public static Date stringToDateConverterMillis(String dateString) throws ParseException { + SimpleDateFormat customDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); + return customDate.parse(dateString); + } } diff --git a/appc-common/src/main/java/org/onap/appc/util/httpClient.java b/appc-common/src/main/java/org/onap/appc/util/httpClient.java index edb27c6f6..b258b5d65 100644 --- a/appc-common/src/main/java/org/onap/appc/util/httpClient.java +++ b/appc-common/src/main/java/org/onap/appc/util/httpClient.java @@ -24,12 +24,15 @@ package org.onap.appc.util; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; @@ -37,7 +40,6 @@ import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.onap.appc.configuration.Configuration; import org.onap.appc.configuration.ConfigurationFactory; @@ -45,11 +47,6 @@ import org.onap.appc.exceptions.APPCException; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; - public class httpClient { @@ -58,7 +55,8 @@ public class httpClient { private static Configuration configuration = ConfigurationFactory.getConfiguration(); @SuppressWarnings("deprecation") - public static int postMethod(String protocol, String ip, int port, String path, String payload, String contentType) throws APPCException { + public static int postMethod(String protocol, String ip, int port, String path, String payload, + String contentType) throws APPCException { logger.info("Sending POST request to " + path); @@ -79,11 +77,10 @@ public class httpClient { logger.debug("Sending request " + post); CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials( - new AuthScope(ip, port), - new UsernamePasswordCredentials(configuration.getProperty("username"), configuration.getProperty("password"))); - CloseableHttpClient client = HttpClients.custom() - .setDefaultCredentialsProvider(credsProvider).build(); + credsProvider.setCredentials(new AuthScope(ip, port), new UsernamePasswordCredentials( + configuration.getProperty("username"), configuration.getProperty("password"))); + CloseableHttpClient client = + HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); int httpCode; try { @@ -96,7 +93,8 @@ public class httpClient { } @SuppressWarnings("deprecation") - public static int putMethod(String protocol, String ip, int port, String path, String payload, String contentType) throws APPCException { + public static int putMethod(String protocol, String ip, int port, String path, String payload, + String contentType) throws APPCException { logger.info("Sending PUT request to " + path); @@ -117,11 +115,10 @@ public class httpClient { logger.debug("Sending request " + put); CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials( - new AuthScope(ip, port), - new UsernamePasswordCredentials(configuration.getProperty("username"), configuration.getProperty("password"))); - CloseableHttpClient client = HttpClients.custom() - .setDefaultCredentialsProvider(credsProvider).build(); + credsProvider.setCredentials(new AuthScope(ip, port), new UsernamePasswordCredentials( + configuration.getProperty("username"), configuration.getProperty("password"))); + CloseableHttpClient client = + HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); int httpCode; try { @@ -134,7 +131,8 @@ public class httpClient { } @SuppressWarnings("deprecation") - public static String getMethod(String protocol, String ip, int port, String path, String contentType) throws APPCException { + public static String getMethod(String protocol, String ip, int port, String path, + String contentType) throws APPCException { logger.info("Sending GET request to " + path); @@ -151,11 +149,10 @@ public class httpClient { logger.debug("Sending request " + get); CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials( - new AuthScope(ip, port), - new UsernamePasswordCredentials(configuration.getProperty("username"), configuration.getProperty("password"))); - CloseableHttpClient client = HttpClients.custom() - .setDefaultCredentialsProvider(credsProvider).build(); + credsProvider.setCredentials(new AuthScope(ip, port), new UsernamePasswordCredentials( + configuration.getProperty("username"), configuration.getProperty("password"))); + CloseableHttpClient client = + HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); int httpCode; String result; @@ -172,7 +169,8 @@ public class httpClient { } @SuppressWarnings("deprecation") - public static int deleteMethod(String protocol, String ip, int port, String path, String contentType) throws APPCException { + public static int deleteMethod(String protocol, String ip, int port, String path, + String contentType) throws APPCException { logger.info("Sending DELETE request to " + path); @@ -189,14 +187,12 @@ public class httpClient { logger.debug("Sending request " + delete); CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials( - new AuthScope(ip, port), - new UsernamePasswordCredentials(configuration.getProperty("username"), configuration.getProperty("password"))); - CloseableHttpClient client = HttpClients.custom() - .setDefaultCredentialsProvider(credsProvider).build(); + credsProvider.setCredentials(new AuthScope(ip, port), new UsernamePasswordCredentials( + configuration.getProperty("username"), configuration.getProperty("password"))); + CloseableHttpClient client = + HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); int httpCode; - String result; try { HttpResponse response = client.execute(delete); |