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>
private static final String RESOURCE_URL_PREFIX = "resources";\r
@Autowired\r
private RefProp refProp;\r
- private CryptoUtils cryptoUtils = new CryptoUtils();\r
\r
// returns SDC id and password as a HTTP Basic Auth string (for example: Basic dGVzdDoxMjM0NTY=)\r
private String getSdcBasicAuth() throws GeneralSecurityException, DecoderException {\r
String sdcId = refProp.getStringValue("sdc.serviceUsername");\r
String sdcPw = refProp.getStringValue("sdc.servicePassword");\r
- String password = cryptoUtils.decrypt(sdcPw);\r
+ String password = CryptoUtils.decrypt(sdcPw);\r
String idPw = Base64.getEncoder().encodeToString((sdcId + ":" + password).getBytes(StandardCharsets.UTF_8));\r
return "Basic " + idPw;\r
}\r
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.
@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) {
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;
* ...)
*/
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;
/**
* 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;
}
}
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;
}
/**
* 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;
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;
}
/**
* 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()) {
/**
* 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);
/**
* 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<>();
/**
* 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);
/**
* 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);
/**
* 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);
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;
*/
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>
/**
* 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;
+ }
}
}
import java.util.Date;\r
import java.util.TimeZone;\r
import java.util.UUID;\r
-\r
+import javax.validation.constraints.NotNull;\r
import org.apache.log4j.MDC;\r
\r
/**\r
* This class handles the special info that appear in the log, like RequestID,\r
* time context, ...\r
- *\r
*/\r
-public class LoggingUtils {\r
+public final class LoggingUtils {\r
+\r
+ private static final DateFormat DATE_FORMAT = createDateFormat();\r
+\r
+ /**\r
+ * Private constructor to avoid creating instances of util class.\r
+ */\r
+ private LoggingUtils() {\r
+ }\r
\r
/**\r
* Set request related logging variables in thread local data via MDC\r
- * \r
- * @param service\r
- * Service Name of API (ex. "PUT template")\r
- * @param partner\r
- * Partner name (client or user invoking API)\r
+ *\r
+ * @param service Service Name of API (ex. "PUT template")\r
+ * @param partner Partner name (client or user invoking API)\r
*/\r
public static void setRequestContext(String service, String partner) {\r
MDC.put("RequestId", UUID.randomUUID().toString());\r
\r
/**\r
* Set time related logging variables in thread local data via MDC.\r
- * \r
- * @param beginTimeStamp\r
- * Start time\r
- * @param endTimeStamp\r
- * End time\r
+ *\r
+ * @param beginTimeStamp Start time\r
+ * @param endTimeStamp End time\r
*/\r
- public static void setTimeContext(Date beginTimeStamp, Date endTimeStamp) {\r
- String beginTime = "";\r
- String endTime = "";\r
- String elapsedTime = "";\r
-\r
- if (beginTimeStamp != null && endTimeStamp != null) {\r
- elapsedTime = String.valueOf(endTimeStamp.getTime() - beginTimeStamp.getTime());\r
- beginTime = generateTimestampStr(beginTimeStamp);\r
- endTime = generateTimestampStr(endTimeStamp);\r
- }\r
-\r
- MDC.put("BeginTimestamp", beginTime);\r
- MDC.put("EndTimestamp", endTime);\r
- MDC.put("ElapsedTime", elapsedTime);\r
+ public static void setTimeContext(@NotNull Date beginTimeStamp, @NotNull Date endTimeStamp) {\r
+ MDC.put("BeginTimestamp", generateTimestampStr(beginTimeStamp));\r
+ MDC.put("EndTimestamp", generateTimestampStr(endTimeStamp));\r
+ MDC.put("ElapsedTime", String.valueOf(endTimeStamp.getTime() - beginTimeStamp.getTime()));\r
}\r
\r
/**\r
* Set response related logging variables in thread local data via MDC.\r
- * \r
- * @param code\r
- * Response code ("0" indicates success)\r
- * @param description\r
- * Response description\r
- * @param className\r
- * class name of invoking class\r
+ *\r
+ * @param code Response code ("0" indicates success)\r
+ * @param description Response description\r
+ * @param className class name of invoking class\r
*/\r
public static void setResponseContext(String code, String description, String className) {\r
MDC.put("ResponseCode", code);\r
\r
/**\r
* Set target related logging variables in thread local data via MDC\r
- * \r
- * @param targetEntity\r
- * Target entity (an external/sub component, for ex. "sdc")\r
- * @param targetServiceName\r
- * Target service name (name of API invoked on target)\r
+ *\r
+ * @param targetEntity Target entity (an external/sub component, for ex. "sdc")\r
+ * @param targetServiceName Target service name (name of API invoked on target)\r
*/\r
public static void setTargetContext(String targetEntity, String targetServiceName) {\r
MDC.put("TargetEntity", targetEntity != null ? targetEntity : "");\r
\r
/**\r
* Set error related logging variables in thread local data via MDC.\r
- * \r
- * @param code\r
- * Error code\r
- * @param description\r
- * Error description\r
+ *\r
+ * @param code Error code\r
+ * @param description Error description\r
*/\r
public static void setErrorContext(String code, String description) {\r
MDC.put("ErrorCode", code);\r
}\r
\r
private static String generateTimestampStr(Date timeStamp) {\r
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");\r
- TimeZone tz = TimeZone.getTimeZone("UTC");\r
- df.setTimeZone(tz);\r
- return df.format(timeStamp);\r
+ return DATE_FORMAT.format(timeStamp);\r
}\r
\r
/**\r
* Get a previously stored RequestID for the thread local data via MDC. If\r
* one was not previously stored, generate one, store it, and return that\r
* one.\r
- * \r
+ *\r
* @return A string with the request ID\r
*/\r
public static String getRequestId() {\r
- String reqid;\r
+ String requestId;\r
\r
- reqid = (String) MDC.get("RequestID");\r
- if (reqid == null || reqid.isEmpty()) {\r
- reqid = UUID.randomUUID().toString();\r
- MDC.put("RequestId", reqid);\r
+ requestId = (String) MDC.get("RequestID");\r
+ if (requestId == null || requestId.isEmpty()) {\r
+ requestId = UUID.randomUUID().toString();\r
+ MDC.put("RequestId", requestId);\r
}\r
- return reqid;\r
+ return requestId;\r
+ }\r
+\r
+ private static DateFormat createDateFormat() {\r
+ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");\r
+ dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));\r
+ return dateFormat;\r
}\r
\r
}\r
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) {
/**
* 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();
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
-import java.io.UnsupportedEncodingException;
-import java.security.GeneralSecurityException;
-
-import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.Test;
-/**
- * Test Crypto Utils with Spring.
- */
+
public class CryptoUtilsTest {
- private CryptoUtils cryptoUtils = new CryptoUtils();
- final String data = "This is a test string";
- /**
- * This method tests encryption.
- *
- * @throws GeneralSecurityException
- * @throws DecoderException
- * @throws UnsupportedEncodingException
- */
+ private final String data = "This is a test string";
+
@Test
- public final void testEncryption() throws GeneralSecurityException, DecoderException, UnsupportedEncodingException {
- String encodedString = cryptoUtils.encrypt(data);
+ public final void testEncryption() throws Exception {
+ String encodedString = CryptoUtils.encrypt(data);
assertNotNull(encodedString);
- assertEquals(data, cryptoUtils.decrypt(encodedString));
+ assertEquals(data, CryptoUtils.decrypt(encodedString));
}
- /**
- * This method tests encryption.
- *
- * @throws GeneralSecurityException
- * @throws DecoderException
- * @throws UnsupportedEncodingException
- */
@Test
- public final void testEncryptedStringIsDifferent()
- throws GeneralSecurityException, DecoderException, UnsupportedEncodingException {
- String encodedString1 = cryptoUtils.encrypt(data);
- String encodedString2 = cryptoUtils.encrypt(data);
+ public final void testEncryptedStringIsDifferent() throws Exception {
+ String encodedString1 = CryptoUtils.encrypt(data);
+ String encodedString2 = CryptoUtils.encrypt(data);
byte[] encryptedMessage1 = Hex.decodeHex(encodedString1.toCharArray());
byte[] encryptedMessage2 = Hex.decodeHex(encodedString2.toCharArray());
assertNotNull(encryptedMessage1);