From 32fb53c13342d5ad353c839b7ffd0ca85d14bd48 Mon Sep 17 00:00:00 2001 From: Jessica Wagantall Date: Tue, 1 Dec 2020 11:48:20 -0800 Subject: Migrate sli-core files Migrate sli-core repo files into new directory "core". Signed-off-by: Jessica Wagantall --- core/sliPluginUtils/.gitignore | 34 + core/sliPluginUtils/.sonar/checkstyle.xml | 1 + core/sliPluginUtils/.sonar/pmd.xml | 67 ++ core/sliPluginUtils/installer/pom.xml | 147 +++ .../src/assembly/assemble_installer_zip.xml | 59 + .../src/assembly/assemble_mvnrepo_zip.xml | 49 + .../src/main/resources/scripts/install-feature.sh | 39 + core/sliPluginUtils/pom.xml | 24 + core/sliPluginUtils/provider/pom.xml | 72 ++ .../sli/core/slipluginutils/SliPluginUtils.java | 1178 ++++++++++++++++++++ .../sli/core/slipluginutils/SliStringUtils.java | 559 ++++++++++ .../core/slipluginutils/SvcLogicContextList.java | 210 ++++ .../core/slipluginutils/SvcLogicContextObject.java | 28 + .../slipluginutils/commondatastructures/YesNo.java | 51 + .../commondatastructures/package-info.java | 28 + .../blueprint/slipluginutils-blueprint.xml | 13 + .../blueprint/slipluginutils-blueprint.xml | 13 + .../SliPluginUtils_StaticFunctionsTest.java | 591 ++++++++++ .../SliPluginUtils_checkParametersTest.java | 117 ++ .../slipluginutils/SliPluginUtils_ctxSortList.java | 149 +++ .../SliPluginUtils_ctxSortListTest.java | 97 ++ .../core/slipluginutils/SliStringUtilsTest.java | 398 +++++++ .../slipluginutils/SvcLogicContextListTest.java | 307 +++++ .../provider/src/test/resources/2dArray.json | 4 + .../provider/src/test/resources/3dArray.json | 4 + .../provider/src/test/resources/ArrayMenu.json | 41 + .../src/test/resources/EmbeddedEscapedJson.json | 16 + .../provider/src/test/resources/EscapedJson.json | 1 + .../provider/src/test/resources/JsonObject.json | 5 + .../provider/src/test/resources/ObjectMenu.json | 43 + .../provider/src/test/resources/Widget.json | 27 + 31 files changed, 4372 insertions(+) create mode 100755 core/sliPluginUtils/.gitignore create mode 100755 core/sliPluginUtils/.sonar/checkstyle.xml create mode 100755 core/sliPluginUtils/.sonar/pmd.xml create mode 100755 core/sliPluginUtils/installer/pom.xml create mode 100644 core/sliPluginUtils/installer/src/assembly/assemble_installer_zip.xml create mode 100644 core/sliPluginUtils/installer/src/assembly/assemble_mvnrepo_zip.xml create mode 100644 core/sliPluginUtils/installer/src/main/resources/scripts/install-feature.sh create mode 100755 core/sliPluginUtils/pom.xml create mode 100755 core/sliPluginUtils/provider/pom.xml create mode 100644 core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils.java create mode 100644 core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SliStringUtils.java create mode 100644 core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextList.java create mode 100644 core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextObject.java create mode 100644 core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/commondatastructures/YesNo.java create mode 100644 core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/commondatastructures/package-info.java create mode 100644 core/sliPluginUtils/provider/src/main/resources/OSGI-INF/blueprint/slipluginutils-blueprint.xml create mode 100644 core/sliPluginUtils/provider/src/main/resources/org/opendaylight/blueprint/slipluginutils-blueprint.xml create mode 100644 core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_StaticFunctionsTest.java create mode 100644 core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_checkParametersTest.java create mode 100644 core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortList.java create mode 100644 core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortListTest.java create mode 100644 core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliStringUtilsTest.java create mode 100644 core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextListTest.java create mode 100644 core/sliPluginUtils/provider/src/test/resources/2dArray.json create mode 100644 core/sliPluginUtils/provider/src/test/resources/3dArray.json create mode 100644 core/sliPluginUtils/provider/src/test/resources/ArrayMenu.json create mode 100644 core/sliPluginUtils/provider/src/test/resources/EmbeddedEscapedJson.json create mode 100644 core/sliPluginUtils/provider/src/test/resources/EscapedJson.json create mode 100644 core/sliPluginUtils/provider/src/test/resources/JsonObject.json create mode 100644 core/sliPluginUtils/provider/src/test/resources/ObjectMenu.json create mode 100644 core/sliPluginUtils/provider/src/test/resources/Widget.json (limited to 'core/sliPluginUtils') diff --git a/core/sliPluginUtils/.gitignore b/core/sliPluginUtils/.gitignore new file mode 100755 index 000000000..b73caf31e --- /dev/null +++ b/core/sliPluginUtils/.gitignore @@ -0,0 +1,34 @@ +#####standard .git ignore entries##### + +## IDE Specific Files ## +org.eclipse.core.resources.prefs +.classpath +.project +.settings +.idea +.externalToolBuilders +maven-eclipse.xml +workspace + +## Compilation Files ## +*.class +**/target +target +target-ide +MANIFEST.MF + +## Misc Ignores (OS specific etc) ## +bin/ +dist +*~ +*.ipr +*.iml +*.iws +classes +out/ +.DS_STORE +.metadata + +## Folders which contain auto generated source code ## +yang-gen-config +yang-gen-sal diff --git a/core/sliPluginUtils/.sonar/checkstyle.xml b/core/sliPluginUtils/.sonar/checkstyle.xml new file mode 100755 index 000000000..3fa231535 --- /dev/null +++ b/core/sliPluginUtils/.sonar/checkstyle.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/core/sliPluginUtils/.sonar/pmd.xml b/core/sliPluginUtils/.sonar/pmd.xml new file mode 100755 index 000000000..80343b3bd --- /dev/null +++ b/core/sliPluginUtils/.sonar/pmd.xml @@ -0,0 +1,67 @@ + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + 2 + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + 5 + + + 2 + + + 3 + + + 3 + + + diff --git a/core/sliPluginUtils/installer/pom.xml b/core/sliPluginUtils/installer/pom.xml new file mode 100755 index 000000000..c133cd05b --- /dev/null +++ b/core/sliPluginUtils/installer/pom.xml @@ -0,0 +1,147 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + odlparent-lite + 2.1.0-SNAPSHOT + + + + org.onap.ccsdk.sli.core + sliPluginUtils-installer + 1.1.1-SNAPSHOT + pom + + ccsdk-sli-core :: sliPluginUtils :: ${project.artifactId} + + + ccsdk-sliPluginUtils + ${application.name} + mvn:org.onap.ccsdk.sli.core/${features.boot}/${project.version}/xml/features + false + + + + + + + org.onap.ccsdk.sli.core + sli-common + ${project.version} + + + org.onap.ccsdk.sli.core + sli-provider + ${project.version} + + + org.onap.ccsdk.sli.core + dblib-provider + ${project.version} + + + + + + + org.onap.ccsdk.sli.core + sliPluginUtils-provider + ${project.version} + + + + + + + + maven-assembly-plugin + + + maven-repo-zip + + single + + package + + true + stage/${application.name}-${project.version} + + src/assembly/assemble_mvnrepo_zip.xml + + true + + + + installer-zip + + single + + package + + true + ${application.name}-${project.version}-installer + + src/assembly/assemble_installer_zip.xml + + false + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + + copy-dependencies + + prepare-package + + false + ${project.build.directory}/assembly/system + false + true + true + true + false + false + sliPluginUtils-provider,ccsdk-sliPluginUtils,features-sliPluginUtils + provided + + + + + + maven-resources-plugin + 2.6 + + + copy-version + + copy-resources + + validate + + ${basedir}/target/stage + + + src/main/resources/scripts + + install-feature.sh + + true + + + + + + + + + + + diff --git a/core/sliPluginUtils/installer/src/assembly/assemble_installer_zip.xml b/core/sliPluginUtils/installer/src/assembly/assemble_installer_zip.xml new file mode 100644 index 000000000..2d3c0606d --- /dev/null +++ b/core/sliPluginUtils/installer/src/assembly/assemble_installer_zip.xml @@ -0,0 +1,59 @@ + + + + + + bin + + zip + + + + false + + + + target/stage/ + ${application.name} + 755 + + *.sh + + + + target/stage/ + ${application.name} + 644 + + *.sh + + + + + + + diff --git a/core/sliPluginUtils/installer/src/assembly/assemble_mvnrepo_zip.xml b/core/sliPluginUtils/installer/src/assembly/assemble_mvnrepo_zip.xml new file mode 100644 index 000000000..63ef515a0 --- /dev/null +++ b/core/sliPluginUtils/installer/src/assembly/assemble_mvnrepo_zip.xml @@ -0,0 +1,49 @@ + + + + + + repo + + zip + + + + false + + + + target/assembly/ + . + + + + + + + + diff --git a/core/sliPluginUtils/installer/src/main/resources/scripts/install-feature.sh b/core/sliPluginUtils/installer/src/main/resources/scripts/install-feature.sh new file mode 100644 index 000000000..638c73394 --- /dev/null +++ b/core/sliPluginUtils/installer/src/main/resources/scripts/install-feature.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +### +# ============LICENSE_START======================================================= +# ONAP : CCSDK +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights +# reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +ODL_HOME=${ODL_HOME:-/opt/opendaylight/current} +ODL_KARAF_CLIENT=${ODL_KARAF_CLIENT:-${ODL_HOME}/bin/client} +INSTALLERDIR=$(dirname $0) + +REPOZIP=${INSTALLERDIR}/${features.boot}-${project.version}.zip + +if [ -f ${REPOZIP} ] +then + unzip -nd ${ODL_HOME} ${REPOZIP} +else + echo "ERROR : repo zip ($REPOZIP) not found" + exit 1 +fi + +${ODL_KARAF_CLIENT} feature:repo-add ${features.repositories} +${ODL_KARAF_CLIENT} feature:install ${features.boot} diff --git a/core/sliPluginUtils/pom.xml b/core/sliPluginUtils/pom.xml new file mode 100755 index 000000000..974e0661c --- /dev/null +++ b/core/sliPluginUtils/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + odlparent-lite + 2.1.0-SNAPSHOT + + + + org.onap.ccsdk.sli.core + sliPluginUtils + 1.1.1-SNAPSHOT + pom + + ccsdk-sli-core :: sliPluginUtils + A package of static utility functions to be used when developing SLI plugins + + + provider + installer + + diff --git a/core/sliPluginUtils/provider/pom.xml b/core/sliPluginUtils/provider/pom.xml new file mode 100755 index 000000000..086faf39e --- /dev/null +++ b/core/sliPluginUtils/provider/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + binding-parent + 2.1.0-SNAPSHOT + + + + org.onap.ccsdk.sli.core + sliPluginUtils-provider + 1.1.1-SNAPSHOT + bundle + + ccsdk-sli-core :: sliPluginUtils :: ${project.artifactId} + http://maven.apache.org + + + UTF-8 + + + + + + org.onap.ccsdk.sli.core + dblib-provider + ${project.version} + + + + + + junit + junit + test + + + ${project.groupId} + sli-common + ${project.version} + compile + + + + org.slf4j + slf4j-api + + + org.slf4j + jcl-over-slf4j + + + org.apache.commons + commons-lang3 + + + org.hamcrest + hamcrest-library + test + + + com.google.code.gson + gson + + + org.apache.commons + commons-text + + + diff --git a/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils.java b/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils.java new file mode 100644 index 000000000..2edb36dc4 --- /dev/null +++ b/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils.java @@ -0,0 +1,1178 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Modifications Copyright (C) 2018 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.ccsdk.sli.core.slipluginutils; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintStream; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +/** + * A utility class used to streamline the interface between Java plugins, + * the Service Logic Context, and Directed Graphs. + * @version 7.0.1 + * @see org.onap.ccsdk.sli.core.sli.SvcLogicContext + */ +public class SliPluginUtils implements SvcLogicJavaPlugin { + public enum LogLevel { + TRACE, DEBUG, INFO, WARN, ERROR; + } + + private static final Logger LOG = LoggerFactory.getLogger(SliPluginUtils.class); + private static final String LOG_MSG="extracting list from context memory"; + private static final String LOG_MSG1="removing elements from list"; + private static final String LENGTH="_length"; + public static final String CTX_NULL_VALUE=""; + + + // ========== CONSTRUCTORS ========== + + public SliPluginUtils() {} + + public SliPluginUtils( Properties props ) {} + + + // ========== CONTEXT MEMORY FUNCTIONS ========== + + /** + * Removes 1 or more elements from a list in context memory. + *

+ * Values are removed based on either the index in the list, a key-value + * pair, or a list of key-value pairs that all must match in the element. + * @param parameters + * @param ctx Reference to context memory + * @throws SvcLogicException All exceptions are wrapped in + * SvcLogicException for compatibility with SLI. + * @since 7.0.1 + */ + public void ctxListRemove( Map parameters, SvcLogicContext ctx ) throws SvcLogicException { + try{ + LOG.debug( "ENTERING Execute Node \"ctxListRemove\"" ); + + // Validate, Log, & read parameters + checkParameters(parameters, new String[]{"list_pfx"}, LOG); + logExecuteNodeParameters(parameters, LOG, LogLevel.DEBUG); + String list_pfx = parameters.get("list_pfx"); + String param_index = parameters.get("index"); + String param_key = parameters.get("key"); + String param_value = parameters.get("value"); + String param_keys_length = parameters.get("keys_length"); + + // Initialize context memory list mimic + SvcLogicContextList list; + + // Process based on input parameters: + // index: remove object at specific index + // key & value: remove all objects with key-value pair + // keys_length: remove all objects that match all key-value pairs + // in list + if( param_index != null ) { + // Parse index + LOG.trace("executing remove by index logic"); + int index; + try { + index = Integer.parseInt(param_index); + } + catch( NumberFormatException e ) { + throw new IllegalArgumentException("\"index\" parameter is not a number. index = " + param_index, e); + } + + // Extract list from context memory & remove object @ index + LOG.trace(LOG_MSG); + list = SvcLogicContextList.extract(ctx, list_pfx); + LOG.trace(LOG_MSG1); + list.remove(index); + } + else if( param_value != null ) { + if( param_key == null ) { param_key = ""; } + + // Extract list from context memory & remove objects with + // key-value pair + LOG.trace("executing remove by key-value pair logic"); + LOG.trace(LOG_MSG); + list = SvcLogicContextList.extract(ctx, list_pfx); + LOG.trace(LOG_MSG1); + list.remove( param_key, param_value ); + } + else if( param_keys_length != null ) { + // Parse keys_length + LOG.trace("executing remove by key-value pair list logic"); + int keys_length; + try { + keys_length = Integer.parseInt(param_keys_length); + } + catch( NumberFormatException e ) { + throw new IllegalArgumentException("\"keys_length\" parameters is not a number. keys_length = " + param_keys_length, e); + } + + // Obtain key-value pairs to check from parameters + LOG.trace("reading keys parameter list"); + HashMap keys_values = new HashMap<>(); + for( int i = 0; i < keys_length; i++ ) { + keys_values.put(parameters.get("keys[" + i + "].key"), parameters.get("keys[" + i + "].value")); + } + + // Extract list from context memory & remove objects with all + // key-value pairs matching + LOG.trace(LOG_MSG); + list = SvcLogicContextList.extract(ctx, list_pfx); + LOG.trace(LOG_MSG1); + list.remove(keys_values); + } + else { + throw new IllegalArgumentException("Required parameters missing. Requires one of: index, key & value, or keys_length array"); + } + + // Remove index from list + LOG.trace("writing list back into context memory"); + list.writeToContext(ctx); + } + catch( Exception e ) { + throw new SvcLogicException( "An error occurred in the ctxListRemove Execute node", e ); + } + finally { + LOG.debug( "EXITING Execute Node \"ctxListRemove\"" ); + } + } + + /** + * ctxSortList + * @param parameters - the set of required parameters must contain list and delimiter. + * @param ctx Reference to context memory + * @throws SvcLogicException if a required parameter is missing an exception is thrown + */ + public void ctxSortList( Map parameters, SvcLogicContext ctx ) throws SvcLogicException { + checkParameters(parameters, new String[]{"list","delimiter"}, LOG); + ArrayList list = new ArrayList<>(); + + String[] sort_fields = null; + if( parameters.containsKey("sort-fields") ) { + sort_fields = parameters.get("sort-fields").split(parameters.get("delimiter"), 0); + } + + String ctx_list_str = parameters.get("list"); + int listSz = getArrayLength(ctx, ctx_list_str); + + + + for( int i = 0; i < listSz; i++ ) { + list.add( new SortableCtxListElement(ctx, ctx_list_str + '[' + i + ']', sort_fields) ); + } + Collections.sort(list); + + ctxBulkErase(ctx, ctx_list_str); + int i = 0; + for( SortableCtxListElement list_element : list ) { + for( Map.Entry entry : list_element.child_elements.entrySet() ) { + if( sort_fields == null ) { + ctx.setAttribute(ctx_list_str + '[' + i + ']', entry.getValue()); + } + else { + ctx.setAttribute(ctx_list_str + '[' + i + "]." + entry.getKey(), entry.getValue()); + } + } + i++; + } + // Reset list length (removed by ctxBulkErase above) + ctx.setAttribute(ctx_list_str+LENGTH, Integer.toString(listSz)); + } + + /** + * generates a UUID and writes it to context memory + * @param parameters - ctx-destination is a required parameter + * @param ctx Reference to context memory + * @throws SvcLogicException thrown if a UUID cannot be generated or if ctx-destination is missing or null + */ + public void generateUUID( Map parameters, SvcLogicContext ctx ) throws SvcLogicException { + checkParameters(parameters, new String[]{"ctx-destination"}, LOG); + ctx.setAttribute(parameters.get("ctx-destination"), UUID.randomUUID().toString() ); + } + + /** + * Provides substring functionality to Directed Graphs. + *

+ * Calls either String.substring(String beginIndex) or + * String.substring(String beginInded, String endIndex) if the end-index + * is present or not. + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
stringMandatoryString to perform substring on
resultMandatoryKey in context memory to populate the resulting string in
begin-indexMandatoryBeginning index to pass to Java substring function
end-indexOptionalEnding index to pass to Java substring function. If not included, String.substring(begin) will be called.
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 8.0.1 + * @see SliPluginUtils#substring(Map, SvcLogicContext) + */ + @Deprecated + public void substring( Map parameters, SvcLogicContext ctx ) throws SvcLogicException { + try { + checkParameters( parameters, new String[]{"string","begin-index","result"}, LOG ); + final String string = parameters.get("string"); + final String result = parameters.get("result"); + final String begin = parameters.get("begin-index"); + final String end = parameters.get("end-index"); + + if( StringUtils.isEmpty(end) ) { + ctx.setAttribute( result, string.substring(Integer.parseInt(begin)) ); + } + else { + ctx.setAttribute( result, string.substring(Integer.parseInt(begin), Integer.parseInt(end)) ); + } + } + catch( Exception e ) { + throw new SvcLogicException( "An error occurred while the Directed Graph was performing a substring", e ); + } + } + + + + // ========== PUBLIC STATIC UTILITY FUNCTIONS ========== + + /** + * Throws an exception and writes an error to the log file if a required + * parameters is not found in the parametersMap. + *

+ * Use at the beginning of functions that can be called by Directed Graphs + * and can take parameters to verify that all parameters have been provided + * by the Directed Graph. + * @param parametersMap parameters Map passed to this node + * @param requiredParams Array of parameters required by the calling function + * @param log Reference to Logger to log to + * @throws SvcLogicException if a String in the requiredParams array is + * not a key in parametersMap. + * @since 1.0 + */ + public static final void checkParameters(Map parametersMap, String[] requiredParams, Logger log) throws SvcLogicException { + if( requiredParams == null || requiredParams.length < 1){ + log.debug("required parameters was empty, exiting early."); + return; + } + if (parametersMap == null || parametersMap.keySet().isEmpty()){ + String errorMessage = "This method requires the parameters [" + StringUtils.join(requiredParams,",") + "], but no parameters were passed in."; + log.error(errorMessage); + throw new SvcLogicException(errorMessage); + } + + for (String param : requiredParams) { + if (!parametersMap.containsKey(param)) { + String errorMessage = "Required parameter \"" + param + "\" was not found in parameter list."; + log.error(errorMessage); + log.error("Total list of required parameters is [" + StringUtils.join(requiredParams, ",") + "]."); + throw new SvcLogicException(errorMessage); + } + } + } + + /** + * Removes all key-value pairs with keys that begin with pfx + * @param ctx Reference to context memory + * @param pfx Prefix of key-value pairs to remove + * @since 1.0 + */ + public static final void ctxBulkErase( SvcLogicContext ctx, String pfx ) { + ArrayList Keys = new ArrayList<>(ctx.getAttributeKeySet()); + for( String key : Keys ) { + if( key.startsWith( pfx ) ) { + ctx.setAttribute( pfx + key.substring(pfx.length()) , null); + } + } + } + + /** + * Copies all context memory key-value pairs that start with src_pfx to + * the keys that start with dest_pfx + suffix, where suffix is the result + * of {@code key.substring(src_pfx.length())}. + *

+ * Does NOT guarantee removal of all keys at the destination before + * copying, but will overwrite any destination keys that have a + * corresponding source key. Use {@link #ctxBulkErase(SvcLogicContext, String) ctxBulkErase} + * before copy to erase destination root before copying from source. + * @param ctx Reference to context memory. + * @param src_pfx Prefix of the keys to copy values from. + * @param dest_pfx Prefix of the keys to copy values to. + * @since 1.0 + */ + public static final void ctxBulkCopy( SvcLogicContext ctx, String src_pfx, String dest_pfx ) { + // Remove trailing period from dest_pfx + if( dest_pfx.charAt(dest_pfx.length()-1) == '.' ) { + dest_pfx = dest_pfx.substring(0,dest_pfx.length()-1); + } + + // For each context key that begins with src_pfx, set the value of the + // key dest_pfx + the suffix of the key to the key's value + ArrayList Keys = new ArrayList<>(ctx.getAttributeKeySet()); + for( String key : Keys ) { + if( key.startsWith(src_pfx) ) { + // Get suffix (no leading period) + String suffix = key.substring(src_pfx.length()); + if( suffix.charAt(0) == '.') { + suffix = suffix.substring(1); + } + + // Set destination's value to key's value + ctx.setAttribute(dest_pfx + '.' + suffix, ctx.getAttribute(key)); + } + } + } + + /** + * Creates and returns a {@code Map} that is a subset of + * context memory where all keys begin with the prefix. + * @param ctx Reference to context memory. + * @param prefix Returned map's keys should all begin with this value. + * @return A {@code Map} containing all the key-value pairs + * in ctx whose key begins with prefix. + */ + public static final Map ctxGetBeginsWith( SvcLogicContext ctx, String prefix ) { + Map prefixMap = new HashMap<>(); + + for( String key : ctx.getAttributeKeySet() ) { + if( key.startsWith(prefix) ) { + prefixMap.put( key, ctx.getAttribute(key) ); + } + } + + return prefixMap; + } + + /** + * Returns true if key's value in context memory is "" or if it doesn't + * exist in context memory. + * @param ctx Reference to context memory. + * @param key Key to search for. + * @return true if key's value in context memory is "" or if it doesn't + * exist in context memory. + * @since 1.0 + */ + public static final boolean ctxKeyEmpty( SvcLogicContext ctx, String key ) { + String value = ctx.getAttribute(key); + return value == null || value.isEmpty(); + } + + /** + * Adds all key-value pairs in the entries Map to context memory. + * @param ctx Reference to context memory. Value's {@code toString()} + * function is used to add it. + * @param entries {@code Map} of key-value pairs to add to + * context memory. Value's {@code toString()} function is used to add it. + * @return Reference to context memory to be used for function chaining. + */ + public static final SvcLogicContext ctxPutAll( SvcLogicContext ctx, Map entries ) { + for( Map.Entry entry : entries.entrySet() ) { + ctxSetAttribute( ctx, entry.getKey(), entry.getValue() ); + //ctx.setAttribute(entry.getKey(), entry.getValue().toString()); + } + + return ctx; + } + + /** + * Sets a key in context memory to the output of object's toString(). The + * key is deleted from context memory if object is null. + * @param ctx Reference to context memory. + * @param key Key to set. + * @param object Object whose toString() will be the value set + */ + public static final void ctxSetAttribute( SvcLogicContext ctx, String key, Object object ) { + if( object == null ) { + ctx.setAttribute(key, null); + } + else { + ctx.setAttribute(key, object.toString()); + } + } + + /** + * Sets a key in context memory to the output of object's toString(). + *

+ * The key is deleted from context memory if object is null. The key and + * value set in context memory are logged to the Logger at the provided + * logLevel level. + * @param Any Java object + * @param ctx Reference to context memory. + * @param key Key to set. + * @param obj Object whose toString() will be the value set + * @param LOG Logger to log to + * @param logLevel level to log at in Logger + */ + public static final void ctxSetAttribute( SvcLogicContext ctx, String key, O obj, Logger LOG, LogLevel logLevel ) { + String value = Objects.toString( obj, null ); + ctx.setAttribute( key, value ); + if( logLevelIsEnabled(LOG, logLevel ) ) { + if( value == null ) { + logMessageAtLevel( LOG, logLevel, "Deleting " + key ); + } + else { + logMessageAtLevel( LOG, logLevel, "Setting " + key + " = " + value ); + } + } + } + + /** + * Utility function used to get an array's length from context memory. + * Will return 0 if key doesn't exist in context memory or isn't numeric. + *

+ * Use to obtain a context memory array length without having to worry + * about throwing a NumberFormatException. + * @param ctx Reference to context memory + * @param key Key in context memory whose value is the array's length. If + * the key doesn't end in "_length", then "_length is appended. + * @param log Reference to Logger to log to + * @return The array length or 0 if the key is not found in context memory. + * @since 1.0 + */ + public static final int getArrayLength( SvcLogicContext ctx, String key ) { + return getArrayLength(ctx, key, null, null, null); + } + + /** + * Utility function used to get an array's length from context memory. + * Will return 0 if key doesn't exist in context memory or isn't numeric + * and print the provided log message to the configured log file. + *

+ * Use to obtain a context memory array length without having to worry + * about throwing a NumberFormatException. + * @param ctx Reference to context memory. + * @param key Key in context memory whose value is the array's length. If + * the key doesn't end in "_length", then "_length is appended. + * @param log Reference to Logger to log to. Doesn't log if null. + * @param logLevel Logging level to log the message at if the context + * memory key isn't found. Doesn't log if null. + * @param log_message Message to log if the context memory key isn't found. + * Doesn't log if null. + * @return The array length or 0 if the key is not found in context memory. + * @since 1.0 + */ + public static final int getArrayLength( SvcLogicContext ctx, String key, Logger log, LogLevel logLevel, String log_message ) { + String ctxKey = key.endsWith(LENGTH) ? key : key + LENGTH; + try { + return Integer.parseInt(ctx.getAttribute(ctxKey)); + } + catch( NumberFormatException e ) { + if( log != null && logLevel != null && log_message != null ) { + switch( logLevel ) { + case TRACE: + log.trace(log_message); + break; + case DEBUG: + log.debug(log_message); + break; + case INFO: + log.info(log_message); + break; + case WARN: + log.warn(log_message); + break; + case ERROR: + log.error(log_message); + break; + } + } + } + + return 0; + } + + /** + * Prints sorted context memory key-value pairs to the log file at the log + * level. Returns immediately if the log level isn't enabled. + *

+ * O(n log(n)) time where n = size of context memory + * @param ctx Reference to context memory + * @param log Reference to Logger to log to + * @param logLevel Logging level to log the context memory key-value pairs + * at. + * @since 1.0 + */ + public static final void logContextMemory( SvcLogicContext ctx, Logger log, LogLevel logLevel ) { + logLevelIsEnabled( log, logLevel ); + + // Print sorted context memory key-value pairs to the log + ArrayList keys = new ArrayList<>(ctx.getAttributeKeySet()); + Collections.sort(keys); + for( String key : keys ) { + logMessageAtLevel( log, logLevel, key + " = " + ctx.getAttribute(key) ); + } + } + + + + // ========== PRIVATE FUNCTIONS ========== + + // TODO: javadoc + /** + * + * @param parameters + * @param log + * @param loglevel + * @since 7.0.1 + */ + public static final void logExecuteNodeParameters( Map parameters, Logger log, LogLevel loglevel ) { + logLevelIsEnabled( log, loglevel ); + + for( Map.Entry param : parameters.entrySet() ) { + logMessageAtLevel( log, loglevel, "PARAM: " + param.getKey() + " = " + param.getValue() ); + } + } + + // TODO: javadoc + /** + * Returns true if the loglevel is enabled. Otherwise, returns false. + * @param log Reference to logger + * @param loglevel Log level to check if enabled + * @return True if the loglevel is enabled. Otherwise, false + * @since 7.0.1 + */ + private static final boolean logLevelIsEnabled( Logger log, LogLevel loglevel ) { + // Return immediately if logging level isn't enabled + switch( loglevel ) { + case TRACE: + if( log.isTraceEnabled() ) { return true; } + return false; + case DEBUG: + if( log.isDebugEnabled() ) { return true; } + return false; + case INFO: + if( log.isInfoEnabled() ) { return true; } + return false; + case WARN: + if( log.isWarnEnabled() ) { return true; } + return false; + case ERROR: + if( log.isErrorEnabled() ) { return true; } + return false; + default: + throw new IllegalArgumentException("Unknown LogLevel: " + loglevel.toString()); + } + } + + // TODO: javadoc + /** + * + * @param log + * @param loglevel + * @param msg + * @since 7.0.1 + */ + private static final void logMessageAtLevel( Logger log, LogLevel loglevel, String msg ) { + switch( loglevel ) { + case TRACE: + log.trace(msg); + return; + case DEBUG: + log.debug(msg); + return; + case INFO: + log.info(msg); + return; + case WARN: + log.warn(msg); + return; + case ERROR: + log.error(msg); + return; + } + } + + + + // ========== LOCAL CLASSES ========== + + private class SortableCtxListElement implements Comparable { + HashMap child_elements = new HashMap<>(); + String[] sort_fields; + + public SortableCtxListElement( SvcLogicContext ctx, String root, String[] sort_fields ) { + this.sort_fields = sort_fields; + + for( String key : ctx.getAttributeKeySet() ) { + if( key.startsWith(root) ) { + if( key.length() == root.length() ) { + child_elements.put("", ctx.getAttribute(key)); + break; + } + else { + child_elements.put(key.substring(root.length()+1), ctx.getAttribute(key)); + } + } + } + } + + @Override + public int compareTo(SortableCtxListElement arg0) { + if( sort_fields == null ) { + return this.child_elements.get("").compareTo(arg0.child_elements.get("")); + } + + for( String field : this.sort_fields ) { + int result = this.child_elements.get(field).compareTo(arg0.child_elements.get(field)); + if( result != 0 ) { + return result; + } + } + + return 0; + } + + @Override + public boolean equals(Object object) { + if (this == object) { + return true; + } + if (!(object instanceof SortableCtxListElement)) { + return false; + } + if (!super.equals(object)) { + return false; + } + + SortableCtxListElement that = (SortableCtxListElement) object; + + if (child_elements != null ? !child_elements.equals(that.child_elements) + : that.child_elements != null) { + return false; + } + // Probably incorrect - comparing Object[] arrays with Arrays.equals + if (!Arrays.equals(sort_fields, that.sort_fields)) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (child_elements != null ? child_elements.hashCode() : 0); + result = 31 * result + Arrays.hashCode(sort_fields); + return result; + } + } + + /** + * Creates a file that contains the content of context memory. + * @param parameters - must contain the parameter filename + * @param ctx Reference to context memory + * @throws SvcLogicException thrown if file cannot be created or if parameters are missing + */ + public static void printContext(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + if (parameters == null || parameters.isEmpty()) { + throw new SvcLogicException("no parameters passed"); + } + + checkParameters(parameters, new String[]{"filename"}, LOG); + + String fileName = parameters.get("filename"); + + + try (FileOutputStream fstr = new FileOutputStream(new File(fileName)); + PrintStream pstr = new PrintStream(fstr, true);) + { + pstr.println("#######################################"); + for (String attr : ctx.getAttributeKeySet()) { + pstr.println(attr + " = " + ctx.getAttribute(attr)); + } + } catch (Exception e) { + throw new SvcLogicException("Cannot write context to file " + fileName, e); + } + + + } + + public static void logContextProperties(Map parameters, SvcLogicContext ctx) + throws SvcLogicException { + if (LOG.isTraceEnabled()) { + String subpath = parameters.get("subpath"); + if (subpath != null && !subpath.isEmpty()) { + ctx.printProperties(ctx.toProperties(), subpath); + } else { + ctx.printProperties(ctx.toProperties()); + } + } + } + + public static void logContextAttributes(Map parameters, SvcLogicContext ctx) + throws SvcLogicException { + if (LOG.isTraceEnabled()) { + String subpath = parameters.get("subpath"); + if (subpath != null && !subpath.isEmpty()) { + ctx.printAttributes(subpath); + } else { + ctx.printAttributes(); + } + } + } + + /** + * Checks context memory for a set of required parameters + * Every parameter aside from prefix will be treated as mandatory + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + *
parameterMandatory/Optionaldescription
prefixOptionalthe prefix will be added to each parameter
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static void requiredParameters(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + if (parameters == null || parameters.keySet().isEmpty()) { + String errorMessage = "requiredParameters should not be called if the parameters hashmap is null or empty!"; + LOG.error(errorMessage); + throw new SvcLogicException(errorMessage); + } + String prefixValue = null; + String prefix = "prefix"; + if(parameters.containsKey(prefix)){ + prefixValue = parameters.get(prefix); + parameters.remove(prefix); + } + checkParameters(prefixValue, ctx.getAttributeKeySet(), parameters.keySet(), LOG); + } + + private static void checkParameters(String prefixValue, Set ctx, Set parameters, Logger log) throws SvcLogicException { + for (String param : parameters) { + if (prefixValue != null) { + param = prefixValue + param; + } + if (!ctx.contains(param)) { + String errorMessage = "This method requires the parameters [" + StringUtils.join(parameters, ",") + + "], but " + param + " was not passed in."; + log.error(errorMessage); + throw new SvcLogicException(errorMessage); + } + } + } + + /** + * is in a different DG invocation just before/after we call NCS and set the state to InProgress + */ + /** + * setTime write the current date time to a string located at outputPath + * @param parameters - requires outputPath to not be null + * @param ctx Reference to context memory + * @throws SvcLogicException if a required parameter is missing an exception is thrown + */ + public static void setTime(Map parameters, SvcLogicContext ctx) throws SvcLogicException + { + checkParameters(parameters, new String[] { "outputPath" }, LOG); + + // Set the DateFormat + // "2015-03-16T12:18:35.138Z" + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + + // Parse the date + String ctxVariable = parameters.get("outputPath"); + try { + String dateTime = format.format(new Date()); + ctx.setAttribute(ctxVariable, dateTime); + } catch (Exception ex) { + throw new SvcLogicException("problem with setTime", ex); + } + } + + /** + * jsonStringToCtx takes a json string stored as a single property in context memory and breaks it into individual properties + * @param parameters - requires source, outputPath and isEscaped to not be null. + * @param ctx Reference to context memory + * @throws SvcLogicException if a required parameter is missing an exception is thrown + */ + public static void jsonStringToCtx(Map parameters, SvcLogicContext ctx) throws SvcLogicException + { + checkParameters(parameters, new String[] { "source","outputPath","isEscaped" }, LOG); + try { + String source = ctx.getAttribute(parameters.get("source")); + if("true".equals(parameters.get("isEscaped"))){ + source = StringEscapeUtils.unescapeJson(source); + } + ctx.mergeJson(parameters.get("outputPath"), source); + // writeJsonToCtx(source, ctx,parameters.get("outputPath")); + } catch (Exception ex) { + throw new SvcLogicException("problem with jsonStringToCtx", ex); + } + } + + protected static void writeJsonToCtx(String resp, SvcLogicContext ctx, String prefix){ + // Refactored code for this method into SvcLogicContext object. Leaving this + // method in place for backward compatibility. + ctx.mergeJson(prefix, resp); + } + + /** + * updateJsonObjectString takes a json object string, and adds or deletes the properties of it + * @param parameters - requires source, outputPath and keys to be added or deleted. + * The key of parameter starts with "add.", e.g. "add.A", and then "A" and its value will be added + * to the JSON object. + * The key of parameter starts with "delete.", e.g. "delete.B", and then "B" will be deleted from + * the JSON object. + * @param ctx Reference to context memory + * @throws SvcLogicException if a required parameter is missing an exception is thrown + */ + public static void updateJsonObjectString(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + checkParameters(parameters, new String[] {"source", "outputPath"}, LOG); + try { + String source = ctx.getAttribute(parameters.get("source")); + JsonParser jp = new JsonParser(); + JsonElement element = jp.parse(source); + if (element.isJsonObject()) { + JsonObject jsonObject = element.getAsJsonObject(); + updateJsonObject(jsonObject, parameters); + + String target = jsonObject.toString(); + ctx.setAttribute(parameters.get("outputPath"), target); + } else { + throw new SvcLogicException("just update JSON object string"); + } + } catch (Exception ex) { + throw new SvcLogicException("problem with updateJsonObjectString", ex); + } + } + + protected static void updateJsonObject(JsonObject jsonObject, Map parameters) throws SvcLogicException { + List deleted_params = parameters.keySet().stream().filter(param -> param.startsWith("delete.")). + collect(Collectors.toList()); + for (String param: deleted_params) { + String[] action_key = param.split("\\.", 2); + if (action_key.length < 2) { + throw new SvcLogicException("error parameter format: " + param + ", must be \"delete.\""); + } + jsonObject.remove(action_key[1]); + } + + List added_params = parameters.keySet().stream().filter(param -> param.startsWith("add.")). + collect(Collectors.toList()); + for (String param: added_params) { + String[] action_key = param.split("\\.", 2); + if (action_key.length < 2) { + throw new SvcLogicException("error parameter format: " + param + ", must be \"add.\""); + } + jsonObject.addProperty(action_key[1], parameters.get(param)); + } + } + + /** + * getAttributeValue takes a ctx memory path as a string, gets the value stored at this path and set this value in context memory at + * outputPath + * @param parameters - requires source and outputPath + * @param ctx Reference to context memory + * @throws SvcLogicException if a required parameter is missing an exception is thrown + */ + public static void getAttributeValue(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + checkParameters(parameters, new String[] { "source", "outputPath" }, LOG); + String source = ctx.getAttribute(parameters.get("source")); + ctx.setAttribute(parameters.get("outputPath"), source); + } + + /** + * ctxListContains provides a way to see if a context memory list contains a key value + * @param parameters - requires list, keyName, keyValue, outputPath to all not be null. + * @param ctx Reference to context memory + * @throws SvcLogicException if a required parameter is missing an exception is thrown + */ + public static String ctxListContains(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + checkParameters(parameters, new String[]{"list", "keyName", "keyValue"}, LOG); + + try { + String ctxList = parameters.get("list"); + ctxList = (ctxList.endsWith(LENGTH)) ? ctxList : ctxList + LENGTH; + int listLength = getArrayLength(ctx, ctxList); + + if (listLength == 0) { + LOG.debug("List is not in context memory"); + return "false"; + } else { + Set keys = new HashSet(); + + String listPrefix = ctxList.substring(0, ctxList.lastIndexOf("_")) + "["; + String listSuffix = "]." + parameters.get("keyName"); + + for (int i = 0; i < listLength; i++) { + String keyLocation = listPrefix + i + listSuffix; + keys.add(ctx.getAttribute(keyLocation)); + } + + if (keys.contains(parameters.get("keyValue"))) { + LOG.debug("List " + parameters.get("list") + " contains " + parameters.get("keyValue")); + return "true"; + } else { + LOG.debug("List " + parameters.get("list") + " do not contains " + parameters.get("keyValue")); + return "false"; + } + } + } catch (Exception ex) { + throw new SvcLogicException("ctxListContains failed", ex); + } + } + + /** + * set properties in context memory for a container
+ * parameters with a null or empty key or value are ignored
+ * required parameter root - root + "." + parameters.key + * is the key to set the value too value in context memory
+ * optional parameter valueRoot - if set: valueRoot + "." + parameters.value + * is the key to get the value from context memory + * + * @param parameters - root (required), valueRoot (optional), properties names and values to be set + * @param ctx Reference to context memory + * @return success or failure of operation + */ + public static String setPropertiesForRoot(Map parameters, SvcLogicContext ctx) { + LOG.debug("Execute Node \"setPropertiesForRoot\""); + try { + checkParameters(parameters, new String[]{"root"}, LOG); + } catch (Exception ex) { + return SvcLogicConstants.FAILURE; + } + + String root = parameters.get("root"); + + if (StringUtils.isEmpty(root)) { + return SvcLogicConstants.FAILURE; + } + + // set context memory to the the properties passed with root as prefix + setParameterValuesToRoot(parameters, ctx, root); + + return SvcLogicConstants.SUCCESS; + } + + private static boolean setParameterValuesToRoot(Map parameters, SvcLogicContext ctx, String root) { + boolean changeFlag = false; + String valueRoot = parameters.get("valueRoot"); + + for (Map.Entry entry : parameters.entrySet()) { + // ignore if it's the root parameter + if (!entry.getKey().equals("root")) { + String keyToBeSet = root + "." + entry.getKey(); + String valueToBeSet = ""; + + if (StringUtils.isEmpty(valueRoot)) { + valueToBeSet = entry.getValue(); + } else { + valueToBeSet = ctx.getAttribute(valueRoot + "." + entry.getValue()); + } + + LOG.debug("Setting context memory: " + keyToBeSet + " = " + valueToBeSet); + + if (!StringUtils.isEmpty(entry.getKey()) && !StringUtils.isEmpty(valueToBeSet)) { + ctxSetAttribute(ctx, keyToBeSet, valueToBeSet); + changeFlag = true; + } + } + } + + return changeFlag; + } + + /** + * takes container list and set the properties with the value provided
+ * parameters with a null or empty key or value are ignored
+ * required parameters
+ * prefixKey + "." + parameters.key is the key to set the value too value in context memory
+ * prefixKey + "[index]." + keyName is the key of the entry in the list in context memory
+ * keyValue is the value of the key of the list entry in context memory (must be actual value)
+ * optional parameter valuePrefixKey - if set: valuePrefixKey + "." + parameters.value + * is the key to get the value from context memory + * + * @param parameters
+ * - prefixKey e.g "service-data.universal-cpe-ft.l2-switch-interfaces"
+ * - keyName e.g "name"
+ * - keyValue e.g "WAN1" (must be actual value and not use the prefixKey as root)
+ * - valuePrefixKey (optional) e.g "input.universal-cpe-ft.l2-switch-interfaces[1]
+ * - properties to be set, values for the properties
+ * @param ctx reference to context memory + * @return success or failure of operation + */ + public static String setPropertiesForList(Map parameters, SvcLogicContext ctx) { + LOG.debug("Execute Node \"setPropertiesForList\""); + try { + checkParameters(parameters, new String[]{"prefixKey", "keyName", "keyValue"}, LOG); + } catch (Exception e) { + LOG.error("a required parameter is missing"); + return SvcLogicConstants.FAILURE; + } + + String prefixKey = parameters.get("prefixKey"); + String keyName = parameters.get("keyName"); + String keyValue = parameters.get("keyValue"); + + if (StringUtils.isEmpty(keyName) || StringUtils.isEmpty(keyValue) || StringUtils.isEmpty(prefixKey)) { + LOG.error("a required parameters value is empty or null"); + return SvcLogicConstants.FAILURE; + } + + int listLength = getArrayLength(ctx, prefixKey); + + Map containParams = new HashMap<>(); + containParams.put("list", prefixKey); + containParams.put("keyName", keyName); + containParams.put("keyValue", keyValue); + + String valuePrefixKey = parameters.get("valuePrefixKey"); + + try { + // create new list in context memory + if (listLength == 0) { + // since there's no length found make sure there's no current data at prefixKey in context memory + Map map = ctxGetBeginsWith(ctx, prefixKey); + + if (map.size() == 0) { + setNewEntryInList(parameters, ctx, keyName, keyValue, prefixKey, valuePrefixKey, listLength); + } else { + LOG.error("there was no length for the list parameter set in context memory " + + "but " + map.size() + " entries were found in context memory " + + "where the key begins with: " + prefixKey); + + return SvcLogicConstants.FAILURE; + } + } else if (ctxListContains(containParams, ctx) == "false") { + setNewEntryInList(parameters, ctx, keyName, keyValue, prefixKey, valuePrefixKey, listLength); + } else if (ctxListContains(containParams, ctx) == "true") { + // else update the context memory with the properties passed in at the right index level + String listPrefix = prefixKey + "["; + String listSuffix = "]."; + + for (int i = 0; i < listLength; i++) { + String listRootWithIndex = listPrefix + i + listSuffix; + String listKeyName = listRootWithIndex + keyName; + String valueAtListIndexKey = ctx.getAttribute(listKeyName); + + if (valueAtListIndexKey.equals(keyValue)) { + setParametersToCtxList(parameters, ctx, listRootWithIndex, valuePrefixKey); + } + } + } + } catch (SvcLogicException e) { + LOG.error("Call to ctxListContains failed: " + e.getMessage()); + + return SvcLogicConstants.FAILURE; + } + + return SvcLogicConstants.SUCCESS; + } + + private static void setNewEntryInList(Map parameters, SvcLogicContext ctx, String keyName, + String keyValue, String prefixKey, String valuePrefixKey, int listLength) { + String prefixKeyWithIndex = prefixKey + "[" + listLength + "]."; + String listKeyName = prefixKeyWithIndex + keyName; + + // set list key + LOG.debug("Setting context memory, new list entry with key: " + listKeyName + " = " + keyValue); + ctxSetAttribute(ctx, listKeyName, keyValue); + + // set the other parameters + setParametersToCtxList(parameters, ctx, prefixKeyWithIndex, valuePrefixKey); + + // set length of list + String ListLengthKeyName = prefixKey + LENGTH; + + ctxSetAttribute(ctx, prefixKey + LENGTH, listLength + 1); + LOG.debug("Updated _length: " + prefixKey + "_length is now " + ctx.getAttribute(ListLengthKeyName)); + } + + /** + * helper function to set the parameter properties for list at the provided prefix key + * + * @param parameters + * @param ctx + * @param prefixKey + * @return true if any new context memory was added and or modified + */ + private static boolean setParametersToCtxList(Map parameters, SvcLogicContext ctx, String prefixKeyWithIndex, + String valuePrefixKey) { + boolean changeFlag = false; + + for (Map.Entry entry : parameters.entrySet()) { + if (! (entry.getKey().equals("prefixKey") || + entry.getKey().equals("keyName") || + entry.getKey().equals("keyValue")) || + entry.getKey().equals("valuePrefixKey")) { + + String keyToBeSet = prefixKeyWithIndex + entry.getKey(); + String valueToBeSet = ""; + + if (StringUtils.isEmpty(valuePrefixKey)) { + valueToBeSet = entry.getValue(); + } else { + valueToBeSet = ctx.getAttribute(valuePrefixKey + "." + entry.getValue()); + } + + LOG.debug("Setting context memory: " + keyToBeSet + " = " + valueToBeSet); + + // only set context memory if properties key and value are not empty or null + if (!StringUtils.isEmpty(entry.getKey()) && !StringUtils.isEmpty(valueToBeSet)) { + ctxSetAttribute(ctx, keyToBeSet, valueToBeSet); + changeFlag = true; + } + } + } + + return changeFlag; + } + + public static String containsKey(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + String key = parameters.get("key"); + Boolean keyFound = ctx.getAttributeKeySet().contains(key); + if (keyFound) { + return "true"; + } + return "false"; + } + +} diff --git a/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SliStringUtils.java b/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SliStringUtils.java new file mode 100644 index 000000000..9e3367d45 --- /dev/null +++ b/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SliStringUtils.java @@ -0,0 +1,559 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Modifications Copyright (C) 2018 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.ccsdk.sli.core.slipluginutils; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.Map; +import java.util.Base64; +import org.apache.commons.text.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A SvcLogicJavaPlugin that exposes java.lang.String functions to DirectedGraph + */ +public class SliStringUtils implements SvcLogicJavaPlugin { + private static final Logger LOG = LoggerFactory.getLogger(SliStringUtils.class); + public static final String INPUT_PARAM_KEY = "key"; + public static final String INPUT_PARAM_SOURCE = "source"; + public static final String INPUT_PARAM_TARGET = "target"; + public static final String TRUE_CONSTANT = "true"; + public static final String FALSE_CONSTANT = "false"; + + public SliStringUtils() {} + + /** + * Provides split functionality to Directed Graphs. + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
original_stringMandatoryString to perform split on
regexMandatorythe delimiting regular expression
limitOptionalresult threshold. See String.split method for further description. Defaults to 0
ctx_memory_result_keyMandatoryKey in context memory to populate the resulting array of strings under
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + * @see String#split(String, int) + */ + public void split( Map parameters, SvcLogicContext ctx ) throws SvcLogicException { + final String original_string = parameters.get("original_string"); + LOG.trace("original_string = " + original_string); + final String regex = parameters.get("regex"); + LOG.trace("regex = " + regex); + final String limit_str = parameters.get("limit"); + LOG.trace("limit_str = " + limit_str); + final String ctx_memory_result_key = parameters.get("ctx_memory_result_key"); + LOG.trace("ctx_memory_result_key = " + ctx_memory_result_key); + + try { + // Validation that parameters are not null + SliPluginUtils.checkParameters( parameters, new String[]{"original_string","regex","ctx_memory_result_key"}, LOG ); + + // Read limit from context memory. Default to 0 if null/empty + int limit = 0; + if( StringUtils.isNotEmpty(limit_str) ) { + try { + limit = Integer.parseInt(limit_str); + } + catch( NumberFormatException e ) { + throw new IllegalArgumentException( "The limit parameter of the SliStringUtils.split() function must be a number, empty string, or null", e ); + } + } + + // Call String.split(regex,limit) on string passed in + String[] split_string = original_string.split(regex, limit); + + // Populate context memory with results + for( int i = 0; i < split_string.length; i++ ) { + SliPluginUtils.ctxSetAttribute(ctx, ctx_memory_result_key + '[' + i + ']', split_string[i], LOG, SliPluginUtils.LogLevel.DEBUG); + } + SliPluginUtils.ctxSetAttribute(ctx, ctx_memory_result_key + "_length", new Integer(split_string.length), LOG, SliPluginUtils.LogLevel.DEBUG); + } + catch( Exception e ) { + // Have error message print parameters + throw new SvcLogicException( "An error occurred during SliStringUtils.split() where original_string = " + quotedOrNULL(regex) + + " regex = " + quotedOrNULL(regex) + + " limit = " + quotedOrNULL(regex) + + " ctx_memory_result_key = " + quotedOrNULL(regex), e ); + } + } + + public static String quotedOrNULL( String str ) { + return (str == null) ? "NULL" : '"' + str + '"'; + } + + /** + * exposes equalsIgnoreCase to directed graph + * @param parameters HashMap of parameters passed by the DG to this function + * emits a true or false outcome + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
sourceMandatorysource string
targetMandatorytarget string
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static String equalsIgnoreCase(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[] {INPUT_PARAM_SOURCE, INPUT_PARAM_TARGET}, LOG); + if (parameters.get(INPUT_PARAM_SOURCE).equalsIgnoreCase(parameters.get(INPUT_PARAM_TARGET))) { + return TRUE_CONSTANT; + } + return FALSE_CONSTANT; + } + + /** + * exposes toUpperCase to directed graph + * writes an upperCase version of source to outputPath + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
sourceMandatorysource string
outputPathMandatorythe location in context memory the result is written to
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static void toUpper(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[]{INPUT_PARAM_SOURCE,"outputPath"}, LOG); + ctx.setAttribute(parameters.get("outputPath"), parameters.get(INPUT_PARAM_SOURCE).toUpperCase()); + } + + /** + * exposes toLowerCase to directed graph + * writes a lowerCase version of source to outputPath + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
sourceMandatorysource string
outputPathMandatorythe location in context memory the result is written to
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static void toLower(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[]{INPUT_PARAM_SOURCE,"outputPath"}, LOG); + ctx.setAttribute(parameters.get("outputPath"), parameters.get(INPUT_PARAM_SOURCE).toLowerCase()); + } + + /** + * exposes contains to directed graph to test if one string contains another + * tests if the source contains the target + * @param parameters HashMap of parameters passed by the DG to this function + * emits a true or false outcome + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
sourceMandatorysource string
targetMandatorytarget string
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static String contains(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[] {INPUT_PARAM_SOURCE, INPUT_PARAM_TARGET}, LOG); + if (parameters.get(INPUT_PARAM_SOURCE).contains(parameters.get(INPUT_PARAM_TARGET))) { + return TRUE_CONSTANT; + } + return FALSE_CONSTANT; + } + + /** + * exposes endsWith to directed graph to test if one string endsWith another string + * tests if the source ends with the target + * @param parameters HashMap of parameters passed by the DG to this function + * emits a true or false outcome + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
sourceMandatorysource string
targetMandatorytarget string
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static String endsWith(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[] {INPUT_PARAM_SOURCE, INPUT_PARAM_TARGET}, LOG); + if (parameters.get(INPUT_PARAM_SOURCE).endsWith(parameters.get(INPUT_PARAM_TARGET))) { + return TRUE_CONSTANT; + } + return FALSE_CONSTANT; + } + + /** + * exposes startsWith to directed graph to test if one string endsWith another string + * tests if the source ends with the target + * @param parameters HashMap of parameters passed by the DG to this function + * emits a true or false outcome + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
sourceMandatorysource string
targetMandatorytarget string
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static String startsWith(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[] {INPUT_PARAM_SOURCE, INPUT_PARAM_TARGET}, LOG); + if (parameters.get(INPUT_PARAM_SOURCE).startsWith(parameters.get(INPUT_PARAM_TARGET))) { + return TRUE_CONSTANT; + } + return FALSE_CONSTANT; + } + + /** + * exposes trim to directed graph + * writes a trimmed version of the string to the outputPath + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
sourceMandatorysource string
outputPathMandatorythe location in context memory the result is written to
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static void trim(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[]{INPUT_PARAM_SOURCE,"outputPath"}, LOG); + ctx.setAttribute(parameters.get("outputPath"), parameters.get(INPUT_PARAM_SOURCE).trim()); + } + + /** + * exposes String.length() to directed graph + * writes the length of source to outputPath + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
sourceMandatorysource string
outputPathMandatorythe location in context memory the result is written to
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static void getLength(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[]{INPUT_PARAM_SOURCE,"outputPath"}, LOG); + ctx.setAttribute(parameters.get("outputPath"), String.valueOf(parameters.get(INPUT_PARAM_SOURCE).length())); + } + + /** + * exposes replace to directed graph + * writes the length of source to outputPath + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
sourceMandatorysource string
targetMandatoryThe sequence of char values to be replaced
replacementMandatoryThe replacement sequence of char values
outputPathMandatorythe location in context memory the result is written to
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static void replace(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, + new String[] {INPUT_PARAM_SOURCE, "outputPath", INPUT_PARAM_TARGET, "replacement"}, LOG); + ctx.setAttribute(parameters.get("outputPath"), (parameters.get(INPUT_PARAM_SOURCE) + .replace(parameters.get(INPUT_PARAM_TARGET), parameters.get("replacement")))); + } + +/** + * exposes base64decoding algo + * writes the length of source to outputPath + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
encodedValueMandatorysource string
decodedValueMandatoryDestination path
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static void base64DecodingAlgo(Map parameters, SvcLogicContext ctx) throws SvcLogicException{ + try { + SliPluginUtils.checkParameters(parameters, new String[]{"encodedValue","decodedValue"}, LOG); + + Base64.Decoder decoder = Base64.getDecoder(); + byte[] decodedByteArray = decoder.decode(parameters.get("encodedValue")); + //Verify the decoded string + String decodeVal = new String(decodedByteArray); + ctx.setAttribute(parameters.get("decodedValue"), decodeVal); + }catch (Exception exc){ + LOG.error("Exception occure "+exc.getMessage()); + throw new SvcLogicException(exc.getMessage()); + } + } + + + /** + * exposes replaceAll to directed graph + * writes the length of source to outputPath + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
sourceMandatorysource string
targetMandatoryThis should be a valid regular expression
replacementMandatoryThe replacement sequence of char values
outputPathMandatorythe location in context memory the result is written to
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static void replaceAll(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, + new String[] {INPUT_PARAM_SOURCE, "outputPath", INPUT_PARAM_TARGET, "replacement"}, LOG); + ctx.setAttribute(parameters.get("outputPath"), parameters.get(INPUT_PARAM_SOURCE) + .replaceAll(parameters.get(INPUT_PARAM_TARGET), parameters.get("replacement"))); + } + + /** + * Provides substring functionality to Directed Graphs. + *

+ * Calls either String.substring(String beginIndex) or + * String.substring(String beginInded, String endIndex) if the end-index + * is present or not. + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
stringMandatoryString to perform substring on
resultMandatoryKey in context memory to populate the resulting string in
begin-indexMandatoryBeginning index to pass to Java substring function
end-indexOptionalEnding index to pass to Java substring function. If not included, String.substring(begin) will be called.
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public void substring( Map parameters, SvcLogicContext ctx ) throws SvcLogicException { + try { + SliPluginUtils.checkParameters( parameters, new String[]{"string","begin-index","result"}, LOG ); + final String string = parameters.get("string"); + final String result = parameters.get("result"); + final String begin = parameters.get("begin-index"); + final String end = parameters.get("end-index"); + if( StringUtils.isEmpty(end) ) { + ctx.setAttribute( result, string.substring(Integer.parseInt(begin)) ); + } + else { + ctx.setAttribute( result, string.substring(Integer.parseInt(begin), Integer.parseInt(end)) ); + } + } + catch( Exception e ) { + throw new SvcLogicException( "An error occurred while the Directed Graph was performing a substring", e ); + } + } + + /** + * Provides concat functionality to Directed Graphs. + *

+ * Will concat target to source and write the result to outputPath + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
sourceMandatorysource string
targetMandatoryThe sequence of char values to be replaced
outputPathMandatorythe location in context memory the result is written to
+ * @param ctx Reference to context memory + * @throws SvcLogicException + * @since 11.0.2 + */ + public static void concat( Map parameters, SvcLogicContext ctx ) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[] {INPUT_PARAM_SOURCE, INPUT_PARAM_TARGET, "outputPath"}, + LOG); + String result = parameters.get(INPUT_PARAM_SOURCE).concat(parameters.get(INPUT_PARAM_TARGET)); + ctx.setAttribute(parameters.get("outputPath"), result); + } + + /** + * Provides url encoding functionality to Directed Graphs. + *

+ * Will url encode the source and write the result to outputPath + * @param parameters HashMap of parameters passed by the DG to this function + * + * + * + * + * + * + * + *
parameterMandatory/Optionaldescription
sourceMandatorysource string
encodingOptionalthe name of a supported character encoding, defaulted to UTF-8 if not supplied
outputPathMandatorythe location in context memory the result is written to
+ * @param ctx Reference to context memory + * @throws SvcLogicException + */ + public static void urlEncode(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[] { INPUT_PARAM_SOURCE, "outputPath" }, LOG); + String encoding = parameters.get("encoding"); + if (encoding == null) { + encoding = "UTF-8"; + } + try { + String result = URLEncoder.encode(parameters.get(INPUT_PARAM_SOURCE), encoding); + ctx.setAttribute(parameters.get("outputPath"), result); + } catch (UnsupportedEncodingException e) { + throw new SvcLogicException("Url encode failed.", e); + } + } + + public static void urlDecode(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[] {INPUT_PARAM_SOURCE, "outputPath"}, LOG); + String encoding = parameters.get("encoding"); + if (encoding == null) { + encoding = "UTF-8"; + } + try { + String result = URLDecoder.decode(parameters.get(INPUT_PARAM_SOURCE), encoding); + ctx.setAttribute(parameters.get("outputPath"), result); + } catch (UnsupportedEncodingException e) { + throw new SvcLogicException("Url decode failed.", e); + } + } + + /** + * xmlEscapeText() will be used to format input xml with text. + * + * @param inParams + * accepts the instance of {@link Map} holds the input xml in string + * format. + * @param ctx + * accepts the instance of {@link SvcLogicContext} holds the service + * logic context. + * + */ + public static void xmlEscapeText(Map inParams, SvcLogicContext ctx) { + String source = inParams.get(INPUT_PARAM_SOURCE); + String target = inParams.get(INPUT_PARAM_TARGET); + source = StringEscapeUtils.escapeXml10(source); + ctx.setAttribute(target, source); + } + + /** + * unescapeJsonString takes an escaped json string stored as a single property in context memory and unescapes it storing it as a single property + * @param parameters - requires source and outputPath to not be null. + * @param ctx Reference to context memory + * @throws SvcLogicException if a required parameter is missing an exception is thrown + */ + public static void unescapeJsonString(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[] { INPUT_PARAM_SOURCE, INPUT_PARAM_TARGET }, LOG); + try { + String source = parameters.get(INPUT_PARAM_SOURCE); + String target = parameters.get(INPUT_PARAM_TARGET); + String unescapedJson = StringEscapeUtils.unescapeJson(source); + ctx.setAttribute(target, unescapedJson); + } catch (Exception ex) { + ex.printStackTrace(); + throw new SvcLogicException("problem with unescapeJsonString", ex); + } + } + + /** + * escapeJsonString takes json stored as a single string in context memory and escapes it storing it as a single property + * @param parameters - requires source and outputPath to not be null. + * @param ctx Reference to context memory + * @throws SvcLogicException if a required parameter is missing an exception is thrown + */ + public static void escapeJsonString(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + SliPluginUtils.checkParameters(parameters, new String[] { INPUT_PARAM_SOURCE, INPUT_PARAM_TARGET }, LOG); + try { + String source = parameters.get(INPUT_PARAM_SOURCE); + String target = parameters.get(INPUT_PARAM_TARGET); + String unescapedJson = StringEscapeUtils.escapeJson(source); + ctx.setAttribute(target, unescapedJson); + } catch (Exception ex) { + ex.printStackTrace(); + throw new SvcLogicException("problem with escapeJsonString", ex); + } + } + + public static String isBlank(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + String ctxLocation = parameters.get(INPUT_PARAM_KEY); + String str = ctx.getAttribute(ctxLocation); + if (str == null || str.isEmpty() || " ".equals(str)) { + return TRUE_CONSTANT; + } + return FALSE_CONSTANT; + } + + public static String isEmpty(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + String ctxLocation = parameters.get(INPUT_PARAM_KEY); + String str = ctx.getAttribute(ctxLocation); + if (str == null || str.isEmpty()) { + return TRUE_CONSTANT; + } + return FALSE_CONSTANT; + } + + public static String isNull(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + String ctxLocation = parameters.get(INPUT_PARAM_KEY); + String str = ctx.getAttribute(ctxLocation); + if (str == null) { + return TRUE_CONSTANT; + } + return FALSE_CONSTANT; + } +} diff --git a/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextList.java b/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextList.java new file mode 100644 index 000000000..32e1aebdc --- /dev/null +++ b/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextList.java @@ -0,0 +1,210 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.core.slipluginutils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.ListIterator; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +/** + * A utility class used to manage list manipulation in the context memory. + * @see org.onap.ccsdk.sli.core.sli.SvcLogicContext + */ +public class SvcLogicContextList { + /** + * Internal flag indicating if list should be deleted from context memory + * when it is copied into the SvcLogicContextList object. + */ + private enum OperType { + COPY, EXTRACT + } + + // TODO: javadoc + protected final String prefix; + // TODO: javadoc + protected final ArrayList> list; + + + // TODO: javadoc + public SvcLogicContextList( SvcLogicContext ctx, String list_prefix ) { + this(ctx, list_prefix, OperType.COPY); + } + + // TODO: javadoc + private SvcLogicContextList( SvcLogicContext ctx, String list_prefix, OperType operation ) { + this.prefix = list_prefix; + + // Initialize list + int capacity = getCtxListLength(ctx, prefix); + this.list = new ArrayList<>(capacity); + for( int i = 0; i < capacity; i++ ) { + this.list.add(i, new HashMap()); + } + + // Populate "elements" in list + String prefix_bracket = this.prefix + '['; + for (String key : new HashSet(ctx.getAttributeKeySet())) { + if( key.startsWith(prefix_bracket) ) { + // Extract the index of the list + int index = getCtxListIndex(key, this.prefix, capacity); + + // Store the + String suffix = key.substring((prefix_bracket + index + ']').length()); + suffix = suffix.isEmpty() ? suffix : suffix.substring(1); + this.list.get(index).put( suffix, ctx.getAttribute(key)); + + // If flag to extract set, remove data from context memory as + // it is read into this list + if( operation == OperType.EXTRACT ) { + ctx.setAttribute(key, null); + } + } + } + + // If flag to extract set, remove list _length value from cxt mem + if( operation == OperType.EXTRACT ) { + ctx.setAttribute(this.prefix + "_length", null); + } + } + + // TODO: javadoc + public static SvcLogicContextList extract( SvcLogicContext ctx, String list_prefix ) { + return new SvcLogicContextList(ctx, list_prefix, OperType.EXTRACT); + } + + + // ========== PUBLIC FUNCTIONS ========== + + // TODO: javadoc + public HashMap get( int index ) { + return this.list.get(index); + } + + // TODO: javadoc + public HashMap remove( int index ) { + return this.list.remove(index); + } + + // TODO: javadoc + public void remove( String value ) { + remove( "", value ); + } + + // TODO: javadoc + public void remove( String key, String value ) { + if( value == null ) { + throw new IllegalArgumentException("value cannot be null"); + } + + ListIterator> itr = this.list.listIterator(); + while( itr.hasNext() ) { + if( value.equals(itr.next().get(key)) ) { + itr.remove(); + } + } + } + + // TODO javadoc + public void remove( Map primary_key ) { + ListIterator> itr = this.list.listIterator(); + while( itr.hasNext() ) { + boolean found = true; + HashMap list_element = itr.next(); + for( Map.Entry key : primary_key.entrySet() ) { + if( !key.getValue().equals(list_element.get(key.getKey())) ) { + found = false; + break; + } + } + + if( found ) { + itr.remove(); + } + } + } + + // TODO: javadoc + public int size() { + return list.size(); + } + + // TODO: javadoc + public void writeToContext( SvcLogicContext ctx ) { + ctx.setAttribute( prefix + "_length", Integer.toString(this.list.size()) ); + + for( int i = 0; i < this.list.size(); i++ ) { + for( Map.Entry entry : this.list.get(i).entrySet() ) { + if("".equals(entry.getKey())) { + ctx.setAttribute(prefix + '[' + i + ']', entry.getValue()); + } else { + ctx.setAttribute(prefix + '[' + i + "]." + entry.getKey(), entry.getValue()); + } + } + } + } + + + + // ========== PRIVATE STATIC FUNCTIONS ========== + + // TODO: javadoc + private static int getCtxListIndex( String key, String prefix, int list_size ) { + int index = getCtxListIndex( key, prefix ); + if( index >= list_size ) { + throw new IllegalArgumentException("Context memory list \"" + prefix + "[]\" contains an index >= the size of the list", new ArrayIndexOutOfBoundsException("index \"" + index + "\" is outside the bounds of the context memory list \"" + prefix + "[]. List Length = " + list_size)); + } else if (index < 0) { + throw new IllegalArgumentException("Context memory list \"" + prefix + "[]\" contains a negative index", new NegativeArraySizeException("index \"" + index + "\" of context memory list is negative")); + } + + return index; + } + + // TODO: javadoc + private static int getCtxListIndex( String key, String prefix ) { + String ctx_index_str = StringUtils.substringBetween(key.substring(prefix.length()), "[", "]"); + try { + return Integer.parseInt( ctx_index_str ); + } catch (NumberFormatException e) { + throw new IllegalStateException("Could not parse index value \"" + ctx_index_str + "\" in context memory key \"" + key + "\"", e); + } + } + + // TODO: javadoc + private static int getCtxListLength( SvcLogicContext ctx, String prefix ) { + String _length_key = prefix + "_length"; + String _length_val_str = ctx.getAttribute(_length_key); + try { + return Integer.parseInt(_length_val_str); + } catch (NumberFormatException e) { + if( _length_val_str == null ) { + throw new IllegalStateException( "Could not find list length \"" + _length_key + "\" in context memory." ); + } else { + throw new IllegalStateException( "Could not parse index value \"" + _length_val_str + "\" of context memory list length \"" + _length_key + "\"" , e ); + } + } + } +} diff --git a/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextObject.java b/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextObject.java new file mode 100644 index 000000000..aa41a5c60 --- /dev/null +++ b/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextObject.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.core.slipluginutils; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public interface SvcLogicContextObject { + void writeToContext(SvcLogicContext ctx, String root ); +} diff --git a/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/commondatastructures/YesNo.java b/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/commondatastructures/YesNo.java new file mode 100644 index 000000000..5db752e29 --- /dev/null +++ b/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/commondatastructures/YesNo.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +/** + * + */ +package org.onap.ccsdk.sli.core.slipluginutils.commondatastructures; + +/** + * An enum found in many Yang models. It is commonly used as a + * substitute for boolean. + */ +public enum YesNo { + N, Y; + + /** + * Method overload for {@link #valueOf(String)} for the char primative + */ + public static YesNo valueOf( final char name ) { + return YesNo.valueOf( Character.toString(name) ); + } + + /** + * Method overload for {@link #valueOf(String)} for the Character object + */ + public static YesNo valueOf( final Character name ) { + if( name == null ) { + return null; + } + + return YesNo.valueOf( name.toString() ); + } +} diff --git a/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/commondatastructures/package-info.java b/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/commondatastructures/package-info.java new file mode 100644 index 000000000..2aa949b03 --- /dev/null +++ b/core/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/commondatastructures/package-info.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +/** + * + */ +/** + * + */ +package org.onap.ccsdk.sli.core.slipluginutils.commondatastructures; diff --git a/core/sliPluginUtils/provider/src/main/resources/OSGI-INF/blueprint/slipluginutils-blueprint.xml b/core/sliPluginUtils/provider/src/main/resources/OSGI-INF/blueprint/slipluginutils-blueprint.xml new file mode 100644 index 000000000..534b92c93 --- /dev/null +++ b/core/sliPluginUtils/provider/src/main/resources/OSGI-INF/blueprint/slipluginutils-blueprint.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/core/sliPluginUtils/provider/src/main/resources/org/opendaylight/blueprint/slipluginutils-blueprint.xml b/core/sliPluginUtils/provider/src/main/resources/org/opendaylight/blueprint/slipluginutils-blueprint.xml new file mode 100644 index 000000000..534b92c93 --- /dev/null +++ b/core/sliPluginUtils/provider/src/main/resources/org/opendaylight/blueprint/slipluginutils-blueprint.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_StaticFunctionsTest.java b/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_StaticFunctionsTest.java new file mode 100644 index 000000000..42e7ceb94 --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_StaticFunctionsTest.java @@ -0,0 +1,591 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.core.slipluginutils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.slipluginutils.SliPluginUtils.LogLevel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.google.gson.JsonObject; + +public class SliPluginUtils_StaticFunctionsTest { + private static final Logger LOG = LoggerFactory.getLogger(SliPluginUtils_StaticFunctionsTest.class); + SliPluginUtils utils = new SliPluginUtils(); + private SvcLogicContext ctx; + private HashMap parameters; + + @Before + public void setUp() throws Exception { + this.ctx = new SvcLogicContext(); + parameters = new HashMap(); + } + + // TODO: javadoc + @Test + public final void testCtxGetBeginsWith() { + ctx.setAttribute("service-data.oper-status.order-status", "InProgress"); + ctx.setAttribute("service-data.service-information.service-instance-id", "my-instance"); + ctx.setAttribute("service-data.service-information.service-type", "my-service"); + + Map entries = SliPluginUtils.ctxGetBeginsWith(ctx, "service-data.service-information"); + + assertEquals("my-instance", entries.get("service-data.service-information.service-instance-id")); + assertEquals("my-service", entries.get("service-data.service-information.service-type")); + assertFalse(entries.containsKey("service-data.oper-status.order-status")); + } + + // TODO: javadoc + @Test + public final void testCtxListRemove_index() throws SvcLogicException { + LOG.trace("=== testCtxListRemove_index ==="); + ctx.setAttribute("service-data.vnf-l3[0].vnf-host-name", "vnf-host-name_0"); + ctx.setAttribute("service-data.vnf-l3[0].device-host-name", "device-host-name_0"); + ctx.setAttribute("service-data.vnf-l3[1].vnf-host-name", "vnf-host-name_1"); + ctx.setAttribute("service-data.vnf-l3[1].device-host-name", "device-host-name_1"); + ctx.setAttribute("service-data.vnf-l3[2].vnf-host-name", "vnf-host-name_2"); + ctx.setAttribute("service-data.vnf-l3[2].device-host-name", "device-host-name_2"); + ctx.setAttribute("service-data.vnf-l3_length", "3"); + + parameters.put("index", "1"); + parameters.put("list_pfx", "service-data.vnf-l3"); + + utils.ctxListRemove(parameters, ctx); + SliPluginUtils.logContextMemory(ctx, LOG, SliPluginUtils.LogLevel.TRACE); + + assertEquals("2", ctx.getAttribute("service-data.vnf-l3_length")); + assertEquals("vnf-host-name_0", ctx.getAttribute("service-data.vnf-l3[0].vnf-host-name")); + assertEquals("device-host-name_0", ctx.getAttribute("service-data.vnf-l3[0].device-host-name")); + assertEquals("vnf-host-name_2", ctx.getAttribute("service-data.vnf-l3[1].vnf-host-name")); + assertEquals("device-host-name_2", ctx.getAttribute("service-data.vnf-l3[1].device-host-name")); + } + + // TODO: javadoc + @Test + public final void textCtxListRemove_keyValue() throws SvcLogicException { + LOG.trace("=== textCtxListRemove_keyValue ==="); + ctx.setAttribute("service-data.vnf-l3[0].vnf-host-name", "vnf-host-name_0"); + ctx.setAttribute("service-data.vnf-l3[0].device-host-name", "device-host-name_0"); + ctx.setAttribute("service-data.vnf-l3[1].vnf-host-name", "vnf-host-name_1"); + ctx.setAttribute("service-data.vnf-l3[1].device-host-name", "device-host-name_1"); + ctx.setAttribute("service-data.vnf-l3[2].vnf-host-name", "vnf-host-name_2"); + ctx.setAttribute("service-data.vnf-l3[2].device-host-name", "device-host-name_2"); + // 2nd entry + ctx.setAttribute("service-data.vnf-l3[3].vnf-host-name", "vnf-host-name_1"); + ctx.setAttribute("service-data.vnf-l3[3].device-host-name", "device-host-name_1"); + ctx.setAttribute("service-data.vnf-l3_length", "4"); + + parameters.put("list_pfx", "service-data.vnf-l3"); + parameters.put("key", "vnf-host-name"); + parameters.put("value", "vnf-host-name_1"); + + utils.ctxListRemove(parameters, ctx); + SliPluginUtils.logContextMemory(ctx, LOG, SliPluginUtils.LogLevel.TRACE); + + assertEquals("2", ctx.getAttribute("service-data.vnf-l3_length")); + assertEquals("vnf-host-name_0", ctx.getAttribute("service-data.vnf-l3[0].vnf-host-name")); + assertEquals("device-host-name_0", ctx.getAttribute("service-data.vnf-l3[0].device-host-name")); + assertEquals("vnf-host-name_2", ctx.getAttribute("service-data.vnf-l3[1].vnf-host-name")); + assertEquals("device-host-name_2", ctx.getAttribute("service-data.vnf-l3[1].device-host-name")); + } + + // TODO: javadoc + @Test + public final void textCtxListRemove_keyValue_nullkey() throws SvcLogicException { + LOG.trace("=== textCtxListRemove_keyValue_nullkey ==="); + ctx.setAttribute("service-data.vnf-l3[0]", "vnf-host-name_0"); + ctx.setAttribute("service-data.vnf-l3[1]", "vnf-host-name_1"); + ctx.setAttribute("service-data.vnf-l3[2]", "vnf-host-name_2"); + ctx.setAttribute("service-data.vnf-l3_length", "3"); + + parameters.put("list_pfx", "service-data.vnf-l3"); + parameters.put("value", "vnf-host-name_1"); + + utils.ctxListRemove(parameters, ctx); + SliPluginUtils.logContextMemory(ctx, LOG, SliPluginUtils.LogLevel.TRACE); + + assertEquals("2", ctx.getAttribute("service-data.vnf-l3_length")); + assertEquals("vnf-host-name_0", ctx.getAttribute("service-data.vnf-l3[0]")); + assertEquals("vnf-host-name_2", ctx.getAttribute("service-data.vnf-l3[1]")); + } + + // TODO: javadoc + @Test + public final void textCtxListRemove_keyValueList() throws SvcLogicException { + LOG.trace("=== textCtxListRemove_keyValueList ==="); + ctx.setAttribute("service-data.vnf-l3[0].vnf-host-name", "vnf-host-name_0"); + ctx.setAttribute("service-data.vnf-l3[0].device-host-name", "device-host-name_0"); + ctx.setAttribute("service-data.vnf-l3[1].vnf-host-name", "vnf-host-name_1"); + ctx.setAttribute("service-data.vnf-l3[1].device-host-name", "device-host-name_1"); + ctx.setAttribute("service-data.vnf-l3[2].vnf-host-name", "vnf-host-name_2"); + ctx.setAttribute("service-data.vnf-l3[2].device-host-name", "device-host-name_2"); + // 2nd entry + ctx.setAttribute("service-data.vnf-l3[3].vnf-host-name", "vnf-host-name_1"); + ctx.setAttribute("service-data.vnf-l3[3].device-host-name", "device-host-name_1"); + // entries with only 1 of 2 key-value pairs matching + ctx.setAttribute("service-data.vnf-l3[4].vnf-host-name", "vnf-host-name_1"); + ctx.setAttribute("service-data.vnf-l3[4].device-host-name", "device-host-name_4"); + ctx.setAttribute("service-data.vnf-l3[5].vnf-host-name", "vnf-host-name_5"); + ctx.setAttribute("service-data.vnf-l3[5].device-host-name", "device-host-name_1"); + ctx.setAttribute("service-data.vnf-l3_length", "6"); + + parameters.put("list_pfx", "service-data.vnf-l3"); + parameters.put("keys_length", "2"); + parameters.put("keys[0].key", "vnf-host-name"); + parameters.put("keys[0].value", "vnf-host-name_1"); + parameters.put("keys[1].key", "device-host-name"); + parameters.put("keys[1].value", "device-host-name_1"); + + utils.ctxListRemove(parameters, ctx); + SliPluginUtils.logContextMemory(ctx, LOG, SliPluginUtils.LogLevel.TRACE); + + assertEquals("4", ctx.getAttribute("service-data.vnf-l3_length")); + assertEquals("vnf-host-name_0", ctx.getAttribute("service-data.vnf-l3[0].vnf-host-name")); + assertEquals("device-host-name_0", ctx.getAttribute("service-data.vnf-l3[0].device-host-name")); + assertEquals("vnf-host-name_2", ctx.getAttribute("service-data.vnf-l3[1].vnf-host-name")); + assertEquals("device-host-name_2", ctx.getAttribute("service-data.vnf-l3[1].device-host-name")); + assertEquals("vnf-host-name_1", ctx.getAttribute("service-data.vnf-l3[2].vnf-host-name")); + assertEquals("device-host-name_4", ctx.getAttribute("service-data.vnf-l3[2].device-host-name")); + assertEquals("vnf-host-name_5", ctx.getAttribute("service-data.vnf-l3[3].vnf-host-name")); + assertEquals("device-host-name_1", ctx.getAttribute("service-data.vnf-l3[3].device-host-name")); + } + + // TODO: javadoc + @Test(expected = SvcLogicException.class) + public final void testCtxListRemove_nullListLength() throws SvcLogicException { + LOG.trace("=== testCtxListRemove_nullListLength ==="); + ctx.setAttribute("service-data.vnf-l3[0].vnf-host-name", "vnf-host-name_0"); + ctx.setAttribute("service-data.vnf-l3[0].device-host-name", "device-host-name_0"); + ctx.setAttribute("service-data.vnf-l3[1].vnf-host-name", "vnf-host-name_1"); + ctx.setAttribute("service-data.vnf-l3[1].device-host-name", "device-host-name_1"); + ctx.setAttribute("service-data.vnf-l3[2].vnf-host-name", "vnf-host-name_2"); + ctx.setAttribute("service-data.vnf-l3[2].device-host-name", "device-host-name_2"); + + parameters.put("index", "1"); + parameters.put("list_pfx", "service-data.vnf-l3"); + + utils.ctxListRemove(parameters, ctx); + } + + // TODO: javadoc + @Test + public final void testCtxPutAll() { + HashMap entries = new HashMap(); + entries.put("service-data.oper-status.order-status", "InProgress"); + entries.put("service-data.service-information.service-instance-id", "my-instance"); + entries.put("service-data.request-information.order-number", 1234); + entries.put("service-data.request-information.request-id", null); + + SliPluginUtils.ctxPutAll(ctx, entries); + + assertEquals("InProgress", ctx.getAttribute("service-data.oper-status.order-status")); + assertEquals("my-instance", ctx.getAttribute("service-data.service-information.service-instance-id")); + assertEquals("1234", ctx.getAttribute("service-data.request-information.order-number")); + assertFalse(ctx.getAttributeKeySet().contains("service-data.request-information.request-id")); + } + + // TODO: javadoc + @Test + public final void testCtxSetAttribute_LOG() { + LOG.debug("=== testCtxSetAttribute_LOG ==="); + Integer i = new Integer(3); + SliPluginUtils.ctxSetAttribute(ctx, "test", i, LOG, SliPluginUtils.LogLevel.TRACE); + } + + @Test + public void setTime() throws SvcLogicException { + String outputPath = "output"; + parameters.put("outputPath", outputPath); + SliPluginUtils.setTime(parameters, ctx); + assertNotNull(ctx.getAttribute(outputPath)); + } + + @Test + public void containsKey() throws Exception { + ctx = new SvcLogicContext(); + parameters.put(SliStringUtils.INPUT_PARAM_KEY, "key_does_not_exist"); + String result = SliPluginUtils.containsKey(parameters, ctx); + assertEquals(SliStringUtils.FALSE_CONSTANT, result); + + ctx.setAttribute("a", null); + parameters.put(SliStringUtils.INPUT_PARAM_KEY, "a"); + result = SliPluginUtils.containsKey(parameters, ctx); + assertEquals(SliStringUtils.FALSE_CONSTANT, result); + + ctx.setAttribute("a", "hellworld"); + parameters.put(SliStringUtils.INPUT_PARAM_KEY, "a"); + result = SliPluginUtils.containsKey(parameters, ctx); + assertEquals(SliStringUtils.TRUE_CONSTANT, result); + } + + @Test + public void testGetAttributeValue() throws Exception { + parameters.put("outputPath", "testPath"); + parameters.put("source", "testSource"); + SliPluginUtils.getAttributeValue(parameters, ctx); + assertNull(ctx.getAttribute(parameters.get("outputPath"))); + } + + @Test + public void testCtxListContains() throws Exception { + parameters.put("list", "10_length"); + parameters.put("keyName", "testName"); + parameters.put("keyValue", "testValue"); + ctx.setAttribute("10_length", "10"); + assertEquals("false", SliPluginUtils.ctxListContains(parameters, ctx)); + + } + + @Test(expected = SvcLogicException.class) + public void testPrintContextForEmptyParameters() throws SvcLogicException { + SliPluginUtils.printContext(parameters, ctx); + } + + @Test(expected = SvcLogicException.class) + public void testPrintContextForNullParameters() throws SvcLogicException { + SliPluginUtils.printContext(null, ctx); + } + + @Test + public void testPrintContext() throws SvcLogicException { + parameters.put("filename", "testFileName"); + SliPluginUtils.printContext(parameters, ctx); + } + + @Test + public void testCtxKeyEmpty() { + ctx.setAttribute("key", ""); + assertTrue(SliPluginUtils.ctxKeyEmpty(ctx, "key")); + } + + @Test + public void testGetArrayLength() { + ctx.setAttribute("key_length", "test"); + Logger log = LoggerFactory.getLogger(getClass()); + SliPluginUtils.getArrayLength(ctx, "key", log, LogLevel.INFO, "invalid input"); + } + + @Test + public void testSetPropertiesForRoot() { + Map parameters = new HashMap<>(); + parameters.put("root", "RootVal"); + parameters.put("valueRoot", "ValueRootVal"); + assertEquals(SvcLogicConstants.SUCCESS, SliPluginUtils.setPropertiesForRoot(parameters, ctx)); + } + + @Test + public void testJsonStringToCtxToplevelArray() throws Exception { + String path = "src/test/resources/ArrayMenu.json"; + String content = new String(Files.readAllBytes(Paths.get(path))); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("input", content); + Map parameters = new HashMap(); + parameters.put("outputPath", "testPath"); + parameters.put("isEscaped", "false"); + parameters.put("source", "input"); + + SliPluginUtils.jsonStringToCtx(parameters, ctx); + + assertEquals("1000", ctx.getAttribute("testPath.[0].calories")); + assertEquals("1", ctx.getAttribute("testPath.[0].id")); + assertEquals("plain", ctx.getAttribute("testPath.[0].name")); + assertEquals("pizza", ctx.getAttribute("testPath.[0].type")); + assertEquals("true", ctx.getAttribute("testPath.[0].vegetarian")); + assertEquals(SliPluginUtils.CTX_NULL_VALUE, ctx.getAttribute("testPath.[1].calories")); + assertEquals("2", ctx.getAttribute("testPath.[1].id")); + assertEquals("Tuesday Special", ctx.getAttribute("testPath.[1].name")); + assertEquals("1", ctx.getAttribute("testPath.[1].topping[0].id")); + assertEquals("onion", ctx.getAttribute("testPath.[1].topping[0].name")); + assertEquals("2", ctx.getAttribute("testPath.[1].topping[1].id")); + assertEquals("pepperoni", ctx.getAttribute("testPath.[1].topping[1].name")); + assertEquals("2", ctx.getAttribute("testPath.[1].topping_length")); + assertEquals("pizza", ctx.getAttribute("testPath.[1].type")); + assertEquals("false", ctx.getAttribute("testPath.[1].vegetarian")); + assertEquals("1500", ctx.getAttribute("testPath.[2].calories")); + assertEquals("3", ctx.getAttribute("testPath.[2].id")); + assertEquals("House Special", ctx.getAttribute("testPath.[2].name")); + assertEquals("3", ctx.getAttribute("testPath.[2].topping[0].id")); + assertEquals("basil", ctx.getAttribute("testPath.[2].topping[0].name")); + assertEquals("4", ctx.getAttribute("testPath.[2].topping[1].id")); + assertEquals("fresh mozzarella", ctx.getAttribute("testPath.[2].topping[1].name")); + assertEquals("5", ctx.getAttribute("testPath.[2].topping[2].id")); + assertEquals("tomato", ctx.getAttribute("testPath.[2].topping[2].name")); + assertEquals("3", ctx.getAttribute("testPath.[2].topping_length")); + assertEquals("pizza", ctx.getAttribute("testPath.[2].type")); + assertEquals("true", ctx.getAttribute("testPath.[2].vegetarian")); + assertEquals("3", ctx.getAttribute("testPath._length")); + } + + @Test + public void testJsonStringToCtx() throws Exception { + String path = "src/test/resources/ObjectMenu.json"; + String content = new String(Files.readAllBytes(Paths.get(path))); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("input", content); + + Map parameters = new HashMap(); + parameters.put("outputPath", "testPath"); + parameters.put("isEscaped", "false"); + parameters.put("source", "input"); + + SliPluginUtils.jsonStringToCtx(parameters, ctx); + + + assertEquals("1000", ctx.getAttribute("testPath.menu[0].calories")); + assertEquals("1", ctx.getAttribute("testPath.menu[0].id")); + assertEquals("plain", ctx.getAttribute("testPath.menu[0].name")); + assertEquals("pizza", ctx.getAttribute("testPath.menu[0].type")); + assertEquals("true", ctx.getAttribute("testPath.menu[0].vegetarian")); + assertEquals("2000", ctx.getAttribute("testPath.menu[1].calories")); + assertEquals("2", ctx.getAttribute("testPath.menu[1].id")); + assertEquals("Tuesday Special", ctx.getAttribute("testPath.menu[1].name")); + assertEquals("1", ctx.getAttribute("testPath.menu[1].topping[0].id")); + assertEquals("onion", ctx.getAttribute("testPath.menu[1].topping[0].name")); + assertEquals("2", ctx.getAttribute("testPath.menu[1].topping[1].id")); + assertEquals("pepperoni", ctx.getAttribute("testPath.menu[1].topping[1].name")); + assertEquals("2", ctx.getAttribute("testPath.menu[1].topping_length")); + assertEquals("pizza", ctx.getAttribute("testPath.menu[1].type")); + assertEquals("false", ctx.getAttribute("testPath.menu[1].vegetarian")); + assertEquals("1500", ctx.getAttribute("testPath.menu[2].calories")); + assertEquals("3", ctx.getAttribute("testPath.menu[2].id")); + assertEquals("House Special", ctx.getAttribute("testPath.menu[2].name")); + assertEquals("3", ctx.getAttribute("testPath.menu[2].topping[0].id")); + assertEquals("basil", ctx.getAttribute("testPath.menu[2].topping[0].name")); + assertEquals("4", ctx.getAttribute("testPath.menu[2].topping[1].id")); + assertEquals("fresh mozzarella", ctx.getAttribute("testPath.menu[2].topping[1].name")); + assertEquals("5", ctx.getAttribute("testPath.menu[2].topping[2].id")); + assertEquals("tomato", ctx.getAttribute("testPath.menu[2].topping[2].name")); + assertEquals("3", ctx.getAttribute("testPath.menu[2].topping_length")); + assertEquals("pizza", ctx.getAttribute("testPath.menu[2].type")); + assertEquals("true", ctx.getAttribute("testPath.menu[2].vegetarian")); + assertEquals("3", ctx.getAttribute("testPath.menu_length")); + } + + @Test + public void test2dJsonStringToCtx() throws Exception { + String path = "src/test/resources/2dArray.json"; + String content = new String(Files.readAllBytes(Paths.get(path))); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("input", content); + + Map parameters = new HashMap(); + parameters.put("outputPath", "testPath"); + parameters.put("isEscaped", "false"); + parameters.put("source", "input"); + + SliPluginUtils.jsonStringToCtx(parameters, ctx); + assertEquals("apple", ctx.getAttribute("testPath.[0][0]")); + assertEquals("orange", ctx.getAttribute("testPath.[0][1]")); + assertEquals("banana", ctx.getAttribute("testPath.[0][2]")); + assertEquals(SliPluginUtils.CTX_NULL_VALUE, ctx.getAttribute("testPath.[0][3]")); + assertEquals("4", ctx.getAttribute("testPath.[0]_length")); + assertEquals("squash", ctx.getAttribute("testPath.[1][0]")); + assertEquals("broccoli", ctx.getAttribute("testPath.[1][1]")); + assertEquals("cauliflower", ctx.getAttribute("testPath.[1][2]")); + assertEquals("3", ctx.getAttribute("testPath.[1]_length")); + assertEquals("2", ctx.getAttribute("testPath._length")); + } + + @Test + public void test3dJsonStringToCtx() throws Exception { + String path = "src/test/resources/3dArray.json"; + String content = new String(Files.readAllBytes(Paths.get(path))); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("input", content); + + Map parameters = new HashMap(); + parameters.put("outputPath", "testPath"); + parameters.put("isEscaped", "false"); + parameters.put("source", "input"); + + SliPluginUtils.jsonStringToCtx(parameters, ctx); + assertEquals("a", ctx.getAttribute("testPath.[0][0][0]")); + assertEquals("b", ctx.getAttribute("testPath.[0][0][1]")); + assertEquals("c", ctx.getAttribute("testPath.[0][0][2]")); + assertEquals("3", ctx.getAttribute("testPath.[0][0]_length")); + assertEquals("d", ctx.getAttribute("testPath.[0][1][0]")); + assertEquals("e", ctx.getAttribute("testPath.[0][1][1]")); + assertEquals("f", ctx.getAttribute("testPath.[0][1][2]")); + assertEquals("3", ctx.getAttribute("testPath.[0][1]_length")); + assertEquals("2", ctx.getAttribute("testPath.[0]_length")); + assertEquals("x", ctx.getAttribute("testPath.[1][0][0]")); + assertEquals("y", ctx.getAttribute("testPath.[1][0][1]")); + assertEquals("z", ctx.getAttribute("testPath.[1][0][2]")); + assertEquals("3", ctx.getAttribute("testPath.[1][0]_length")); + assertEquals("1", ctx.getAttribute("testPath.[1]_length")); + assertEquals("2", ctx.getAttribute("testPath._length")); + } + + @Test + public void testJsonWidgetStringToCtx() throws Exception { + String path = "src/test/resources/Widget.json"; + String content = new String(Files.readAllBytes(Paths.get(path))); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("input", content); + + Map parameters = new HashMap(); + parameters.put("outputPath", "testPath"); + parameters.put("isEscaped", "false"); + parameters.put("source", "input"); + + SliPluginUtils.jsonStringToCtx(parameters, ctx); + assertEquals("false", ctx.getAttribute("testPath.widget.debug")); + assertEquals("center", ctx.getAttribute("testPath.widget.image.alignment")); + assertEquals("150", ctx.getAttribute("testPath.widget.image.hOffset")); + assertEquals("moon", ctx.getAttribute("testPath.widget.image.name")); + assertEquals("images/moon.png", ctx.getAttribute("testPath.widget.image.src")); + assertEquals("150", ctx.getAttribute("testPath.widget.image.vOffset")); + assertEquals("center", ctx.getAttribute("testPath.widget.text.alignment")); + assertEquals("Click Me", ctx.getAttribute("testPath.widget.text.data")); + assertEquals("350", ctx.getAttribute("testPath.widget.text.hOffset")); + assertEquals("text1", ctx.getAttribute("testPath.widget.text.name")); + assertEquals("21", ctx.getAttribute("testPath.widget.text.size")); + assertEquals("bold", ctx.getAttribute("testPath.widget.text.style")); + assertEquals(SliPluginUtils.CTX_NULL_VALUE, ctx.getAttribute("testPath.widget.text.vOffset")); + assertEquals("300", ctx.getAttribute("testPath.widget.window.height")); + assertEquals("main_window", ctx.getAttribute("testPath.widget.window.name")); + assertEquals("ONAP Widget", ctx.getAttribute("testPath.widget.window.title")); + assertEquals("200", ctx.getAttribute("testPath.widget.window.width")); + } + + @Test + public void testUpdateJsonObjectString() throws Exception { + String path = "src/test/resources/JsonObject.json"; + String content = new String(Files.readAllBytes(Paths.get(path))); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("input", content); + + Map parametersUpdateJson = new HashMap(); + parametersUpdateJson.put("source", "input"); + parametersUpdateJson.put("outputPath", "newJsonString"); + + // add key "ccc" and its value + parametersUpdateJson.put("add.ccc", "abcxyz"); + + // update keys and their values of "aaa" and "c.d" + parametersUpdateJson.put("add.aaa", "4567"); + parametersUpdateJson.put("add.c.d", "defg"); + + // delete key "bbb" + parametersUpdateJson.put("delete.bbb", ""); + + SliPluginUtils.updateJsonObjectString(parametersUpdateJson, ctx); + + Map parametersJsonToCtx = new HashMap(); + parametersJsonToCtx.put("source", "newJsonString"); + parametersJsonToCtx.put("outputPath", "testPath"); + parametersJsonToCtx.put("isEscaped", "false"); + + SliPluginUtils.jsonStringToCtx(parametersJsonToCtx, ctx); + + assertEquals("abcxyz", ctx.getAttribute("testPath.ccc")); + assertEquals("4567", ctx.getAttribute("testPath.aaa")); + assertEquals("defg", ctx.getAttribute("testPath.c.d")); + assertEquals(null, ctx.getAttribute("testPath.bbb")); + } + + @Test + public void testEmbeddedEscapedJsonJsonStringToCtx() throws Exception { + String path = "src/test/resources/EmbeddedEscapedJson.json"; + String content = new String(Files.readAllBytes(Paths.get(path))); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("input", content); + + Map parameters = new HashMap(); + parameters.put("outputPath", "testPath"); + parameters.put("isEscaped", "false"); + parameters.put("source", "input"); + + SliPluginUtils.jsonStringToCtx(parameters, ctx); + + assertEquals("escapedJsonObject", ctx.getAttribute("testPath.input.parameters[0].name")); + assertEquals("[{\"id\":\"0.2.0.0/16\"},{\"id\":\"ge04::/64\"}]", + ctx.getAttribute("testPath.input.parameters[0].value")); + assertEquals("Hello/World", ctx.getAttribute("testPath.input.parameters[1].value")); + assertEquals("resourceName", ctx.getAttribute("testPath.input.parameters[2].name")); + assertEquals("The\t\"Best\"\tName", ctx.getAttribute("testPath.input.parameters[2].value")); + assertEquals("3", ctx.getAttribute("testPath.input.parameters_length")); + + + // Break the embedded json object into properties + parameters.put("outputPath", "testPath.input.parameters[0].value"); + parameters.put("source", "testPath.input.parameters[0].value"); + SliPluginUtils.jsonStringToCtx(parameters, ctx); + + assertEquals("0.2.0.0/16", ctx.getAttribute("testPath.input.parameters[0].value.[0].id")); + assertEquals("ge04::/64", ctx.getAttribute("testPath.input.parameters[0].value.[1].id")); + assertEquals("2", ctx.getAttribute("testPath.input.parameters[0].value._length")); + } + + @Test + public void testEscapedJsonStringToCtx() throws Exception { + String path = "src/test/resources/EscapedJson.json"; + String content = new String(Files.readAllBytes(Paths.get(path))); + + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("input", content); + + Map parameters = new HashMap(); + parameters.put("outputPath", "testPath"); + parameters.put("isEscaped", "true"); // set to true because the entire json content has been escaped + parameters.put("source", "input"); + + + SliPluginUtils.jsonStringToCtx(parameters, ctx); + assertEquals("false", ctx.getAttribute("testPath.widget.debug")); + assertEquals("center", ctx.getAttribute("testPath.widget.image.alignment")); + assertEquals("150", ctx.getAttribute("testPath.widget.image.hOffset")); + assertEquals("moon", ctx.getAttribute("testPath.widget.image.name")); + assertEquals("images/moon.png", ctx.getAttribute("testPath.widget.image.src")); + assertEquals("150", ctx.getAttribute("testPath.widget.image.vOffset")); + assertEquals("center", ctx.getAttribute("testPath.widget.text.alignment")); + assertEquals("Click Me", ctx.getAttribute("testPath.widget.text.data")); + assertEquals("350", ctx.getAttribute("testPath.widget.text.hOffset")); + assertEquals("text1", ctx.getAttribute("testPath.widget.text.name")); + assertEquals("21", ctx.getAttribute("testPath.widget.text.size")); + assertEquals("bold", ctx.getAttribute("testPath.widget.text.style")); + assertEquals("200", ctx.getAttribute("testPath.widget.text.vOffset")); + assertEquals("300", ctx.getAttribute("testPath.widget.window.height")); + assertEquals("main_window", ctx.getAttribute("testPath.widget.window.name")); + assertEquals("ONAP Widget", ctx.getAttribute("testPath.widget.window.title")); + assertEquals("200", ctx.getAttribute("testPath.widget.window.width")); + } + +} diff --git a/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_checkParametersTest.java b/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_checkParametersTest.java new file mode 100644 index 000000000..f92271f7c --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_checkParametersTest.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Modifications Copyright (C) 2018 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.ccsdk.sli.core.slipluginutils; + +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SliPluginUtils_checkParametersTest { + + @Test + public void nullRequiredParameters() throws Exception { + Map parametersMap = new HashMap(); + String[] requiredParams = null; + Logger Log = LoggerFactory.getLogger(SliPluginUtils.class); + SliPluginUtils.checkParameters(parametersMap, requiredParams, Log); + } + + @Test(expected = SvcLogicException.class) + public void emptyParametersMap() throws Exception { + Map parametersMap = new HashMap(); + String[] requiredParams = new String[] { "param1", "param2", "param3" }; + Logger Log = LoggerFactory.getLogger(SliPluginUtils.class); + SliPluginUtils.checkParameters(parametersMap, requiredParams, Log); + } + + @Test(expected = SvcLogicException.class) + public void paramNotFound() throws Exception { + Map parametersMap = new HashMap(); + parametersMap.put("tst", "me"); + String[] requiredParams = new String[] { "param1", "parm2", "param3" }; + Logger Log = LoggerFactory.getLogger(SliPluginUtils.class); + SliPluginUtils.checkParameters(parametersMap, requiredParams, Log); + } + + @Test + public void testSunnyRequiredParameters() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("param1", "hello"); + ctx.setAttribute("param2", "world"); + ctx.setAttribute("param3", "!"); + + Map parameters = new HashMap(); + parameters.put("param1", "dog"); + parameters.put("param2", "cat"); + parameters.put("param3", "fish"); + + SliPluginUtils.requiredParameters(parameters, ctx); + } + + @Test + public void testSunnyRequiredParametersWithPrefix() throws Exception { + String prefixValue = "my.unique.path."; + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute(prefixValue + "param1", "hello"); + ctx.setAttribute(prefixValue + "param2", "world"); + ctx.setAttribute(prefixValue + "param3", "!"); + + Map parameters = new HashMap(); + parameters.put("prefix", prefixValue); + parameters.put("param1", "dog"); + parameters.put("param2", "cat"); + parameters.put("param3", "fish"); + + SliPluginUtils.requiredParameters(parameters, ctx); + } + + @Test(expected = SvcLogicException.class) + public void testRainyMissingRequiredParameters() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("param1", "hello"); + ctx.setAttribute("param3", "!"); + + Map parameters = new HashMap(); + parameters.put("param1", null); + parameters.put("param2", null); + parameters.put("param3", null); + + SliPluginUtils.requiredParameters(parameters, ctx); + } + + @Test(expected = SvcLogicException.class) + public void testEmptyRequiredParameters() throws Exception { + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("param1", "hello"); + ctx.setAttribute("param3", "!"); + + Map parameters = new HashMap(); + + SliPluginUtils.requiredParameters(parameters, ctx); + } +} diff --git a/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortList.java b/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortList.java new file mode 100644 index 000000000..3d4469bf2 --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortList.java @@ -0,0 +1,149 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Modifications Copyright (C) 2018 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.ccsdk.sli.core.slipluginutils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import java.util.HashMap; +import java.util.Random; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicConstants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@SuppressWarnings("unused") +public class SliPluginUtils_ctxSortList { + private static final Logger LOG = LoggerFactory.getLogger(SliPluginUtils_ctxSortList.class); + SliPluginUtils utils = new SliPluginUtils(); + SvcLogicContext ctx; + HashMap parameters; + Random rand = new Random(); + + @Before + public void setUp() throws Exception { + this.ctx = new SvcLogicContext(); + this.parameters = new HashMap(); + } + + @Test + public final void list_of_containers() throws SvcLogicException { + this.parameters.put("list", "input.list"); + this.parameters.put("sort-fields", "sort-key"); + this.parameters.put("delimiter", ","); + + ctx.setAttribute("input.list_length", "10"); + for (int i = 0; i < 10; i++) { + this.ctx.setAttribute("input.list[" + i + "].sort-key", Integer.toString(rand.nextInt(10))); + this.ctx.setAttribute("input.list[" + i + "].value", Integer.toString(rand.nextInt(10))); + } + + LOG.trace("BEFORE SORT:"); + SliPluginUtils.logContextMemory(ctx, LOG, SliPluginUtils.LogLevel.TRACE); + + utils.ctxSortList(this.parameters, this.ctx); + + LOG.trace("AFTER SORT:"); + SliPluginUtils.logContextMemory(ctx, LOG, SliPluginUtils.LogLevel.TRACE); + + for (int i = 0; i < 9; i++) { + assertTrue(this.ctx.getAttribute("input.list[" + i + "].sort-key") + .compareTo(this.ctx.getAttribute("input.list[" + (i + 1) + "].sort-key")) < 1); + } + } + + @Test + public final void list_of_elements() throws SvcLogicException { + this.parameters.put("list", "input.list"); + this.parameters.put("delimiter", ","); + + this.ctx.setAttribute("input.list_length", "10"); + for (int i = 0; i < 10; i++) { + this.ctx.setAttribute("input.list[" + i + ']', Integer.toString(rand.nextInt(10))); + } + + LOG.trace("BEFORE SORT:"); + SliPluginUtils.logContextMemory(ctx, LOG, SliPluginUtils.LogLevel.TRACE); + + utils.ctxSortList(this.parameters, this.ctx); + + LOG.trace("AFTER SORT:"); + SliPluginUtils.logContextMemory(ctx, LOG, SliPluginUtils.LogLevel.TRACE); + + for (int i = 0; i < 9; i++) { + assertTrue(this.ctx.getAttribute("input.list[" + i + ']') + .compareTo(this.ctx.getAttribute("input.list[" + (i + 1) + ']')) < 1); + } + } + + @Test + public void testGenerateUUID() throws SvcLogicException { + SliPluginUtils utils = new SliPluginUtils(); + this.parameters.put("ctx-destination", "testDestination"); + utils.generateUUID(this.parameters, ctx); + } + + @Test + public void testSubstring() throws SvcLogicException { + SliPluginUtils utils = new SliPluginUtils(); + this.parameters.put("string", "testString"); + this.parameters.put("begin-index", "1"); + this.parameters.put("result", "testResult"); + this.parameters.put("end-index", "5"); + utils.substring(this.parameters, ctx); + assertEquals("estS", ctx.getAttribute("testResult")); + } + + @Test + public void testSubstringForNullEndIndex() throws SvcLogicException { + SliPluginUtils utils = new SliPluginUtils(); + this.parameters.put("string", "testString"); + this.parameters.put("begin-index", "1"); + this.parameters.put("result", "testResult"); + utils.substring(this.parameters, ctx); + assertEquals("estString", ctx.getAttribute("testResult")); + } + + @Test + public void testCtxBulkCopy() { + ctx.setAttribute("Mykey1", "MyValue1"); + ctx.setAttribute("Mykey2", "MyValue2"); + SliPluginUtils.ctxBulkCopy(ctx, "Mykey", "test."); + assertEquals("MyValue1", ctx.getAttribute("test.1")); + assertEquals("MyValue2", ctx.getAttribute("test.2")); + } + + @Test + public void testSetPropertiesForList() { + parameters.put("prefixKey", "testPrefixKey"); + parameters.put("valuePrefixKey", "testPrefixValue"); + parameters.put("keyName", "testKey"); + parameters.put("keyValue", "testValue"); + + assertEquals(SvcLogicConstants.SUCCESS, SliPluginUtils.setPropertiesForList(parameters, ctx)); + + } +} diff --git a/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortListTest.java b/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortListTest.java new file mode 100644 index 000000000..bf7cc1399 --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortListTest.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.core.slipluginutils; + +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.Random; + +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@SuppressWarnings("unused") +public class SliPluginUtils_ctxSortListTest { + private static final Logger LOG = LoggerFactory.getLogger(SliPluginUtils_ctxSortListTest.class); + SliPluginUtils utils = new SliPluginUtils(); + SvcLogicContext ctx; + HashMap parameters; + Random rand = new Random(); + + @Before + public void setUp() throws Exception { + this.ctx = new SvcLogicContext(); + this.parameters = new HashMap(); + } + + @Test + public final void list_of_containers() throws SvcLogicException { + this.parameters.put("list", "input.list"); + this.parameters.put("sort-fields", "sort-key"); + this.parameters.put("delimiter", ","); + + ctx.setAttribute("input.list_length", "10"); + for (int i = 0; i < 10; i++) { + this.ctx.setAttribute("input.list[" + i + "].sort-key", Integer.toString(rand.nextInt(10))); + this.ctx.setAttribute("input.list[" + i + "].value", Integer.toString(rand.nextInt(10))); + } + + LOG.trace("BEFORE SORT:"); + SliPluginUtils.logContextMemory(ctx, LOG, SliPluginUtils.LogLevel.TRACE); + + utils.ctxSortList(this.parameters, this.ctx); + + LOG.trace("AFTER SORT:"); + SliPluginUtils.logContextMemory(ctx, LOG, SliPluginUtils.LogLevel.TRACE); + + for (int i = 0; i < 9; i++) { + assertTrue(this.ctx.getAttribute("input.list[" + i + "].sort-key").compareTo(this.ctx.getAttribute("input.list[" + (i + 1) + "].sort-key")) < 1); + } + } + + @Test + public final void list_of_elements() throws SvcLogicException { + this.parameters.put("list", "input.list"); + this.parameters.put("delimiter", ","); + + this.ctx.setAttribute("input.list_length", "10"); + for (int i = 0; i < 10; i++) { + this.ctx.setAttribute("input.list[" + i + ']', Integer.toString(rand.nextInt(10))); + } + + LOG.trace("BEFORE SORT:"); + SliPluginUtils.logContextMemory(ctx, LOG, SliPluginUtils.LogLevel.TRACE); + + utils.ctxSortList(this.parameters, this.ctx); + + LOG.trace("AFTER SORT:"); + SliPluginUtils.logContextMemory(ctx, LOG, SliPluginUtils.LogLevel.TRACE); + + for (int i = 0; i < 9; i++) { + assertTrue(this.ctx.getAttribute("input.list[" + i + ']').compareTo(this.ctx.getAttribute("input.list[" + (i + 1) + ']')) < 1); + } + } +} diff --git a/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliStringUtilsTest.java b/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliStringUtilsTest.java new file mode 100644 index 000000000..da7046f43 --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliStringUtilsTest.java @@ -0,0 +1,398 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Modifications Copyright (C) 2018 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.ccsdk.sli.core.slipluginutils; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +/** + * @author km991u + * + */ +public class SliStringUtilsTest { + private SvcLogicContext ctx; + private HashMap param; + private SliStringUtils stringUtils = new SliStringUtils(); + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + this.ctx = new SvcLogicContext(); + param = new HashMap(); + } + + /** + * @throws SvcLogicException + * @see SliStringUtils#split(Map, SvcLogicContext) + */ + @Test + public final void testSplit() throws SvcLogicException { + param.put("original_string", "one ## two ## three"); + param.put("regex", " ## "); + param.put("ctx_memory_result_key", "result"); + + stringUtils.split(param, ctx); + + assertThat(ctx.getAttribute("result[0]"), equalTo("one")); + assertThat(ctx.getAttribute("result[1]"), equalTo("two")); + assertThat(ctx.getAttribute("result[2]"), equalTo("three")); + assertThat(ctx.getAttribute("result_length"), equalTo("3")); + } + + /** + * @throws SvcLogicException + * @see SliStringUtils#split(Map, SvcLogicContext) + */ + @Test + public final void testSplit_limit() throws SvcLogicException { + param.put("original_string", "one ## two ## three"); + param.put("regex", " ## "); + param.put("limit", "2"); + param.put("ctx_memory_result_key", "result"); + + stringUtils.split(param, ctx); + + assertThat(ctx.getAttribute("result[0]"), equalTo("one")); + assertThat(ctx.getAttribute("result[1]"), equalTo("two ## three")); + assertThat(ctx.getAttribute("result_length"), equalTo("2")); + } + + @Test + public final void testSubString() throws SvcLogicException { + param.put("string", "splitatgivenindex"); + param.put("begin-index", "0"); + param.put("end-index", "5"); + param.put("result", "result"); + + stringUtils.substring(param, ctx); + + assertEquals("split", ctx.getAttribute("result")); + } + + @Test + public final void testQuotedOrNull() throws SvcLogicException { + // param.put("nullString",null); + assertEquals("NULL", SliStringUtils.quotedOrNULL(null)); + } + + @Test + public void equalsIgnoreCaseTrue() throws SvcLogicException { + String sourceString = "HeLlOwORLD"; + String targetSTring = "HELLOWORLD"; + param.put("source", sourceString); + param.put("target", targetSTring); + assertEquals("true", SliStringUtils.equalsIgnoreCase(param, ctx)); + } + + @Test + public void equalsIgnoreCaseFalse() throws SvcLogicException { + String sourceString = "HeLlOwORLD"; + String targetSTring = "goodbyeWORLD"; + param.put("source", sourceString); + param.put("target", targetSTring); + assertEquals("false", SliStringUtils.equalsIgnoreCase(param, ctx)); + } + + @Test + public void toUpper() throws SvcLogicException { + String sourceString = "HeLlOwORLD"; + param.put("source", sourceString); + String path = "my.unique.path."; + param.put("outputPath", path); + SliStringUtils.toUpper(param, ctx); + assertEquals(sourceString.toUpperCase(), ctx.getAttribute(path)); + } + + @Test + public void toLower() throws SvcLogicException { + String sourceString = "HeLlOwORLD"; + param.put("source", sourceString); + String path = "my.unique.path."; + param.put("outputPath", path); + SliStringUtils.toLower(param, ctx); + assertEquals(sourceString.toLowerCase(), ctx.getAttribute(path)); + } + + @Test + public void containsTrue() throws SvcLogicException { + String sourceString = "Pizza"; + String targetSTring = "izza"; + param.put("source", sourceString); + param.put("target", targetSTring); + assertEquals("true", SliStringUtils.contains(param, ctx)); + } + + @Test + public void containsFalse() throws SvcLogicException { + String sourceString = "Pizza"; + String targetSTring = "muffin"; + param.put("source", sourceString); + param.put("target", targetSTring); + assertEquals("false", SliStringUtils.contains(param, ctx)); + } + + @Test + public void endsWithTrue() throws SvcLogicException { + String sourceString = "Pizza"; + String targetSTring = "za"; + param.put("source", sourceString); + param.put("target", targetSTring); + assertEquals("true", SliStringUtils.endsWith(param, ctx)); + } + + @Test + public void endsWithFalse() throws SvcLogicException { + String sourceString = "Pizza"; + String targetSTring = "muffin"; + param.put("source", sourceString); + param.put("target", targetSTring); + assertEquals("false", SliStringUtils.endsWith(param, ctx)); + } + + @Test + public void trim() throws SvcLogicException { + String sourceString = " H E L L O W O R L D"; + String outputPath = "muffin"; + param.put("source", sourceString); + param.put("outputPath", outputPath); + SliStringUtils.trim(param, ctx); + assertEquals(sourceString.trim(), ctx.getAttribute(outputPath)); + } + + @Test + public void getLength() throws SvcLogicException { + String sourceString = "SomeRandomString"; + String outputPath = "muffin"; + param.put("source", sourceString); + param.put("outputPath", outputPath); + SliStringUtils.getLength(param, ctx); + assertEquals(String.valueOf(sourceString.length()), ctx.getAttribute(outputPath)); + } + + @Test + public void startsWithFalse() throws SvcLogicException { + String sourceString = "Java"; + String targetSTring = "DG"; + param.put("source", sourceString); + param.put("target", targetSTring); + assertEquals("false", SliStringUtils.startsWith(param, ctx)); + } + + @Test + public void startsWithTrue() throws SvcLogicException { + String sourceString = "Java"; + String targetSTring = "Ja"; + param.put("source", sourceString); + param.put("target", targetSTring); + assertEquals("true", SliStringUtils.startsWith(param, ctx)); + } + + @Test + public void replace() throws SvcLogicException { + String sourceString = "cat Hello World cat"; + String old = "cat"; + String neww = "dog"; + String outputPath = "out"; + + param.put("source", sourceString); + param.put("target", old); + param.put("replacement", neww); + param.put("outputPath", outputPath); + SliStringUtils.replace(param, ctx); + assertEquals(sourceString.replace(old, neww), ctx.getAttribute(outputPath)); + } + + @Test + public void replaceAll() throws SvcLogicException { + String source = "cat Hello World cat"; + String target = "\\s"; + String replacement = ""; + String outputPath = "out"; + + param.put("source", source); + param.put("target", target); + param.put("replacement", replacement); + param.put("outputPath", outputPath); + SliStringUtils.replaceAll(param, ctx); + assertEquals(source.replaceAll(target, replacement), ctx.getAttribute(outputPath)); + } + + @Test + public void concat() throws SvcLogicException { + String sourceString = "cat"; + String targetString = "dog"; + String outputPath = "out"; + + param.put("source", sourceString); + param.put("target", targetString); + param.put("outputPath", outputPath); + SliStringUtils.concat(param, ctx); + assertEquals(sourceString + targetString, ctx.getAttribute(outputPath)); + } + + @Test + public void urlEncode() throws SvcLogicException { + String sourceString = "102/GE100/SNJSCAMCJP8/SNJSCAMCJT4"; + String outputPath = "out"; + + param.put("source", sourceString); + param.put("outputPath", outputPath); + SliStringUtils.urlEncode(param, ctx); + assertEquals("102%2FGE100%2FSNJSCAMCJP8%2FSNJSCAMCJT4", ctx.getAttribute(outputPath)); + } + + @Test + public void urlDecode() throws SvcLogicException { + String sourceString = "102%2FGE100%2FSNJSCAMCJP8%2FSNJSCAMCJT4"; + String outputPath = "out"; + + param.put("source", sourceString); + param.put("outputPath", outputPath); + SliStringUtils.urlDecode(param, ctx); + assertEquals("102/GE100/SNJSCAMCJP8/SNJSCAMCJT4", ctx.getAttribute(outputPath)); + } + + @Test + public void testXmlEscapeText() { + param.put("source", "102/GE100/SNJSCAMCJP8/SNJSCAMCJT4"); + param.put("target", "target"); + SliStringUtils.xmlEscapeText(param, ctx); + assertEquals("102/GE100/SNJSCAMCJP8/SNJSCAMCJT4", ctx.getAttribute("target")); + } + + @Test(expected = Exception.class) + public void testSplitForEmptyParams() throws Exception { + SliStringUtils utils = new SliStringUtils(); + ctx = new SvcLogicContext(); + param = new HashMap<>(); + utils.split(param, ctx); + } + + @Test(expected = Exception.class) + public void testSubstringForEmptyParams() throws Exception { + SliStringUtils utils = new SliStringUtils(); + ctx = new SvcLogicContext(); + param = new HashMap<>(); + utils.substring(param, ctx); + } + + @Test + public void testUnescapeJsonString() throws Exception { + String source = "{\\\"image_name\\\":\\\"Ubuntu 14.04\\\",\\\"service-instance-id\\\":\\\"1\\\",\\\"vnf-model-customization-uuid\\\":\\\"2f\\\",\\\"vnf-id\\\":\\\"3b\\\"}"; + param.put(SliStringUtils.INPUT_PARAM_SOURCE, source); + String outputPath = "unescaped"; + param.put(SliStringUtils.INPUT_PARAM_TARGET, outputPath); + SliStringUtils.unescapeJsonString(param, ctx); + assertEquals("{\"image_name\":\"Ubuntu 14.04\",\"service-instance-id\":\"1\",\"vnf-model-customization-uuid\":\"2f\",\"vnf-id\":\"3b\"}", ctx.getAttribute(outputPath)); + } + + @Test + public void testEscapeJsonString() throws Exception { + String source = "{\"image_name\":\"Ubuntu 14.04\",\"service-instance-id\":\"1\",\"vnf-model-customization-uuid\":\"2f\",\"vnf-id\":\"3b\"}"; + param.put(SliStringUtils.INPUT_PARAM_SOURCE, source); + String outputPath = "unescaped"; + param.put(SliStringUtils.INPUT_PARAM_TARGET, outputPath); + SliStringUtils.escapeJsonString(param, ctx); + assertEquals("{\\\"image_name\\\":\\\"Ubuntu 14.04\\\",\\\"service-instance-id\\\":\\\"1\\\",\\\"vnf-model-customization-uuid\\\":\\\"2f\\\",\\\"vnf-id\\\":\\\"3b\\\"}", ctx.getAttribute(outputPath)); + } + + @Test + public void isEmpty() throws Exception { + String result = SliStringUtils.isEmpty(param, ctx); + param.put(SliStringUtils.INPUT_PARAM_KEY, "key_does_not_exist"); + assertEquals(SliStringUtils.TRUE_CONSTANT, result); + + ctx.setAttribute("a", null); + param.put(SliStringUtils.INPUT_PARAM_KEY, "a"); + result = SliStringUtils.isEmpty(param, ctx); + assertEquals(SliStringUtils.TRUE_CONSTANT, result); + + ctx.setAttribute("a", ""); + result = SliStringUtils.isEmpty(param, ctx); + assertEquals(SliStringUtils.TRUE_CONSTANT, result); + + ctx.setAttribute("a", " "); + result = SliStringUtils.isEmpty(param, ctx); + assertEquals(SliStringUtils.FALSE_CONSTANT, result); + } + + @Test + public void isBlank() throws Exception { + String result = SliStringUtils.isBlank(param, ctx); + param.put(SliStringUtils.INPUT_PARAM_KEY, "key_does_not_exist"); + assertEquals(SliStringUtils.TRUE_CONSTANT, result); + + ctx.setAttribute("a", null); + param.put(SliStringUtils.INPUT_PARAM_KEY, "a"); + result = SliStringUtils.isBlank(param, ctx); + assertEquals(SliStringUtils.TRUE_CONSTANT, result); + + ctx.setAttribute("a", ""); + result = SliStringUtils.isBlank(param, ctx); + assertEquals(SliStringUtils.TRUE_CONSTANT, result); + + ctx.setAttribute("a", " "); + result = SliStringUtils.isBlank(param, ctx); + assertEquals(SliStringUtils.TRUE_CONSTANT, result); + } + + @Test + public void isNull() throws Exception { + String result = SliStringUtils.isNull(param, ctx); + param.put(SliStringUtils.INPUT_PARAM_KEY, "key_does_not_exist"); + assertEquals(SliStringUtils.TRUE_CONSTANT, result); + + ctx.setAttribute("a", null); + param.put(SliStringUtils.INPUT_PARAM_KEY, "a"); + result = SliStringUtils.isNull(param, ctx); + assertEquals(SliStringUtils.TRUE_CONSTANT, result); + + ctx.setAttribute("a", ""); + result = SliStringUtils.isNull(param, ctx); + assertEquals(SliStringUtils.FALSE_CONSTANT, result); + + ctx.setAttribute("a", " "); + result = SliStringUtils.isNull(param, ctx); + assertEquals(SliStringUtils.FALSE_CONSTANT, result); + } + + @Test + public void testBase64DecodingAlgo() throws Exception{ + String input = "MDUxMDAw"; + String decodeVal = "decodedPath"; + param.put("encodedValue",input); + param.put("decodedValue", decodeVal); + SliStringUtils.base64DecodingAlgo(param,ctx); + assertEquals("051000",ctx.getAttribute(decodeVal)); + } +} diff --git a/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextListTest.java b/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextListTest.java new file mode 100644 index 000000000..f916bbfca --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextListTest.java @@ -0,0 +1,307 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.core.slipluginutils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.HashMap; + +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class SvcLogicContextListTest { + //private static final Logger LOG = LoggerFactory.getLogger(SvcLogicContextTest.class); + private SvcLogicContext ctx; + + @Before + public void setUp() throws Exception { + this.ctx = new SvcLogicContext(); + } + + // TODO: javadoc + @Test + public final void testSvcLogicContextList_SingleValueList() { + ctx.setAttribute("list[0]", "0"); + ctx.setAttribute("list[1]", "1"); + ctx.setAttribute("list[2]", "2"); + ctx.setAttribute("list[3]", "3"); + ctx.setAttribute("list[4]", "4"); + ctx.setAttribute("list_length", "5"); + + SvcLogicContextList list = new SvcLogicContextList( ctx, "list" ); + + // Check that size of list is 5 + assertEquals(5, list.size()); + + // Check that each HashMap has it's list value in the empty string key + // and has no other values + assertEquals(1, list.get(0).size()); + assertEquals("0", list.get(0).get("")); + assertEquals(1, list.get(1).size()); + assertEquals("1", list.get(1).get("")); + assertEquals(1, list.get(2).size()); + assertEquals("2", list.get(2).get("")); + assertEquals(1, list.get(3).size()); + assertEquals("3", list.get(3).get("")); + assertEquals(1, list.get(4).size()); + assertEquals("4", list.get(4).get("")); + } + + // TODO: javadoc + @Test + public final void testSvcLogicContextList_ObjectList() { + ctx.setAttribute("list[0].ipv4", "1.1.1.0"); + ctx.setAttribute("list[0].ipv6", "2001::0"); + ctx.setAttribute("list[1].ipv4", "1.1.1.1"); + ctx.setAttribute("list[1].ipv6", "2001::1"); + ctx.setAttribute("list[2].ipv4", "1.1.1.2"); + ctx.setAttribute("list[2].ipv6", "2001::2"); + ctx.setAttribute("list[3].ipv4", "1.1.1.3"); + ctx.setAttribute("list[3].ipv6", "2001::3"); + ctx.setAttribute("list[4].ipv4", "1.1.1.4"); + ctx.setAttribute("list[4].ipv6", "2001::4"); + ctx.setAttribute("list_length", "5"); + + SvcLogicContextList list = new SvcLogicContextList( ctx, "list" ); + + // Check that size of list is 5 + assertEquals(5, list.size()); + + assertEquals(2, list.get(0).size()); + assertEquals("1.1.1.0", list.get(0).get("ipv4")); + assertEquals("2001::0", list.get(0).get("ipv6")); + assertEquals(2, list.get(1).size()); + assertEquals("1.1.1.1", list.get(1).get("ipv4")); + assertEquals("2001::1", list.get(1).get("ipv6")); + assertEquals(2, list.get(2).size()); + assertEquals("1.1.1.2", list.get(2).get("ipv4")); + assertEquals("2001::2", list.get(2).get("ipv6")); + assertEquals(2, list.get(3).size()); + assertEquals("1.1.1.3", list.get(3).get("ipv4")); + assertEquals("2001::3", list.get(3).get("ipv6")); + assertEquals(2, list.get(4).size()); + assertEquals("1.1.1.4", list.get(4).get("ipv4")); + assertEquals("2001::4", list.get(4).get("ipv6")); + } + + // TODO: javadoc + @Test + public final void testExtract() { + ctx.setAttribute("list[0]", "0"); + ctx.setAttribute("list[1]", "1"); + ctx.setAttribute("list[2]", "2"); + ctx.setAttribute("list[3]", "3"); + ctx.setAttribute("list[4]", "4"); + ctx.setAttribute("list_length", "5"); + ctx.setAttribute("Other", "other"); + + SvcLogicContextList list = SvcLogicContextList.extract(ctx, "list"); + + // Check that size of list is 5 + assertEquals(5, list.size()); + + // Check that all list values exist in list object + assertEquals(1, list.get(0).size()); + assertEquals("0", list.get(0).get("")); + assertEquals(1, list.get(1).size()); + assertEquals("1", list.get(1).get("")); + assertEquals(1, list.get(2).size()); + assertEquals("2", list.get(2).get("")); + assertEquals(1, list.get(3).size()); + assertEquals("3", list.get(3).get("")); + assertEquals(1, list.get(4).size()); + assertEquals("4", list.get(4).get("")); + + // Check that all list values no longer exist in ctx + assertNull(ctx.getAttribute("list[0]")); + assertNull(ctx.getAttribute("list[1]")); + assertNull(ctx.getAttribute("list[2]")); + assertNull(ctx.getAttribute("list[3]")); + assertNull(ctx.getAttribute("list[4]")); + assertNull(ctx.getAttribute("list_length")); + + // Check that non-list values still exist in ctx + assertEquals("other", ctx.getAttribute("Other")); + } + + // TODO: javadoc + @Test + public final void testRemove_int() { + ctx.setAttribute("list[0]", "0"); + ctx.setAttribute("list[1]", "1"); + ctx.setAttribute("list[2]", "2"); + ctx.setAttribute("list[3]", "3"); + ctx.setAttribute("list[4]", "4"); + ctx.setAttribute("list_length", "5"); + + SvcLogicContextList list = new SvcLogicContextList( ctx, "list" ); + list.remove(2); + + // Check that size of list is 4 (1 less than original) + assertEquals(4, list.size()); + + // Check that value was remove from list + assertEquals(1, list.get(0).size()); + assertEquals("0", list.get(0).get("")); + assertEquals(1, list.get(1).size()); + assertEquals("1", list.get(1).get("")); + assertEquals(1, list.get(2).size()); + assertEquals("3", list.get(2).get("")); + assertEquals(1, list.get(3).size()); + assertEquals("4", list.get(3).get("")); + } + + // TODO: javadoc + @Test + public final void testRemove_StringString() { + ctx.setAttribute("list[0].ipv4", "1.1.1.0"); + ctx.setAttribute("list[0].ipv6", "2001::0"); + ctx.setAttribute("list[1].ipv4", "1.1.1.1"); + ctx.setAttribute("list[1].ipv6", "2001::1"); + ctx.setAttribute("list[2].ipv4", "1.1.1.2"); + ctx.setAttribute("list[2].ipv6", "2001::2"); + ctx.setAttribute("list[3].ipv4", "1.1.1.3"); + ctx.setAttribute("list[3].ipv6", "2001::3"); + ctx.setAttribute("list[4].ipv4", "1.1.1.4"); + ctx.setAttribute("list[4].ipv6", "2001::4"); + ctx.setAttribute("list[5].ipv4", "1.1.1.2"); + ctx.setAttribute("list[5].ipv6", "2001::2"); + ctx.setAttribute("list_length", "6"); + + SvcLogicContextList list = new SvcLogicContextList( ctx, "list" ); + list.remove("ipv4", "1.1.1.2"); + + // Check that size of list is 4 (2 less than original) + assertEquals(4, list.size()); + + // Check that all elements with values ending in 2 were removed + assertEquals("1.1.1.0", list.get(0).get("ipv4")); + assertEquals("2001::0", list.get(0).get("ipv6")); + assertEquals("1.1.1.1", list.get(1).get("ipv4")); + assertEquals("2001::1", list.get(1).get("ipv6")); + assertEquals("1.1.1.3", list.get(2).get("ipv4")); + assertEquals("2001::3", list.get(2).get("ipv6")); + assertEquals("1.1.1.4", list.get(3).get("ipv4")); + assertEquals("2001::4", list.get(3).get("ipv6")); + } + + // TODO: javadoc + @Test + public final void testRemove_StringString_ValueList() { + ctx.setAttribute("list[0]", "5"); + ctx.setAttribute("list[1]", "6"); + ctx.setAttribute("list[2]", "7"); + ctx.setAttribute("list[3]", "8"); + ctx.setAttribute("list[4]", "9"); + ctx.setAttribute("list_length", "5"); + + SvcLogicContextList list = new SvcLogicContextList( ctx, "list" ); + list.remove("", "6"); + + // Check that size of list is 4 (1 less than original) + assertEquals(4, list.size()); + + // Check that value was remove from list + assertEquals(1, list.get(0).size()); + assertEquals("5", list.get(0).get("")); + assertEquals(1, list.get(1).size()); + assertEquals("7", list.get(1).get("")); + assertEquals(1, list.get(2).size()); + assertEquals("8", list.get(2).get("")); + assertEquals(1, list.get(3).size()); + assertEquals("9", list.get(3).get("")); + } + + // TODO: javadoc + @Test + public final void testRemove_Map() { + ctx.setAttribute("list[0].ipv4", "1.1.1.0"); + ctx.setAttribute("list[0].ipv6", "2001::0"); + ctx.setAttribute("list[1].ipv4", "1.1.1.1"); + ctx.setAttribute("list[1].ipv6", "2001::1"); + ctx.setAttribute("list[2].ipv4", "1.1.1.2"); + ctx.setAttribute("list[2].ipv6", "2001::2"); + ctx.setAttribute("list[3].ipv4", "1.1.1.3"); + ctx.setAttribute("list[3].ipv6", "2001::3"); + ctx.setAttribute("list[4].ipv4", "1.1.1.4"); + ctx.setAttribute("list[4].ipv6", "2001::4"); + ctx.setAttribute("list[5].ipv4", "1.1.1.2"); + ctx.setAttribute("list[5].ipv6", "2001::2"); + ctx.setAttribute("list_length", "6"); + + HashMap remove_key = new HashMap(); + remove_key.put("ipv4", "1.1.1.2"); + remove_key.put("ipv6", "2001::2"); + + SvcLogicContextList list = new SvcLogicContextList( ctx, "list" ); + list.remove(remove_key); + + // Check that size of list is 4 (2 less than original) + assertEquals(4, list.size()); + + // Check that all elements with values ending in 2 were removed + assertEquals("1.1.1.0", list.get(0).get("ipv4")); + assertEquals("2001::0", list.get(0).get("ipv6")); + assertEquals("1.1.1.1", list.get(1).get("ipv4")); + assertEquals("2001::1", list.get(1).get("ipv6")); + assertEquals("1.1.1.3", list.get(2).get("ipv4")); + assertEquals("2001::3", list.get(2).get("ipv6")); + assertEquals("1.1.1.4", list.get(3).get("ipv4")); + assertEquals("2001::4", list.get(3).get("ipv6")); + } + + // TODO: javadoc + @Test + public final void testWriteToContext() { + ctx.setAttribute("list[0]", "0"); + ctx.setAttribute("list[1]", "1"); + ctx.setAttribute("list[2]", "2"); + ctx.setAttribute("list[3]", "3"); + ctx.setAttribute("list[4]", "4"); + ctx.setAttribute("list_length", "5"); + ctx.setAttribute("Other", "other"); + + SvcLogicContextList list = new SvcLogicContextList( ctx, "list" ); + + // Erase context memory + ctx = new SvcLogicContext(); + + // Write list back into context memory + list.writeToContext(ctx); + + // Check that size of list is 5 + assertEquals(5, list.size()); + + // Check that all list values exist in list object + assertEquals("0", ctx.getAttribute("list[0]")); + assertEquals("1", ctx.getAttribute("list[1]")); + assertEquals("2", ctx.getAttribute("list[2]")); + assertEquals("3", ctx.getAttribute("list[3]")); + assertEquals("4", ctx.getAttribute("list[4]")); + assertEquals("5", ctx.getAttribute("list_length")); + + // Check that old list values aren't in new list + assertNull(ctx.getAttribute("Other")); + } +} diff --git a/core/sliPluginUtils/provider/src/test/resources/2dArray.json b/core/sliPluginUtils/provider/src/test/resources/2dArray.json new file mode 100644 index 000000000..2a94b46f4 --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/resources/2dArray.json @@ -0,0 +1,4 @@ +[ + ["apple", "orange", "banana", null], + ["squash", "broccoli", "cauliflower"] +] \ No newline at end of file diff --git a/core/sliPluginUtils/provider/src/test/resources/3dArray.json b/core/sliPluginUtils/provider/src/test/resources/3dArray.json new file mode 100644 index 000000000..149955596 --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/resources/3dArray.json @@ -0,0 +1,4 @@ +[ + [["a","b","c"], ["d","e","f"]], + [["x","y","z"]] +] \ No newline at end of file diff --git a/core/sliPluginUtils/provider/src/test/resources/ArrayMenu.json b/core/sliPluginUtils/provider/src/test/resources/ArrayMenu.json new file mode 100644 index 000000000..26a24f292 --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/resources/ArrayMenu.json @@ -0,0 +1,41 @@ +[{ + "id": "1", + "type": "pizza", + "name": "plain", + "calories": 1000, + "vegetarian": true + }, { + "id": "2", + "type": "pizza", + "name": "Tuesday Special", + "calories": null, + "vegetarian": false, + "topping": + [{ + "id": "1", + "name": "onion" + }, { + "id": "2", + "name": "pepperoni" + } + ] + }, { + "id": "3", + "type": "pizza", + "name": "House Special", + "calories": 1500, + "vegetarian": true, + "topping": + [{ + "id": "3", + "name": "basil" + }, { + "id": "4", + "name": "fresh mozzarella" + }, { + "id": "5", + "name": "tomato" + } + ] + } +] diff --git a/core/sliPluginUtils/provider/src/test/resources/EmbeddedEscapedJson.json b/core/sliPluginUtils/provider/src/test/resources/EmbeddedEscapedJson.json new file mode 100644 index 000000000..dbb6d8d3a --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/resources/EmbeddedEscapedJson.json @@ -0,0 +1,16 @@ +{ + "input": { + "parameters": + [{ + "name": "escapedJsonObject", + "value": "[{\"id\":\"0.2.0.0\/16\"},{\"id\":\"ge04::\/64\"}]" + }, { + "name": "password", + "value": "Hello\/World" + }, { + "name": "resourceName", + "value": "The\t\"Best\"\tName" + } + ] + } +} \ No newline at end of file diff --git a/core/sliPluginUtils/provider/src/test/resources/EscapedJson.json b/core/sliPluginUtils/provider/src/test/resources/EscapedJson.json new file mode 100644 index 000000000..a7719e819 --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/resources/EscapedJson.json @@ -0,0 +1 @@ +{\"widget\":{\"debug\":false,\"window\":{\"title\":\"ONAP Widget\",\"name\":\"main_window\",\"width\":200,\"height\":300},\"image\":{\"src\":\"images\/moon.png\",\"name\":\"moon\",\"hOffset\":150,\"vOffset\":150,\"alignment\":\"center\"},\"text\":{\"data\":\"Click Me\",\"size\":21,\"style\":\"bold\",\"name\":\"text1\",\"hOffset\":350,\"vOffset\":200,\"alignment\":\"center\"}}} \ No newline at end of file diff --git a/core/sliPluginUtils/provider/src/test/resources/JsonObject.json b/core/sliPluginUtils/provider/src/test/resources/JsonObject.json new file mode 100644 index 000000000..0578368f8 --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/resources/JsonObject.json @@ -0,0 +1,5 @@ +{ + "aaa": "123", + "bbb": "xyz", + "c.d": "abc" +} \ No newline at end of file diff --git a/core/sliPluginUtils/provider/src/test/resources/ObjectMenu.json b/core/sliPluginUtils/provider/src/test/resources/ObjectMenu.json new file mode 100644 index 000000000..56f842d48 --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/resources/ObjectMenu.json @@ -0,0 +1,43 @@ +{ + "menu": [{ + "id": "1", + "type": "pizza", + "name": "plain", + "calories": 1000, + "vegetarian": true + }, { + "id": "2", + "type": "pizza", + "name": "Tuesday Special", + "calories": 2000, + "vegetarian": false, + "topping": + [{ + "id": "1", + "name": "onion" + }, { + "id": "2", + "name": "pepperoni" + } + ] + }, { + "id": "3", + "type": "pizza", + "name": "House Special", + "calories": 1500, + "vegetarian": true, + "topping": + [{ + "id": "3", + "name": "basil" + }, { + "id": "4", + "name": "fresh mozzarella" + }, { + "id": "5", + "name": "tomato" + } + ] + } + ] +} diff --git a/core/sliPluginUtils/provider/src/test/resources/Widget.json b/core/sliPluginUtils/provider/src/test/resources/Widget.json new file mode 100644 index 000000000..6b90907ce --- /dev/null +++ b/core/sliPluginUtils/provider/src/test/resources/Widget.json @@ -0,0 +1,27 @@ +{ + "widget": { + "debug": false, + "window": { + "title": "ONAP Widget", + "name": "main_window", + "width": 200, + "height": 300 + }, + "image": { + "src": "images/moon.png", + "name": "moon", + "hOffset": 150, + "vOffset": 150, + "alignment": "center" + }, + "text": { + "data": "Click Me", + "size": 21, + "style": "bold", + "name": "text1", + "hOffset": 350, + "vOffset": null, + "alignment": "center" + } + } +} \ No newline at end of file -- cgit 1.2.3-korg