diff options
Diffstat (limited to 'appc-core/appc-common-bundle/java/org/onap/appc/util')
10 files changed, 0 insertions, 2504 deletions
diff --git a/appc-core/appc-common-bundle/java/org/onap/appc/util/JsonUtil.java b/appc-core/appc-common-bundle/java/org/onap/appc/util/JsonUtil.java deleted file mode 100644 index 14784595c..000000000 --- a/appc-core/appc-common-bundle/java/org/onap/appc/util/JsonUtil.java +++ /dev/null @@ -1,126 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017-2018 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. - * - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.util; - -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"}} - * @throws IOException when the object is not valid json Map - */ - 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-core/appc-common-bundle/java/org/onap/appc/util/MessageFormatter.java b/appc-core/appc-common-bundle/java/org/onap/appc/util/MessageFormatter.java deleted file mode 100644 index a46047eaa..000000000 --- a/appc-core/appc-common-bundle/java/org/onap/appc/util/MessageFormatter.java +++ /dev/null @@ -1,90 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017-2018 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. - * - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.util; - -import org.apache.commons.lang3.StringUtils; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -public class MessageFormatter { - private final static String paramNameRegexGroupName = "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>[^}$]+)\\}"; - - public static String format(String messageTemplate, Map<String, Object> params) { - if (StringUtils.isEmpty(messageTemplate)) - return ""; - if (params == null || params.isEmpty()) - return messageTemplate; - - String formattedMessage = messageTemplate; - if (formattedMessage.contains("$")) { - for (Map.Entry<String, Object> entry : params.entrySet()) { - 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)) { - paramsNames = new ArrayList<>(); - Matcher m = Pattern.compile(paramRegex).matcher(messageTemplate); - while (m.find()) { - String paramName = m.group(paramNameRegexGroupName); - paramsNames.add(paramName); - } - } - return paramsNames; - } - - public static Set<String> getParamsNamesSet(String messageTemplate) { - List<String> paramsNamesList = getParamsNamesList(messageTemplate); - Set<String> paramsNamesSet = null; - if (paramsNamesList != null && !paramsNamesList.isEmpty()) { - paramsNamesSet = new HashSet<String>(); - for (String paramName : paramsNamesList) { - paramsNamesSet.add(paramName); - } - } - return paramsNamesSet; - } -} diff --git a/appc-core/appc-common-bundle/java/org/onap/appc/util/ObjectMapper.java b/appc-core/appc-common-bundle/java/org/onap/appc/util/ObjectMapper.java deleted file mode 100644 index e4b76dd7c..000000000 --- a/appc-core/appc-common-bundle/java/org/onap/appc/util/ObjectMapper.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017-2018 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. - * - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.util; - -import java.lang.reflect.Array; -import java.util.Map; - -public class ObjectMapper { - - private ObjectMapper() { - } - - private static void dispatch(PathContext context, Object obj) { - - if (obj == null) { - return; - } - - final Class<?> cls = obj.getClass(); - - if (cls.isPrimitive() - || String.class.isAssignableFrom(cls) - || Number.class.isAssignableFrom(cls) - || Boolean.class.isAssignableFrom(cls)) { - handlePrimitive(context, obj); - } else if (cls.isArray()) { - handleArray(context, obj); - } else if (Map.class.isAssignableFrom(cls)) { - handleMap(context, (Map<?, ?>) obj); - } else if (Iterable.class.isAssignableFrom(cls)) { - handleCollection(context, Iterable.class.cast(obj)); - } else { - throw new IllegalArgumentException(obj.getClass().getName()); - } - } - - public static Map<String, String> map(Object obj) { - PathContext context = new PathContext(); - dispatch(context, obj); - return context.entries(); - } - - private static void handleMap(PathContext context, Map<?, ?> val) { - for (Map.Entry<?, ?> entry : val.entrySet()) { - context.pushToken(entry.getKey().toString()); - dispatch(context, entry.getValue()); - context.popToken(); - } - } - - private static void handleCollection(PathContext context, Iterable<?> val) { - int index = 0; - for (Object elem : val) { - handleElement(context, index++, elem); - } - } - - private static void handleArray(PathContext context, Object val) { - for (int i = 0, n = Array.getLength(val); i < n; i++) { - handleElement(context, i, Array.get(val, i)); - } - } - - private static void handleElement(PathContext context, int index, Object val) { - if (val == null) { - return; - } - - String modifier = new StringBuilder().append('[').append(Integer.valueOf(index)).append(']').toString(); - - context.pushModifier(modifier); - dispatch(context, val); - context.popModifier(); - } - - private static void handlePrimitive(PathContext context, Object val) { - context.entry(context.getPath(), val.toString()); - } -} diff --git a/appc-core/appc-common-bundle/java/org/onap/appc/util/PathContext.java b/appc-core/appc-common-bundle/java/org/onap/appc/util/PathContext.java deleted file mode 100644 index d57837c14..000000000 --- a/appc-core/appc-common-bundle/java/org/onap/appc/util/PathContext.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017-2018 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. - * - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.util; - - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.Map; - -class PathContext { - - private StringBuilder path = new StringBuilder(128); - - private LinkedList<Integer> indexes = new LinkedList<>(); - private Map<String, String> entries = new LinkedHashMap<>(); - private int offset = 0; - - private final String delimiter; - - PathContext() { - this("."); - } - - PathContext(String delimiter) { - this.delimiter = delimiter; - } - - private void push(String elem, boolean delimit) { - if (elem == null) { - throw new IllegalArgumentException(); - } - - int length = elem.length(); - - if (delimit && !indexes.isEmpty()) { - path.append(delimiter); - length += delimiter.length(); - } - - path.append(elem); - offset += length; - indexes.addLast(Integer.valueOf(length)); - } - - private void pop() { - if (indexes.isEmpty()) { - throw new IllegalStateException(); - } - offset -= indexes.removeLast(); - path.setLength(offset); - } - - void pushToken(String token) { - push(token, true); - } - - void popToken() { - pop(); - } - - void pushModifier(String modifier) { - push(modifier, false); - } - - void popModifier() { - pop(); - } - - String getPath() { - return path.substring(0, offset); - } - - void entry(String name, String value) { - entries.put(name, value); - } - - Map<String, String> entries() { - return Collections.unmodifiableMap(entries); - } -} diff --git a/appc-core/appc-common-bundle/java/org/onap/appc/util/StreamHelper.java b/appc-core/appc-common-bundle/java/org/onap/appc/util/StreamHelper.java deleted file mode 100644 index 4468c841b..000000000 --- a/appc-core/appc-common-bundle/java/org/onap/appc/util/StreamHelper.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017-2018 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. - * - * ============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-core/appc-common-bundle/java/org/onap/appc/util/StringHelper.java b/appc-core/appc-common-bundle/java/org/onap/appc/util/StringHelper.java deleted file mode 100644 index 920ce4228..000000000 --- a/appc-core/appc-common-bundle/java/org/onap/appc/util/StringHelper.java +++ /dev/null @@ -1,604 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017-2018 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. - * - * ============LICENSE_END========================================================= - */ - - -package org.onap.appc.util; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * This class contains several static helper methods that can be used to perform string manipulation algorithms. - */ - -public final class StringHelper { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(StringHelper.class); - - public static final String DASH = "-"; - public static final String DOT = "."; - public static final String ELLIPSES = "..."; - public static final String LINE_FEED = "\n"; - public static final String SLASH = "/"; - public static final String COMMA = ","; - - /** - * Converts the specified string pattern to a regular expression string. If the supplied string is null or empty, - * then a regular expression that matches all strings (.*) is returned. - * <p> - * The expression passed to this method should not already be a regular expression. If it contains problematic - * meta-characters for this routine (such as period, asterisk, and plus), they will be escaped and matched literally - * in the resulting regular expression returned. - * </p> - * - * @param value - * The pattern that we need to convert to a regular expression - * @return The regular expression that is equivalent to the pattern - */ - public static String convertToRegex(String value) { - if (value == null || value.trim().length() == 0) { - return ".*"; - } - - StringBuilder builder = new StringBuilder(value.trim()); - - /* - * If there are any period characters, we need to escape them so that they are exactly matched - */ - Pattern pattern = Pattern.compile("\\."); - Matcher matcher = pattern.matcher(builder); - int position = 0; - while (matcher.find(position)) { - builder.replace(matcher.start(), matcher.end(), "\\."); - position = matcher.end() + 1; - } - - /* - * If there are any asterisks or pluses, which we need to interpret as wildcard characters, we need to convert - * them into .* or . - */ - pattern = Pattern.compile("\\*|\\+"); - matcher = pattern.matcher(builder); - - /* - * If the string contains a .* meta-character sequence anywhere in the middle of the string (i.e., there are - * other characters following the .* meta-characters), OR the string ends with the .+ sequence, then we need to - * append the "end-of-line" boundary condition to the end of the string to get predictable results. - */ - if (resolveAppendingEOL(builder, matcher)) { - builder.append("$"); - } - return builder.toString(); - } - - private static boolean resolveAppendingEOL(StringBuilder builder, Matcher matcher) { - int position = 0; - boolean appendEOL = false; - - while (matcher.find(position)) { - String metachar = builder.substring(matcher.start(), matcher.end()); - if ("*".equals(metachar)) { - builder.replace(matcher.start(), matcher.end(), ".*"); - position = matcher.end() + 1; - if (matcher.end() < builder.length() - 1) { - appendEOL = true; - } - } else if ("+".equals(metachar)) { - builder.replace(matcher.start(), matcher.end(), "."); - position = matcher.end(); - if (matcher.end() == builder.length()) { - appendEOL = true; - } - } - } - return appendEOL; - } - - /** - * Takes a string that may possibly be very long and return a string that is at most maxLength. If the string is - * longer than maxLength, the last three characters will be the ellipses (...) to indicate that the string was - * shortened. - * - * @param possiblyLongString - * @param maxLength - * must be at least 4 (one character plus ellipses) - * @return possibly shortened string - */ - public static String getShortenedString(String possiblyLongString, int maxLength) { - if ((possiblyLongString != null) && (maxLength > ELLIPSES.length()) - && (possiblyLongString.length() > maxLength)) { - return possiblyLongString.substring(0, maxLength - ELLIPSES.length()) + ELLIPSES; - - } - return possiblyLongString; - } - - /** - * Determines that a provided string is not null and not empty (length = 0 after trimming) - * - * @param theString - * The string to be tested - * @return true if the string IS NOT null and is NOT empty - */ - public static boolean isNotNullNotEmpty(String theString) { - return theString != null && !theString.trim().isEmpty(); - } - - /** - * Determines that a provided string IS null or an empty string (length = 0 after trimming) - * - * @param theString - * The string to be tested - * @return true if the string IS null OR is empty - */ - public static boolean isNullOrEmpty(String theString) { - return theString == null || theString.trim().isEmpty(); - } - - /** - * Returns an indication if the first string is equal to the second string, allowing for either or both strings to - * be null. - * - * @param a - * The first string to be compared - * @param b - * The second string to be compared - * @return True if both strings are null, or both strings are non-null AND they are equal. False otherwise. - */ - public static boolean areEqual(String a, String b) { - return areEqual(a, b, false); - } - - /** - * Returns an indication if the first string is equal to the second string, allowing for either or both strings to - * be null, and ignoring case. - * - * @param a - * The first string to be compared - * @param b - * The second string to be compared - * @return True if both strings are null, or both strings are non-null AND they are equal (without regard to case). - * False otherwise. - */ - public static boolean equalsIgnoreCase(String a, String b) { - return areEqual(a, b, true); - } - - /** - * Compares two strings (allowing either or both to be null), and allowing for optional case sensitive or - * insensitive comparison. - * - * @param a - * The first string to be compared - * @param b - * The second string to be compared - * @param caseInsensitive - * True if the comparison is to be case in-sensitive. - * @return True if both strings are null, or both strings are non-null and they are equal - */ - private static boolean areEqual(String a, String b, boolean caseInsensitive) { - if (a == null && b == null) { - return true; - } - if (a != null && b != null) { - if (caseInsensitive) { - return a.equalsIgnoreCase(b); - } else { - return a.equals(b); - } - } - - return false; - } - - /** - * This method is used to mangle a name. - * <p> - * This method will first remove all unacceptable characters from the name and translate all characters to lower - * case. This is done to eliminate any potentially troublesome characters. If the resulting string is empty, then a - * random string of characters for the minimum desired length is returned. If the string is too short to meet the - * minimum length requirement, it is padded with random characters. - * </p> - * <p> - * Once the string has been scrubbed and possibly padded, it may be truncated (if longer than the maximum value) and - * the result is returned. To make the string as unique as possible, the algorithm removes excess letters from the - * center of the string, concatenating the first nad last parts of the name together. The assumption is that users - * tend to start the names of multiple things in similar ways, and get more descriptive as the name progresses. If - * for example, several objects were named "A test Object", "A test Object1", and "A test Object2", shortening the - * name only from the left does not generate a unique name. - * </p> - * - * @param name - * The name to be mangled - * @param minLen - * minimum number of characters for the name - * @param maxLen - * maximum number of characters for the name - * @return The mangled name, or an empty string if the value is null or an empty string. - */ - public static String mangleName(String name, int minLen, int maxLen) { - StringBuilder builder = new StringBuilder(name == null ? "" : name); - Pattern pattern = Pattern.compile("[^a-z0-9]+", Pattern.CASE_INSENSITIVE); - Matcher matcher = pattern.matcher(builder); - int position = 0; - while (matcher.find(position)) { - builder.delete(matcher.start(), matcher.end()); - position = matcher.start(); - } - - if (builder.length() < minLen) { - for (int i = builder.length(); i <= minLen; i++) { - builder.append("A"); - } - } - - /* - * Remove out of the center of the name to preserve start and end and result in a string of max len - */ - if (builder.length() > maxLen) { - int excess = builder.length() - maxLen; - int left = maxLen / 2; - - builder.delete(left, excess + left); - } - - return builder.toString().toLowerCase(); - } - - /** - * This method is used to normalize a string value. - * <p> - * This method will ensure that the string value is trimmed of all leading and trailing whitespace if not null. If - * it is null or an empty string, then it will return null. - * </p> - * - * @param value - * The value to be normalized - * @return The normalized (no leading or trailing whitespace) value, or null if the string was null or an empty - * string (or all whitespace). This method will never return an empty string. - */ - public static String normalizeString(String value) { - if (value != null) { - String temp = value.trim(); - if (temp.length() > 0) { - return temp; - } - } - return null; - } - - /** - * This method is used to strip all carriage returns and line feed characters from a string - * - * @param value - * @return The original value less all carriage returns and line feeds - */ - public static String stripCRLF(String value) { - - if (value == null) { - return null; - } - String[] tokens = value.split("\r\n|\n\r|\r|\n"); - StringBuilder builder = new StringBuilder(); - for (String token : tokens) { - builder.append(token.trim()); - } - return builder.toString(); - } - - /** - * Converts UNIX-style line endings to DOS-style. Replaces LF with CR+LF as long as the LF does not already exist - * paired with a CR. - * - * @param content - * The content to be converted - * @return The converted content. - */ - public static String toDOSLines(String content) { - if (content == null) { - return null; - } - - StringBuilder builder = new StringBuilder(content); - Pattern pattern = Pattern.compile("^(\n)[^\r]|[^\r](\n)[^\r]|[^\r](\n)$"); - Matcher matcher = pattern.matcher(builder); - int position = 0; - while (matcher.find(position)) { - int index = matcher.start(1); - if (index == -1) { - index = matcher.start(2); - } - if (index == -1) { - index = matcher.start(3); - } - - builder.replace(index, index + 1, "\r\n"); - position = index + 1; - } - - return builder.toString(); - } - - /** - * This method will convert a string contents to use the UNIX-style line endings. That is, all occurrences of CR - * (Carriage Return) and LF (Line Feed) are reduced to just use LF. - * - * @param content - * The buffer to be processed - * @return The converted contents - */ - public static String toUnixLines(String content) { - if (content == null) { - return null; - } - - StringBuilder builder = new StringBuilder(content); - Pattern pattern = Pattern.compile("\r\n|\n\r"); - Matcher matcher = pattern.matcher(builder); - int position = 0; - while (matcher.find(position)) { - builder.replace(matcher.start(), matcher.end(), "\n"); - position = matcher.start(); - } - - return builder.toString(); - } - - /** - * This method is used to translate characters in the input sequence that match the characters in the match list to - * the corresponding character in the replacement list. If the replacement list is shorter than the match list, then - * the character from the replacement list is taken as the modulo of the match character position and the length of - * the replacement list. - * - * @param sequence - * The input sequence to be processed - * @param match - * The list of matching characters to be searched - * @param replacement - * The list of replacement characters, positional coincident with the match list. If shorter than the - * match list, then the position "wraps" around on the replacement list. - * @return The translated string contents. - */ - public static Object translate(String sequence, String match, String replacement) { - - if (sequence == null) { - return null; - } - - StringBuilder builder = new StringBuilder(sequence); - - for (int index = 0; index < builder.length(); index++) { - char ch = builder.charAt(index); - - int position = match.indexOf(ch); - if (position == -1) { - continue; - } - - if (position >= replacement.length()) { - position %= replacement.length(); - } - builder.setCharAt(index, replacement.charAt(position)); - } - - return builder.toString(); - } - - /** - * Ensures that the name provided is a valid identifier. This means that no spaces are allowed as well as special - * characters. This method translates all spaces and illegal characters to underscores (_). - * - * @param name - * The name to be checked and converted to an identifier if needed - * @return The valid identifier from the name - */ - public static String validIdentifier(String name) { - if (name == null || name.length() == 0) { - return name; - } - StringBuilder builder = new StringBuilder(name); - for (int index = 0; index < builder.length(); index++) { - char ch = builder.charAt(index); - - if ((index == 0 && !Character.isJavaIdentifierStart(ch)) || (!Character.isJavaIdentifierPart(ch))) { - builder.setCharAt(index, '_'); - } - } - return builder.toString(); - } - - - /** - * Private constructor to prevent instantiation of this class - All methods are static! - */ - private StringHelper() { - - } - - /** - * This method verifies that the provided string only contains characters from the legal set, and replaces any - * character not in the legal set with the specified replacement character. - * - * @param sequence - * The sequence to be verified - * @param legal - * The set of all legal characters - * @param replacement - * The replacement character if a character is not in the legal set - * @return The verified *and possibly updated) string - */ - public static String verify(String sequence, String legal, char replacement) { - if (sequence == null) { - return null; - } - - StringBuilder builder = new StringBuilder(sequence); - for (int index = 0; index < builder.length(); index++) { - char ch = builder.charAt(index); - if (legal.indexOf(ch) == -1) { - builder.setCharAt(index, replacement); - } - } - return builder.toString(); - } - - /** - * @param list - * The list of elements - * @return The list of elements formatted as a comma-delimited list - */ - public static String asList(List<String> list) { - StringBuilder builder = new StringBuilder(); - - if (list != null) { - if (list.size() == 1) { - builder.append(list.get(0)); - } else { - for (String element : list) { - builder.append(element); - builder.append(", "); - } - - if (builder.length() > 2) { - builder.delete(builder.length() - 2, builder.length()); - } - } - } - return builder.toString(); - } - - /** - * @param map - * A map of strings - * @return A map expressed as a comma-delimited list of name=value tuples - */ - public static String asList(Map<String, String> map) { - StringBuilder builder = new StringBuilder(); - if (map != null) { - Set<String> keys = map.keySet(); - for (String key : keys) { - builder.append(String.format("%s=%s, ", key, map.get(key))); - } - - if (builder.length() > 2) { - builder.delete(builder.length() - 2, builder.length()); - } - } - return builder.toString(); - } - - /** - * @param values - * An array or varargs of Strings to be concatenated into a comma-separated list - * @return The comma-seprated list of values - */ - public static String asList(String... values) { - StringBuilder builder = new StringBuilder(); - builder.append('['); - if (values != null && values.length > 0) { - int count = values.length; - for (int index = 0; index < count - 1; index++) { - builder.append(values[index]); - builder.append(','); - } - builder.append(values[count - 1]); - } - builder.append(']'); - return builder.toString(); - } - - public static Object resolveToType(String input) { - String intRegex = "^(\\-)?[0-9]+$"; - String doubleRegex = "^(\\-)?[0-9\\.]+$"; - String boolRegex = "(^(?i)((true)|(false))$)"; - - // Check for null - if (input == null) { - return null; - } - - // Check int first - if (input.matches(intRegex)) { - try { - return Integer.parseInt(input); - } catch (NumberFormatException nfe) { - // Should not happen - logger.error(nfe.getMessage()); - } - } - - // Check double (int + decimal point) - if (input.matches(doubleRegex)) { - try { - return Double.parseDouble(input); - } catch (NumberFormatException | NullPointerException e) { - // NPE won't happen bc of regex check - logger.error("Parsing input failed", e); - } - } - - // Check boolean - if (input.matches(boolRegex)) { - return Boolean.parseBoolean(input); - } - - // Try to parse a date - Date date = Time.utcParse(input); - if (date != null) { - return date; - } - - // No special type, return string - return input; - } - - /** - * Converts a properties object to a string in the format of <pre>[ key=value, key=value, ... ]</pre> - * - * @param props - * The properties object to format - * @return A string in the format <pre>[ key=value, ... ]</pre> or null if the input was null - */ - public static String propertiesToString(Properties props) { - if (props == null) { - return null; - } - StringBuilder out = new StringBuilder(); - out.append("["); - for (Object key : props.keySet()) { - out.append(String.format(" %s = %s,", key.toString(), props.getProperty(key.toString()))); - } - if (props.size() > 0) { - out.deleteCharAt(out.lastIndexOf(",")); - } - out.append(" ]"); - return out.toString(); - } -} diff --git a/appc-core/appc-common-bundle/java/org/onap/appc/util/StructuredPropertyHelper.java b/appc-core/appc-common-bundle/java/org/onap/appc/util/StructuredPropertyHelper.java deleted file mode 100644 index 5c18f3a1c..000000000 --- a/appc-core/appc-common-bundle/java/org/onap/appc/util/StructuredPropertyHelper.java +++ /dev/null @@ -1,259 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017-2018 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. - * - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.util; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * This class is used to assemble properties that are defined using a structured name into groups, and allow them to be - * processed as sets of definitions. - * <p> - * For example, a structured name uses a dotted-notation, like "provider.name". Further, the nodes of the structured - * name may be serialized using a suffix ordinal number (e.g., "provider1.name"). These structured properties form a - * hierarchical name space where the names are grouped together and can be retrieved as a set. - * </p> - * - */ - -public class StructuredPropertyHelper { - - /** - * This method scans the properties object for all properties that match the root name and constructs a list of - * structured property node graphs that represents the namespaces of the properties. - * <p> - * For example, assume that there are structured properties of the form "provider1.name", "provider2.name", - * "provider3.name", and so forth. There may also be other subordinate properties as well (e.g., "provider1.type"). - * This method would construct a list of graphs of nodes, where each node represents one value of the structured - * name. The roots would be the values "provider1", "provider2", "provider3", and so forth. The values of the - * subordinate nodes would be the second, third, and so forth name nodes of the compound name. The value of the - * property is associated with nodes that are representative of the leaf of the name space. - * </p> - * - * @param properties - * The properties to be processed - * @param prefix - * The prefix of the root structured property name - * @return The node graph of the properties - */ - public static List<Node> getStructuredProperties(Properties properties, String prefix) { - List<Node> roots = new ArrayList<>(); - - for (String name : properties.stringPropertyNames()) { - if (name.startsWith(prefix)) { - String value = properties.getProperty(name); - processNamespace(roots, name, value); - } - } - - return roots; - } - - /** - * This method recursively walks the name space of the structured property and constructs the node graph to - * represent the property - * - * @param nodes - * The collection of nodes for the current level of the name space - * @param propertyName - * The name of the node - * @param value - * The value, if any - * @return The node for this level in the namespace - */ - @SuppressWarnings("nls") - private static Node processNamespace(List<Node> nodes, String propertyName, String value) { - String[] tokens = propertyName.split("\\.", 2); - String nodeName = normalizeNodeName(tokens[0]); - - Node namespaceNode = null; - for (Node node : nodes) { - if (node.getName().equals(nodeName)) { - namespaceNode = node; - break; - } - } - if (namespaceNode == null) { - namespaceNode = new Node(); - namespaceNode.setName(nodeName); - nodes.add(namespaceNode); - } - - if (tokens.length == 1 || tokens[1] == null || tokens[1].length() == 0) { - namespaceNode.setValue(value); - } else { - processNamespace(namespaceNode.getChildren(), tokens[1], value); - } - - return namespaceNode; - } - - /** - * This method normalizes a node name of the structured property name by removing leading and trailing whitespace, - * and by converting any ordinal position to a simple expression without leading zeroes. - * - * @param token - * The token to be normalized - * @return The normalized name, or null if the token was null; - */ - @SuppressWarnings("nls") - private static String normalizeNodeName(String token) { - if (token == null) { - return null; - } - - StringBuffer buffer = new StringBuffer(token.trim()); - Pattern pattern = Pattern.compile("([^0-9]+)([0-9]*)"); - Matcher matcher = pattern.matcher(buffer); - if (matcher.matches()) { - String nameRoot = matcher.group(1); - String ordinal = matcher.group(2); - if (ordinal != null && ordinal.length() > 0) { - int i = Integer.parseInt(ordinal); - buffer.setLength(0); - buffer.append(nameRoot); - buffer.append(Integer.toString(i)); - } - } - return buffer.toString(); - } - - /** - * This class represents a node in the structured property name space - * - */ - public static class Node implements Comparable<Node> { - - /** - * The name of the structured property node - */ - private String name; - - /** - * If the node is a leaf, then the value of the property - */ - private String value; - - /** - * If the node is not a leaf, then the sub-nodes of the property - */ - private List<Node> children; - - /** - * @return the value of name - */ - public String getName() { - return name; - } - - /** - * @param name - * the value for name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the value of value - */ - public String getValue() { - return value; - } - - /** - * @param value - * the value for value - */ - public void setValue(String value) { - this.value = value; - } - - /** - * @return the value of children - */ - public List<Node> getChildren() { - if (children == null) { - children = new ArrayList<>(); - } - return children; - } - - /** - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return name.hashCode() + (value != null ? value.hashCode() : children.hashCode()); - } - - /** - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - if (this.getClass() != obj.getClass()) - return false; - - Node other = (Node) obj; - boolean result = name.equals(other.name); - - if (value == null) { - result &= other.value == null; - } else { - result &= value.equals(other.value); - } - if (children == null) { - result &= other.children == null; - } else { - result &= children.equals(other.children); - } - return result; - } - - /** - * @see java.lang.Object#toString() - */ - @SuppressWarnings("nls") - @Override - public String toString() { - if (value != null) { - return String.format("%s = %s", name, value); - } - return String.format("%s.%s", name, children.toString()); - } - - @Override - public int compareTo(StructuredPropertyHelper.Node o) { - return name.compareTo(o.name); - } - } -} diff --git a/appc-core/appc-common-bundle/java/org/onap/appc/util/Time.java b/appc-core/appc-common-bundle/java/org/onap/appc/util/Time.java deleted file mode 100644 index dfd1ee769..000000000 --- a/appc-core/appc-common-bundle/java/org/onap/appc/util/Time.java +++ /dev/null @@ -1,601 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ================================================================================ - * Modifications Copyright (c) 2019 IBM - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.util; - -import java.sql.Timestamp; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -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; - -/** - * This class is a general purpose helper class to augment standard Java time support. - * - */ - -public final class Time { - - /** - * Logger to log operations - */ - private static final Logger LOG = LoggerFactory.getLogger(Time.class); - - /** - * A formatter to be used to format values - */ - private static SimpleDateFormat dateformatter = null; - - /** - * The UTC timezone (for UTC or GMT time) - */ - @SuppressWarnings("nls") - private static final TimeZone utcTZ = TimeZone.getTimeZone("UTC"); - - /** - * The cached reference to the datatype factory - */ - private static DatatypeFactory xmlDatatypeFactory = null; - - /** - * Private default constructor prevents instantiation - */ - private Time() { - // - } - - /** - * 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 - * @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) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - cal.add(Calendar.MONTH, months); - cal.add(Calendar.DATE, days); - cal.add(Calendar.HOUR_OF_DAY, hours); - cal.add(Calendar.MINUTE, minutes); - cal.add(Calendar.SECOND, seconds); - return cal.getTime(); - } - - /** - * Clears the time components of a calendar to zero, leaving the date components unchanged. - * - * @param cal the calendar to be updated - * @return The updated calendar object - */ - public static Calendar dateOnly(final Calendar cal) { - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.set(Calendar.MINUTE, 0); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - return cal; - } - - /** - * This method returns the local time that corresponds to the end of the current day - * - * @return The time that corresponds to the end of the current day, expressed as local time - */ - public static Date endOfDayLocal() { - return endOfDayLocal(new Date()); - } - - /** - * 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. - * @return The millisecond prior to midnight, local time. - */ - public static Date endOfDayLocal(final Date localTime) { - // @sonar:off - GregorianCalendar calendar = new GregorianCalendar(); - calendar.setTime(localTime); - calendar.set(Calendar.HOUR, 11); - calendar.set(Calendar.AM_PM, Calendar.PM); - calendar.set(Calendar.MINUTE, 59); - calendar.set(Calendar.SECOND, 59); - calendar.set(Calendar.MILLISECOND, 999); - // @sonar:on - - return calendar.getTime(); - } - - /** - * The end of the current day and in the current time zone expressed as a UTC time. - * - * @return The UTC time that corresponds to the end of the current day - */ - public static Date endOfDayUTC() { - return endOfDayUTC(new Date()); - } - - /** - * 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. - */ - 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. - * - * @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); - return utcDate(endOfDay, localTimeZone); - } - - /** - * returns current Date in 'UTC' Timezone - * - * @return The current date, expressed in the UTC timezone. - */ - @SuppressWarnings("nls") - public static Date getCurrentUTCDate() { - - // 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(); - calendar.setTimeZone(TimeZone.getTimeZone("UTC")); - calendar.setTimeInMillis(utcTime()); - return calendar.getTime(); - } - - /** - * This method loads and caches the reference to the XML data type factory object. - * - * @return The XML Data Type Factory object - */ - public static DatatypeFactory getDatatypeFactory() { - if (xmlDatatypeFactory == null) { - try { - xmlDatatypeFactory = DatatypeFactory.newInstance(); - } catch (DatatypeConfigurationException e) { - LOG.error("Error while getting DatatypeFactory ::", e); - } - } - return xmlDatatypeFactory; - } - - /** - * 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 - * @return The formatted value - */ - 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); - df.setTimeZone(timezone); - synchronized (df) { - strDate = df.format(date); - } - return strDate; - } - - /** - * Returns singleton UTC date formatter. - * - * @return - */ - @SuppressWarnings("nls") - private static SimpleDateFormat getDateFormatter() { - if (dateformatter == null) { - dateformatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); - dateformatter.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC")); - } - return dateformatter; - } - - /** - * 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. - * @return The local time that is equivalent to the given UTC time for the current time zone - */ - public static long localTime(final long utcTime) { - return localTime(utcTime, TimeZone.getDefault()); - } - - /** - * 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. - * </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 - * @return The local time for the specified time zone and the given UTC time - */ - public static long localTime(final long utcTime, final TimeZone localTZ) { - int offset = localTZ.getOffset(utcTime + localTZ.getRawOffset()); - long result = utcTime + offset; - - return result; - } - - /** - * 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 - * @return The updated calendar object - */ - 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); - return cal; - } - - /** - * Returns the start of the day expressed in local time for the current local time. - * - * @return The start of the day - */ - public static Date startOfDayLocal() { - return startOfDayLocal(new Date()); - } - - /** - * 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. - * @return The date that corresponds to the start of the local day - */ - public static Date startOfDayLocal(final Date localTime) { - GregorianCalendar calendar = new GregorianCalendar(); - calendar.setTime(localTime); - calendar.set(Calendar.HOUR, 0); - calendar.set(Calendar.AM_PM, Calendar.AM); - calendar.set(Calendar.MINUTE, 0); - calendar.set(Calendar.SECOND, 0); - calendar.set(Calendar.MILLISECOND, 0); - - return calendar.getTime(); - } - - /** - * 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. - */ - public static Date startOfDayUTC() { - return startOfDayUTC(new Date()); - } - - /** - * 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 - * @return The start of the local day expressed as a UTC time. - */ - public static Date startOfDayUTC(final Date localTime) { - return startOfDayUTC(localTime, TimeZone.getDefault()); - } - - /** - * 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 - * @return The corresponding UTC date - */ - public static Date startOfDayUTC(final Date localTime, final TimeZone localTimeZone) { - Date startOfDay = startOfDayLocal(localTime); - return utcDate(startOfDay, localTimeZone); - } - - /** - * 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 - */ - - public static XMLGregorianCalendar timestamp() { - getDatatypeFactory(); - XMLGregorianCalendar ts = xmlDatatypeFactory.newXMLGregorianCalendar(); - GregorianCalendar utc = new GregorianCalendar(); - utc.setTime(utcDate()); - ts.setTimezone(0); - ts.setYear(utc.get(Calendar.YEAR)); - // Calendar Months are from 0-11 need to +1 - ts.setMonth(utc.get(Calendar.MONTH) + 1); - ts.setDay(utc.get(Calendar.DAY_OF_MONTH)); - ts.setHour(utc.get(Calendar.HOUR_OF_DAY)); - ts.setMinute(utc.get(Calendar.MINUTE)); - ts.setSecond(utc.get(Calendar.SECOND)); - ts.setMillisecond(utc.get(Calendar.MILLISECOND)); - return ts; - } - - /** - * Converts XMLGregorianCalendar to java.util.Date in Java - * - * @param calendar the calendar object to be converted - * @return The equivalent Date object - */ - public static Date toDate(final XMLGregorianCalendar calendar) { - if (calendar == null) { - return null; - } - return calendar.toGregorianCalendar().getTime(); - } - - /** - * Converts java Date to XMLGregorianCalendar. - * - * @param date The date to convert - * @return The XMLGregorianCalendar for the specified date - */ - @SuppressWarnings("nls") - public static XMLGregorianCalendar toXMLCalendar(final Date date) { - GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); - cal.setTime(date); - - XMLGregorianCalendar xmlCal = null; - try { - xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal); - } catch (DatatypeConfigurationException e) { - LOG.error("toXMLCalendar", e); - } - return xmlCal; - } - - /** - * 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 - * @return The date with only the year, month, day, hours, and minutes significant. - */ - public static Date truncDate(final Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - return cal.getTime(); - } - - /** - * The UTC date that corresponds to the current date in the local time zone. - * - * @return The UTC date for now in the current time zone. - */ - public static Date utcDate() { - return new Date(); - } - - /** - * 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. - * @return The UTC date that corresponds to the date in the current time zone. - */ - public static Date utcDate(final Date date) { - TimeZone tz = TimeZone.getDefault(); - return utcDate(date, tz); - } - - /** - * 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 - * @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) { - return new Date(utcTime(date.getTime(), tz)); - } - - /** - * Format incoming date as string in GMT or UTC. - * - * @param dt The date to be formatted - * @return The date formatted for UTC timezone - */ - public static String utcFormat(final Date dt) { - String strDate = null; - DateFormat df = getDateFormatter(); - synchronized (df) { - strDate = df.format(dt); - } - return strDate; - } - - /** - * 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 - */ - @SuppressWarnings("nls") - public static Date utcParse(final String dateStr) { - 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 - */ - @SuppressWarnings("nls") - public static Date utcParse(final String dateStr, String... adtlFormatStrings) { - if (dateStr != null) { - // Build the list of formatters starting with the default defined in the class - List<DateFormat> formats = new ArrayList<>(); - formats.add(getDateFormatter()); - - if (adtlFormatStrings != null) { - for (String s : adtlFormatStrings) { - formats.add(new SimpleDateFormat(s)); - } - } - - // Return the first matching date formatter's result - for (DateFormat df : formats) { - df.setTimeZone(utcTZ); - try { - return df.parse(dateStr); - } catch (ParseException e) { - LOG.debug(String.format("IGNORE - Date string [%s] does not fit pattern [%s]", - dateStr, df.toString())); - } - } - } - return null; - } - - /** - * This method returns the current time for the UTC timezone - * - * @return The time in the UTC time zone that corresponds to the current local time. - */ - public static long utcTime() { - return new Date().getTime(); - } - - /** - * 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. - * @return The UTC time - */ - public static long utcTime(final long localTime) { - TimeZone tz = TimeZone.getDefault(); - return utcTime(localTime, tz); - } - - /** - * 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. - * </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. - * @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) { - int offset = localTZ.getOffset(localTime); - return localTime - offset; - - } - - /** - * Creates a timestamp value from a time - * - * @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-core/appc-common-bundle/java/org/onap/appc/util/UnmodifiableProperties.java b/appc-core/appc-common-bundle/java/org/onap/appc/util/UnmodifiableProperties.java deleted file mode 100644 index 6d20b64a4..000000000 --- a/appc-core/appc-common-bundle/java/org/onap/appc/util/UnmodifiableProperties.java +++ /dev/null @@ -1,355 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017-2018 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. - * - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.util; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.Reader; -import java.io.Writer; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.InvalidPropertiesFormatException; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -/** - * This utility class is used to wrap a properties object and to delegate all read operations to the property object, - * while disallowing any write or modification to the property object. - * - */ -public class UnmodifiableProperties extends Properties implements Cloneable { - - /** - * Serial number - */ - private static final long serialVersionUID = 1L; - - private static final String PROPERTY_CANNOT_BE_MODIFIED_MSG = "Property cannot be modified!"; - - /** - * The properties object which we are wrapping - */ - private Properties properties; - - /** - * Create the unmodifiable wrapper around the provided properties object - * - * @param properties - * The properties to be wrapped and protected from modification - */ - public UnmodifiableProperties(Properties properties) { - this.properties = properties; - } - - /** - * @see java.util.Hashtable#clear() - */ - @Override - public synchronized void clear() { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Hashtable#clone() - */ - // @sonar:off - @Override - public synchronized Object clone() { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - // @sonar:on - - /** - * @see java.util.Hashtable#contains(java.lang.Object) - */ - @Override - public synchronized boolean contains(Object value) { - return properties.contains(value); - } - - /** - * @see java.util.Hashtable#containsKey(java.lang.Object) - */ - @Override - public synchronized boolean containsKey(Object key) { - return properties.containsKey(key); - } - - /** - * @see java.util.Hashtable#containsValue(java.lang.Object) - */ - @Override - public boolean containsValue(Object value) { - return properties.containsValue(value); - } - - /** - * @see java.util.Hashtable#elements() - */ - @Override - public synchronized Enumeration<Object> elements() { - return properties.elements(); - } - - /** - * @see java.util.Hashtable#entrySet() - */ - @Override - public Set<java.util.Map.Entry<Object, Object>> entrySet() { - return Collections.unmodifiableSet(properties.entrySet()); - } - - /** - * @see java.util.Hashtable#equals(java.lang.Object) - */ - @Override - public synchronized boolean equals(Object o) { - return properties.equals(o); - } - - /** - * @see java.util.Hashtable#get(java.lang.Object) - */ - @Override - public synchronized Object get(Object key) { - return properties.get(key); - } - - /** - * @see java.util.Properties#getProperty(java.lang.String) - */ - @Override - public String getProperty(String key) { - return properties.getProperty(key); - } - - /** - * @see java.util.Properties#getProperty(java.lang.String, java.lang.String) - */ - @Override - public String getProperty(String key, String defaultValue) { - return properties.getProperty(key, defaultValue); - } - - /** - * @see java.util.Hashtable#hashCode() - */ - @Override - public synchronized int hashCode() { - return properties.hashCode(); - } - - /** - * @see java.util.Hashtable#isEmpty() - */ - @Override - public synchronized boolean isEmpty() { - return properties.isEmpty(); - } - - /** - * @see java.util.Hashtable#keys() - */ - @Override - public synchronized Enumeration<Object> keys() { - return properties.keys(); - } - - /** - * @see java.util.Hashtable#keySet() - */ - @Override - public Set<Object> keySet() { - return Collections.unmodifiableSet(properties.keySet()); - } - - /** - * @see java.util.Properties#list(java.io.PrintStream) - */ - @Override - public void list(PrintStream out) { - properties.list(out); - } - - /** - * @see java.util.Properties#list(java.io.PrintWriter) - */ - @Override - public void list(PrintWriter out) { - properties.list(out); - } - - /** - * @see java.util.Properties#load(java.io.InputStream) - */ - @Override - public synchronized void load(InputStream inStream) throws IOException { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Properties#load(java.io.Reader) - */ - @Override - public synchronized void load(Reader reader) throws IOException { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Properties#loadFromXML(java.io.InputStream) - */ - @Override - public synchronized void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Properties#propertyNames() - */ - @Override - public Enumeration<?> propertyNames() { - return properties.propertyNames(); - } - - /** - * @see java.util.Hashtable#put(java.lang.Object, java.lang.Object) - */ - @Override - public synchronized Object put(Object key, Object value) { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Hashtable#putAll(java.util.Map) - */ - @Override - public synchronized void putAll(Map<? extends Object, ? extends Object> t) { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Hashtable#rehash() - */ - @Override - protected void rehash() { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Hashtable#remove(java.lang.Object) - */ - @Override - public synchronized Object remove(Object key) { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Properties#save(java.io.OutputStream, java.lang.String) - */ - @Override - @Deprecated - public synchronized void save(OutputStream out, String comments) { - properties.save(out, comments); - } - - /** - * @see java.util.Properties#setProperty(java.lang.String, java.lang.String) - */ - @Override - public synchronized Object setProperty(String key, String value) { - throw new UnsupportedOperationException(PROPERTY_CANNOT_BE_MODIFIED_MSG); - } - - /** - * @see java.util.Hashtable#size() - */ - @Override - public synchronized int size() { - return properties.size(); - } - - /** - * @see java.util.Properties#store(java.io.OutputStream, java.lang.String) - */ - @Override - public void store(OutputStream out, String comments) throws IOException { - properties.store(out, comments); - } - - /** - * @see java.util.Properties#store(java.io.Writer, java.lang.String) - */ - @Override - public void store(Writer writer, String comments) throws IOException { - properties.store(writer, comments); - } - - /** - * @see java.util.Properties#storeToXML(java.io.OutputStream, java.lang.String) - */ - @Override - public synchronized void storeToXML(OutputStream os, String comment) throws IOException { - properties.storeToXML(os, comment); - } - - /** - * @see java.util.Properties#storeToXML(java.io.OutputStream, java.lang.String, java.lang.String) - */ - @Override - public synchronized void storeToXML(OutputStream os, String comment, String encoding) throws IOException { - properties.storeToXML(os, comment, encoding); - } - - /** - * @see java.util.Properties#stringPropertyNames() - */ - @Override - public Set<String> stringPropertyNames() { - return properties.stringPropertyNames(); - } - - /** - * @see java.util.Hashtable#toString() - */ - @Override - public synchronized String toString() { - return properties.toString(); - } - - /** - * @see java.util.Hashtable#values() - */ - @Override - public Collection<Object> values() { - return Collections.unmodifiableCollection(properties.values()); - } -} diff --git a/appc-core/appc-common-bundle/java/org/onap/appc/util/httpClient.java b/appc-core/appc-common-bundle/java/org/onap/appc/util/httpClient.java deleted file mode 100644 index a2ce8af2a..000000000 --- a/appc-core/appc-common-bundle/java/org/onap/appc/util/httpClient.java +++ /dev/null @@ -1,205 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017-2018 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. - * - * ============LICENSE_END========================================================= - */ - -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.methods.HttpDelete; -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.entity.StringEntity; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class httpClient { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(httpClient.class); - - 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 { - - logger.info("Sending POST request to " + path); - - HttpPost post; - try { - - URL serviceUrl = new URL(protocol, ip, port, path); - post = new HttpPost(serviceUrl.toExternalForm()); - post.setHeader("Content-Type", contentType); - - StringEntity entity = new StringEntity(payload); - entity.setContentType(contentType); - post.setEntity(new StringEntity(payload)); - } catch (UnsupportedEncodingException | MalformedURLException e) { - throw new APPCException(e); - } - - 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(); - - int httpCode; - try { - HttpResponse response = client.execute(post); - httpCode = response.getStatusLine().getStatusCode(); - } catch (IOException e) { - throw new APPCException(e); - } - return httpCode; - } - - @SuppressWarnings("deprecation") - 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); - - HttpPut put; - try { - - URL serviceUrl = new URL(protocol, ip, port, path); - put = new HttpPut(serviceUrl.toExternalForm()); - put.setHeader("Content-Type", contentType); - - StringEntity entity = new StringEntity(payload); - entity.setContentType(contentType); - put.setEntity(new StringEntity(payload)); - } catch (UnsupportedEncodingException | MalformedURLException e) { - throw new APPCException(e); - } - - 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(); - - int httpCode; - try { - HttpResponse response = client.execute(put); - httpCode = response.getStatusLine().getStatusCode(); - } catch (IOException e) { - throw new APPCException(e); - } - return httpCode; - } - - @SuppressWarnings("deprecation") - public static String getMethod(String protocol, String ip, int port, String path, - String contentType) throws APPCException { - - logger.info("Sending GET request to " + path); - - HttpGet get; - try { - - URL serviceUrl = new URL(protocol, ip, port, path); - get = new HttpGet(serviceUrl.toExternalForm()); - get.setHeader("Content-Type", contentType); - } catch (MalformedURLException e) { - throw new APPCException(e); - } - - 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(); - - int httpCode; - String result; - - try { - HttpResponse response = client.execute(get); - httpCode = response.getStatusLine().getStatusCode(); - result = (httpCode == HttpStatus.SC_OK) ? response.getEntity().toString() : null; - } catch (IOException e) { - throw new APPCException(e); - } - - return result; - } - - @SuppressWarnings("deprecation") - public static int deleteMethod(String protocol, String ip, int port, String path, - String contentType) throws APPCException { - - logger.info("Sending DELETE request to " + path); - - HttpDelete delete; - try { - - URL serviceUrl = new URL(protocol, ip, port, path); - delete = new HttpDelete(serviceUrl.toExternalForm()); - delete.setHeader("Content-Type", contentType); - } catch (MalformedURLException e) { - throw new APPCException(e); - } - - 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(); - - int httpCode; - - try { - HttpResponse response = client.execute(delete); - httpCode = response.getStatusLine().getStatusCode(); - } catch (IOException e) { - throw new APPCException(e); - } - - return httpCode; - } -} |