diff options
author | biniek <lukasz.biniek@nokia.com> | 2017-12-19 11:57:06 +0100 |
---|---|---|
committer | biniek <lukasz.biniek@nokia.com> | 2017-12-19 14:58:08 +0100 |
commit | a029b8b76a2a2d028f8a97f6a6884d90ebfd3fbc (patch) | |
tree | 7c9dcd129ca1e1e40d2bf47b8158d985cc41eea1 /src/main | |
parent | a4096a47f893c1ed0a231303093c3fbba6865641 (diff) |
Cleanup of utils classes.
Removed javadoc without any information; enforced util class won't be initialized;
extracted constants.
Change-Id: Ie30156472d929dfc95819a1d5affaaf867eed611
Issue-ID: CLAMP-96
Signed-off-by: biniek <lukasz.biniek@nokia.com>
Diffstat (limited to 'src/main')
6 files changed, 120 insertions, 188 deletions
diff --git a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java index 14421da5f..372f8e818 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java +++ b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java @@ -93,13 +93,12 @@ public class SdcCatalogServices { private static final String RESOURCE_URL_PREFIX = "resources";
@Autowired
private RefProp refProp;
- private CryptoUtils cryptoUtils = new CryptoUtils();
// returns SDC id and password as a HTTP Basic Auth string (for example: Basic dGVzdDoxMjM0NTY=)
private String getSdcBasicAuth() throws GeneralSecurityException, DecoderException {
String sdcId = refProp.getStringValue("sdc.serviceUsername");
String sdcPw = refProp.getStringValue("sdc.servicePassword");
- String password = cryptoUtils.decrypt(sdcPw);
+ String password = CryptoUtils.decrypt(sdcPw);
String idPw = Base64.getEncoder().encodeToString((sdcId + ":" + password).getBytes(StandardCharsets.UTF_8));
return "Basic " + idPw;
}
diff --git a/src/main/java/org/onap/clamp/clds/config/EncodedPasswordBasicDataSource.java b/src/main/java/org/onap/clamp/clds/config/EncodedPasswordBasicDataSource.java index 453689bea..9914ea739 100644 --- a/src/main/java/org/onap/clamp/clds/config/EncodedPasswordBasicDataSource.java +++ b/src/main/java/org/onap/clamp/clds/config/EncodedPasswordBasicDataSource.java @@ -41,14 +41,6 @@ public class EncodedPasswordBasicDataSource extends BasicDataSource { protected static final EELFLogger logger = EELFManager.getInstance() .getLogger(EncodedPasswordBasicDataSource.class); protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - private CryptoUtils cryptoUtils = new CryptoUtils(); - - /** - * The default constructor calling the parent one. - */ - public EncodedPasswordBasicDataSource() { - super(); - } /** * This method is used automatically by Spring to decode the password. @@ -56,7 +48,7 @@ public class EncodedPasswordBasicDataSource extends BasicDataSource { @Override public synchronized void setPassword(String encodedPassword) { try { - this.password = cryptoUtils.decrypt(encodedPassword); + this.password = CryptoUtils.decrypt(encodedPassword); } catch (GeneralSecurityException e) { logger.error("Unable to decrypt the DB password", e); } catch (DecoderException e) { diff --git a/src/main/java/org/onap/clamp/clds/model/prop/AbstractModelElement.java b/src/main/java/org/onap/clamp/clds/model/prop/AbstractModelElement.java index 9ced01998..a0685228b 100644 --- a/src/main/java/org/onap/clamp/clds/model/prop/AbstractModelElement.java +++ b/src/main/java/org/onap/clamp/clds/model/prop/AbstractModelElement.java @@ -26,7 +26,6 @@ package org.onap.clamp.clds.model.prop; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import com.fasterxml.jackson.databind.JsonNode; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -37,29 +36,25 @@ import java.util.List; * ...) */ public abstract class AbstractModelElement { - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractModelElement.class); - protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); - private final String type; - private final ModelBpmn modelBpmn; - private final String id; - protected String topicPublishes; - protected final JsonNode modelElementJsonNode; - private boolean isFound; + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractModelElement.class); + protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + + private final String type; + private final ModelBpmn modelBpmn; + private final String id; + protected String topicPublishes; + protected final JsonNode modelElementJsonNode; + private boolean isFound; - private final ModelProperties modelProp; + private final ModelProperties modelProp; - private static final String LOG_ELEMENT = "Value '"; - private static final String LOG_NOT_FOUND = "' for key 'name' not found in JSON"; + private static final String LOG_ELEMENT_NOT_FOUND = "Value '{}' for key 'name' not found in JSON"; + private static final String LOG_ELEMENT_NOT_FOUND_IN_JSON = "Value '{}' for key 'name' not found in JSON {}"; /** * Perform base parsing of properties for a ModelElement (such as, * VesCollector, Policy and Tca) - * - * @param type - * @param modelProp - * @param modelBpmn - * @param modelJson */ protected AbstractModelElement(String type, ModelProperties modelProp, ModelBpmn modelBpmn, JsonNode modelJson) { this.type = type; @@ -97,10 +92,6 @@ public abstract class AbstractModelElement { /** * Return the value field of the json node element that has a name field * equals to the given name. - * - * @param nodeIn - * @param name - * @return */ public static String getValueByName(JsonNode nodeIn, String name) { String value = null; @@ -119,9 +110,9 @@ public abstract class AbstractModelElement { } } if (value == null || value.length() == 0) { - logger.warn(LOG_ELEMENT + name + LOG_NOT_FOUND); + logger.warn(LOG_ELEMENT_NOT_FOUND, name); } else { - logger.debug(LOG_ELEMENT + name + LOG_NOT_FOUND + nodeIn.toString()); + logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, nodeIn.toString()); } return value; } @@ -129,10 +120,6 @@ public abstract class AbstractModelElement { /** * Return the value field of the json node element that has a name field * that equals the given name. - * - * @param nodeIn - * @param name - * @return */ public static String getNodeValueByName(JsonNode nodeIn, String name) { String value = null; @@ -140,9 +127,9 @@ public abstract class AbstractModelElement { value = nodeIn.path(name).asText(); } if (value == null || value.length() == 0) { - logger.warn(LOG_ELEMENT + name + LOG_NOT_FOUND); + logger.warn(LOG_ELEMENT_NOT_FOUND, name); } else { - logger.debug(LOG_ELEMENT + name + LOG_NOT_FOUND + nodeIn.toString()); + logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, nodeIn.toString()); } return value; } @@ -150,17 +137,11 @@ public abstract class AbstractModelElement { /** * Return the value field of the json node element that has a name field * that equals the given name. - * - * @param nodeIn - * @param name - * @return */ public static List<String> getNodeValuesByName(JsonNode nodeIn, String name) { List<String> values = new ArrayList<>(); if (nodeIn != null) { - Iterator<JsonNode> i = nodeIn.iterator(); - while (i.hasNext()) { - JsonNode node = i.next(); + for (JsonNode node : nodeIn) { if (node.path("name").asText().equals(name)) { JsonNode vnode = node.path("value"); if (vnode.isArray()) { @@ -179,10 +160,6 @@ public abstract class AbstractModelElement { /** * Return the int value field of the json node element that has a name field * equals to the given name. - * - * @param nodeIn - * @param name - * @return */ public static Integer getIntValueByName(JsonNode nodeIn, String name) { String value = getValueByName(nodeIn, name); @@ -192,35 +169,26 @@ public abstract class AbstractModelElement { /** * Return an array of values for the field of the json node element that has * a name field equals to the given name. - * - * @param nodeIn - * @param name - * @return */ public static List<String> getValuesByName(JsonNode nodeIn, String name) { List<String> values = null; if (nodeIn != null) { - Iterator<JsonNode> i = nodeIn.iterator(); - while (i.hasNext()) { - JsonNode node = i.next(); + for (JsonNode node : nodeIn) { if (node.path("name").asText().equals(name)) { values = getValuesList(node); } } } if (values == null || values.isEmpty()) { - logger.warn(LOG_ELEMENT + name + LOG_NOT_FOUND); + logger.warn(LOG_ELEMENT_NOT_FOUND, name); } else { - logger.debug(LOG_ELEMENT + name + LOG_NOT_FOUND + nodeIn.toString()); + logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, nodeIn.toString()); } return values; } /** * Return an array of String values. - * - * @param nodeIn - * @return */ public static List<String> getValuesList(JsonNode nodeIn) { ArrayList<String> al = new ArrayList<>(); @@ -237,9 +205,6 @@ public abstract class AbstractModelElement { /** * Return the value field of the json node element that has a name field * equals to the given name. - * - * @param name - * @return */ public String getValueByName(String name) { return getValueByName(modelElementJsonNode, name); @@ -248,9 +213,6 @@ public abstract class AbstractModelElement { /** * Return the int value field of the json node element that has a name field * equals to the given name. - * - * @param name - * @return */ public Integer getIntValueByName(String name) { return getIntValueByName(modelElementJsonNode, name); @@ -259,9 +221,6 @@ public abstract class AbstractModelElement { /** * Return an array of values for the field of the json node element that has * a name field equals to the given name. - * - * @param name - * @return */ public List<String> getValuesByName(String name) { return getValuesByName(modelElementJsonNode, name); diff --git a/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java b/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java index 2c91f0091..424399614 100644 --- a/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java @@ -25,17 +25,15 @@ package org.onap.clamp.clds.util; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; - +import com.google.common.base.Charsets; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.SecureRandom; import java.util.Properties; - import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; - import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.ArrayUtils; @@ -46,9 +44,6 @@ import org.apache.commons.lang3.ArrayUtils; */ public final class CryptoUtils { - /** - * Used to log. - */ private static final EELFLogger logger = EELFManager.getInstance().getLogger(CryptoUtils.class); // Openssl commands: // Encrypt: echo -n "123456" | openssl aes-128-cbc -e -K <Private Hex key> @@ -66,85 +61,87 @@ public final class CryptoUtils { /** * Detailed definition of encryption algorithm. */ - private static final String ALGORYTHM_DETAILS = ALGORITHM + "/CBC/PKCS5PADDING"; - /** - * Block SIze in bits. - */ - private static final int BLOCK_SIZE = 128; + private static final String ALGORITHM_DETAILS = ALGORITHM + "/CBC/PKCS5PADDING"; + private static final int BLOCK_SIZE_IN_BITS = 128; + private static final int BLOCK_SIZE_IN_BYTES = BLOCK_SIZE_IN_BITS / 8; /** * Key to read in the key.properties file. */ private static final String KEY_PARAM = "org.onap.clamp.encryption.aes.key"; + private static final String PROPERTIES_FILE_NAME = "clds/key.properties"; /** * The SecretKeySpec created from the Base 64 String key. */ - private static SecretKeySpec secretKeySpec = null; + private static final SecretKeySpec SECRET_KEY_SPEC = readSecretKeySpec(PROPERTIES_FILE_NAME); - // Static init - static { - Properties props = new Properties(); - try { - props.load(ResourceFileUtil.getResourceAsStream("clds/key.properties")); - secretKeySpec = getSecretKeySpec(props.getProperty(KEY_PARAM)); - } catch (IOException | DecoderException e) { - logger.error("Exception occurred during the key reading", e); - } + /** + * Private constructor to avoid creating instances of util class. + */ + private CryptoUtils() { } /** * Encrypt a value based on the Clamp Encryption Key. - * - * @param value - * The value to encrypt + * + * @param value The value to encrypt * @return The encrypted string - * @throws GeneralSecurityException - * In case of issue with the encryption - * @throws UnsupportedEncodingException - * In case of issue with the charset conversion + * @throws GeneralSecurityException In case of issue with the encryption + * @throws UnsupportedEncodingException In case of issue with the charset conversion */ - public String encrypt(String value) throws GeneralSecurityException, UnsupportedEncodingException { - Cipher cipher = Cipher.getInstance(CryptoUtils.ALGORYTHM_DETAILS, "SunJCE"); + public static String encrypt(String value) throws GeneralSecurityException, UnsupportedEncodingException { + Cipher cipher = Cipher.getInstance(ALGORITHM_DETAILS, "SunJCE"); SecureRandom randomNumber = SecureRandom.getInstance("SHA1PRNG"); - byte[] iv = new byte[BLOCK_SIZE / 8]; + byte[] iv = new byte[BLOCK_SIZE_IN_BYTES]; randomNumber.nextBytes(iv); IvParameterSpec ivspec = new IvParameterSpec(iv); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec); - return Hex.encodeHexString(ArrayUtils.addAll(iv, cipher.doFinal(value.getBytes("UTF-8")))); + cipher.init(Cipher.ENCRYPT_MODE, SECRET_KEY_SPEC, ivspec); + return Hex.encodeHexString(ArrayUtils.addAll(iv, cipher.doFinal(value.getBytes(Charsets.UTF_8)))); } /** * Decrypt a value based on the Clamp Encryption Key. - * - * @param message - * The encrypted string that must be decrypted using the Clamp - * Encryption Key + * + * @param message The encrypted string that must be decrypted using the Clamp Encryption Key * @return The String decrypted - * @throws GeneralSecurityException - * In case of issue with the encryption - * @throws DecoderException - * In case of issue to decode the HexString + * @throws GeneralSecurityException In case of issue with the encryption + * @throws DecoderException In case of issue to decode the HexString */ - public String decrypt(String message) throws GeneralSecurityException, DecoderException { + public static String decrypt(String message) throws GeneralSecurityException, DecoderException { byte[] encryptedMessage = Hex.decodeHex(message.toCharArray()); - Cipher cipher = Cipher.getInstance(CryptoUtils.ALGORYTHM_DETAILS, "SunJCE"); - IvParameterSpec ivspec = new IvParameterSpec(ArrayUtils.subarray(encryptedMessage, 0, BLOCK_SIZE / 8)); - byte[] realData = ArrayUtils.subarray(encryptedMessage, BLOCK_SIZE / 8, encryptedMessage.length); - cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec); + Cipher cipher = Cipher.getInstance(ALGORITHM_DETAILS, "SunJCE"); + IvParameterSpec ivspec = new IvParameterSpec(ArrayUtils.subarray(encryptedMessage, 0, BLOCK_SIZE_IN_BYTES)); + byte[] realData = ArrayUtils.subarray(encryptedMessage, BLOCK_SIZE_IN_BYTES, encryptedMessage.length); + cipher.init(Cipher.DECRYPT_MODE, SECRET_KEY_SPEC, ivspec); byte[] decrypted = cipher.doFinal(realData); return new String(decrypted); } /** * Method used to generate the SecretKeySpec from a Base64 String. - * - * @param keyString - * The key as a string in Base 64 + * + * @param keyString The key as a string in Base 64 * @return The SecretKeySpec created - * @throws DecoderException - * In case of issues with the decoding of Base64 + * @throws DecoderException In case of issues with the decoding of Base64 */ private static SecretKeySpec getSecretKeySpec(String keyString) throws DecoderException { byte[] key = Hex.decodeHex(keyString.toCharArray()); - return new SecretKeySpec(key, CryptoUtils.ALGORITHM); + return new SecretKeySpec(key, ALGORITHM); + } + + /** + * Reads SecretKeySpec from file specified by propertiesFileName + * + * @param propertiesFileName File name with properties + * @return SecretKeySpec secret key spec read from propertiesFileName + */ + private static SecretKeySpec readSecretKeySpec(String propertiesFileName) { + Properties props = new Properties(); + try { + props.load(ResourceFileUtil.getResourceAsStream(propertiesFileName)); + return getSecretKeySpec(props.getProperty(KEY_PARAM)); + } catch (IOException | DecoderException e) { + logger.error("Exception occurred during the key reading", e); + return null; + } } } diff --git a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java index b501b2df0..bca413415 100644 --- a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java @@ -28,23 +28,28 @@ import java.text.SimpleDateFormat; import java.util.Date;
import java.util.TimeZone;
import java.util.UUID;
-
+import javax.validation.constraints.NotNull;
import org.apache.log4j.MDC;
/**
* This class handles the special info that appear in the log, like RequestID,
* time context, ...
- *
*/
-public class LoggingUtils {
+public final class LoggingUtils {
+
+ private static final DateFormat DATE_FORMAT = createDateFormat();
+
+ /**
+ * Private constructor to avoid creating instances of util class.
+ */
+ private LoggingUtils() {
+ }
/**
* Set request related logging variables in thread local data via MDC
- *
- * @param service
- * Service Name of API (ex. "PUT template")
- * @param partner
- * Partner name (client or user invoking API)
+ *
+ * @param service Service Name of API (ex. "PUT template")
+ * @param partner Partner name (client or user invoking API)
*/
public static void setRequestContext(String service, String partner) {
MDC.put("RequestId", UUID.randomUUID().toString());
@@ -54,37 +59,22 @@ public class LoggingUtils { /**
* Set time related logging variables in thread local data via MDC.
- *
- * @param beginTimeStamp
- * Start time
- * @param endTimeStamp
- * End time
+ *
+ * @param beginTimeStamp Start time
+ * @param endTimeStamp End time
*/
- public static void setTimeContext(Date beginTimeStamp, Date endTimeStamp) {
- String beginTime = "";
- String endTime = "";
- String elapsedTime = "";
-
- if (beginTimeStamp != null && endTimeStamp != null) {
- elapsedTime = String.valueOf(endTimeStamp.getTime() - beginTimeStamp.getTime());
- beginTime = generateTimestampStr(beginTimeStamp);
- endTime = generateTimestampStr(endTimeStamp);
- }
-
- MDC.put("BeginTimestamp", beginTime);
- MDC.put("EndTimestamp", endTime);
- MDC.put("ElapsedTime", elapsedTime);
+ public static void setTimeContext(@NotNull Date beginTimeStamp, @NotNull Date endTimeStamp) {
+ MDC.put("BeginTimestamp", generateTimestampStr(beginTimeStamp));
+ MDC.put("EndTimestamp", generateTimestampStr(endTimeStamp));
+ MDC.put("ElapsedTime", String.valueOf(endTimeStamp.getTime() - beginTimeStamp.getTime()));
}
/**
* Set response related logging variables in thread local data via MDC.
- *
- * @param code
- * Response code ("0" indicates success)
- * @param description
- * Response description
- * @param className
- * class name of invoking class
+ *
+ * @param code Response code ("0" indicates success)
+ * @param description Response description
+ * @param className class name of invoking class
*/
public static void setResponseContext(String code, String description, String className) {
MDC.put("ResponseCode", code);
@@ -95,11 +85,9 @@ public class LoggingUtils { /**
* Set target related logging variables in thread local data via MDC
- *
- * @param targetEntity
- * Target entity (an external/sub component, for ex. "sdc")
- * @param targetServiceName
- * Target service name (name of API invoked on target)
+ *
+ * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
+ * @param targetServiceName Target service name (name of API invoked on target)
*/
public static void setTargetContext(String targetEntity, String targetServiceName) {
MDC.put("TargetEntity", targetEntity != null ? targetEntity : "");
@@ -108,11 +96,9 @@ public class LoggingUtils { /**
* Set error related logging variables in thread local data via MDC.
- *
- * @param code
- * Error code
- * @param description
- * Error description
+ *
+ * @param code Error code
+ * @param description Error description
*/
public static void setErrorContext(String code, String description) {
MDC.put("ErrorCode", code);
@@ -120,28 +106,31 @@ public class LoggingUtils { }
private static String generateTimestampStr(Date timeStamp) {
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
- TimeZone tz = TimeZone.getTimeZone("UTC");
- df.setTimeZone(tz);
- return df.format(timeStamp);
+ return DATE_FORMAT.format(timeStamp);
}
/**
* Get a previously stored RequestID for the thread local data via MDC. If
* one was not previously stored, generate one, store it, and return that
* one.
- *
+ *
* @return A string with the request ID
*/
public static String getRequestId() {
- String reqid;
+ String requestId;
- reqid = (String) MDC.get("RequestID");
- if (reqid == null || reqid.isEmpty()) {
- reqid = UUID.randomUUID().toString();
- MDC.put("RequestId", reqid);
+ requestId = (String) MDC.get("RequestID");
+ if (requestId == null || requestId.isEmpty()) {
+ requestId = UUID.randomUUID().toString();
+ MDC.put("RequestId", requestId);
}
- return reqid;
+ return requestId;
+ }
+
+ private static DateFormat createDateFormat() {
+ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
+ dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ return dateFormat;
}
}
diff --git a/src/main/java/org/onap/clamp/clds/util/ResourceFileUtil.java b/src/main/java/org/onap/clamp/clds/util/ResourceFileUtil.java index 0aaa09ac2..57705d8fd 100644 --- a/src/main/java/org/onap/clamp/clds/util/ResourceFileUtil.java +++ b/src/main/java/org/onap/clamp/clds/util/ResourceFileUtil.java @@ -25,23 +25,22 @@ package org.onap.clamp.clds.util; import java.io.IOException; import java.io.InputStream; +import java.util.Scanner; /** * Utility methods supporting transforms. */ -public class ResourceFileUtil { +public final class ResourceFileUtil { /** - * Disable the ResourceFileUtil constructor. + * Private constructor to avoid creating instances of util class. */ private ResourceFileUtil() { - } /** * Return resource as a Stream. * - * @param name * @return resource - resource as stream */ public static InputStream getResourceAsStream(String name) { @@ -54,14 +53,11 @@ public class ResourceFileUtil { /** * Return resource as a Stream. - * - * @param name - * @throws IOException */ public static String getResourceAsString(String name) throws IOException { InputStream is = getResourceAsStream(name); - java.util.Scanner scanner = new java.util.Scanner(is); - java.util.Scanner delimitedScanner = scanner.useDelimiter("\\A"); + Scanner scanner = new Scanner(is); + Scanner delimitedScanner = scanner.useDelimiter("\\A"); String text = delimitedScanner.hasNext() ? delimitedScanner.next() : ""; delimitedScanner.close(); scanner.close(); |