diff options
Diffstat (limited to 'bpmn/MSOCoreBPMN')
72 files changed, 5499 insertions, 5525 deletions
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BadInjectedFieldException.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BadInjectedFieldException.java index 3002d0e70a..7bf1a108a0 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BadInjectedFieldException.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BadInjectedFieldException.java @@ -22,31 +22,28 @@ package org.onap.so.bpmn.core; public class BadInjectedFieldException extends RuntimeException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * Constructor. - * - * @param fieldName the field name - * @param taskName the task name - * @param info additional information, e.g. the field value - */ - public BadInjectedFieldException(String fieldName, String taskName, - Object info) { - super(taskName + " injected field '" + fieldName + "' is bad: " + info); - } + /** + * Constructor. + * + * @param fieldName the field name + * @param taskName the task name + * @param info additional information, e.g. the field value + */ + public BadInjectedFieldException(String fieldName, String taskName, Object info) { + super(taskName + " injected field '" + fieldName + "' is bad: " + info); + } - /** - * Constructor. - * - * @param fieldName the field name - * @param taskName the task name - * @param info additional information, e.g. the field value - * @param cause the cause - */ - public BadInjectedFieldException(String fieldName, - String taskName, Object info, Throwable cause) { - super(taskName + " injected field '" + fieldName + "' is bad: " - + info, cause); - } + /** + * Constructor. + * + * @param fieldName the field name + * @param taskName the task name + * @param info additional information, e.g. the field value + * @param cause the cause + */ + public BadInjectedFieldException(String fieldName, String taskName, Object info, Throwable cause) { + super(taskName + " injected field '" + fieldName + "' is bad: " + info, cause); + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java index 99157410d5..2e66493a25 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java @@ -31,31 +31,25 @@ import org.onap.so.bpmn.core.internal.VariableNameExtractor; public class BaseTask implements JavaDelegate { /** - * Get the value of a required field. This method throws - * MissingInjectedFieldException if the expression is null, and - * BadInjectedFieldException if the expression evaluates to a null - * value. + * Get the value of a required field. This method throws MissingInjectedFieldException if the expression is null, + * and BadInjectedFieldException if the expression evaluates to a null value. * * @param expression the expression * @param execution the execution * @param fieldName the field name (for logging and exceptions) * @return the field value */ - protected Object getField(Expression expression, - DelegateExecution execution, String fieldName) { + protected Object getField(Expression expression, DelegateExecution execution, String fieldName) { return getFieldImpl(expression, execution, fieldName, false); } /** - * Gets the value of an optional field. There are three conditions - * in which this method returns null: + * Gets the value of an optional field. There are three conditions in which this method returns null: * <p> * <ol> - * <li> The expression itself is null (i.e. the field is missing - * altogether.</li> + * <li>The expression itself is null (i.e. the field is missing altogether.</li> * <li>The expression evaluates to a null value.</li> - * <li>The expression references a single variable which has not - * been set.</li> + * <li>The expression references a single variable which has not been set.</li> * </ol> * <p> * Examples:<br> @@ -68,77 +62,65 @@ public class BaseTask implements JavaDelegate { * @param fieldName the field name (for logging and exceptions) * @return the field value, possibly null */ - protected Object getOptionalField(Expression expression, - DelegateExecution execution, String fieldName) { + protected Object getOptionalField(Expression expression, DelegateExecution execution, String fieldName) { return getFieldImpl(expression, execution, fieldName, true); } /** - * Get the value of a required output variable field. This method - * throws MissingInjectedFieldException if the expression is null, and - * BadInjectedFieldException if the expression produces a null or - * illegal variable name. Legal variable names contain only letters, - * numbers, and the underscore character ('_'). + * Get the value of a required output variable field. This method throws MissingInjectedFieldException if the + * expression is null, and BadInjectedFieldException if the expression produces a null or illegal variable name. + * Legal variable names contain only letters, numbers, and the underscore character ('_'). * * @param expression the expression * @param execution the execution * @param fieldName the field name (for logging and exceptions) * @return the output variable name */ - protected String getOutputField(Expression expression, - DelegateExecution execution, String fieldName) { + protected String getOutputField(Expression expression, DelegateExecution execution, String fieldName) { Object o = getFieldImpl(expression, execution, fieldName, false); if (o instanceof String) { String variable = (String) o; if (!isLegalVariable(variable)) { - throw new BadInjectedFieldException( - fieldName, getTaskName(), "'" + variable - + "' is not a legal variable name"); + throw new BadInjectedFieldException(fieldName, getTaskName(), + "'" + variable + "' is not a legal variable name"); } return variable; } else { - throw new BadInjectedFieldException( - fieldName, getTaskName(), "expected a variable name string" - + ", got object of type " + o.getClass().getName()); + throw new BadInjectedFieldException(fieldName, getTaskName(), + "expected a variable name string" + ", got object of type " + o.getClass().getName()); } } /** - * Get the value of an optional output variable field. This method - * throws BadInjectedFieldException if the expression produces an illegal - * variable name. Legal variable names contain only letters, numbers, - * and the underscore character ('_'). + * Get the value of an optional output variable field. This method throws BadInjectedFieldException if the + * expression produces an illegal variable name. Legal variable names contain only letters, numbers, and the + * underscore character ('_'). * * @param expression the expression * @param execution the execution * @param fieldName the field name (for logging and exceptions) * @return the output variable name, possibly null */ - protected String getOptionalOutputField(Expression expression, - DelegateExecution execution, String fieldName) { + protected String getOptionalOutputField(Expression expression, DelegateExecution execution, String fieldName) { Object o = getFieldImpl(expression, execution, fieldName, true); if (o instanceof String) { String variable = (String) o; if (!isLegalVariable(variable)) { - throw new BadInjectedFieldException( - fieldName, getTaskName(), "'" + variable - + "' is not a legal variable name"); + throw new BadInjectedFieldException(fieldName, getTaskName(), + "'" + variable + "' is not a legal variable name"); } return variable; } else if (o == null) { return null; } else { - throw new BadInjectedFieldException( - fieldName, getTaskName(), "expected a variable name string" - + ", got object of type " + o.getClass().getName()); + throw new BadInjectedFieldException(fieldName, getTaskName(), + "expected a variable name string" + ", got object of type " + o.getClass().getName()); } } /** - * Get the value of a required string field. This method throws - * MissingInjectedFieldException if the expression is null, and - * BadInjectedFieldException if the expression evaluates to a null - * value. + * Get the value of a required string field. This method throws MissingInjectedFieldException if the expression is + * null, and BadInjectedFieldException if the expression evaluates to a null value. * <p> * Note: the result is coerced to a string value, if necessary. * @@ -147,28 +129,23 @@ public class BaseTask implements JavaDelegate { * @param fieldName the field name (for logging and exceptions) * @return the field value */ - protected String getStringField(Expression expression, - DelegateExecution execution, String fieldName) { + protected String getStringField(Expression expression, DelegateExecution execution, String fieldName) { Object o = getFieldImpl(expression, execution, fieldName, false); if (o instanceof String) { return (String) o; } else { - throw new BadInjectedFieldException( - fieldName, getTaskName(), "cannot convert '" + o.toString() - + "' to Integer"); + throw new BadInjectedFieldException(fieldName, getTaskName(), + "cannot convert '" + o.toString() + "' to Integer"); } } /** - * Gets the value of an optional string field. There are three conditions - * in which this method returns null: + * Gets the value of an optional string field. There are three conditions in which this method returns null: * <p> * <ol> - * <li> The expression itself is null (i.e. the field is missing - * altogether.</li> + * <li>The expression itself is null (i.e. the field is missing altogether.</li> * <li>The expression evaluates to a null value.</li> - * <li>The expression references a single variable which has not - * been set.</li> + * <li>The expression references a single variable which has not been set.</li> * </ol> * <p> * Examples:<br> @@ -183,8 +160,7 @@ public class BaseTask implements JavaDelegate { * @param fieldName the field name (for logging and exceptions) * @return the field value, possibly null */ - protected String getOptionalStringField(Expression expression, - DelegateExecution execution, String fieldName) { + protected String getOptionalStringField(Expression expression, DelegateExecution execution, String fieldName) { Object o = getFieldImpl(expression, execution, fieldName, true); if (o instanceof String) { return (String) o; @@ -196,18 +172,16 @@ public class BaseTask implements JavaDelegate { } /** - * Get the value of a required integer field. This method throws - * MissingInjectedFieldException if the expression is null, and - * BadInjectedFieldException if the expression evaluates to a null - * value or a value that cannot be coerced to an integer. + * Get the value of a required integer field. This method throws MissingInjectedFieldException if the expression is + * null, and BadInjectedFieldException if the expression evaluates to a null value or a value that cannot be coerced + * to an integer. * * @param expression the expression * @param execution the execution * @param fieldName the field name (for logging and exceptions) * @return the field value */ - protected Integer getIntegerField(Expression expression, - DelegateExecution execution, String fieldName) { + protected Integer getIntegerField(Expression expression, DelegateExecution execution, String fieldName) { Object o = getFieldImpl(expression, execution, fieldName, false); if (o instanceof Integer) { return (Integer) o; @@ -215,23 +189,19 @@ public class BaseTask implements JavaDelegate { try { return Integer.parseInt(o.toString()); } catch (NumberFormatException e) { - throw new BadInjectedFieldException( - fieldName, getTaskName(), "cannot convert '" + o.toString() - + "' to Integer"); + throw new BadInjectedFieldException(fieldName, getTaskName(), + "cannot convert '" + o.toString() + "' to Integer"); } } } /** - * Gets the value of an optional integer field. There are three conditions - * in which this method returns null: + * Gets the value of an optional integer field. There are three conditions in which this method returns null: * <p> * <ol> - * <li> The expression itself is null (i.e. the field is missing - * altogether.</li> + * <li>The expression itself is null (i.e. the field is missing altogether.</li> * <li>The expression evaluates to a null value.</li> - * <li>The expression references a single variable which has not - * been set.</li> + * <li>The expression references a single variable which has not been set.</li> * </ol> * <p> * Examples:<br> @@ -239,17 +209,15 @@ public class BaseTask implements JavaDelegate { * Expression ${x} when x is unset: return null<br> * Expression ${x+y} when x and/or y are unset: exception<br> * <p> - * Note: the result is coerced to an integer value, if necessary. This - * method throws BadInjectedFieldException if the result cannot be coerced - * to an integer. + * Note: the result is coerced to an integer value, if necessary. This method throws BadInjectedFieldException if + * the result cannot be coerced to an integer. * * @param expression the expression * @param execution the execution * @param fieldName the field name (for logging and exceptions) * @return the field value, possibly null */ - protected Integer getOptionalIntegerField(Expression expression, - DelegateExecution execution, String fieldName) { + protected Integer getOptionalIntegerField(Expression expression, DelegateExecution execution, String fieldName) { Object o = getFieldImpl(expression, execution, fieldName, true); if (o instanceof Integer) { return (Integer) o; @@ -259,23 +227,19 @@ public class BaseTask implements JavaDelegate { try { return Integer.parseInt(o.toString()); } catch (NumberFormatException e) { - throw new BadInjectedFieldException( - fieldName, getTaskName(), "cannot convert '" + o.toString() - + "' to Integer"); + throw new BadInjectedFieldException(fieldName, getTaskName(), + "cannot convert '" + o.toString() + "' to Integer"); } } } /** - * Gets the value of an optional long field. There are three conditions - * in which this method returns null: + * Gets the value of an optional long field. There are three conditions in which this method returns null: * <p> * <ol> - * <li> The expression itself is null (i.e. the field is missing - * altogether.</li> + * <li>The expression itself is null (i.e. the field is missing altogether.</li> * <li>The expression evaluates to a null value.</li> - * <li>The expression references a single variable which has not - * been set.</li> + * <li>The expression references a single variable which has not been set.</li> * </ol> * <p> * Examples:<br> @@ -283,17 +247,15 @@ public class BaseTask implements JavaDelegate { * Expression ${x} when x is unset: return null<br> * Expression ${x+y} when x and/or y are unset: exception<br> * <p> - * Note: the result is coerced to a long value, if necessary. This - * method throws BadInjectedFieldException if the result cannot be coerced - * to a long. + * Note: the result is coerced to a long value, if necessary. This method throws BadInjectedFieldException if the + * result cannot be coerced to a long. * * @param expression the expression * @param execution the execution * @param fieldName the field name (for logging and exceptions) * @return the field value, possibly null */ - protected Long getOptionalLongField(Expression expression, - DelegateExecution execution, String fieldName) { + protected Long getOptionalLongField(Expression expression, DelegateExecution execution, String fieldName) { Object o = getFieldImpl(expression, execution, fieldName, true); if (o instanceof Long) { return (Long) o; @@ -303,26 +265,23 @@ public class BaseTask implements JavaDelegate { try { return Long.parseLong(o.toString()); } catch (NumberFormatException e) { - throw new BadInjectedFieldException( - fieldName, getTaskName(), "cannot convert '" + o.toString() - + "' to Long"); + throw new BadInjectedFieldException(fieldName, getTaskName(), + "cannot convert '" + o.toString() + "' to Long"); } } } /** - * Get the value of a required long field. This method throws - * MissingInjectedFieldException if the expression is null, and - * BadInjectedFieldException if the expression evaluates to a null - * value or a value that cannot be coerced to a long. + * Get the value of a required long field. This method throws MissingInjectedFieldException if the expression is + * null, and BadInjectedFieldException if the expression evaluates to a null value or a value that cannot be coerced + * to a long. * * @param expression the expression * @param execution the execution * @param fieldName the field name (for logging and exceptions) * @return the field value */ - protected Long getLongField(Expression expression, - DelegateExecution execution, String fieldName) { + protected Long getLongField(Expression expression, DelegateExecution execution, String fieldName) { Object o = getFieldImpl(expression, execution, fieldName, false); if (o instanceof Long) { return (Long) o; @@ -330,9 +289,8 @@ public class BaseTask implements JavaDelegate { try { return Long.parseLong(o.toString()); } catch (NumberFormatException e) { - throw new BadInjectedFieldException( - fieldName, getTaskName(), "cannot convert '" + o.toString() - + "' to Long"); + throw new BadInjectedFieldException(fieldName, getTaskName(), + "cannot convert '" + o.toString() + "' to Long"); } } } @@ -346,12 +304,11 @@ public class BaseTask implements JavaDelegate { * @param optional true if the field is optional * @return the field value, possibly null */ - private Object getFieldImpl(Expression expression, - DelegateExecution execution, String fieldName, boolean optional) { + private Object getFieldImpl(Expression expression, DelegateExecution execution, String fieldName, + boolean optional) { if (expression == null) { if (!optional) { - throw new MissingInjectedFieldException( - fieldName, getTaskName()); + throw new MissingInjectedFieldException(fieldName, getTaskName()); } return null; } @@ -362,8 +319,7 @@ public class BaseTask implements JavaDelegate { value = expression.getValue(execution); } catch (Exception e) { if (!optional) { - throw new BadInjectedFieldException( - fieldName, getTaskName(), e.getClass().getSimpleName(), e); + throw new BadInjectedFieldException(fieldName, getTaskName(), e.getClass().getSimpleName(), e); } // At this point, we have an exception that occurred while @@ -373,7 +329,7 @@ public class BaseTask implements JavaDelegate { // ${x}. The normal activiti behavior is to throw an exception, // but we don't like that, so we have the following workaround, // which parses the expression text to see if it is a "simple" - // variable reference, and if so, returns null. If the + // variable reference, and if so, returns null. If the // expression is anything other than a single variable // reference, then an exception is thrown, as it would have // been without this workaround. @@ -382,15 +338,13 @@ public class BaseTask implements JavaDelegate { String s = expression.getExpressionText(); new VariableNameExtractor(s).extract().ifPresent(name -> { if (execution.hasVariable(name)) { - throw new BadInjectedFieldException( - fieldName, getTaskName(), e.getClass().getSimpleName(), e); + throw new BadInjectedFieldException(fieldName, getTaskName(), e.getClass().getSimpleName(), e); } }); } if (value == null && !optional) { - throw new BadInjectedFieldException( - fieldName, getTaskName(), "required field has null value"); + throw new BadInjectedFieldException(fieldName, getTaskName(), "required field has null value"); } return value; @@ -449,6 +403,5 @@ public class BaseTask implements JavaDelegate { } @Override - public void execute(DelegateExecution execution) throws Exception { - } + public void execute(DelegateExecution execution) throws Exception {} } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/MissingInjectedFieldException.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/MissingInjectedFieldException.java index 17a78d37b8..f0b56364af 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/MissingInjectedFieldException.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/MissingInjectedFieldException.java @@ -25,15 +25,15 @@ package org.onap.so.bpmn.core; */ public class MissingInjectedFieldException extends BadInjectedFieldException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * Constructor. - * - * @param fieldName the field name - * @param taskName the task name - */ - public MissingInjectedFieldException(String fieldName, String taskName) { - super(fieldName, taskName, "missing required field"); - } + /** + * Constructor. + * + * @param fieldName the field name + * @param taskName the task name + */ + public MissingInjectedFieldException(String fieldName, String taskName) { + super(fieldName, taskName, "missing required field"); + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java index fb794e251d..a3f5253765 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java @@ -27,11 +27,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Used in the output variable mapping configuration of subflow call activity - * tasks to normalize subflow responses. The output mapping is normally set up - * as follows. Note that the order of these mappings is important! + * Used in the output variable mapping configuration of subflow call activity tasks to normalize subflow responses. The + * output mapping is normally set up as follows. Note that the order of these mappings is important! * <p> * OUTPUT MAPPING + * * <pre> * SOURCE EXPRESSION TARGET * ${ResponseBuilder.buildWorkflowException(execution)} WorkflowException @@ -39,254 +39,254 @@ import org.slf4j.LoggerFactory; * </pre> */ public class ResponseBuilder implements java.io.Serializable { - private static final long serialVersionUID = 1L; - private static final Logger logger = LoggerFactory.getLogger(ResponseBuilder.class); - - /** - * Creates a WorkflowException using data from the execution variables. - * If the variables do not indicate that there was an error, null - * is returned. - * @param execution the execution - */ - public WorkflowException buildWorkflowException(DelegateExecution execution) { - - String method = getClass().getSimpleName() + ".buildWorkflowException(" + - "execution=" + execution.getId() + - ")"; - - logger.debug("Entered " + method); - - String prefix = (String) execution.getVariable("prefix"); - String processKey = getProcessKey(execution); - - logger.debug("processKey=" + processKey); - - // See if there"s already a WorkflowException object in the execution. - WorkflowException theException = (WorkflowException) execution.getVariable("WorkflowException"); - - if (theException != null) { - logger.debug("Exited " + method + " - propagated " + theException); - return theException; - } - - // Look in the legacy variables: ErrorResponse and ResponseCode - - String errorResponse = trimString(execution.getVariable(prefix + "ErrorResponse"), null); - String responseCode = trimString(execution.getVariable(prefix + "ResponseCode"), null); - logger.debug("errorResponse=" + errorResponse); - logger.debug("responseCode=" + responseCode); - if (errorResponse != null || !isOneOf(responseCode, null, "0", "200", "201", "202", "204")) { - // This is an error condition. We need to return a WorkflowExcpetion - - if (errorResponse == null) { - // No errorResponse string. See if there"s something in the Response variable - String response = trimString(execution.getVariable(processKey + "Response"), null); - if (response == null) { - errorResponse = "Received response code " + responseCode + " from " + processKey; - } else { - errorResponse = response; - } - } - - // Some subflows may try to return a WorkflowException as XML in the - // errorResponse. If provided, use the errorCode and errorMessage - // from the XML - - String maybeXML = removeXMLNamespaces(errorResponse); - - String xmlErrorMessage = trimString(getXMLTextElement(maybeXML, "ErrorMessage"), null); - String xmlErrorCode = trimString(getXMLTextElement(maybeXML, "ErrorCode"), null); - - if (xmlErrorMessage != null || xmlErrorCode != null) { - logger.debug("xmlErrorMessage=" + xmlErrorMessage); - logger.debug("xmlErrorCode=" + xmlErrorCode); - - if (xmlErrorMessage == null) { - errorResponse = "Received error code " + xmlErrorCode + " from " + processKey; - } else { - errorResponse = xmlErrorMessage; - } - - if (xmlErrorCode != null) { - responseCode = xmlErrorCode; - } - } - - // Convert the responseCode to an integer - - int intResponseCode; - - try { - intResponseCode = Integer.valueOf(responseCode); - } catch (NumberFormatException e) { - // Internal Error - intResponseCode = 2000; - } - - // Convert 3-digit HTTP response codes (we should not be using them here) - // to appropriate 4-digit response codes - - if (intResponseCode < 1000) { - if (intResponseCode >= 400 && intResponseCode <= 499) { - // Invalid Message - intResponseCode = 1002; - } else { - // Internal Error - intResponseCode = 2000; - } - } - - // Create a new WorkflowException object - - theException = new WorkflowException(processKey, intResponseCode, errorResponse); - execution.setVariable("WorkflowException", theException); - logger.debug("Exited " + method + " - created " + theException); - return theException; - } - - logger.debug("Exited " + method + " - no WorkflowException"); - return null; - } - - /** - * Returns the "Response" variable, unless the execution variables - * indicate there was an error. In that case, null is returned. - * @param execution the execution - */ - public Object buildWorkflowResponse(DelegateExecution execution) { - - String method = getClass().getSimpleName() + ".buildWorkflowResponse(" + - "execution=" + execution.getId() + - ")"; - logger.debug("Entered " + method); - - String prefix = (String) execution.getVariable("prefix"); - String processKey = getProcessKey(execution); - - Object theResponse = null; - - WorkflowException theException = (WorkflowException) execution.getVariable("WorkflowException"); - String errorResponse = trimString(execution.getVariable(prefix + "ErrorResponse"), null); - String responseCode = trimString(execution.getVariable(prefix + "ResponseCode"), null); - - if (theException == null && errorResponse == null && - isOneOf(responseCode, null, "0", "200", "201", "202", "204")) { - - theResponse = execution.getVariable("WorkflowResponse"); - - if (theResponse == null) { - theResponse = execution.getVariable(processKey + "Response"); - } - } - - logger.debug("Exited " + method); - return theResponse; - } - - /** - * Checks if the specified item is one of the specified values. - * @param item the item - * @param values the list of values - * @return true if the item is in the list of values - */ - private boolean isOneOf(Object item, Object ... values) { - if (values == null) { - return item == null; - } - - for (Object value : values) { - if (value == null) { - if (item == null) { - return true; - } - } else { - if (value.equals(item)) { - return true; - } - } - } - - return false; - } - - /** - * Creates a string value of the specified object, trimming whitespace in - * the process. If the result is null or empty, the specified empty string - * value is returned. Otherwise the trimmed value is returned. This method - * helps ensure consistent treatment of empty and null strings. - * @param object the object to convert (possibly null) - * @param emptyStringValue the desired value for empty results - */ - private String trimString(Object object, String emptyStringValue) { - if (object == null) { - return emptyStringValue; - } - - String s = String.valueOf(object).trim(); - return s.equals("") ? emptyStringValue : s; - } - - /** - * Returns the process definition key (i.e. the process name) from the - * execution. - * @param execution the execution - */ - private String getProcessKey(DelegateExecution execution) { - Object testKey = execution.getVariable("testProcessKey"); - - if (testKey instanceof String) { - return (String) testKey; - } - - return execution.getProcessEngineServices().getRepositoryService() - .getProcessDefinition(execution.getProcessDefinitionId()).getKey(); - } - - /** - * Removes namespace definitions and prefixes from XML, if any. - */ - private String removeXMLNamespaces(String xml) { - // remove xmlns declaration - xml = xml.replaceAll("xmlns.*?(\"|\').*?(\"|\')", ""); - - // remove opening tag prefix - xml = xml.replaceAll("(<)(\\w+:)(.*?>)", "$1$3"); - - // remove closing tags prefix - xml = xml.replaceAll("(</)(\\w+:)(.*?>)", "$1$3"); - - // remove extra spaces left when xmlns declarations are removed - xml = xml.replaceAll("\\s+>", ">"); - - return xml; - } - - /** - * Extracts text from an XML element. This method is not namespace aware - * (namespaces are ignored). The first matching element is selected. - * @param xml the XML document or fragment - * @param tag the desired element, e.g. "<name>" - * @return the element text, or null if the element was not found - */ - private String getXMLTextElement(String xml, String tag) { - xml = removeXMLNamespaces(xml); - - if (!tag.startsWith("<")) { - tag = "<" + tag + ">"; - } - - int start = xml.indexOf(tag); - - if (start == -1) { - return null; - } - - int end = xml.indexOf('<', start + tag.length()); - - if (end == -1) { - return null; - } - - return xml.substring(start + tag.length(), end); - } + private static final long serialVersionUID = 1L; + private static final Logger logger = LoggerFactory.getLogger(ResponseBuilder.class); + + /** + * Creates a WorkflowException using data from the execution variables. If the variables do not indicate that there + * was an error, null is returned. + * + * @param execution the execution + */ + public WorkflowException buildWorkflowException(DelegateExecution execution) { + + String method = + getClass().getSimpleName() + ".buildWorkflowException(" + "execution=" + execution.getId() + ")"; + + logger.debug("Entered " + method); + + String prefix = (String) execution.getVariable("prefix"); + String processKey = getProcessKey(execution); + + logger.debug("processKey=" + processKey); + + // See if there"s already a WorkflowException object in the execution. + WorkflowException theException = (WorkflowException) execution.getVariable("WorkflowException"); + + if (theException != null) { + logger.debug("Exited " + method + " - propagated " + theException); + return theException; + } + + // Look in the legacy variables: ErrorResponse and ResponseCode + + String errorResponse = trimString(execution.getVariable(prefix + "ErrorResponse"), null); + String responseCode = trimString(execution.getVariable(prefix + "ResponseCode"), null); + logger.debug("errorResponse=" + errorResponse); + logger.debug("responseCode=" + responseCode); + if (errorResponse != null || !isOneOf(responseCode, null, "0", "200", "201", "202", "204")) { + // This is an error condition. We need to return a WorkflowExcpetion + + if (errorResponse == null) { + // No errorResponse string. See if there"s something in the Response variable + String response = trimString(execution.getVariable(processKey + "Response"), null); + if (response == null) { + errorResponse = "Received response code " + responseCode + " from " + processKey; + } else { + errorResponse = response; + } + } + + // Some subflows may try to return a WorkflowException as XML in the + // errorResponse. If provided, use the errorCode and errorMessage + // from the XML + + String maybeXML = removeXMLNamespaces(errorResponse); + + String xmlErrorMessage = trimString(getXMLTextElement(maybeXML, "ErrorMessage"), null); + String xmlErrorCode = trimString(getXMLTextElement(maybeXML, "ErrorCode"), null); + + if (xmlErrorMessage != null || xmlErrorCode != null) { + logger.debug("xmlErrorMessage=" + xmlErrorMessage); + logger.debug("xmlErrorCode=" + xmlErrorCode); + + if (xmlErrorMessage == null) { + errorResponse = "Received error code " + xmlErrorCode + " from " + processKey; + } else { + errorResponse = xmlErrorMessage; + } + + if (xmlErrorCode != null) { + responseCode = xmlErrorCode; + } + } + + // Convert the responseCode to an integer + + int intResponseCode; + + try { + intResponseCode = Integer.valueOf(responseCode); + } catch (NumberFormatException e) { + // Internal Error + intResponseCode = 2000; + } + + // Convert 3-digit HTTP response codes (we should not be using them here) + // to appropriate 4-digit response codes + + if (intResponseCode < 1000) { + if (intResponseCode >= 400 && intResponseCode <= 499) { + // Invalid Message + intResponseCode = 1002; + } else { + // Internal Error + intResponseCode = 2000; + } + } + + // Create a new WorkflowException object + + theException = new WorkflowException(processKey, intResponseCode, errorResponse); + execution.setVariable("WorkflowException", theException); + logger.debug("Exited " + method + " - created " + theException); + return theException; + } + + logger.debug("Exited " + method + " - no WorkflowException"); + return null; + } + + /** + * Returns the "Response" variable, unless the execution variables indicate there was an error. In that case, null + * is returned. + * + * @param execution the execution + */ + public Object buildWorkflowResponse(DelegateExecution execution) { + + String method = getClass().getSimpleName() + ".buildWorkflowResponse(" + "execution=" + execution.getId() + ")"; + logger.debug("Entered " + method); + + String prefix = (String) execution.getVariable("prefix"); + String processKey = getProcessKey(execution); + + Object theResponse = null; + + WorkflowException theException = (WorkflowException) execution.getVariable("WorkflowException"); + String errorResponse = trimString(execution.getVariable(prefix + "ErrorResponse"), null); + String responseCode = trimString(execution.getVariable(prefix + "ResponseCode"), null); + + if (theException == null && errorResponse == null + && isOneOf(responseCode, null, "0", "200", "201", "202", "204")) { + + theResponse = execution.getVariable("WorkflowResponse"); + + if (theResponse == null) { + theResponse = execution.getVariable(processKey + "Response"); + } + } + + logger.debug("Exited " + method); + return theResponse; + } + + /** + * Checks if the specified item is one of the specified values. + * + * @param item the item + * @param values the list of values + * @return true if the item is in the list of values + */ + private boolean isOneOf(Object item, Object... values) { + if (values == null) { + return item == null; + } + + for (Object value : values) { + if (value == null) { + if (item == null) { + return true; + } + } else { + if (value.equals(item)) { + return true; + } + } + } + + return false; + } + + /** + * Creates a string value of the specified object, trimming whitespace in the process. If the result is null or + * empty, the specified empty string value is returned. Otherwise the trimmed value is returned. This method helps + * ensure consistent treatment of empty and null strings. + * + * @param object the object to convert (possibly null) + * @param emptyStringValue the desired value for empty results + */ + private String trimString(Object object, String emptyStringValue) { + if (object == null) { + return emptyStringValue; + } + + String s = String.valueOf(object).trim(); + return s.equals("") ? emptyStringValue : s; + } + + /** + * Returns the process definition key (i.e. the process name) from the execution. + * + * @param execution the execution + */ + private String getProcessKey(DelegateExecution execution) { + Object testKey = execution.getVariable("testProcessKey"); + + if (testKey instanceof String) { + return (String) testKey; + } + + return execution.getProcessEngineServices().getRepositoryService() + .getProcessDefinition(execution.getProcessDefinitionId()).getKey(); + } + + /** + * Removes namespace definitions and prefixes from XML, if any. + */ + private String removeXMLNamespaces(String xml) { + // remove xmlns declaration + xml = xml.replaceAll("xmlns.*?(\"|\').*?(\"|\')", ""); + + // remove opening tag prefix + xml = xml.replaceAll("(<)(\\w+:)(.*?>)", "$1$3"); + + // remove closing tags prefix + xml = xml.replaceAll("(</)(\\w+:)(.*?>)", "$1$3"); + + // remove extra spaces left when xmlns declarations are removed + xml = xml.replaceAll("\\s+>", ">"); + + return xml; + } + + /** + * Extracts text from an XML element. This method is not namespace aware (namespaces are ignored). The first + * matching element is selected. + * + * @param xml the XML document or fragment + * @param tag the desired element, e.g. "<name>" + * @return the element text, or null if the element was not found + */ + private String getXMLTextElement(String xml, String tag) { + xml = removeXMLNamespaces(xml); + + if (!tag.startsWith("<")) { + tag = "<" + tag + ">"; + } + + int start = xml.indexOf(tag); + + if (start == -1) { + return null; + } + + int end = xml.indexOf('<', start + tag.length()); + + if (end == -1) { + return null; + } + + return xml.substring(start + tag.length(), end); + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/RollbackData.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/RollbackData.java index 52207f2156..68ce85f7df 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/RollbackData.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/RollbackData.java @@ -24,13 +24,11 @@ import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; - import com.fasterxml.jackson.annotation.JsonProperty; /** - * An object that stores data for rollbacks. Data is organized by type. A type is simply a string - * identifier. Multiple types of data may be stored in the same object for separate rollback - * operations. + * An object that stores data for rollbacks. Data is organized by type. A type is simply a string identifier. Multiple + * types of data may be stored in the same object for separate rollback operations. */ public class RollbackData implements Serializable { diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/UrnPropertiesReader.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/UrnPropertiesReader.java index 0c88e3ed88..78a73c5a10 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/UrnPropertiesReader.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/UrnPropertiesReader.java @@ -23,7 +23,6 @@ package org.onap.so.bpmn.core; import java.util.Optional; - import org.camunda.bpm.engine.delegate.DelegateExecution; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,31 +42,30 @@ public class UrnPropertiesReader { private static Environment environment; @Autowired - public void setEnvironment(Environment environment) { - this.environment = environment; - } - /** - * Return the URN property value - * if property is present in the execution object, return the same - * else search in the environment object. If found, add it to the execution object and return the value - * otherwise return null + public void setEnvironment(Environment environment) { + this.environment = environment; + } + + /** + * Return the URN property value if property is present in the execution object, return the same else search in the + * environment object. If found, add it to the execution object and return the value otherwise return null * * @param variableName URN property name - * @param execution The flow's execution instance. + * @param execution The flow's execution instance. * @return URN property value */ public static String getVariable(String variableName, DelegateExecution execution) { Object value = execution.getVariable(variableName); if (value != null) { logger.trace("Retrieved value for the URN variable, {}, from the execution object: {}", variableName, - String.valueOf(value)); + String.valueOf(value)); return String.valueOf(value); } String variableValue = null; if (environment != null && environment.getProperty(variableName) != null) { variableValue = environment.getProperty(variableName); logger.trace("Retrieved value for the URN variable, {}, from the environment variable: {}", variableName, - variableValue); + variableValue); execution.setVariable(variableName, variableValue); return variableValue; } @@ -80,33 +78,35 @@ public class UrnPropertiesReader { /** * Return the URN property value from the environment object + * * @param variableName URN property name * @return URN property value */ - public static String getVariable(String variableName){ + public static String getVariable(String variableName) { if (environment != null) { return environment.getProperty(variableName); } else { return null; } } - + /** * Return the String array URN property value from the environment object + * * @param variableName URN property name * @return URN property value */ - public static String[] getVariablesArray(String variableName){ + public static String[] getVariablesArray(String variableName) { if (environment != null) { return environment.getProperty(variableName, String[].class); } else { return null; } } - + public static String getVariable(String variableName, String defaultValue) { - return Optional.ofNullable(getVariable(variableName)).orElse(defaultValue); + return Optional.ofNullable(getVariable(variableName)).orElse(defaultValue); } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java index 8551007795..1692045d33 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java @@ -26,69 +26,68 @@ import java.io.Serializable; * An object that represents a workflow exception. */ public class WorkflowException implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private final String processKey; - private final int errorCode; - private final String errorMessage; - private final String workStep; + private final String processKey; + private final int errorCode; + private final String errorMessage; + private final String workStep; - /** - * Constructor - * @param processKey the process key for the process that generated the exception - * @param errorCode the numeric error code (normally 1xxx or greater) - * @param errorMessage a short error message - */ - public WorkflowException(String processKey, int errorCode, - String errorMessage) { - this.processKey = processKey; - this.errorCode = errorCode; - this.errorMessage = errorMessage; - workStep = "*"; - } - - public WorkflowException(String processKey, int errorCode, - String errorMessage, String workStep) { - this.processKey = processKey; - this.errorCode = errorCode; - this.errorMessage = errorMessage; - this.workStep = workStep; - } + /** + * Constructor + * + * @param processKey the process key for the process that generated the exception + * @param errorCode the numeric error code (normally 1xxx or greater) + * @param errorMessage a short error message + */ + public WorkflowException(String processKey, int errorCode, String errorMessage) { + this.processKey = processKey; + this.errorCode = errorCode; + this.errorMessage = errorMessage; + workStep = "*"; + } - /** - * Returns the process key. - */ - public String getProcessKey() { - return processKey; - } + public WorkflowException(String processKey, int errorCode, String errorMessage, String workStep) { + this.processKey = processKey; + this.errorCode = errorCode; + this.errorMessage = errorMessage; + this.workStep = workStep; + } - /** - * Returns the error code. - */ - public int getErrorCode() { - return errorCode; - } + /** + * Returns the process key. + */ + public String getProcessKey() { + return processKey; + } - /** - * Returns the error message. - */ - public String getErrorMessage() { - return errorMessage; - } - - /** - * Returns the error message. - */ - public String getWorkStep() { - return workStep; - } + /** + * Returns the error code. + */ + public int getErrorCode() { + return errorCode; + } - /** - * Returns a string representation of this object. - */ + /** + * Returns the error message. + */ + public String getErrorMessage() { + return errorMessage; + } + + /** + * Returns the error message. + */ + public String getWorkStep() { + return workStep; + } + + /** + * Returns a string representation of this object. + */ @Override - public String toString() { - return getClass().getSimpleName() + "[processKey=" + getProcessKey() + ",errorCode=" + getErrorCode() - + ",errorMessage=" + getErrorMessage() + ",workStep=" + getWorkStep() + "]"; - } + public String toString() { + return getClass().getSimpleName() + "[processKey=" + getProcessKey() + ",errorCode=" + getErrorCode() + + ",errorMessage=" + getErrorMessage() + ",workStep=" + getWorkStep() + "]"; + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java index c7c7bba20c..841eaee675 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java @@ -21,7 +21,6 @@ package org.onap.so.bpmn.core.domain; import java.util.UUID; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonRootName; @@ -33,104 +32,122 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("allottedResource") public class AllottedResource extends Resource { - private static final long serialVersionUID = 1L; - - /* - * set resourceType for this object - */ - public AllottedResource(){ - resourceType = ResourceType.ALLOTTED_RESOURCE; - setResourceId(UUID.randomUUID().toString()); - } - - /* - * fields specific to Allotted Resource resource type - */ - private String allottedResourceType; - private String allottedResourceRole; - private String providingServiceModelName; - private String providingServiceModelInvariantUuid; - private String providingServiceModelUuid; - private String nfFunction; - private String nfType; - private String nfRole; - private String nfNamingCode; - private String orchestrationStatus; - - @JsonIgnore - private String resourceInput; - - /* - * GET and SET - */ - public String getAllottedResourceType() { - return allottedResourceType; - } - public void setAllottedResourceType(String allottedResourceType) { - this.allottedResourceType = allottedResourceType; - } - public String getAllottedResourceRole() { - return allottedResourceRole; - } - public void setAllottedResourceRole(String allottedResourceRole) { - this.allottedResourceRole = allottedResourceRole; - } - public String getProvidingServiceModelName() { - return providingServiceModelName; - } - public void setProvidingServiceModelName(String providingServiceModelName) { - this.providingServiceModelName = providingServiceModelName; - } - public String getProvidingServiceModelInvariantUuid() { - return providingServiceModelInvariantUuid; - } - public void setProvidingServiceModelInvariantUuid( - String providingServiceModelInvariantUuid) { - this.providingServiceModelInvariantUuid = providingServiceModelInvariantUuid; - } - public String getProvidingServiceModelUuid() { - return providingServiceModelUuid; - } - public void setProvidingServiceModelUuid(String providingServiceModelUuid) { - this.providingServiceModelUuid = providingServiceModelUuid; - } - public String getNfFunction() { - return nfFunction; - } - public void setNfFunction(String nfFunction) { - this.nfFunction = nfFunction; - } - public String getNfType() { - return nfType; - } - public void setNfType(String nfType) { - this.nfType = nfType; - } - public String getNfRole() { - return nfRole; - } - public void setNfRole(String nfRole) { - this.nfRole = nfRole; - } - public String getNfNamingCode() { - return nfNamingCode; - } - public void setNfNamingCode(String nfNamingCode) { - this.nfNamingCode = nfNamingCode; - } - public String getOrchestrationStatus() { - return orchestrationStatus; - } - public void setOrchestrationStatus(String orchestrationStatus) { - this.orchestrationStatus = orchestrationStatus; - } - - - public String getResourceInput() { - return resourceInput; - } - - public void setResourceInput(String resourceInput) { - this.resourceInput = resourceInput; - } -}
\ No newline at end of file + private static final long serialVersionUID = 1L; + + /* + * set resourceType for this object + */ + public AllottedResource() { + resourceType = ResourceType.ALLOTTED_RESOURCE; + setResourceId(UUID.randomUUID().toString()); + } + + /* + * fields specific to Allotted Resource resource type + */ + private String allottedResourceType; + private String allottedResourceRole; + private String providingServiceModelName; + private String providingServiceModelInvariantUuid; + private String providingServiceModelUuid; + private String nfFunction; + private String nfType; + private String nfRole; + private String nfNamingCode; + private String orchestrationStatus; + + @JsonIgnore + private String resourceInput; + + /* + * GET and SET + */ + public String getAllottedResourceType() { + return allottedResourceType; + } + + public void setAllottedResourceType(String allottedResourceType) { + this.allottedResourceType = allottedResourceType; + } + + public String getAllottedResourceRole() { + return allottedResourceRole; + } + + public void setAllottedResourceRole(String allottedResourceRole) { + this.allottedResourceRole = allottedResourceRole; + } + + public String getProvidingServiceModelName() { + return providingServiceModelName; + } + + public void setProvidingServiceModelName(String providingServiceModelName) { + this.providingServiceModelName = providingServiceModelName; + } + + public String getProvidingServiceModelInvariantUuid() { + return providingServiceModelInvariantUuid; + } + + public void setProvidingServiceModelInvariantUuid(String providingServiceModelInvariantUuid) { + this.providingServiceModelInvariantUuid = providingServiceModelInvariantUuid; + } + + public String getProvidingServiceModelUuid() { + return providingServiceModelUuid; + } + + public void setProvidingServiceModelUuid(String providingServiceModelUuid) { + this.providingServiceModelUuid = providingServiceModelUuid; + } + + public String getNfFunction() { + return nfFunction; + } + + public void setNfFunction(String nfFunction) { + this.nfFunction = nfFunction; + } + + public String getNfType() { + return nfType; + } + + public void setNfType(String nfType) { + this.nfType = nfType; + } + + public String getNfRole() { + return nfRole; + } + + public void setNfRole(String nfRole) { + this.nfRole = nfRole; + } + + public String getNfNamingCode() { + return nfNamingCode; + } + + public void setNfNamingCode(String nfNamingCode) { + this.nfNamingCode = nfNamingCode; + } + + public String getOrchestrationStatus() { + return orchestrationStatus; + } + + public void setOrchestrationStatus(String orchestrationStatus) { + this.orchestrationStatus = orchestrationStatus; + } + + + public String getResourceInput() { + return resourceInput; + } + + public void setResourceInput(String resourceInput) { + this.resourceInput = resourceInput; + } +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/CompareModelsResult.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/CompareModelsResult.java index d021394731..7afd864062 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/CompareModelsResult.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/CompareModelsResult.java @@ -23,31 +23,35 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; import java.util.List; -public class CompareModelsResult extends JsonWrapper implements Serializable -{ - private static final long serialVersionUID = 1L; - - private List<ResourceModelInfo> addedResourceList; - private List<ResourceModelInfo> deletedResourceList; - private List<String> requestInputs; - - public List<ResourceModelInfo> getAddedResourceList() { - return addedResourceList; - } - public void setAddedResourceList(List<ResourceModelInfo> addedResourceList) { - this.addedResourceList = addedResourceList; - } - public List<ResourceModelInfo> getDeletedResourceList() { - return deletedResourceList; - } - public void setDeletedResourceList(List<ResourceModelInfo> deletedResourceList) { - this.deletedResourceList = deletedResourceList; - } - public List<String> getRequestInputs() { - return requestInputs; - } - public void setRequestInputs(List<String> requestInputs) { - this.requestInputs = requestInputs; - } +public class CompareModelsResult extends JsonWrapper implements Serializable { + private static final long serialVersionUID = 1L; + + private List<ResourceModelInfo> addedResourceList; + private List<ResourceModelInfo> deletedResourceList; + private List<String> requestInputs; + + public List<ResourceModelInfo> getAddedResourceList() { + return addedResourceList; + } + + public void setAddedResourceList(List<ResourceModelInfo> addedResourceList) { + this.addedResourceList = addedResourceList; + } + + public List<ResourceModelInfo> getDeletedResourceList() { + return deletedResourceList; + } + + public void setDeletedResourceList(List<ResourceModelInfo> deletedResourceList) { + this.deletedResourceList = deletedResourceList; + } + + public List<String> getRequestInputs() { + return requestInputs; + } + + public void setRequestInputs(List<String> requestInputs) { + this.requestInputs = requestInputs; + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ConfigResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ConfigResource.java index 1a8a1d83d9..95a82772db 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ConfigResource.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ConfigResource.java @@ -21,25 +21,24 @@ package org.onap.so.bpmn.core.domain; import java.util.UUID; - import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("configResource") public class ConfigResource extends Resource { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /* - * set resourceType for this object - */ - public ConfigResource(){ - resourceType = ResourceType.CONFIGURATION; - setResourceId(UUID.randomUUID().toString()); - } + /* + * set resourceType for this object + */ + public ConfigResource() { + resourceType = ResourceType.CONFIGURATION; + setResourceId(UUID.randomUUID().toString()); + } - /* - * fields specific to Config Resource resource type - */ + /* + * fields specific to Config Resource resource type + */ } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Configuration.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Configuration.java index 815d85692e..baf7d198a1 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Configuration.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Configuration.java @@ -21,68 +21,80 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonRootName; /** - * Stores configuration information and modeled off - * of the AAI configuration object + * Stores configuration information and modeled off of the AAI configuration object * */ @JsonRootName("configuration") -public class Configuration extends JsonWrapper implements Serializable{ - - private static final long serialVersionUID = 1L; - - private String id; - private String name; - private String type; - private String orchestrationStatus; - private String tunnelBandwidth; - private String vendorAllowedMaxBandwidth; - private String resourceVersion; - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - public String getOrchestrationStatus() { - return orchestrationStatus; - } - public void setOrchestrationStatus(String orchestrationStatus) { - this.orchestrationStatus = orchestrationStatus; - } - public String getTunnelBandwidth() { - return tunnelBandwidth; - } - public void setTunnelBandwidth(String tunnelBandwidth) { - this.tunnelBandwidth = tunnelBandwidth; - } - public String getVendorAllowedMaxBandwidth() { - return vendorAllowedMaxBandwidth; - } - public void setVendorAllowedMaxBandwidth(String vendorAllowedMaxBandwidth) { - this.vendorAllowedMaxBandwidth = vendorAllowedMaxBandwidth; - } - public String getResourceVersion() { - return resourceVersion; - } - public void setResourceVersion(String resourceVersion) { - this.resourceVersion = resourceVersion; - } +public class Configuration extends JsonWrapper implements Serializable { + + private static final long serialVersionUID = 1L; + + private String id; + private String name; + private String type; + private String orchestrationStatus; + private String tunnelBandwidth; + private String vendorAllowedMaxBandwidth; + private String resourceVersion; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getOrchestrationStatus() { + return orchestrationStatus; + } + + public void setOrchestrationStatus(String orchestrationStatus) { + this.orchestrationStatus = orchestrationStatus; + } + + public String getTunnelBandwidth() { + return tunnelBandwidth; + } + + public void setTunnelBandwidth(String tunnelBandwidth) { + this.tunnelBandwidth = tunnelBandwidth; + } + + public String getVendorAllowedMaxBandwidth() { + return vendorAllowedMaxBandwidth; + } + + public void setVendorAllowedMaxBandwidth(String vendorAllowedMaxBandwidth) { + this.vendorAllowedMaxBandwidth = vendorAllowedMaxBandwidth; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Customer.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Customer.java index ca6d35cf46..f76ed9497c 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Customer.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Customer.java @@ -21,9 +21,9 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; + /** - * This class is used to store customer - * data of services aka ServiceDecomposition + * This class is used to store customer data of services aka ServiceDecomposition * * @author bb3476 * @@ -31,22 +31,25 @@ import java.io.Serializable; public class Customer extends JsonWrapper implements Serializable { - private static final long serialVersionUID = 1L; - private String subscriptionServiceType; - private String globalSubscriberId; - - - public String getSubscriptionServiceType() { - return subscriptionServiceType; - } - public void setSubscriptionServiceType(String subscriptionServiceType) { - this.subscriptionServiceType = subscriptionServiceType; - } - public String getGlobalSubscriberId() { - return globalSubscriberId; - } - public void setGlobalSubscriberId(String globalSubscriberId) { - this.globalSubscriberId = globalSubscriberId; - } - + private static final long serialVersionUID = 1L; + private String subscriptionServiceType; + private String globalSubscriberId; + + + public String getSubscriptionServiceType() { + return subscriptionServiceType; + } + + public void setSubscriptionServiceType(String subscriptionServiceType) { + this.subscriptionServiceType = subscriptionServiceType; + } + + public String getGlobalSubscriberId() { + return globalSubscriberId; + } + + public void setGlobalSubscriberId(String globalSubscriberId) { + this.globalSubscriberId = globalSubscriberId; + } + } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java index e4eb01e7fb..897cbe3573 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java @@ -22,7 +22,6 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; import java.util.List; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonRootName; @@ -32,124 +31,127 @@ import com.fasterxml.jackson.annotation.JsonRootName; */ @JsonRootName("homingSolution") @JsonInclude(JsonInclude.Include.NON_NULL) -public class HomingSolution extends JsonWrapper implements Serializable { - - private static final long serialVersionUID = 1L; - - private InventoryType inventoryType; - private boolean isRehome; - private String serviceInstanceId; //TODO should start using si object instead - private String cloudOwner; - private String cloudRegionId; - private String aicClli; - private String aicVersion; - private String tenant; - private VnfResource vnf; - private String oofDirectives; - private License license = new License(); - - - /** - * @return the inventoryType which indicates the solution type - */ - public InventoryType getInventoryType() { - return inventoryType; - } - - public void setInventoryType(InventoryType inventoryType) { - this.inventoryType = inventoryType; - } - public boolean isRehome() { - return isRehome; - } - public void setRehome(boolean isRehome) { - this.isRehome = isRehome; - } - - public String getServiceInstanceId() { - return serviceInstanceId; - } - - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } - - public String getCloudOwner() { - return cloudOwner; - } - - public void setCloudOwner(String cloudOwner) { - this.cloudOwner = cloudOwner; - } - - public String getCloudRegionId() { - return cloudRegionId; - } - - public void setCloudRegionId(String cloudRegionId) { - this.cloudRegionId = cloudRegionId; - } - /** - * @return the aicClli (aka aic site, physical location id) - */ - public String getAicClli() { - return aicClli; - } - - public void setAicClli(String aicClli) { - this.aicClli = aicClli; - } - - public String getAicVersion() { - return aicVersion; - } - - public void setAicVersion(String aicVersion) { - this.aicVersion = aicVersion; - } - - public String getTenant() { - return tenant; - } - - public void setTenant(String tenant) { - this.tenant = tenant; - } - - /** - * @return the vnf that the resource was homed too. - */ - public VnfResource getVnf() { - return vnf; - } - - public void setVnf(VnfResource vnf) { - this.vnf = vnf; - } - - /** - * @return a map<string, string> key is label name, value is any flavor - */ - public String getOofDirectives() { - return oofDirectives; - } - - public void setOofDirectives(String oofDirectives) { - this.oofDirectives = oofDirectives; - } - - public License getLicense() { - return license; - } - - public void setLicense(License license) { - this.license = license; - } - - - public static long getSerialversionuid() { - return serialVersionUID; - } - - -}
\ No newline at end of file +public class HomingSolution extends JsonWrapper implements Serializable { + + private static final long serialVersionUID = 1L; + + private InventoryType inventoryType; + private boolean isRehome; + private String serviceInstanceId; // TODO should start using si object instead + private String cloudOwner; + private String cloudRegionId; + private String aicClli; + private String aicVersion; + private String tenant; + private VnfResource vnf; + private String oofDirectives; + private License license = new License(); + + + /** + * @return the inventoryType which indicates the solution type + */ + public InventoryType getInventoryType() { + return inventoryType; + } + + public void setInventoryType(InventoryType inventoryType) { + this.inventoryType = inventoryType; + } + + public boolean isRehome() { + return isRehome; + } + + public void setRehome(boolean isRehome) { + this.isRehome = isRehome; + } + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getCloudOwner() { + return cloudOwner; + } + + public void setCloudOwner(String cloudOwner) { + this.cloudOwner = cloudOwner; + } + + public String getCloudRegionId() { + return cloudRegionId; + } + + public void setCloudRegionId(String cloudRegionId) { + this.cloudRegionId = cloudRegionId; + } + + /** + * @return the aicClli (aka aic site, physical location id) + */ + public String getAicClli() { + return aicClli; + } + + public void setAicClli(String aicClli) { + this.aicClli = aicClli; + } + + public String getAicVersion() { + return aicVersion; + } + + public void setAicVersion(String aicVersion) { + this.aicVersion = aicVersion; + } + + public String getTenant() { + return tenant; + } + + public void setTenant(String tenant) { + this.tenant = tenant; + } + + /** + * @return the vnf that the resource was homed too. + */ + public VnfResource getVnf() { + return vnf; + } + + public void setVnf(VnfResource vnf) { + this.vnf = vnf; + } + + /** + * @return a map<string, string> key is label name, value is any flavor + */ + public String getOofDirectives() { + return oofDirectives; + } + + public void setOofDirectives(String oofDirectives) { + this.oofDirectives = oofDirectives; + } + + public License getLicense() { + return license; + } + + public void setLicense(License license) { + this.license = license; + } + + + public static long getSerialversionuid() { + return serialVersionUID; + } + + +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/InventoryType.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/InventoryType.java index e56ca76b2b..494eb2a61d 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/InventoryType.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/InventoryType.java @@ -20,18 +20,17 @@ package org.onap.so.bpmn.core.domain; -public enum InventoryType{ +public enum InventoryType { - cloud("CLOUD"), - service("SERVICE"); + cloud("CLOUD"), service("SERVICE"); - private String type; + private String type; - InventoryType(String type){ - this.type = type; - } + InventoryType(String type) { + this.type = type; + } - public String type(){ - return type; - } -}
\ No newline at end of file + public String type() { + return type; + } +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java index c3eefcd3cd..602172f8a4 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java @@ -25,10 +25,8 @@ package org.onap.so.bpmn.core.domain; import java.io.IOException; import java.io.Serializable; import java.util.List; - import org.json.JSONException; import org.json.JSONObject; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonGenerationException; @@ -36,100 +34,99 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Wrapper encapsulates needed JSON functionality - * to be extended by MSO service decomposition objects - * providing ways to convert to and from JSON + * Wrapper encapsulates needed JSON functionality to be extended by MSO service decomposition objects providing ways to + * convert to and from JSON * */ @JsonInclude(Include.NON_NULL) -public abstract class JsonWrapper implements Serializable { - - private static final Logger logger = LoggerFactory.getLogger(JsonWrapper.class); - @JsonInclude(Include.NON_NULL) - public String toJsonString(){ - - String jsonString = ""; - //convert with Jackson - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); - - mapper.setSerializationInclusion(Include.NON_NULL); - - ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); - try { - jsonString = ow.writeValueAsString(this); - } catch (Exception e){ - - logger.debug("Exception :",e); - } - return jsonString; - } - - @JsonInclude(Include.NON_NULL) - public JSONObject toJsonObject(){ - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); - JSONObject json = new JSONObject(); - try { - json = new JSONObject(mapper.writeValueAsString(this)); - } catch (JsonGenerationException e) { - logger.debug("Exception :",e); - } catch (JsonMappingException e) { - logger.debug("Exception :",e); - } catch (JSONException e) { - logger.debug("Exception :",e); - } catch (IOException e) { - logger.debug("Exception :",e); - } - return json; - } - - public String listToJson(List list) { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); - - String jsonString = ""; - try { - jsonString = mapper.writeValueAsString(list); - } catch (JsonGenerationException e) { - logger.debug("Exception :",e); - } catch (JsonMappingException e) { - logger.debug("Exception :",e); - } catch (IOException e) { - logger.debug("Exception :",e); - } - return jsonString; - } - - @JsonInclude(Include.NON_NULL) - public String toJsonStringNoRootName(){ - - String jsonString = ""; - //convert with Jackson - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - - ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); - try { - jsonString = ow.writeValueAsString(this); - } catch (Exception e){ - - logger.debug("Exception :",e); - } - return jsonString; - } - - /** - * Returns a string representation of this object. - */ - public String toString() { - return this.toJsonString(); - } +public abstract class JsonWrapper implements Serializable { + + private static final Logger logger = LoggerFactory.getLogger(JsonWrapper.class); + + @JsonInclude(Include.NON_NULL) + public String toJsonString() { + + String jsonString = ""; + // convert with Jackson + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); + + mapper.setSerializationInclusion(Include.NON_NULL); + + ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); + try { + jsonString = ow.writeValueAsString(this); + } catch (Exception e) { + + logger.debug("Exception :", e); + } + return jsonString; + } + + @JsonInclude(Include.NON_NULL) + public JSONObject toJsonObject() { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); + JSONObject json = new JSONObject(); + try { + json = new JSONObject(mapper.writeValueAsString(this)); + } catch (JsonGenerationException e) { + logger.debug("Exception :", e); + } catch (JsonMappingException e) { + logger.debug("Exception :", e); + } catch (JSONException e) { + logger.debug("Exception :", e); + } catch (IOException e) { + logger.debug("Exception :", e); + } + return json; + } + + public String listToJson(List list) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); + + String jsonString = ""; + try { + jsonString = mapper.writeValueAsString(list); + } catch (JsonGenerationException e) { + logger.debug("Exception :", e); + } catch (JsonMappingException e) { + logger.debug("Exception :", e); + } catch (IOException e) { + logger.debug("Exception :", e); + } + return jsonString; + } + + @JsonInclude(Include.NON_NULL) + public String toJsonStringNoRootName() { + + String jsonString = ""; + // convert with Jackson + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + + ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); + try { + jsonString = ow.writeValueAsString(this); + } catch (Exception e) { + + logger.debug("Exception :", e); + } + return jsonString; + } + + /** + * Returns a string representation of this object. + */ + public String toString() { + return this.toJsonString(); + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java index 93dfd4f1f1..1db360f391 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java @@ -24,95 +24,88 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.json.JSONArray; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonRootName; /** - * Stores licensing information and is an attribute - * of a <class>HomingSolution</class> + * Stores licensing information and is an attribute of a <class>HomingSolution</class> * */ @JsonRootName("license") @JsonInclude(JsonInclude.Include.NON_EMPTY) -public class License extends JsonWrapper implements Serializable { - - private static final long serialVersionUID = 1L; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - private List<String> entitlementPoolList = new ArrayList<String>(); - @JsonInclude(JsonInclude.Include.NON_EMPTY) - private List<String> licenseKeyGroupList = new ArrayList<String>(); - - - public List<String> getEntitlementPoolList() { - return entitlementPoolList; - } - - public void setEntitlementPoolList(List<String> entitlementPoolList) { - this.entitlementPoolList = entitlementPoolList; - } - - public List<String> getLicenseKeyGroupList() { - return licenseKeyGroupList; - } - - public void setLicenseKeyGroupList(List<String> licenseKeyGroupList) { - this.licenseKeyGroupList = licenseKeyGroupList; - } - - /** - * This method adds a Entitlement Pool Uuid - * to the EntitlementPoolList - * - * @param the EntitlementPoolUuid - */ - public void addEntitlementPool(String entitlementPoolUuid) { - entitlementPoolList.add(entitlementPoolUuid); - } - - /** - * This method adds a License Key Group Uuid - * to the LicenseKeyGroupList - * - * @param the licenseKeyGroupUuid - */ - public void addLicenseKeyGroup(String licenseKeyGroupUuid) { - licenseKeyGroupList.add(licenseKeyGroupUuid); - } - - /** - * This method returns the licenseKeyGroupList - * as a json array - * - * @return the strList - */ - @JsonIgnore - public JSONArray getLicenseKeyGroupListAsString() { +public class License extends JsonWrapper implements Serializable { + + private static final long serialVersionUID = 1L; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + private List<String> entitlementPoolList = new ArrayList<String>(); + @JsonInclude(JsonInclude.Include.NON_EMPTY) + private List<String> licenseKeyGroupList = new ArrayList<String>(); + + + public List<String> getEntitlementPoolList() { + return entitlementPoolList; + } + + public void setEntitlementPoolList(List<String> entitlementPoolList) { + this.entitlementPoolList = entitlementPoolList; + } + + public List<String> getLicenseKeyGroupList() { + return licenseKeyGroupList; + } + + public void setLicenseKeyGroupList(List<String> licenseKeyGroupList) { + this.licenseKeyGroupList = licenseKeyGroupList; + } + + /** + * This method adds a Entitlement Pool Uuid to the EntitlementPoolList + * + * @param the EntitlementPoolUuid + */ + public void addEntitlementPool(String entitlementPoolUuid) { + entitlementPoolList.add(entitlementPoolUuid); + } + + /** + * This method adds a License Key Group Uuid to the LicenseKeyGroupList + * + * @param the licenseKeyGroupUuid + */ + public void addLicenseKeyGroup(String licenseKeyGroupUuid) { + licenseKeyGroupList.add(licenseKeyGroupUuid); + } + + /** + * This method returns the licenseKeyGroupList as a json array + * + * @return the strList + */ + @JsonIgnore + public JSONArray getLicenseKeyGroupListAsString() { JSONArray array = new JSONArray(licenseKeyGroupList); - return array; - } - - /** - * This method returns the entitlementPoolList - * as a json array - * - * @return the strList - */ - @JsonIgnore - public JSONArray getEntitlementPoolListAsString() { + return array; + } + + /** + * This method returns the entitlementPoolList as a json array + * + * @return the strList + */ + @JsonIgnore + public JSONArray getEntitlementPoolListAsString() { JSONArray array = new JSONArray(entitlementPoolList); - return array; - } - - /** - * @return the serialversionuid - */ - public static long getSerialversionuid() { - return serialVersionUID; - } + return array; + } + + /** + * @return the serialversionuid + */ + public static long getSerialversionuid() { + return serialVersionUID; + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModelInfo.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModelInfo.java index 983fe50d88..4c8401335d 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModelInfo.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModelInfo.java @@ -21,77 +21,90 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("modelInfo") -public class ModelInfo extends JsonWrapper implements Serializable { - - /** - * This is domain object defining structure for MODEL INFO - * It will be valid for each Resource type object - */ - private static final long serialVersionUID = 1L; - - private String modelName = ""; - private String modelUuid = ""; - private String modelInvariantUuid = ""; - private String modelVersion = ""; - //additionally on resource level - private String modelCustomizationUuid = ""; - private String modelCustomizationName = ""; - private String modelInstanceName = ""; - private String modelType = ""; - - //GET and SET methods - - public String getModelName() { - return modelName; - } - public void setModelName(String modelName) { - this.modelName = modelName; - } - public String getModelUuid() { - return modelUuid; - } - public void setModelUuid(String modelUuid) { - this.modelUuid = modelUuid; - } - public String getModelInvariantUuid() { - return modelInvariantUuid; - } - public void setModelInvariantUuid(String modelInvariantUuid) { - this.modelInvariantUuid = modelInvariantUuid; - } - public String getModelVersion() { - return modelVersion; - } - public void setModelVersion(String modelVersion) { - this.modelVersion = modelVersion; - } - public String getModelCustomizationUuid() { - return modelCustomizationUuid; - } - public void setModelCustomizationUuid(String modelCustomizationUuid) { - this.modelCustomizationUuid = modelCustomizationUuid; - } - public String getModelCustomizationName() { - return modelCustomizationName; - } - public void setModelCustomizationName(String modelCustomizationName) { - this.modelCustomizationName = modelCustomizationName; - } - public String getModelInstanceName() { - return modelInstanceName; - } - public void setModelInstanceName(String modelInstanceName) { - this.modelInstanceName = modelInstanceName; - } - public String getModelType() { - return modelType; - } - public void setModelType(String modelType) { - this.modelType = modelType; - } - -}
\ No newline at end of file +public class ModelInfo extends JsonWrapper implements Serializable { + + /** + * This is domain object defining structure for MODEL INFO It will be valid for each Resource type object + */ + private static final long serialVersionUID = 1L; + + private String modelName = ""; + private String modelUuid = ""; + private String modelInvariantUuid = ""; + private String modelVersion = ""; + // additionally on resource level + private String modelCustomizationUuid = ""; + private String modelCustomizationName = ""; + private String modelInstanceName = ""; + private String modelType = ""; + + // GET and SET methods + + public String getModelName() { + return modelName; + } + + public void setModelName(String modelName) { + this.modelName = modelName; + } + + public String getModelUuid() { + return modelUuid; + } + + public void setModelUuid(String modelUuid) { + this.modelUuid = modelUuid; + } + + public String getModelInvariantUuid() { + return modelInvariantUuid; + } + + public void setModelInvariantUuid(String modelInvariantUuid) { + this.modelInvariantUuid = modelInvariantUuid; + } + + public String getModelVersion() { + return modelVersion; + } + + public void setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + } + + public String getModelCustomizationUuid() { + return modelCustomizationUuid; + } + + public void setModelCustomizationUuid(String modelCustomizationUuid) { + this.modelCustomizationUuid = modelCustomizationUuid; + } + + public String getModelCustomizationName() { + return modelCustomizationName; + } + + public void setModelCustomizationName(String modelCustomizationName) { + this.modelCustomizationName = modelCustomizationName; + } + + public String getModelInstanceName() { + return modelInstanceName; + } + + public void setModelInstanceName(String modelInstanceName) { + this.modelInstanceName = modelInstanceName; + } + + public String getModelType() { + return modelType; + } + + public void setModelType(String modelType) { + this.modelType = modelType; + } + +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModuleResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModuleResource.java index 459d203325..a67149b71f 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModuleResource.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModuleResource.java @@ -23,72 +23,85 @@ package org.onap.so.bpmn.core.domain; import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("vfModule") -public class ModuleResource extends Resource { - - private static final long serialVersionUID = 1L; - - /* - * set resourceType for this object - */ - public ModuleResource(){ - resourceType = ResourceType.MODULE; - } - - /* - * fields specific to VF Module resource type - */ - private String vfModuleName; - private String vfModuleType; - private String heatStackId; - private boolean hasVolumeGroup; - private boolean isBase; - private String vfModuleLabel; - private int initialCount; - - /* - * GET && SET - */ - public String getVfModuleName() { - return vfModuleName; - } - public void setVfModuleName(String vfModuleName) { - this.vfModuleName = vfModuleName; - } - public String getHeatStackId() { - return heatStackId; - } - public void setHeatStackId(String heatStackId) { - this.heatStackId = heatStackId; - } - public boolean getIsBase() { - return isBase; - } - public void setIsBase(boolean isBase) { - this.isBase = isBase; - } - public String getVfModuleLabel() { - return vfModuleLabel; - } - public void setVfModuleLabel(String vfModuleLabel) { - this.vfModuleLabel = vfModuleLabel; - } - public int getInitialCount() { - return initialCount; - } - public void setInitialCount(int initialCount) { - this.initialCount = initialCount; - } - public String getVfModuleType() { - return vfModuleType; - } - public void setVfModuleType(String vfModuleType) { - this.vfModuleType = vfModuleType; - } - public boolean isHasVolumeGroup() { - return hasVolumeGroup; - } - public void setHasVolumeGroup(boolean hasVolumeGroup) { - this.hasVolumeGroup = hasVolumeGroup; - } - -}
\ No newline at end of file +public class ModuleResource extends Resource { + + private static final long serialVersionUID = 1L; + + /* + * set resourceType for this object + */ + public ModuleResource() { + resourceType = ResourceType.MODULE; + } + + /* + * fields specific to VF Module resource type + */ + private String vfModuleName; + private String vfModuleType; + private String heatStackId; + private boolean hasVolumeGroup; + private boolean isBase; + private String vfModuleLabel; + private int initialCount; + + /* + * GET && SET + */ + public String getVfModuleName() { + return vfModuleName; + } + + public void setVfModuleName(String vfModuleName) { + this.vfModuleName = vfModuleName; + } + + public String getHeatStackId() { + return heatStackId; + } + + public void setHeatStackId(String heatStackId) { + this.heatStackId = heatStackId; + } + + public boolean getIsBase() { + return isBase; + } + + public void setIsBase(boolean isBase) { + this.isBase = isBase; + } + + public String getVfModuleLabel() { + return vfModuleLabel; + } + + public void setVfModuleLabel(String vfModuleLabel) { + this.vfModuleLabel = vfModuleLabel; + } + + public int getInitialCount() { + return initialCount; + } + + public void setInitialCount(int initialCount) { + this.initialCount = initialCount; + } + + public String getVfModuleType() { + return vfModuleType; + } + + public void setVfModuleType(String vfModuleType) { + this.vfModuleType = vfModuleType; + } + + public boolean isHasVolumeGroup() { + return hasVolumeGroup; + } + + public void setHasVolumeGroup(boolean hasVolumeGroup) { + this.hasVolumeGroup = hasVolumeGroup; + } + +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/NetworkResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/NetworkResource.java index f0e97f15ef..7523c378e9 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/NetworkResource.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/NetworkResource.java @@ -21,7 +21,6 @@ package org.onap.so.bpmn.core.domain; import java.util.UUID; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonRootName; @@ -34,58 +33,67 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("networkResource") public class NetworkResource extends Resource { - private static final long serialVersionUID = 1L; - /* - * set resourceType for this object - */ - public NetworkResource(){ - resourceType = ResourceType.NETWORK; - setResourceId(UUID.randomUUID().toString()); - } - /* - * fields specific to Network resource type - */ - private String networkType; - private String networkRole; - private String networkTechnology; - private String networkScope; - - @JsonIgnore - private String resourceInput; - - /* - * GET and SET - */ - public String getNetworkType() { - return networkType; - } - public void setNetworkType(String networkType) { - this.networkType = networkType; - } - public String getNetworkRole() { - return networkRole; - } - public void setNetworkRole(String networkRole) { - this.networkRole = networkRole; - } - public String getNetworkTechnology() { - return networkTechnology; - } - public void setNetworkTechnology(String networkTechnology) { - this.networkTechnology = networkTechnology; - } - public String getNetworkScope() { - return networkScope; - } - public void setNetworkScope(String networkScope) { - this.networkScope = networkScope; - } - - public String getResourceInput() { - return resourceInput; - } - - public void setResourceInput(String resourceInput) { - this.resourceInput = resourceInput; - } -}
\ No newline at end of file + private static final long serialVersionUID = 1L; + + /* + * set resourceType for this object + */ + public NetworkResource() { + resourceType = ResourceType.NETWORK; + setResourceId(UUID.randomUUID().toString()); + } + + /* + * fields specific to Network resource type + */ + private String networkType; + private String networkRole; + private String networkTechnology; + private String networkScope; + + @JsonIgnore + private String resourceInput; + + /* + * GET and SET + */ + public String getNetworkType() { + return networkType; + } + + public void setNetworkType(String networkType) { + this.networkType = networkType; + } + + public String getNetworkRole() { + return networkRole; + } + + public void setNetworkRole(String networkRole) { + this.networkRole = networkRole; + } + + public String getNetworkTechnology() { + return networkTechnology; + } + + public void setNetworkTechnology(String networkTechnology) { + this.networkTechnology = networkTechnology; + } + + public String getNetworkScope() { + return networkScope; + } + + public void setNetworkScope(String networkScope) { + this.networkScope = networkScope; + } + + public String getResourceInput() { + return resourceInput; + } + + public void setResourceInput(String resourceInput) { + this.resourceInput = resourceInput; + } +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/OwningEntity.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/OwningEntity.java index 903b84ac8a..de637fdcc6 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/OwningEntity.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/OwningEntity.java @@ -21,12 +21,10 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonRootName; /** - * This class is used to store instance - * data of owningEntity for ServiceDecomposition + * This class is used to store instance data of owningEntity for ServiceDecomposition * * @author bb3476 * @@ -34,20 +32,24 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("owningEntity") public class OwningEntity extends JsonWrapper implements Serializable { - private static final long serialVersionUID = 1L; - private String owningEntityId; - private String owningEntityName; - public String getOwningEntityId() { - return owningEntityId; - } - public void setOwningEntityId(String owningEntityId) { - this.owningEntityId = owningEntityId; - } - public String getOwningEntityName() { - return owningEntityName; - } - public void setOwningEntityName(String owningEntityName) { - this.owningEntityName = owningEntityName; - } - + private static final long serialVersionUID = 1L; + private String owningEntityId; + private String owningEntityName; + + public String getOwningEntityId() { + return owningEntityId; + } + + public void setOwningEntityId(String owningEntityId) { + this.owningEntityId = owningEntityId; + } + + public String getOwningEntityName() { + return owningEntityName; + } + + public void setOwningEntityName(String owningEntityName) { + this.owningEntityName = owningEntityName; + } + } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Project.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Project.java index 337626ec61..e05035a92d 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Project.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Project.java @@ -21,12 +21,10 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonRootName; /** - * This class is used to store instance - * data of projects for ServiceDecomposition + * This class is used to store instance data of projects for ServiceDecomposition * * @author bb3476 * @@ -34,14 +32,15 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("project") public class Project extends JsonWrapper implements Serializable { - private static final long serialVersionUID = 1L; - private String projectName; + private static final long serialVersionUID = 1L; + private String projectName; + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } - public String getProjectName() { - return projectName; - } - public void setProjectName(String projectName) { - this.projectName = projectName; - } - } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java index dac7336013..6c33d37cfe 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java @@ -21,12 +21,10 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonRootName; /** - * This class is used to store instance - * data of services aka ServiceDecomposition + * This class is used to store instance data of services aka ServiceDecomposition * * @author bb3476 * @@ -34,63 +32,78 @@ import com.fasterxml.jackson.annotation.JsonRootName; public class Request extends JsonWrapper implements Serializable { - private static final long serialVersionUID = 1L; - private String sdncRequestId; - private String requestId; - private ModelInfo modelInfo; - private String productFamilyId; - private String callbackUrl; - private String serviceId; - private String tenantId; - private String cloudRegion; - - public String getSdncRequestId() { - return sdncRequestId; - } - public void setSdncRequestId(String sdncRequestId) { - this.sdncRequestId = sdncRequestId; - } - public String getRequestId() { - return requestId; - } - public void setRequestId(String requestId) { - this.requestId = requestId; - } - public ModelInfo getModelInfo() { - return modelInfo; - } - public void setModelInfo(ModelInfo modelInfo) { - this.modelInfo = modelInfo; - } - public String getProductFamilyId() { - return productFamilyId; - } - public void setProductFamilyId(String productFamilyId) { - this.productFamilyId = productFamilyId; - } - public String getCallbackUrl() { - return callbackUrl; - } - public void setCallbackUrl(String callbackUrl) { - this.callbackUrl = callbackUrl; - } - public String getServiceId() { - return serviceId; - } - public void setServiceId(String serviceId) { - this.serviceId = serviceId; - } - public String getCloudRegion() { - return cloudRegion; - } - public void setCloudRegion(String cloudRegion) { - this.cloudRegion = cloudRegion; - } - public String getTenantId() { - return tenantId; - } - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } - + private static final long serialVersionUID = 1L; + private String sdncRequestId; + private String requestId; + private ModelInfo modelInfo; + private String productFamilyId; + private String callbackUrl; + private String serviceId; + private String tenantId; + private String cloudRegion; + + public String getSdncRequestId() { + return sdncRequestId; + } + + public void setSdncRequestId(String sdncRequestId) { + this.sdncRequestId = sdncRequestId; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public ModelInfo getModelInfo() { + return modelInfo; + } + + public void setModelInfo(ModelInfo modelInfo) { + this.modelInfo = modelInfo; + } + + public String getProductFamilyId() { + return productFamilyId; + } + + public void setProductFamilyId(String productFamilyId) { + this.productFamilyId = productFamilyId; + } + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + public String getServiceId() { + return serviceId; + } + + public void setServiceId(String serviceId) { + this.serviceId = serviceId; + } + + public String getCloudRegion() { + return cloudRegion; + } + + public void setCloudRegion(String cloudRegion) { + this.cloudRegion = cloudRegion; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Resource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Resource.java index 00fdbec305..62a2e9370e 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Resource.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Resource.java @@ -21,114 +21,126 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; -public abstract class Resource extends JsonWrapper implements Serializable { - - private static final long serialVersionUID = 1L; - private String resourceId; // TODO name this field just id instead, should be the id of the object as it is in aai - protected ResourceType resourceType; // Enum of vnf or network or allotted resource - protected ModelInfo modelInfo; - private long concurrencyCounter = 1L; - - //private List modules; - private ResourceInstance resourceInstance = new ResourceInstance(); // TODO possibly remove - private HomingSolution homingSolution = new HomingSolution(); - @JsonInclude(JsonInclude.Include.NON_NULL) - private HomingSolution currentHomingSolution; - - //common parameters for all Resources - private String toscaNodeType; - - // GET and SET - public String getResourceId() { - return resourceId; - } - public void setResourceId(String resourceId) { - this.resourceId = resourceId; - } - public ModelInfo getModelInfo() { - return modelInfo; - } - public void setModelInfo(ModelInfo modelInfo) { - this.modelInfo = modelInfo; - } - - public ResourceInstance getResourceInstance() { - return resourceInstance; - } - public void setResourceInstance(ResourceInstance resourceInstance) { - this.resourceInstance = resourceInstance; - } - public HomingSolution getHomingSolution(){ - return homingSolution; - } - - public void setHomingSolution(HomingSolution homingSolution){ - this.homingSolution = homingSolution; - } - public HomingSolution getCurrentHomingSolution() { - return currentHomingSolution; - } - public void setCurrentHomingSolution(HomingSolution currentHomingSolution) { - this.currentHomingSolution = currentHomingSolution; - } - public void setResourceType(ResourceType resourceType) { - this.resourceType = resourceType; - } - - public ResourceType getResourceType(){ - return resourceType; - } - - public String getToscaNodeType() { - return toscaNodeType; - } - public void setToscaNodeType(String toscaNodeType) { - this.toscaNodeType = toscaNodeType; - } - - //Utility methods - - public String getResourceInstanceId() { - return this.getResourceInstance().getInstanceId(); - } - public String getResourceInstanceName() { - return this.getResourceInstance().getInstanceName(); - } - //TODO -// @JsonIgnore -// public String getResourceHomingSolution() { -// } - - public void setResourceInstanceId(String newInstanceId){ - this.getResourceInstance().setInstanceId(newInstanceId); - } - public void setResourceInstanceName(String newInstanceName){ - this.getResourceInstance().setInstanceName(newInstanceName); - } - - //TODO -// @JsonIgnore -// public String setResourceHomingSolution() { -// } - /** - * To be used by macro flow to increment concurrency counter after update to it's structure was completed - */ - public void incrementConcurrencyCounter(){ - this.concurrencyCounter ++; - } - /** - * Method to get concurrency counter data - * @return long value for the counter - */ - @JsonIgnore - public long getConcurrencyCounter(){ - return concurrencyCounter; - } - -}
\ No newline at end of file +public abstract class Resource extends JsonWrapper implements Serializable { + + private static final long serialVersionUID = 1L; + private String resourceId; // TODO name this field just id instead, should be the id of the object as it is in aai + protected ResourceType resourceType; // Enum of vnf or network or allotted resource + protected ModelInfo modelInfo; + private long concurrencyCounter = 1L; + + // private List modules; + private ResourceInstance resourceInstance = new ResourceInstance(); // TODO possibly remove + private HomingSolution homingSolution = new HomingSolution(); + @JsonInclude(JsonInclude.Include.NON_NULL) + private HomingSolution currentHomingSolution; + + // common parameters for all Resources + private String toscaNodeType; + + // GET and SET + public String getResourceId() { + return resourceId; + } + + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + + public ModelInfo getModelInfo() { + return modelInfo; + } + + public void setModelInfo(ModelInfo modelInfo) { + this.modelInfo = modelInfo; + } + + public ResourceInstance getResourceInstance() { + return resourceInstance; + } + + public void setResourceInstance(ResourceInstance resourceInstance) { + this.resourceInstance = resourceInstance; + } + + public HomingSolution getHomingSolution() { + return homingSolution; + } + + public void setHomingSolution(HomingSolution homingSolution) { + this.homingSolution = homingSolution; + } + + public HomingSolution getCurrentHomingSolution() { + return currentHomingSolution; + } + + public void setCurrentHomingSolution(HomingSolution currentHomingSolution) { + this.currentHomingSolution = currentHomingSolution; + } + + public void setResourceType(ResourceType resourceType) { + this.resourceType = resourceType; + } + + public ResourceType getResourceType() { + return resourceType; + } + + public String getToscaNodeType() { + return toscaNodeType; + } + + public void setToscaNodeType(String toscaNodeType) { + this.toscaNodeType = toscaNodeType; + } + + // Utility methods + + public String getResourceInstanceId() { + return this.getResourceInstance().getInstanceId(); + } + + public String getResourceInstanceName() { + return this.getResourceInstance().getInstanceName(); + } + // TODO + // @JsonIgnore + // public String getResourceHomingSolution() { + // } + + public void setResourceInstanceId(String newInstanceId) { + this.getResourceInstance().setInstanceId(newInstanceId); + } + + public void setResourceInstanceName(String newInstanceName) { + this.getResourceInstance().setInstanceName(newInstanceName); + } + + // TODO + // @JsonIgnore + // public String setResourceHomingSolution() { + // } + /** + * To be used by macro flow to increment concurrency counter after update to it's structure was completed + */ + public void incrementConcurrencyCounter() { + this.concurrencyCounter++; + } + + /** + * Method to get concurrency counter data + * + * @return long value for the counter + */ + @JsonIgnore + public long getConcurrencyCounter() { + return concurrencyCounter; + } + +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java index 7cbd565c77..b291765252 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java @@ -21,66 +21,71 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonIgnore; /** * Abstract superclass for all individual decomposition resources * */ -//@JsonIgnoreProperties -public abstract class ResourceDecomposition extends JsonWrapper implements Serializable { - - private static final long serialVersionUID = 1L; - - protected String resourceType; // Enum of vnf or network or allotted resource - private ModelInfo modelInfo; - - //private List modules; - private ResourceInstance instanceData = new ResourceInstance(); - - // GET and SET - public ModelInfo getModelInfo() { - return modelInfo; - } - public void setModelInfo(ModelInfo modelInfo) { - this.modelInfo = modelInfo; - } - - public ResourceInstance getInstanceData() { - return instanceData; - } - public void setInstanceData(ResourceInstance instanceData) { - this.instanceData = instanceData; - } - public void setResourceType(String resourceType) { - this.resourceType = resourceType; - } - - //Utility methods - @JsonIgnore - public ModelInfo getResourceModel() { - return modelInfo; - } - @JsonIgnore - public String getResourceInstanceId() { - return this.getInstanceData().getInstanceId(); - } - @JsonIgnore - public String getResourceInstanceName() { - return this.getInstanceData().getInstanceName(); - } -// @JsonIgnore -// public String getResourceHomingSolution() { -// } - - public void setResourceInstanceId(String newInstanceId){ - this.getInstanceData().setInstanceId(newInstanceId); - } - public void setResourceInstanceName(String newInstanceName){ - this.getInstanceData().setInstanceName(newInstanceName); - } -// @JsonIgnore -// public String setResourceHomingSolution() { -// } +// @JsonIgnoreProperties +public abstract class ResourceDecomposition extends JsonWrapper implements Serializable { + + private static final long serialVersionUID = 1L; + + protected String resourceType; // Enum of vnf or network or allotted resource + private ModelInfo modelInfo; + + // private List modules; + private ResourceInstance instanceData = new ResourceInstance(); + + // GET and SET + public ModelInfo getModelInfo() { + return modelInfo; + } + + public void setModelInfo(ModelInfo modelInfo) { + this.modelInfo = modelInfo; + } + + public ResourceInstance getInstanceData() { + return instanceData; + } + + public void setInstanceData(ResourceInstance instanceData) { + this.instanceData = instanceData; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + // Utility methods + @JsonIgnore + public ModelInfo getResourceModel() { + return modelInfo; + } + + @JsonIgnore + public String getResourceInstanceId() { + return this.getInstanceData().getInstanceId(); + } + + @JsonIgnore + public String getResourceInstanceName() { + return this.getInstanceData().getInstanceName(); + } + // @JsonIgnore + // public String getResourceHomingSolution() { + // } + + public void setResourceInstanceId(String newInstanceId) { + this.getInstanceData().setInstanceId(newInstanceId); + } + + public void setResourceInstanceName(String newInstanceName) { + this.getInstanceData().setInstanceName(newInstanceName); + } + // @JsonIgnore + // public String setResourceHomingSolution() { + // } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceInstance.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceInstance.java index 085e278e11..2c29ff882d 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceInstance.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceInstance.java @@ -21,7 +21,6 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** @@ -30,36 +29,37 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; * @author cb645j * */ -//@JsonIgnoreProperties -//TODO update any existing references then remove this pointless class +// @JsonIgnoreProperties +// TODO update any existing references then remove this pointless class @Deprecated -public class ResourceInstance extends JsonWrapper implements Serializable { +public class ResourceInstance extends JsonWrapper implements Serializable { + + private static final long serialVersionUID = 1L; + + private String instanceId; + private String instanceName; - private static final long serialVersionUID = 1L; - private String instanceId; - private String instanceName; + public String getInstanceId() { + return instanceId; + } + /** + * This class and method is deprecated so use resourceId field in resource class instead + * + * @author cb645j + * + */ + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } - public String getInstanceId() { - return instanceId; - } + public String getInstanceName() { + return instanceName; + } - /** - * This class and method is deprecated so use - * resourceId field in resource class instead - * - * @author cb645j - * - */ - public void setInstanceId(String instanceId) { - this.instanceId = instanceId; - } - public String getInstanceName() { - return instanceName; - } - public void setInstanceName(String instanceName) { - this.instanceName = instanceName; - } + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } -}
\ No newline at end of file +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceModelInfo.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceModelInfo.java index af36fa01df..95ecd7ee85 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceModelInfo.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceModelInfo.java @@ -22,37 +22,44 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; -public class ResourceModelInfo extends JsonWrapper implements Serializable{ - - private static final long serialVersionUID = 1L; - String resourceName; - String resourceInvariantUuid; - String resourceUuid; - String resourceCustomizationUuid; - - public String getResourceName() { - return resourceName; - } - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - public String getResourceInvariantUuid() { - return resourceInvariantUuid; - } - public void setResourceInvariantUuid(String resourceInvariantUuid) { - this.resourceInvariantUuid = resourceInvariantUuid; - } - public String getResourceUuid() { - return resourceUuid; - } - public void setResourceUuid(String resourceUuid) { - this.resourceUuid = resourceUuid; - } - public String getResourceCustomizationUuid() { - return resourceCustomizationUuid; - } - public void setResourceCustomizationUuid(String resourceCustomizationUuid) { - this.resourceCustomizationUuid = resourceCustomizationUuid; - } +public class ResourceModelInfo extends JsonWrapper implements Serializable { + + private static final long serialVersionUID = 1L; + String resourceName; + String resourceInvariantUuid; + String resourceUuid; + String resourceCustomizationUuid; + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceInvariantUuid() { + return resourceInvariantUuid; + } + + public void setResourceInvariantUuid(String resourceInvariantUuid) { + this.resourceInvariantUuid = resourceInvariantUuid; + } + + public String getResourceUuid() { + return resourceUuid; + } + + public void setResourceUuid(String resourceUuid) { + this.resourceUuid = resourceUuid; + } + + public String getResourceCustomizationUuid() { + return resourceCustomizationUuid; + } + + public void setResourceCustomizationUuid(String resourceCustomizationUuid) { + this.resourceCustomizationUuid = resourceCustomizationUuid; + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java index 6147822d31..a30d0df825 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java @@ -22,5 +22,5 @@ package org.onap.so.bpmn.core.domain; public enum ResourceType { - VNF, NETWORK, MODULE, ALLOTTED_RESOURCE, CONFIGURATION // etc. -}
\ No newline at end of file + VNF, NETWORK, MODULE, ALLOTTED_RESOURCE, CONFIGURATION // etc. +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/RollbackData.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/RollbackData.java index 5be0fb4f59..633736a25a 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/RollbackData.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/RollbackData.java @@ -24,24 +24,24 @@ import java.io.Serializable; import java.util.HashMap; import java.util.Map; -public class RollbackData implements Serializable{ +public class RollbackData implements Serializable { - private static final long serialVersionUID = -4811571658272937718L; + private static final long serialVersionUID = -4811571658272937718L; - private String requestId; - private Map<String, String> additionalData = new HashMap<String, String>(); + private String requestId; + private Map<String, String> additionalData = new HashMap<String, String>(); - public String getRequestId(){ - return requestId; - } + public String getRequestId() { + return requestId; + } - public void setRequestId(String requestId){ - this.requestId = requestId; - } + public void setRequestId(String requestId) { + this.requestId = requestId; + } - public Map<String, String> getAdditionalData(){ - return additionalData; - } + public Map<String, String> getAdditionalData() { + return additionalData; + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java index 5e7a4796c4..0e03989e64 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java @@ -26,7 +26,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; @@ -36,509 +35,556 @@ import org.onap.so.bpmn.core.json.JsonDecomposingException; - /** - * Service Decomposition Structure - * This Java object contains service information: - * - Service model info - * - Service type and role - * - list of VNF resource's decompositon - * - list of network resource's decompositon - * - list of allotted resource's decompositon + * Service Decomposition Structure This Java object contains service information: - Service model info - Service type + * and role - list of VNF resource's decompositon - list of network resource's decompositon - list of allotted + * resource's decompositon */ @JsonRootName(value = "serviceResources") -//@JsonTypeInfo(include=As.WRAPPER_OBJECT, use=Id.NAME) +// @JsonTypeInfo(include=As.WRAPPER_OBJECT, use=Id.NAME) public class ServiceDecomposition extends JsonWrapper implements Serializable { - private static final long serialVersionUID = 1L; - - @JsonProperty("modelInfo") - private ModelInfo modelInfo; - @JsonProperty("serviceType") - private String serviceType; - @JsonProperty("serviceRole") - private String serviceRole; - private ServiceInstance serviceInstance; - private Request request; - private Customer customer; - private String callbackURN; - private String sdncVersion; - @JsonProperty("project") - private Project project; - @JsonProperty("owningEntity") - private OwningEntity owningEntity; - @JsonProperty("serviceVnfs") - private List <VnfResource> vnfResources; - @JsonProperty("serviceNetworks") - private List <NetworkResource> networkResources; - @JsonProperty("serviceAllottedResources") - private List <AllottedResource> allottedResources; - @JsonProperty("configResource") - private List <ConfigResource> configResources; - - public ServiceDecomposition () { - super(); - } - - public ServiceDecomposition (String catalogRestOutput) throws JsonDecomposingException { - ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.jsonToServiceDecomposition(catalogRestOutput); - this.modelInfo = serviceDecomposition.getModelInfo(); - this.vnfResources = serviceDecomposition.getVnfResources(); - this.allottedResources = serviceDecomposition.getAllottedResources(); - this.networkResources = serviceDecomposition.getNetworkResources(); - this.serviceRole = serviceDecomposition.getServiceRole(); - this.serviceType = serviceDecomposition.getServiceType(); - this.configResources = serviceDecomposition.getConfigResources(); - } - - /** - * Constructor taking Catalog DB Adapter REST output (serviceResources model) + service Instance ID - * - * @param catalogRestOutput - * @param serviceInstanceId - */ - public ServiceDecomposition (String catalogRestOutput, String serviceInstanceId) throws JsonDecomposingException { - ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.jsonToServiceDecomposition(catalogRestOutput); - this.modelInfo = serviceDecomposition.getModelInfo(); - this.vnfResources = serviceDecomposition.getVnfResources(); - this.allottedResources = serviceDecomposition.getAllottedResources(); - this.configResources = serviceDecomposition.getConfigResources(); - this.networkResources = serviceDecomposition.getNetworkResources(); - - this.serviceRole = serviceDecomposition.getServiceRole(); - this.serviceType = serviceDecomposition.getServiceType(); - - this.serviceInstance = new ServiceInstance(); - this.serviceInstance.setInstanceId(serviceInstanceId); - - this.project = serviceDecomposition.getProject(); - this.owningEntity = serviceDecomposition.getOwningEntity(); - } - - /** - * Constructor taking a Service Decomposition JSON serialization - * @param catalogRestOutput - * @param serviceInstanceId - */ - public ServiceDecomposition (JSONObject jsonServiceDecomposition, String serviceInstanceId) { - //TODO provide constructor implementation - - } - - //***** - //GET and SET section - /** - * Return just the service model portion of the Service Decomposition as a Java object. - * The service model object should support retrieval as JSON string that is formatted correctly for sending serviceModelInfo to Building Blocks. - * @return - */ - public ModelInfo getModelInfo() { - return modelInfo; - } - public void setModelInfo(ModelInfo modelInfo) { - this.modelInfo = modelInfo; - } - public ServiceInstance getServiceInstance() { - return serviceInstance; - } - public void setServiceInstance(ServiceInstance serviceInstance) { - this.serviceInstance = serviceInstance; - } - public Project getProject() { - return project; - } - public OwningEntity getOwningEntity() { - return owningEntity; - } - public void setProject(Project project) { - this.project = project; - } - public void setOwningEntity(OwningEntity owningEntity) { - this.owningEntity = owningEntity; - } - public List<VnfResource> getVnfResources() { - return vnfResources; - } - public void setVnfResources(List<VnfResource> vnfResources) { - this.vnfResources = vnfResources; - } - public void setConfigResources(List<ConfigResource> configResources) { - this.configResources = configResources; - } - public List<ConfigResource> getConfigResources() { - return configResources; - } - public void setNetworkResources(List<NetworkResource> networkResources) { - this.networkResources = networkResources; - } - public List<NetworkResource> getNetworkResources() { - return networkResources; - } - public List<AllottedResource> getAllottedResources() { - return allottedResources; - } - public void setAllottedResources(List<AllottedResource> allottedResources) { - this.allottedResources = allottedResources; - } - public String getServiceType() { - return serviceType; - } - - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - - public String getServiceRole() { - return serviceRole; - } - - public void setServiceRole(String serviceRole) { - this.serviceRole = serviceRole; - } - public Request getRequest() { - return request; - } - - public void setRequest(Request request) { - this.request = request; - } - public Customer getCustomer() { - return customer; - } - public void setCustomer(Customer customer) { - this.customer = customer; - } - public String getCallbackURN() { - return callbackURN; - } - - public void setCallbackURN(String callbackURN) { - this.callbackURN = callbackURN; - } - public String getSdncVersion() { - return sdncVersion; - } - - public void setSdncVersion(String sdncVersion) { - this.sdncVersion = sdncVersion; - } - - //***** - - //***** - //Access methods - - - /** - * This method returns one combined list of Resources of All Types - * @return - */ - @JsonIgnore - public List<Resource> getServiceResources(){ - ArrayList serviceResources = new ArrayList(); - if(this.getAllottedResources() != null){ - serviceResources.addAll(this.getAllottedResources()); - } - if(this.getNetworkResources() != null){ - serviceResources.addAll(this.getNetworkResources()); - } - if(this.getVnfResources() != null){ - serviceResources.addAll(this.getVnfResources()); - } - if(this.getConfigResources() != null){ - serviceResources.addAll(this.getConfigResources()); - } - return serviceResources; - } - - /** - * This method returns String representation of one combined list of Resources of All Types - */ - @JsonIgnore - public String getServiceResourcesJsonString() { - return getServiceNetworksJson() + - getServiceVnfsJson() + - getServiceAllottedResourcesJson() + - getServiceConfigResourcesJson(); - } - - /** - * Returns a JSON list of all Network Resource structures (i.e. the serialized NetworkDecomposition objects). - * @return - */ - @JsonIgnore - public String getServiceNetworksJson(){ - return listToJson(this.getNetworkResources()); - } - /** - * Returns a JSON list of all VnfResource structures (i.e. the serialized VnfResource objects). - * @return - */ - @JsonIgnore - public String getServiceVnfsJson(){ - return listToJson(this.getVnfResources()); - } - /** - * Returns a JSON list of all Allotted Resource structures (i.e. the serialized AllottedResource objects). - * @return - */ - @JsonIgnore - public String getServiceAllottedResourcesJson(){ - return listToJson(this.getAllottedResources()); - } - /** - * Returns a JSON list of all Config Resource structures (i.e. the serialized ConfigResource objects). - * @return - */ - @JsonIgnore - public String getServiceConfigResourcesJson(){ - return listToJson(this.getConfigResources()); - } - - //TODO - define Resource Object ID - @JsonIgnore - public String getVnfResource(String resourceObjectId) { + private static final long serialVersionUID = 1L; + + @JsonProperty("modelInfo") + private ModelInfo modelInfo; + @JsonProperty("serviceType") + private String serviceType; + @JsonProperty("serviceRole") + private String serviceRole; + private ServiceInstance serviceInstance; + private Request request; + private Customer customer; + private String callbackURN; + private String sdncVersion; + @JsonProperty("project") + private Project project; + @JsonProperty("owningEntity") + private OwningEntity owningEntity; + @JsonProperty("serviceVnfs") + private List<VnfResource> vnfResources; + @JsonProperty("serviceNetworks") + private List<NetworkResource> networkResources; + @JsonProperty("serviceAllottedResources") + private List<AllottedResource> allottedResources; + @JsonProperty("configResource") + private List<ConfigResource> configResources; + + public ServiceDecomposition() { + super(); + } + + public ServiceDecomposition(String catalogRestOutput) throws JsonDecomposingException { + ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.jsonToServiceDecomposition(catalogRestOutput); + this.modelInfo = serviceDecomposition.getModelInfo(); + this.vnfResources = serviceDecomposition.getVnfResources(); + this.allottedResources = serviceDecomposition.getAllottedResources(); + this.networkResources = serviceDecomposition.getNetworkResources(); + this.serviceRole = serviceDecomposition.getServiceRole(); + this.serviceType = serviceDecomposition.getServiceType(); + this.configResources = serviceDecomposition.getConfigResources(); + } + + /** + * Constructor taking Catalog DB Adapter REST output (serviceResources model) + service Instance ID + * + * @param catalogRestOutput + * @param serviceInstanceId + */ + public ServiceDecomposition(String catalogRestOutput, String serviceInstanceId) throws JsonDecomposingException { + ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.jsonToServiceDecomposition(catalogRestOutput); + this.modelInfo = serviceDecomposition.getModelInfo(); + this.vnfResources = serviceDecomposition.getVnfResources(); + this.allottedResources = serviceDecomposition.getAllottedResources(); + this.configResources = serviceDecomposition.getConfigResources(); + this.networkResources = serviceDecomposition.getNetworkResources(); + + this.serviceRole = serviceDecomposition.getServiceRole(); + this.serviceType = serviceDecomposition.getServiceType(); + + this.serviceInstance = new ServiceInstance(); + this.serviceInstance.setInstanceId(serviceInstanceId); + + this.project = serviceDecomposition.getProject(); + this.owningEntity = serviceDecomposition.getOwningEntity(); + } + + /** + * Constructor taking a Service Decomposition JSON serialization + * + * @param catalogRestOutput + * @param serviceInstanceId + */ + public ServiceDecomposition(JSONObject jsonServiceDecomposition, String serviceInstanceId) { + // TODO provide constructor implementation + + } + + // ***** + // GET and SET section + /** + * Return just the service model portion of the Service Decomposition as a Java object. The service model object + * should support retrieval as JSON string that is formatted correctly for sending serviceModelInfo to Building + * Blocks. + * + * @return + */ + public ModelInfo getModelInfo() { + return modelInfo; + } + + public void setModelInfo(ModelInfo modelInfo) { + this.modelInfo = modelInfo; + } + + public ServiceInstance getServiceInstance() { + return serviceInstance; + } + + public void setServiceInstance(ServiceInstance serviceInstance) { + this.serviceInstance = serviceInstance; + } + + public Project getProject() { + return project; + } + + public OwningEntity getOwningEntity() { + return owningEntity; + } + + public void setProject(Project project) { + this.project = project; + } + + public void setOwningEntity(OwningEntity owningEntity) { + this.owningEntity = owningEntity; + } + + public List<VnfResource> getVnfResources() { + return vnfResources; + } + + public void setVnfResources(List<VnfResource> vnfResources) { + this.vnfResources = vnfResources; + } + + public void setConfigResources(List<ConfigResource> configResources) { + this.configResources = configResources; + } + + public List<ConfigResource> getConfigResources() { + return configResources; + } + + public void setNetworkResources(List<NetworkResource> networkResources) { + this.networkResources = networkResources; + } + + public List<NetworkResource> getNetworkResources() { + return networkResources; + } + + public List<AllottedResource> getAllottedResources() { + return allottedResources; + } + + public void setAllottedResources(List<AllottedResource> allottedResources) { + this.allottedResources = allottedResources; + } + + public String getServiceType() { + return serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceRole() { + return serviceRole; + } + + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } + + public Request getRequest() { + return request; + } + + public void setRequest(Request request) { + this.request = request; + } + + public Customer getCustomer() { + return customer; + } + + public void setCustomer(Customer customer) { + this.customer = customer; + } + + public String getCallbackURN() { + return callbackURN; + } + + public void setCallbackURN(String callbackURN) { + this.callbackURN = callbackURN; + } + + public String getSdncVersion() { + return sdncVersion; + } + + public void setSdncVersion(String sdncVersion) { + this.sdncVersion = sdncVersion; + } + + // ***** + + // ***** + // Access methods + + + /** + * This method returns one combined list of Resources of All Types + * + * @return + */ + @JsonIgnore + public List<Resource> getServiceResources() { + ArrayList serviceResources = new ArrayList(); + if (this.getAllottedResources() != null) { + serviceResources.addAll(this.getAllottedResources()); + } + if (this.getNetworkResources() != null) { + serviceResources.addAll(this.getNetworkResources()); + } + if (this.getVnfResources() != null) { + serviceResources.addAll(this.getVnfResources()); + } + if (this.getConfigResources() != null) { + serviceResources.addAll(this.getConfigResources()); + } + return serviceResources; + } + + /** + * This method returns String representation of one combined list of Resources of All Types + */ + @JsonIgnore + public String getServiceResourcesJsonString() { + return getServiceNetworksJson() + getServiceVnfsJson() + getServiceAllottedResourcesJson() + + getServiceConfigResourcesJson(); + } + + /** + * Returns a JSON list of all Network Resource structures (i.e. the serialized NetworkDecomposition objects). + * + * @return + */ + @JsonIgnore + public String getServiceNetworksJson() { + return listToJson(this.getNetworkResources()); + } + + /** + * Returns a JSON list of all VnfResource structures (i.e. the serialized VnfResource objects). + * + * @return + */ + @JsonIgnore + public String getServiceVnfsJson() { + return listToJson(this.getVnfResources()); + } + + /** + * Returns a JSON list of all Allotted Resource structures (i.e. the serialized AllottedResource objects). + * + * @return + */ + @JsonIgnore + public String getServiceAllottedResourcesJson() { + return listToJson(this.getAllottedResources()); + } + + /** + * Returns a JSON list of all Config Resource structures (i.e. the serialized ConfigResource objects). + * + * @return + */ + @JsonIgnore + public String getServiceConfigResourcesJson() { + return listToJson(this.getConfigResources()); + } + + // TODO - define Resource Object ID + @JsonIgnore + public String getVnfResource(String resourceObjectId) { for (Resource resource : getServiceResources()) { - //resource.getModelInfo().getModelInvariantId(); + // resource.getModelInfo().getModelInvariantId(); if ("extracted information".equals(resourceObjectId)) { return resource.toJsonString(); } } - return ""; - } - - //Methods to add Resource to the list - /** - * Add VNF resource to the list - * @param vnfResource - */ - public void addVnfResource(Resource vnfResource) { - if (vnfResources == null){ - vnfResources = new ArrayList<>(); - } - this.vnfResources.add((VnfResource)vnfResource); - } - /** - * Add Network resource to the list - * @param networkResource - */ - public void addNetworkResource(Resource networkResource) { - if (networkResources == null){ - networkResources = new ArrayList<>(); - } - this.networkResources.add((NetworkResource)networkResource); - } - /** - * Add Allotted resource to the list - * @param allottedResource - */ - public void addAllottedResource(Resource allottedResource) { - if (allottedResources == null){ - allottedResources = new ArrayList<>(); - } - this.allottedResources.add((AllottedResource)allottedResource); - } - /** - * Add Config resource to the list - * @param allottedResource - */ - public void addConfigResource(Resource configResource) { - if (configResources == null){ - configResources = new ArrayList<>(); - } - this.configResources.add((ConfigResource)configResource); - } - /** - * Add resource to the list - * Given a ResourceDecomposition (subclass) object, add it to the Service Decomposition (in the appropriate category, e.g. as a VNF, Network, or Allotted Resource). - * As dependencies are not currently supported, add it to the end of any ordered lists. - * @param resource - */ - public void addResource(Resource resource) { - //create resource based upon type - switch (resource.resourceType) { - case VNF: - this.addVnfResource(resource); - break; - case NETWORK: - this.addNetworkResource(resource); - break; - case ALLOTTED_RESOURCE: - this.addAllottedResource(resource); - break; - case CONFIGURATION: - this.addConfigResource(resource); - break; - default: - throw new IllegalArgumentException("Invalid resource type: " + resource.resourceType); - } - } - - /** - * Add resource to the list - * @param jsonResource - */ - public void addVnfResource(String jsonResource) throws JsonDecomposingException { - VnfResource vnfResource = null; - vnfResource = DecomposeJsonUtil.jsonToVnfResource(jsonResource); - this.addVnfResource(vnfResource); - } - /** - * Add resource to the list - * @param jsonResource - */ - public void addNetworkResource(String jsonResource) throws JsonDecomposingException { - NetworkResource networkResource = null; - networkResource = DecomposeJsonUtil.jsonToNetworkResource(jsonResource); - this.addNetworkResource(networkResource); - } - /** - * Add resource to the list - * @param Resource - */ - public void addAllottedResource(String jsonResource) throws JsonDecomposingException { - AllottedResource allottedResource = null; - allottedResource = DecomposeJsonUtil.jsonToAllottedResource(jsonResource); - this.addAllottedResource(allottedResource); - } - /** - * Add resource to the list - * @param Resource - */ - public void addConfigResource(String jsonResource) throws JsonDecomposingException { - ConfigResource configResource = null; - configResource = DecomposeJsonUtil.jsonToConfigResource(jsonResource); - this.addConfigResource(configResource); - } - /** - * Given a ResourceDecomposition (subclass) object, locate it in the Service Decomposition by its unique ID, and replace the current version with the new one. - * This method should support concurrency control via an auto-incrementing field in the ResourceDecomposition class. - * @param newResource - * @return TRUE if replacement was a success - */ - public boolean replaceResource(Resource newResource){ - List resources = getResourceList(newResource); - - boolean result = false; - for (Resource resource : (Iterable<Resource>) resources) { - System.out.println("resource found"); - if (resource.resourceType == newResource.resourceType) { - System.out.println("resource type matches"); - if (resource.getResourceId().equalsIgnoreCase(newResource.getResourceId())) { - System.out.println("resource id matches"); - //returns TRUE if replacement is a success - result = Collections.replaceAll(resources, resource, newResource); - } - } - } - return result; - } - - /** - * Given a ResourceDecomposition as a JSON string, locate it in the Service Decomposition by its unique ID, - * and replace the current version with the new one. - * @param jsonString - * @return - */ - public boolean replaceResource(String jsonString){ - //TODO: define unique ID for the Resource! - return false; - } - - /** - * Given a resource object ID, locate it in the Service Decomposition by its unique ID, and delete it. - * @param resource - * @return TRUE if delete was a success - */ - public boolean deleteResource(Resource resource){ - List serviceResourceList = getResourceList(resource); - for (Resource item : (Iterable<Resource>) serviceResourceList) { - if (item.resourceType == resource.resourceType) { - if (item.getResourceId().equalsIgnoreCase(resource.getResourceId())) { - //returns TRUE if replacement is a success - return serviceResourceList.remove(resource); - } - } - } - - return false; - } - - /** - * Generic method to get List of Resource objects based on input resource's resourceType - * @param resource - * @return List matching the resourceType of resource - */ - public List getResourceList(Resource resource) { - List resourceList; - switch(resource.getResourceType()) { - case VNF: - resourceList = getVnfResources(); - break; - case NETWORK: - resourceList = getNetworkResources(); - break; - case ALLOTTED_RESOURCE: - resourceList = getAllottedResources(); - break; - case CONFIGURATION: - resourceList = getConfigResources(); - break; - default: - resourceList = new ArrayList<>(); - } - return resourceList; - } - - /** - * Generic method to set List of ResourceDecomposition objects - * @param resources - * @return - */ - public boolean setResourceList(List<Resource> resources){ - if(resources != null && !resources.isEmpty()) { - //create resource based upon type - switch (resources.get(0).resourceType) { - case VNF: - this.setVnfResources((List<VnfResource>)(List<?>)resources); - break; - case NETWORK: - this.setNetworkResources((List<NetworkResource>)(List<?>)resources); - break; - case ALLOTTED_RESOURCE: - this.setAllottedResources((List<AllottedResource>)(List<?>)resources); - break; - case CONFIGURATION: - this.setConfigResources((List<ConfigResource>)(List<?>)resources); - break; - default: - throw new IllegalArgumentException("Invalid resource type: " + resources.get(0).resourceType); - } - } - - return false; - } - - /** - * - * This method locates and returns a resource in a given - * Service Decomposition object by its unique resource id. - * Returns null if resource doesn't exist. - * - * @param resourceId - id of the resource - * @return resource - */ - @JsonIgnore - public Resource getServiceResource(String resourceId){ - List<Resource> resources = getServiceResources(); - for (Resource resource : resources) { - if (resource.getResourceId().equalsIgnoreCase(resourceId)) { - //match - return resource; - } - } - return null; - } + return ""; + } + + // Methods to add Resource to the list + /** + * Add VNF resource to the list + * + * @param vnfResource + */ + public void addVnfResource(Resource vnfResource) { + if (vnfResources == null) { + vnfResources = new ArrayList<>(); + } + this.vnfResources.add((VnfResource) vnfResource); + } + + /** + * Add Network resource to the list + * + * @param networkResource + */ + public void addNetworkResource(Resource networkResource) { + if (networkResources == null) { + networkResources = new ArrayList<>(); + } + this.networkResources.add((NetworkResource) networkResource); + } + + /** + * Add Allotted resource to the list + * + * @param allottedResource + */ + public void addAllottedResource(Resource allottedResource) { + if (allottedResources == null) { + allottedResources = new ArrayList<>(); + } + this.allottedResources.add((AllottedResource) allottedResource); + } + + /** + * Add Config resource to the list + * + * @param allottedResource + */ + public void addConfigResource(Resource configResource) { + if (configResources == null) { + configResources = new ArrayList<>(); + } + this.configResources.add((ConfigResource) configResource); + } + + /** + * Add resource to the list Given a ResourceDecomposition (subclass) object, add it to the Service Decomposition (in + * the appropriate category, e.g. as a VNF, Network, or Allotted Resource). As dependencies are not currently + * supported, add it to the end of any ordered lists. + * + * @param resource + */ + public void addResource(Resource resource) { + // create resource based upon type + switch (resource.resourceType) { + case VNF: + this.addVnfResource(resource); + break; + case NETWORK: + this.addNetworkResource(resource); + break; + case ALLOTTED_RESOURCE: + this.addAllottedResource(resource); + break; + case CONFIGURATION: + this.addConfigResource(resource); + break; + default: + throw new IllegalArgumentException("Invalid resource type: " + resource.resourceType); + } + } + + /** + * Add resource to the list + * + * @param jsonResource + */ + public void addVnfResource(String jsonResource) throws JsonDecomposingException { + VnfResource vnfResource = null; + vnfResource = DecomposeJsonUtil.jsonToVnfResource(jsonResource); + this.addVnfResource(vnfResource); + } + + /** + * Add resource to the list + * + * @param jsonResource + */ + public void addNetworkResource(String jsonResource) throws JsonDecomposingException { + NetworkResource networkResource = null; + networkResource = DecomposeJsonUtil.jsonToNetworkResource(jsonResource); + this.addNetworkResource(networkResource); + } + + /** + * Add resource to the list + * + * @param Resource + */ + public void addAllottedResource(String jsonResource) throws JsonDecomposingException { + AllottedResource allottedResource = null; + allottedResource = DecomposeJsonUtil.jsonToAllottedResource(jsonResource); + this.addAllottedResource(allottedResource); + } + + /** + * Add resource to the list + * + * @param Resource + */ + public void addConfigResource(String jsonResource) throws JsonDecomposingException { + ConfigResource configResource = null; + configResource = DecomposeJsonUtil.jsonToConfigResource(jsonResource); + this.addConfigResource(configResource); + } + + /** + * Given a ResourceDecomposition (subclass) object, locate it in the Service Decomposition by its unique ID, and + * replace the current version with the new one. This method should support concurrency control via an + * auto-incrementing field in the ResourceDecomposition class. + * + * @param newResource + * @return TRUE if replacement was a success + */ + public boolean replaceResource(Resource newResource) { + List resources = getResourceList(newResource); + + boolean result = false; + for (Resource resource : (Iterable<Resource>) resources) { + System.out.println("resource found"); + if (resource.resourceType == newResource.resourceType) { + System.out.println("resource type matches"); + if (resource.getResourceId().equalsIgnoreCase(newResource.getResourceId())) { + System.out.println("resource id matches"); + // returns TRUE if replacement is a success + result = Collections.replaceAll(resources, resource, newResource); + } + } + } + return result; + } + + /** + * Given a ResourceDecomposition as a JSON string, locate it in the Service Decomposition by its unique ID, and + * replace the current version with the new one. + * + * @param jsonString + * @return + */ + public boolean replaceResource(String jsonString) { + // TODO: define unique ID for the Resource! + return false; + } + + /** + * Given a resource object ID, locate it in the Service Decomposition by its unique ID, and delete it. + * + * @param resource + * @return TRUE if delete was a success + */ + public boolean deleteResource(Resource resource) { + List serviceResourceList = getResourceList(resource); + for (Resource item : (Iterable<Resource>) serviceResourceList) { + if (item.resourceType == resource.resourceType) { + if (item.getResourceId().equalsIgnoreCase(resource.getResourceId())) { + // returns TRUE if replacement is a success + return serviceResourceList.remove(resource); + } + } + } + + return false; + } + + /** + * Generic method to get List of Resource objects based on input resource's resourceType + * + * @param resource + * @return List matching the resourceType of resource + */ + public List getResourceList(Resource resource) { + List resourceList; + switch (resource.getResourceType()) { + case VNF: + resourceList = getVnfResources(); + break; + case NETWORK: + resourceList = getNetworkResources(); + break; + case ALLOTTED_RESOURCE: + resourceList = getAllottedResources(); + break; + case CONFIGURATION: + resourceList = getConfigResources(); + break; + default: + resourceList = new ArrayList<>(); + } + return resourceList; + } + + /** + * Generic method to set List of ResourceDecomposition objects + * + * @param resources + * @return + */ + public boolean setResourceList(List<Resource> resources) { + if (resources != null && !resources.isEmpty()) { + // create resource based upon type + switch (resources.get(0).resourceType) { + case VNF: + this.setVnfResources((List<VnfResource>) (List<?>) resources); + break; + case NETWORK: + this.setNetworkResources((List<NetworkResource>) (List<?>) resources); + break; + case ALLOTTED_RESOURCE: + this.setAllottedResources((List<AllottedResource>) (List<?>) resources); + break; + case CONFIGURATION: + this.setConfigResources((List<ConfigResource>) (List<?>) resources); + break; + default: + throw new IllegalArgumentException("Invalid resource type: " + resources.get(0).resourceType); + } + } + + return false; + } + + /** + * + * This method locates and returns a resource in a given Service Decomposition object by its unique resource id. + * Returns null if resource doesn't exist. + * + * @param resourceId - id of the resource + * @return resource + */ + @JsonIgnore + public Resource getServiceResource(String resourceId) { + List<Resource> resources = getServiceResources(); + for (Resource resource : resources) { + if (resource.getResourceId().equalsIgnoreCase(resourceId)) { + // match + return resource; + } + } + return null; + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceInstance.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceInstance.java index 5cdbbcb7c9..b0b837b3b9 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceInstance.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceInstance.java @@ -22,14 +22,12 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; import java.util.Map; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonRootName; /** - * This class is used to store instance - * data of services aka ServiceDecomposition + * This class is used to store instance data of services aka ServiceDecomposition * * @author cb645j * @@ -37,96 +35,118 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonIgnoreProperties(ignoreUnknown = true) public class ServiceInstance extends JsonWrapper implements Serializable { - private static final long serialVersionUID = 1L; - private String instanceId; - private String instanceName; - private String orchestrationStatus; - private Configuration configuration; - private String serviceType; - private String serviceRole; - private String serviceId; - private ModelInfo modelInfo; - private String environmentContext; - private String workloadContext; - private Map serviceParams; - private Customer customer = new Customer(); - private String e2eVpnKey; - - public String getServiceType() { - return serviceType; - } - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - public String getServiceId() { - return serviceId; - } - public void setServiceId(String serviceId) { - this.serviceId = serviceId; - } - public Map getServiceParams() { - return serviceParams; - } - public void setServiceParams(Map serviceParams) { - this.serviceParams = serviceParams; - } - public String getInstanceId() { - return instanceId; - } - public void setInstanceId(String instanceId) { - this.instanceId = instanceId; - } - public String getInstanceName() { - return instanceName; - } - public void setInstanceName(String instanceName) { - this.instanceName = instanceName; - } - public String getOrchestrationStatus() { - return orchestrationStatus; - } - public void setOrchestrationStatus(String orchestrationStatus) { - this.orchestrationStatus = orchestrationStatus; - } - public Configuration getConfiguration() { - return configuration; - } - public void setConfiguration(Configuration configuration) { - this.configuration = configuration; - } - public ModelInfo getModelInfo() { - return modelInfo; - } - public void setModelInfo(ModelInfo modelInfo) { - this.modelInfo = modelInfo; - } - public String getEnvironmentContext() { - return environmentContext; - } - public void setEnvironmentContext(String environmentContext) { - this.environmentContext = environmentContext; - } - public String getWorkloadContext() { - return workloadContext; - } - public void setWorkloadContext(String workloadContext) { - this.workloadContext = workloadContext; - } - public String getServiceRole() { - return serviceRole; - } - public void setServiceRole(String serviceRole) { - this.serviceRole = serviceRole; - } - public Customer getCustomer(){ - return customer; - } - - public String getE2eVpnKey(){ - return e2eVpnKey; - } - - public void setE2eVpnKey(String e2eVpnKey){ - this.e2eVpnKey = e2eVpnKey; - } + private static final long serialVersionUID = 1L; + private String instanceId; + private String instanceName; + private String orchestrationStatus; + private Configuration configuration; + private String serviceType; + private String serviceRole; + private String serviceId; + private ModelInfo modelInfo; + private String environmentContext; + private String workloadContext; + private Map serviceParams; + private Customer customer = new Customer(); + private String e2eVpnKey; + + public String getServiceType() { + return serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceId() { + return serviceId; + } + + public void setServiceId(String serviceId) { + this.serviceId = serviceId; + } + + public Map getServiceParams() { + return serviceParams; + } + + public void setServiceParams(Map serviceParams) { + this.serviceParams = serviceParams; + } + + public String getInstanceId() { + return instanceId; + } + + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + public String getInstanceName() { + return instanceName; + } + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + public String getOrchestrationStatus() { + return orchestrationStatus; + } + + public void setOrchestrationStatus(String orchestrationStatus) { + this.orchestrationStatus = orchestrationStatus; + } + + public Configuration getConfiguration() { + return configuration; + } + + public void setConfiguration(Configuration configuration) { + this.configuration = configuration; + } + + public ModelInfo getModelInfo() { + return modelInfo; + } + + public void setModelInfo(ModelInfo modelInfo) { + this.modelInfo = modelInfo; + } + + public String getEnvironmentContext() { + return environmentContext; + } + + public void setEnvironmentContext(String environmentContext) { + this.environmentContext = environmentContext; + } + + public String getWorkloadContext() { + return workloadContext; + } + + public void setWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } + + public String getServiceRole() { + return serviceRole; + } + + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } + + public Customer getCustomer() { + return customer; + } + + public String getE2eVpnKey() { + return e2eVpnKey; + } + + public void setE2eVpnKey(String e2eVpnKey) { + this.e2eVpnKey = e2eVpnKey; + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Subscriber.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Subscriber.java index e9028ded17..620d8311e7 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Subscriber.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Subscriber.java @@ -24,46 +24,46 @@ import java.io.Serializable; public class Subscriber implements Serializable { - private static final long serialVersionUID = -2416018315129127022L; - private String globalId; - private String name; - private String commonSiteId; + private static final long serialVersionUID = -2416018315129127022L; + private String globalId; + private String name; + private String commonSiteId; - public Subscriber(String globalId, String name, String commonSiteId){ - super(); - this.globalId = globalId; - this.name = name; - this.commonSiteId = commonSiteId; - } + public Subscriber(String globalId, String name, String commonSiteId) { + super(); + this.globalId = globalId; + this.name = name; + this.commonSiteId = commonSiteId; + } - public String getGlobalId(){ - return globalId; - } + public String getGlobalId() { + return globalId; + } - public void setGlobalId(String globalId){ - this.globalId = globalId; - } + public void setGlobalId(String globalId) { + this.globalId = globalId; + } - public String getName(){ - return name; - } + public String getName() { + return name; + } - public void setName(String name){ - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getCommonSiteId(){ - return commonSiteId; - } + public String getCommonSiteId() { + return commonSiteId; + } - public void setCommonSiteId(String commonSiteId){ - this.commonSiteId = commonSiteId; - } + public void setCommonSiteId(String commonSiteId) { + this.commonSiteId = commonSiteId; + } -}
\ No newline at end of file +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Vnf.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Vnf.java index 83043b3ec5..293378f969 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Vnf.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Vnf.java @@ -21,12 +21,10 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonRootName; /** - * This class is used to store instance - * data of Vnf for ServiceDecomposition + * This class is used to store instance data of Vnf for ServiceDecomposition * * @author bb3476 * @@ -34,106 +32,133 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("vnf") public class Vnf extends JsonWrapper implements Serializable { - private static final long serialVersionUID = 1L; - private String vnfId; - private String vnfName; - private String serviceId; - private String vnfType; - private String orchStatus; - private String modelInvariantId; - private String modelVersionId; - private String modelCustomizationId; - private String nfType; - private String nfRole; - private String nfFunction; - private String nfNamingCode; - private String tenantId; - private String cloudSiteId; - - - public String getVnfName() { - return vnfName; - } - public void setVnfName(String vnfName) { - this.vnfName = vnfName; - } - public String getServiceId() { - return serviceId; - } - public void setServiceId(String serviceId) { - this.serviceId = serviceId; - } - public String getVnfType() { - return vnfType; - } - public void setVnfType(String vnfType) { - this.vnfType = vnfType; - } - public String getOrchStatus() { - return orchStatus; - } - public void setOrchStatus(String orchStatus) { - this.orchStatus = orchStatus; - } - public String getModelInvariantId() { - return modelInvariantId; - } - public void setModelInvariantId(String modelInvariantId) { - this.modelInvariantId = modelInvariantId; - } - public String getModelVersionId() { - return modelVersionId; - } - public void setModelVersionId(String modelVersionId) { - this.modelVersionId = modelVersionId; - } - public String getModelCustomizationId() { - return modelCustomizationId; - } - public void setModelCustomizationId(String modelCustomizationId) { - this.modelCustomizationId = modelCustomizationId; - } - public String getNfType() { - return nfType; - } - public void setNfType(String nfType) { - this.nfType = nfType; - } - public String getNfRole() { - return nfRole; - } - public void setNfRole(String nfRole) { - this.nfRole = nfRole; - } - public String getNfFunction() { - return nfFunction; - } - public void setNfFunction(String nfFunction) { - this.nfFunction = nfFunction; - } - public String getNfNamingCode() { - return nfNamingCode; - } - public void setNfNamingCode(String nfNamingCode) { - this.nfNamingCode = nfNamingCode; - } - public String getVnfId() { - return vnfId; - } - public void setVnfId(String vnfId) { - this.vnfId = vnfId; - } - public String getTenantId() { - return tenantId; - } - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } - public String getCloudSiteId() { - return cloudSiteId; - } - public void setCloudSiteId(String cloudSiteId) { - this.cloudSiteId = cloudSiteId; - } - + private static final long serialVersionUID = 1L; + private String vnfId; + private String vnfName; + private String serviceId; + private String vnfType; + private String orchStatus; + private String modelInvariantId; + private String modelVersionId; + private String modelCustomizationId; + private String nfType; + private String nfRole; + private String nfFunction; + private String nfNamingCode; + private String tenantId; + private String cloudSiteId; + + + public String getVnfName() { + return vnfName; + } + + public void setVnfName(String vnfName) { + this.vnfName = vnfName; + } + + public String getServiceId() { + return serviceId; + } + + public void setServiceId(String serviceId) { + this.serviceId = serviceId; + } + + public String getVnfType() { + return vnfType; + } + + public void setVnfType(String vnfType) { + this.vnfType = vnfType; + } + + public String getOrchStatus() { + return orchStatus; + } + + public void setOrchStatus(String orchStatus) { + this.orchStatus = orchStatus; + } + + public String getModelInvariantId() { + return modelInvariantId; + } + + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + public String getModelVersionId() { + return modelVersionId; + } + + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + public String getModelCustomizationId() { + return modelCustomizationId; + } + + public void setModelCustomizationId(String modelCustomizationId) { + this.modelCustomizationId = modelCustomizationId; + } + + public String getNfType() { + return nfType; + } + + public void setNfType(String nfType) { + this.nfType = nfType; + } + + public String getNfRole() { + return nfRole; + } + + public void setNfRole(String nfRole) { + this.nfRole = nfRole; + } + + public String getNfFunction() { + return nfFunction; + } + + public void setNfFunction(String nfFunction) { + this.nfFunction = nfFunction; + } + + public String getNfNamingCode() { + return nfNamingCode; + } + + public void setNfNamingCode(String nfNamingCode) { + this.nfNamingCode = nfNamingCode; + } + + public String getVnfId() { + return vnfId; + } + + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public String getCloudSiteId() { + return cloudSiteId; + } + + public void setCloudSiteId(String cloudSiteId) { + this.cloudSiteId = cloudSiteId; + } + } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java index a7e5389583..f66ad36058 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java @@ -23,7 +23,6 @@ package org.onap.so.bpmn.core.domain; import java.util.ArrayList; import java.util.List; import java.util.UUID; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @@ -36,154 +35,170 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("vnfResource") public class VnfResource extends Resource { - private static final long serialVersionUID = 1L; - - /* - * set resourceType for this object - */ - public VnfResource(){ - resourceType = ResourceType.VNF; - setResourceId(UUID.randomUUID().toString()); - } - - /* - * fields specific to VNF resource type - */ - @JsonProperty("vfModules") - private List <ModuleResource> vfModules; - private String vnfHostname; - private String vnfType; - private String nfFunction; - private String nfType; - private String nfRole; - private String nfNamingCode; - private String multiStageDesign; - private String orchestrationStatus; - - @JsonIgnore - private String resourceInput; - - /* - * GET and SET - */ - public List<ModuleResource> getVfModules() { - return vfModules; - } - public void setModules(List<ModuleResource> moduleResources) { - this.vfModules = moduleResources; - } - public String getVnfHostname() { - return vnfHostname; - } - public void setVnfHostname(String vnfHostname) { - this.vnfHostname = vnfHostname; - } - @Deprecated - public void setVnfType(String vnfType) { - this.vnfType = vnfType; - } - public String getVnfType() { - return vnfType; - } - public String getNfFunction() { - return nfFunction; - } - public void setNfFunction(String nfFunction) { - this.nfFunction = nfFunction; - } - public String getNfType() { - return nfType; - } - public void setNfType(String nfType) { - this.nfType = nfType; - } - public String getNfRole() { - return nfRole; - } - public void setNfRole(String nfRole) { - this.nfRole = nfRole; - } - public String getNfNamingCode() { - return nfNamingCode; - } - public void setNfNamingCode(String nfNamingCode) { - this.nfNamingCode = nfNamingCode; - } - public String getMultiStageDesign() { - return multiStageDesign; - } - public void setMultiStageDesign(String multiStageDesign) { - this.multiStageDesign = multiStageDesign; - } - /* - * GET accessors per design requirements - */ - - - public String getOrchestrationStatus(){ - return orchestrationStatus; - } - - public void setOrchestrationStatus(String orchestrationStatus){ - this.orchestrationStatus = orchestrationStatus; - } - - public String getResourceInput() { - return resourceInput; - } - - public void setResourceInput(String resourceInput) { - this.resourceInput = resourceInput; - } - - /** - * Returns a list of all VfModule objects. - * Base module is first entry in the list - * @return ordered list of ModuleResources objects - */ - @JsonIgnore - public List<ModuleResource> getAllVfModuleObjects(){ - if (vfModules == null) { - return null; - } - - for (int i = 0; i < vfModules.size(); i++) { - ModuleResource moduleResource = vfModules.get(i); - if (moduleResource.getIsBase()){ - vfModules.remove(moduleResource); - vfModules.add(0,moduleResource); - } - } - return vfModules; - } - - /** - * - * @return Returns JSON list of all VfModule structures. - */ - @JsonIgnore - public String getAllVfModulesJson(){ - - return listToJson(vfModules); - } - - // methods to add to the list - public void addVfModule(ModuleResource moduleResource) { - if (vfModules == null){ - vfModules = new ArrayList<>(); - } - this.vfModules.add(moduleResource); - } - - - /** - * Utility method to allow construction of the filed in the form of - * <serviceResources.modelInfo.modelName>/<serviceVnfs.modelInfo.modelInstanceName> - * - * default setter for this field deprecated - * @param modelName << serviceResources.modelInfo.modelName - */ - public void constructVnfType(String modelName) { - this.vnfType = modelName.concat("/").concat(this.modelInfo.getModelInstanceName()); - } -}
\ No newline at end of file + private static final long serialVersionUID = 1L; + + /* + * set resourceType for this object + */ + public VnfResource() { + resourceType = ResourceType.VNF; + setResourceId(UUID.randomUUID().toString()); + } + + /* + * fields specific to VNF resource type + */ + @JsonProperty("vfModules") + private List<ModuleResource> vfModules; + private String vnfHostname; + private String vnfType; + private String nfFunction; + private String nfType; + private String nfRole; + private String nfNamingCode; + private String multiStageDesign; + private String orchestrationStatus; + + @JsonIgnore + private String resourceInput; + + /* + * GET and SET + */ + public List<ModuleResource> getVfModules() { + return vfModules; + } + + public void setModules(List<ModuleResource> moduleResources) { + this.vfModules = moduleResources; + } + + public String getVnfHostname() { + return vnfHostname; + } + + public void setVnfHostname(String vnfHostname) { + this.vnfHostname = vnfHostname; + } + + @Deprecated + public void setVnfType(String vnfType) { + this.vnfType = vnfType; + } + + public String getVnfType() { + return vnfType; + } + + public String getNfFunction() { + return nfFunction; + } + + public void setNfFunction(String nfFunction) { + this.nfFunction = nfFunction; + } + + public String getNfType() { + return nfType; + } + + public void setNfType(String nfType) { + this.nfType = nfType; + } + + public String getNfRole() { + return nfRole; + } + + public void setNfRole(String nfRole) { + this.nfRole = nfRole; + } + + public String getNfNamingCode() { + return nfNamingCode; + } + + public void setNfNamingCode(String nfNamingCode) { + this.nfNamingCode = nfNamingCode; + } + + public String getMultiStageDesign() { + return multiStageDesign; + } + + public void setMultiStageDesign(String multiStageDesign) { + this.multiStageDesign = multiStageDesign; + } + /* + * GET accessors per design requirements + */ + + + public String getOrchestrationStatus() { + return orchestrationStatus; + } + + public void setOrchestrationStatus(String orchestrationStatus) { + this.orchestrationStatus = orchestrationStatus; + } + + public String getResourceInput() { + return resourceInput; + } + + public void setResourceInput(String resourceInput) { + this.resourceInput = resourceInput; + } + + /** + * Returns a list of all VfModule objects. Base module is first entry in the list + * + * @return ordered list of ModuleResources objects + */ + @JsonIgnore + public List<ModuleResource> getAllVfModuleObjects() { + if (vfModules == null) { + return null; + } + + for (int i = 0; i < vfModules.size(); i++) { + ModuleResource moduleResource = vfModules.get(i); + if (moduleResource.getIsBase()) { + vfModules.remove(moduleResource); + vfModules.add(0, moduleResource); + } + } + return vfModules; + } + + /** + * + * @return Returns JSON list of all VfModule structures. + */ + @JsonIgnore + public String getAllVfModulesJson() { + + return listToJson(vfModules); + } + + // methods to add to the list + public void addVfModule(ModuleResource moduleResource) { + if (vfModules == null) { + vfModules = new ArrayList<>(); + } + this.vfModules.add(moduleResource); + } + + + /** + * Utility method to allow construction of the filed in the form of + * <serviceResources.modelInfo.modelName>/<serviceVnfs.modelInfo.modelInstanceName> + * + * default setter for this field deprecated + * + * @param modelName << serviceResources.modelInfo.modelName + */ + public void constructVnfType(String modelName) { + this.vnfType = modelName.concat("/").concat(this.modelInfo.getModelInstanceName()); + } +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/internal/VariableNameExtractor.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/internal/VariableNameExtractor.java index f63ab31496..1604e91979 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/internal/VariableNameExtractor.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/internal/VariableNameExtractor.java @@ -25,27 +25,24 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * Extracts variable name from expression if entire expression is just - * one variable, for example "${x}". + * Extracts variable name from expression if entire expression is just one variable, for example "${x}". * * Ignores all whitespaces, except inside variable name. * - * Examples: - * "${x}", extracted variable name is "x" - * " ${\t weird_NAME }", extracted variable name is "weird_NAME" - * "${incorrect name}", no extracted name - * "${two}+${two}", no extracted name + * Examples: "${x}", extracted variable name is "x" " ${\t weird_NAME }", extracted variable name is "weird_NAME" + * "${incorrect name}", no extracted name "${two}+${two}", no extracted name */ public class VariableNameExtractor { - private static final Pattern VARIABLE_NAME_PATTERN = Pattern - .compile("^\\s*\\$\\s*\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\s*$"); + private static final Pattern VARIABLE_NAME_PATTERN = + Pattern.compile("^\\s*\\$\\s*\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\s*$"); private final String expression; /** * Creates new VariableNameExtractor + * * @param expression expression to be parsed */ public VariableNameExtractor(String expression) { @@ -54,6 +51,7 @@ public class VariableNameExtractor { /** * Extracts variable name from expression given in constructor + * * @return Optional of variable name, empty if expression wasn't single variable */ public Optional<String> extract() { diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/DecomposeJsonUtil.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/DecomposeJsonUtil.java index 89f61fec75..93a47ff6b1 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/DecomposeJsonUtil.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/DecomposeJsonUtil.java @@ -24,14 +24,12 @@ package org.onap.so.bpmn.core.json; import java.io.IOException; import java.io.Serializable; - import org.onap.so.bpmn.core.domain.AllottedResource; import org.onap.so.bpmn.core.domain.ConfigResource; import org.onap.so.bpmn.core.domain.NetworkResource; import org.onap.so.bpmn.core.domain.ServiceDecomposition; import org.onap.so.bpmn.core.domain.ServiceInstance; import org.onap.so.bpmn.core.domain.VnfResource; - import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; @@ -39,16 +37,15 @@ import org.slf4j.LoggerFactory; public class DecomposeJsonUtil implements Serializable { - private static final Logger logger = LoggerFactory.getLogger(DecomposeJsonUtil.class); - /** - * - */ - private static final long serialVersionUID = 1L; + private static final Logger logger = LoggerFactory.getLogger(DecomposeJsonUtil.class); + /** + * + */ + private static final long serialVersionUID = 1L; private static final ObjectMapper OBJECT_MAPPER = createObjectMapper(); - private DecomposeJsonUtil() { - } + private DecomposeJsonUtil() {} private static ObjectMapper createObjectMapper() { ObjectMapper om = new ObjectMapper(); @@ -56,24 +53,24 @@ public class DecomposeJsonUtil implements Serializable { return om; } - /** + /** * Method to construct Service Decomposition object converting JSON structure - * + * * @param jsonString input in JSON format confirming ServiceDecomposition * @return decoded object * @throws JsonDecomposingException thrown when decoding json fails - */ + */ public static ServiceDecomposition jsonToServiceDecomposition(String jsonString) throws JsonDecomposingException { try { - ObjectMapper om = new ObjectMapper(); - om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); - om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + ObjectMapper om = new ObjectMapper(); + om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return om.readValue(jsonString, ServiceDecomposition.class); - } catch (IOException e) { + } catch (IOException e) { throw new JsonDecomposingException("Exception while converting json to service decomposition", e); } - } - + } + /** * Method to construct Service Decomposition object converting JSON structure * @@ -88,59 +85,59 @@ public class DecomposeJsonUtil implements Serializable { ServiceInstance serviceInstance = new ServiceInstance(); serviceInstance.setInstanceId(serviceInstanceId); serviceDecomposition.setServiceInstance(serviceInstance); - return serviceDecomposition; - } - - /** + return serviceDecomposition; + } + + /** * Method to construct Resource Decomposition object converting JSON structure - * + * * @param jsonString input in JSON format confirming ResourceDecomposition * @return decoded object * @throws JsonDecomposingException thrown when decoding json fails - */ + */ public static VnfResource jsonToVnfResource(String jsonString) throws JsonDecomposingException { - try { + try { return OBJECT_MAPPER.readValue(jsonString, VnfResource.class); - } catch (IOException e) { + } catch (IOException e) { throw new JsonDecomposingException("Exception while converting json to vnf resource", e); - } - } - - /** + } + } + + /** * Method to construct Resource Decomposition object converting JSON structure - * + * * @param jsonString input in JSON format confirming ResourceDecomposition * @return decoded object * @throws JsonDecomposingException thrown when decoding json fails - */ + */ public static NetworkResource jsonToNetworkResource(String jsonString) throws JsonDecomposingException { - try { + try { return OBJECT_MAPPER.readValue(jsonString, NetworkResource.class); - } catch (IOException e) { + } catch (IOException e) { throw new JsonDecomposingException("Exception while converting json to network resource", e); - } - } - - /** + } + } + + /** * Method to construct Resource Decomposition object converting JSON structure - * - * @param jsonString - input in JSON format confirming ResourceDecomposition + * + * @param jsonString - input in JSON format confirming ResourceDecomposition * @return decoded object * @throws JsonDecomposingException thrown when decoding json fails - */ + */ public static AllottedResource jsonToAllottedResource(String jsonString) throws JsonDecomposingException { - try { + try { return OBJECT_MAPPER.readValue(jsonString, AllottedResource.class); - } catch (IOException e) { + } catch (IOException e) { throw new JsonDecomposingException("Exception while converting json to allotted resource", e); - } - } - + } + } + public static ConfigResource jsonToConfigResource(String jsonString) throws JsonDecomposingException { - try { + try { return OBJECT_MAPPER.readValue(jsonString, ConfigResource.class); - } catch (IOException e) { + } catch (IOException e) { throw new JsonDecomposingException("Exception while converting json to allotted resource", e); - } - } + } + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/JsonUtils.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/JsonUtils.java index ccc5ea667e..d3d07f9014 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/JsonUtils.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/JsonUtils.java @@ -30,7 +30,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; - import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.runtime.Execution; import org.json.JSONArray; @@ -39,7 +38,6 @@ import org.json.JSONObject; import org.json.XML; import org.onap.so.bpmn.core.xml.XmlTool; import org.onap.so.exceptions.ValidationException; - import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import com.github.fge.jsonschema.core.exceptions.ProcessingException; @@ -54,1016 +52,1019 @@ import org.slf4j.LoggerFactory; * * @version 1.0 * - * Note: It was observed, that depending on the JSON implementation, an org.json.JSONException or a - * java.util.NoSuchElementException will be thrown in the event of the key value being "not found" - * in a JSON document. A general check has been added to the applicable catch blocks for this - * this type of behavior to reduce the amount of logging. As a key value not being found is - * expect behavior, it makes no sense to log the stack trace associated with this type of failure. + * Note: It was observed, that depending on the JSON implementation, an org.json.JSONException or a + * java.util.NoSuchElementException will be thrown in the event of the key value being "not found" in a JSON + * document. A general check has been added to the applicable catch blocks for this this type of behavior to + * reduce the amount of logging. As a key value not being found is expect behavior, it makes no sense to log + * the stack trace associated with this type of failure. */ public class JsonUtils { - private static Logger logger = LoggerFactory.getLogger(JsonUtils.class); - private static int MSOJsonIndentFactor = 3; - - /** - * Uses the JSONObject static method to convert a XML doc to JSON. - * - * @param xml String containing the XML doc - * @param pretty flag to determine if the output should be formatted - * @return String containing the JSON translation - */ - public static String xml2json(String xml, Boolean pretty) { - try { - // name spaces cause problems, so just remove them - JSONObject jsonObj = XML.toJSONObject(XmlTool.removeNamespaces(xml)); - if (!pretty) { - return jsonObj.toString(); - } else { - // add an indent to make it 'pretty' - return jsonObj.toString(MSOJsonIndentFactor); - } - } catch (Exception e){ - logger.debug("xml2json(): unable to parse xml and convert to json. Exception was: {}", e.toString(), e); - return null; - } - } - - /** - * Invokes xml2json(String, Boolean) defaulting to 'pretty' output. - * - * @param xml String containing the XML doc - * @return String containing the JSON translation - */ - public static String xml2json(String xml) { - return xml2json(xml, true); - } - - /** - * Uses the JSONObject static method to convert a JSON doc to XML. - * Note: this method may not generate valid XML if the JSONObject - * contains JSONArrays which are used to represent XML attributes - * in the JSON doc. - * - * @param jsonStr String containing the JSON doc - * @param pretty flag to determine if the output should be formatted - * @return String containing the XML translation - */ - public static String json2xml(String jsonStr, Boolean pretty) { - - try { - JSONObject jsonObj = new JSONObject(jsonStr); - if (pretty) { -// use the local class method which properly handles certain JSONArray content - return XmlTool.normalize(toXMLString(jsonObj, null)); - } else { -// use the local class method which properly handles certain JSONArray content - return toXMLString(jsonObj, null); - } - } catch (Exception e){ - logger.debug("json2xml(): unable to parse json and convert to xml. Exception was: {}", e.toString(), e); - return null; - } - } - - /** - * Uses a modified version of the org.json.XML toString() algorithm - * to convert a JSONObject to an XML Doc. The intent of this is to - * correctly generate XML from JSON including TAGs for JSONArrays - * - * @param obj org.json.JSON object to be converted to XML - * @param tagName optional XML tagname supplied primarily during recursive calls - * @return String containing the XML translation - */ - public static String toXMLString(Object obj, String tagName) throws JSONException { - StringBuilder strBuf = new StringBuilder(); - int i; - JSONArray jsonArr; - JSONObject jsonObj; - String key; - Iterator<String> keys; - int len; - String str; - Object curObj; - if (obj instanceof JSONObject) { - // append "<tagName>" to the XML output - if (tagName != null) { - strBuf.append("<"); - strBuf.append(tagName); - strBuf.append(">"); - } - // iterate thru the keys. - jsonObj = (JSONObject) obj; - keys = jsonObj.keys(); - while (keys.hasNext()) { - key = keys.next(); - curObj = jsonObj.opt(key); - if (curObj == null) { - curObj = ""; - } - if (curObj instanceof String) { - str = (String) curObj; - } else { - str = null; - } - // append the content to the XML output - if ("content".equals(key)) { - if (curObj instanceof JSONArray) { - jsonArr = (JSONArray) curObj; - len = jsonArr.length(); - for (i = 0; i < len; i += 1) { - if (i > 0) { - strBuf.append('\n'); - } - strBuf.append(XML.escape(jsonArr.get(i).toString())); - } - } else { - strBuf.append(XML.escape(curObj.toString())); - } - // append an array of similar keys to the XML output - } else if (curObj instanceof JSONArray) { - jsonArr = (JSONArray) curObj; - len = jsonArr.length(); - for (i = 0; i < len; i += 1) { - curObj = jsonArr.get(i); - if (curObj instanceof JSONArray) { -// The XML tags for the nested array should be generated below when this method -// is called recursively and the JSONArray object is passed -// strBuf.append("<"); -// strBuf.append(key); -// strBuf.append(">"); - strBuf.append(toXMLString(curObj, null)); -// strBuf.append("</"); -// strBuf.append(key); -// strBuf.append(">"); - } else { - // append the opening tag for the array (before 1st element) - if (i == 0) { - strBuf.append("<"); - strBuf.append(key); - strBuf.append(">"); - } - // append the opening tag for the array - strBuf.append(toXMLString(curObj, null)); - // append the closing tag for the array (after last element) - if (i == (len - 1)) { - strBuf.append("</"); - strBuf.append(key); - strBuf.append(">"); - } - } - } - } else if (curObj.equals("")) { - // append a closing tag "<key>" to the XML output - strBuf.append("<"); - strBuf.append(key); - strBuf.append("/>"); - } else { - strBuf.append(toXMLString(curObj, key)); - } - } - if (tagName != null) { - // append the closing tag "</tagName>" to the XML output - strBuf.append("</"); - strBuf.append(tagName); - strBuf.append(">"); - } - return strBuf.toString(); - // XML does not have good support for arrays. If an array appears in a place - // where XML is lacking, synthesize an < array > element. - } else if (obj instanceof JSONArray) { - jsonArr = (JSONArray) obj; - len = jsonArr.length(); - for (i = 0; i < len; ++i) { - curObj = jsonArr.opt(i); - strBuf.append(toXMLString(curObj, (tagName == null) ? "array" - : tagName)); - } - return strBuf.toString(); - } else { - str = (obj == null) ? "null" : XML.escape(obj.toString()); - return (tagName == null) ? "\"" + str + "\"" - : (str.length() == 0) ? "<" + tagName + "/>" : "<" - + tagName + ">" + str + "</" + tagName + ">"; - } - } - - /** - * Invokes json2xml(String, Boolean) defaulting to 'pretty' output. - * - * @param jsonStr String containing the XML doc - * @return String containing the JSON translation - */ - public static String json2xml(String jsonStr) { - return json2xml(jsonStr, true); - } - - /** - * Formats the JSON String using the value of MSOJsonIndentFactor. - * - * @param jsonStr String containing the JSON doc - * @return String containing the formatted JSON doc - */ - public static String prettyJson(String jsonStr) { - try { - JSONObject jsonObj = new JSONObject(jsonStr); - return jsonObj.toString(MSOJsonIndentFactor); - } catch (Exception e){ - logger.debug("prettyJson(): unable to parse/format json input. Exception was: {}", e.toString(), e); - return null; - } - } - - /** - * Returns an Iterator over the JSON keys in the specified JSON doc. - * - * @param jsonStr String containing the JSON doc - * @return Iterator over the JSON keys - * @throws JSONException if the doc cannot be parsed - */ - public static Iterator <String> getJsonIterator(String jsonStr) throws JSONException { - return new JSONObject(jsonStr).keys(); - } - - /** - * Returns the name of the "root" property in the specified JSON doc. The - * "root" property is the single top-level property in the JSON doc. An - * exception is thrown if the doc is empty or if it contains more than one - * top-level property. - * - * @param jsonStr String containing the JSON doc - * @return the name of the "root" property - * @throws JSONException if the doc cannot be parsed, or if it is empty, or if - * it contains more than one top-level property - */ - public static String getJsonRootProperty(String jsonStr) throws JSONException { - Iterator<String> iter = getJsonIterator(jsonStr); - - if (!iter.hasNext()) { - throw new JSONException("Empty JSON object"); - } - - String rootPropertyName = iter.next(); - - if (iter.hasNext()) { - throw new JSONException("JSON object has more than one root property"); - } - - return rootPropertyName; - } - - /** - * Invokes the getJsonRawValue() method and returns the String equivalent of - * the object returned. - * - * TBD: May need separate methods for boolean, float, and integer fields if the - * String representation is not sufficient to meet client needs. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @return String field value associated with keys - */ - public static String getJsonValue(String jsonStr, String keys) { - try { - Object rawValue = getJsonRawValue(jsonStr, keys); - if (rawValue == null) { - return null; - } else { - if (rawValue instanceof String) { - logger.debug("getJsonValue(): the raw value is a String Object={}", rawValue); - return (String) rawValue; - } else { - logger.debug("getJsonValue(): the raw value is NOT a String Object={}", rawValue.toString()); - return rawValue.toString(); - } - } - } catch (Exception e) { - logger.debug("getJsonValue(): unable to parse json to retrieve value for field={}. Exception was: {}", keys, - e.toString(), e); - } - return null; - } - - /** - * Invokes the getJsonRawValue() method with the wrap flag set to true - * and returns the String equivalent of the json node object returned. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @return String field value associated with keys - */ - public static String getJsonNodeValue(String jsonStr, String keys) { - try { - Object rawValue = getJsonRawValue(jsonStr, keys, true); - if (rawValue == null) { - return null; - } else { - if (rawValue instanceof String) { - logger.debug("getJsonNodeValue(): the raw value is a String Object={}", rawValue); - return (String) rawValue; - } else { - logger.debug("getJsonNodeValue(): the raw value is NOT a String Object={}", rawValue.toString()); - return rawValue.toString(); - } - } - } catch (Exception e) { - logger.debug("getJsonNodeValue(): unable to parse json to retrieve node for field={}. Exception was: {}", keys, - e.toString(), e); - } - return null; - } - - /** - * Invokes the getJsonRawValue() method and returns the String equivalent of - * the object returned. - * - * TBD: May need separate methods for boolean, float, and integer fields if the - * String representation is not sufficient to meet client needs. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @return String field value associated with keys - */ - public static int getJsonIntValue(String jsonStr, String keys) { - try { - Object rawValue = getJsonRawValue(jsonStr, keys); - if (rawValue == null) { - return 0; - } else { - if (rawValue instanceof Integer) { - logger.debug("getJsonIntValue(): the raw value is an Integer Object={}", ((String) rawValue).toString()); - return (Integer) rawValue; - } else { - logger.debug("getJsonIntValue(): the raw value is NOT an Integer Object={}", rawValue.toString()); - return 0; - } - } - } catch (Exception e) { - logger.debug("getJsonIntValue(): unable to parse json to retrieve value for field={}. Exception was: {}", keys, - e.toString(), e); - } - return 0; - } - - /** - * Invokes the getJsonRawValue() method and returns the boolean equivalent of - * the object returned. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @return boolean field value associated with keys - default is false - */ - public static boolean getJsonBooleanValue(String jsonStr, String keys) { - try { - Object rawValue = getJsonRawValue(jsonStr, keys); - if (rawValue == null) { - return false; - } else { - if (rawValue instanceof Boolean) { - logger.debug("getJsonBooleanValue(): the raw value is a Boolean Object={}", rawValue); - return (Boolean) rawValue; - } else { - logger.debug("getJsonBooleanValue(): the raw value is NOT an Boolean Object={}", rawValue.toString()); - return false; - } - } - } catch (Exception e) { - logger.debug("getJsonBooleanValue(): unable to parse json to retrieve value for field={}. Exception was: {}", keys, - e.toString(), e); - } - return false; - } - - /** - * Invokes the getJsonParamValue() method to obtain the JSONArray associated with - * the specified keys. The JSONArray is then walked to retrieve the first array - * value associated with the specified field name (index=0). - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @param name field name for the param to be retrieved - * @return String param value associated with field name - */ - public static String getJsonParamValue(String jsonStr, String keys, String name) { - return getJsonParamValue(jsonStr, keys, name, 0); - } - - /** - * Invokes the getJsonRawValue() method to obtain the JSONArray associated with - * the specified keys. The JSONArray is then walked to retrieve the nth array - * value associated with the specified field name and index. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @param name field name for the param to be retrieved - * @param index the nth param associated with name starting at 0 - * @return String param value associated with field name - */ - public static String getJsonParamValue(String jsonStr, String keys, String name, int index) { - try { - Object rawValue = getJsonRawValue(jsonStr, keys); - if (rawValue == null) { - return null; - } else { - if (rawValue instanceof JSONArray) { - logger.debug("getJsonParamValue(): keys={} points to JSONArray: {}", keys, rawValue.toString()); - int arrayLen = ((JSONArray) rawValue).length(); - if (index < 0 || arrayLen < index+1) { - logger.debug("getJsonParamValue(): index: {} is out of bounds for array size of {}", index, arrayLen); - return null; - } - int foundCnt = 0; - for (int i = 0; i < arrayLen; i++) { - logger.debug("getJsonParamValue(): index: {}, value: {}", i, ((JSONArray) rawValue).get(i).toString()); - if (((JSONArray) rawValue).get(i) instanceof JSONObject) { - JSONObject jsonObj = (JSONObject)((JSONArray) rawValue).get(i); - String parmValue = jsonObj.get(name).toString(); - if (parmValue != null) { - logger.debug("getJsonParamValue(): found value: {} for name: {} and index: {}", parmValue, name, i); - if (foundCnt == index) { - return parmValue; - } else { - foundCnt++; - continue; - } - } else { - continue; - } - } else { - logger.debug("getJsonParamValue(): the JSONArray element is NOT a JSONObject={}", rawValue.toString()); - return null; - } - } - logger.debug("getJsonParamValue(): content value NOT found for name: {}", name); - return null; - } else { - logger.debug("getJsonParamValue(): the raw value is NOT a JSONArray Object={}", rawValue.toString()); - return null; - } - } - } catch (Exception e) { - if (e.getMessage().contains("not found")) { - logger.debug("getJsonParamValue(): failed to retrieve param value for keys:{}, name={} : {}", keys, name, - e.getMessage()); - } else { - logger.debug("getJsonParamValue(): unable to parse json to retrieve value for field={}. Exception was: {}", keys, - e.toString(), e); - } - } - return null; - } - - /** - * Wrapper to generate the JSONObject to pass to the getJsonValueForKey(JSONObject, String) - * method so that recursion over the subobjects can be supported there - * - * @param jsonStr String containing the JSON doc - * @param key key to the target value - * @return String field value associated with key - */ - public static String getJsonValueForKey(String jsonStr, String key) { - - try { - JSONObject jsonObj = new JSONObject(jsonStr); - return getJsonValueForKey(jsonObj, key); - } catch (Exception e) { - logger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field={}. Exception was: {}", key, - e.toString(), e); - } - return null; - } - - /** - * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the - * single key/field name specified. Returns the associated value if found or null if the key is not found - * - * @param jsonObj JSONObject representation of the the JSON doc - * @param key key to the target value - * @return String field value associated with key - */ - public static String getJsonValueForKey(JSONObject jsonObj, String key) { - - String keyValue = null; - try { - if (jsonObj.has(key)) { - Object value = jsonObj.get(key); - logger.debug("getJsonValueForKey(): found value={}, for key={}", (String) value, key); - if (value == null) { - return null; - } else { - return ((String) value); - } - } else { - Iterator <String> itr = jsonObj.keys(); - while (itr.hasNext()) { - String nextKey = itr.next(); - Object obj = jsonObj.get(nextKey); - if (obj instanceof JSONObject) { - keyValue = getJsonValueForKey((JSONObject) obj, key); - if (keyValue != null) { - break; - } - } else { - logger.debug("getJsonValueForKey(): key={}, does not point to a JSONObject, next key", nextKey); - } - } - } - } catch (Exception e) { - // JSONObject::get() throws a "not found" exception if one of the specified keys is not found - if (e.getMessage().contains("not found")) { - logger.debug("getJsonValueForKey(): failed to retrieve param value for key={}: {}", key, e.getMessage()); - } else { - logger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field={}. Exception was {}", key, - e.toString(), e); - } - keyValue = null; - } - return keyValue; - } - - /** - * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the - * single key/field name specified. Returns the associated value if found or null if the key is not found - * - * @param jsonObj JSONObject representation of the the JSON doc - * @param key key to the target value - * @return String field value associated with key - */ - public static Integer getJsonIntValueForKey(JSONObject jsonObj, String key) { - Integer keyValue = null; - try { - if (jsonObj.has(key)) { - Integer value = (Integer) jsonObj.get(key); - logger.debug("getJsonIntValueForKey(): found value={}, for key={}", value, key); - return value; - } else { - Iterator <String> itr = jsonObj.keys(); - while (itr.hasNext()) { - String nextKey = itr.next(); - Object obj = jsonObj.get(nextKey); - if (obj instanceof JSONObject) { - keyValue = getJsonIntValueForKey((JSONObject) obj, key); - if (keyValue != null) { - break; - } - } else { - logger.debug("getJsonIntValueForKey(): key={}, does not point to a JSONObject, next key", nextKey); - } - } - } - } catch (Exception e) { - // JSONObject::get() throws a "not found" exception if one of the specified keys is not found - if (e.getMessage().contains("not found")) { - logger.debug("getJsonIntValueForKey(): failed to retrieve param value for key={}: {}", key, e.getMessage()); - } else { - logger.debug("getJsonIntValueForKey(): unable to parse json to retrieve value for field={}. Exception was: {}", key, - e.toString(), e); - } - keyValue = null; - } - return keyValue; - } - - /** - * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the - * single key/field name specified. Returns the associated value if found or null if the key is not found - * - * @param jsonObj JSONObject representation of the the JSON doc - * @param key key to the target value - * @return String field value associated with key - */ - public static Boolean getJsonBooleanValueForKey(JSONObject jsonObj, String key) { - Boolean keyValue = null; - try { - if (jsonObj.has(key)) { - Boolean value = (Boolean) jsonObj.get(key); - logger.debug("getJsonBooleanValueForKey(): found value={}, for key={}", value, key); - return value; - } else { - Iterator <String> itr = jsonObj.keys(); - while (itr.hasNext()) { - String nextKey = itr.next(); - Object obj = jsonObj.get(nextKey); - if (obj instanceof JSONObject) { - keyValue = getJsonBooleanValueForKey((JSONObject) obj, key); - if (keyValue != null) { - break; - } - } else { - logger.debug("getJsonBooleanValueForKey(): key={}, does not point to a JSONObject, next key", nextKey); - } - } - } - } catch (Exception e) { - // JSONObject::get() throws a "not found" exception if one of the specified keys is not found - if (e.getMessage().contains("not found")) { - logger.debug("getJsonBooleanValueForKey(): failed to retrieve param value for key={}: {}", key, e.getMessage()); - } else { - logger.debug("getJsonBooleanValueForKey(): unable to parse json to retrieve value for field={}. Exception was: {}", - key, e.toString(), e); - } - keyValue = null; - } - return keyValue; - } + private static Logger logger = LoggerFactory.getLogger(JsonUtils.class); + private static int MSOJsonIndentFactor = 3; + + /** + * Uses the JSONObject static method to convert a XML doc to JSON. + * + * @param xml String containing the XML doc + * @param pretty flag to determine if the output should be formatted + * @return String containing the JSON translation + */ + public static String xml2json(String xml, Boolean pretty) { + try { + // name spaces cause problems, so just remove them + JSONObject jsonObj = XML.toJSONObject(XmlTool.removeNamespaces(xml)); + if (!pretty) { + return jsonObj.toString(); + } else { + // add an indent to make it 'pretty' + return jsonObj.toString(MSOJsonIndentFactor); + } + } catch (Exception e) { + logger.debug("xml2json(): unable to parse xml and convert to json. Exception was: {}", e.toString(), e); + return null; + } + } - /** - * Boolean method to determine if a key path is valid for the JSON doc. Invokes - * getJsonValue(). - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @return Boolean true if keys points to value in the JSON doc - */ - public static Boolean jsonValueExists(String jsonStr, String keys) { - if (getJsonRawValue(jsonStr, keys) == null) { - return false; - } else { - return true; - } - } + /** + * Invokes xml2json(String, Boolean) defaulting to 'pretty' output. + * + * @param xml String containing the XML doc + * @return String containing the JSON translation + */ + public static String xml2json(String xml) { + return xml2json(xml, true); + } - /** - * Inserts the new key/value pair at the appropriate location in the JSON - * document after first determining if keyed field already exists. If - * it does exist, return the JSON unmodified, otherwise return the new JSON - * Note: this method currently only supports String value inserts. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the value to be added in the format of "key1.key2.key3..." - * @return String containing the updated JSON doc - */ - public static String addJsonValue(String jsonStr, String keys, String value) { + /** + * Uses the JSONObject static method to convert a JSON doc to XML. Note: this method may not generate valid XML if + * the JSONObject contains JSONArrays which are used to represent XML attributes in the JSON doc. + * + * @param jsonStr String containing the JSON doc + * @param pretty flag to determine if the output should be formatted + * @return String containing the XML translation + */ + public static String json2xml(String jsonStr, Boolean pretty) { + + try { + JSONObject jsonObj = new JSONObject(jsonStr); + if (pretty) { + // use the local class method which properly handles certain JSONArray content + return XmlTool.normalize(toXMLString(jsonObj, null)); + } else { + // use the local class method which properly handles certain JSONArray content + return toXMLString(jsonObj, null); + } + } catch (Exception e) { + logger.debug("json2xml(): unable to parse json and convert to xml. Exception was: {}", e.toString(), e); + return null; + } + } - // only attempt to insert the key/value pair if it does not exist - if (!jsonValueExists(jsonStr, keys)) { - return putJsonValue(jsonStr, keys, value); - } else { - logger.debug("addJsonValue(): JSON add failed, key={}/value={} already exists", keys, value); - return jsonStr; - } - } + /** + * Uses a modified version of the org.json.XML toString() algorithm to convert a JSONObject to an XML Doc. The + * intent of this is to correctly generate XML from JSON including TAGs for JSONArrays + * + * @param obj org.json.JSON object to be converted to XML + * @param tagName optional XML tagname supplied primarily during recursive calls + * @return String containing the XML translation + */ + public static String toXMLString(Object obj, String tagName) throws JSONException { + StringBuilder strBuf = new StringBuilder(); + int i; + JSONArray jsonArr; + JSONObject jsonObj; + String key; + Iterator<String> keys; + int len; + String str; + Object curObj; + if (obj instanceof JSONObject) { + // append "<tagName>" to the XML output + if (tagName != null) { + strBuf.append("<"); + strBuf.append(tagName); + strBuf.append(">"); + } + // iterate thru the keys. + jsonObj = (JSONObject) obj; + keys = jsonObj.keys(); + while (keys.hasNext()) { + key = keys.next(); + curObj = jsonObj.opt(key); + if (curObj == null) { + curObj = ""; + } + if (curObj instanceof String) { + str = (String) curObj; + } else { + str = null; + } + // append the content to the XML output + if ("content".equals(key)) { + if (curObj instanceof JSONArray) { + jsonArr = (JSONArray) curObj; + len = jsonArr.length(); + for (i = 0; i < len; i += 1) { + if (i > 0) { + strBuf.append('\n'); + } + strBuf.append(XML.escape(jsonArr.get(i).toString())); + } + } else { + strBuf.append(XML.escape(curObj.toString())); + } + // append an array of similar keys to the XML output + } else if (curObj instanceof JSONArray) { + jsonArr = (JSONArray) curObj; + len = jsonArr.length(); + for (i = 0; i < len; i += 1) { + curObj = jsonArr.get(i); + if (curObj instanceof JSONArray) { + // The XML tags for the nested array should be generated below when this method + // is called recursively and the JSONArray object is passed + // strBuf.append("<"); + // strBuf.append(key); + // strBuf.append(">"); + strBuf.append(toXMLString(curObj, null)); + // strBuf.append("</"); + // strBuf.append(key); + // strBuf.append(">"); + } else { + // append the opening tag for the array (before 1st element) + if (i == 0) { + strBuf.append("<"); + strBuf.append(key); + strBuf.append(">"); + } + // append the opening tag for the array + strBuf.append(toXMLString(curObj, null)); + // append the closing tag for the array (after last element) + if (i == (len - 1)) { + strBuf.append("</"); + strBuf.append(key); + strBuf.append(">"); + } + } + } + } else if (curObj.equals("")) { + // append a closing tag "<key>" to the XML output + strBuf.append("<"); + strBuf.append(key); + strBuf.append("/>"); + } else { + strBuf.append(toXMLString(curObj, key)); + } + } + if (tagName != null) { + // append the closing tag "</tagName>" to the XML output + strBuf.append("</"); + strBuf.append(tagName); + strBuf.append(">"); + } + return strBuf.toString(); + // XML does not have good support for arrays. If an array appears in a place + // where XML is lacking, synthesize an < array > element. + } else if (obj instanceof JSONArray) { + jsonArr = (JSONArray) obj; + len = jsonArr.length(); + for (i = 0; i < len; ++i) { + curObj = jsonArr.opt(i); + strBuf.append(toXMLString(curObj, (tagName == null) ? "array" : tagName)); + } + return strBuf.toString(); + } else { + str = (obj == null) ? "null" : XML.escape(obj.toString()); + return (tagName == null) ? "\"" + str + "\"" + : (str.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + str + "</" + tagName + ">"; + } + } - /** - * Updates the value for the specified key in the JSON document - * after first determining if keyed field exists. If it does - * not exist, return the JSON unmodified, otherwise return the updated JSON. - * Note: this method currently only supports String value updates. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the value to be updated in the format of "key1.key2.key3..." - * @return String containing the updated JSON doc - */ - public static String updJsonValue(String jsonStr, String keys, String newValue) { - // only attempt to modify the key/value pair if it exists - if (jsonValueExists(jsonStr, keys)) { - return putJsonValue(jsonStr, keys, newValue); - } else { - logger.debug("updJsonValue(): JSON update failed, no value exists for key={}", keys); - return jsonStr; - } - } + /** + * Invokes json2xml(String, Boolean) defaulting to 'pretty' output. + * + * @param jsonStr String containing the XML doc + * @return String containing the JSON translation + */ + public static String json2xml(String jsonStr) { + return json2xml(jsonStr, true); + } - /** - * Deletes the value for the specified key in the JSON document - * after first determining if keyed field exists. If it does - * not exist, return the JSON unmodified, otherwise return the updated JSON - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..." - * @return String containing the updated JSON doc - */ - public static String delJsonValue(String jsonStr, String keys) { + /** + * Formats the JSON String using the value of MSOJsonIndentFactor. + * + * @param jsonStr String containing the JSON doc + * @return String containing the formatted JSON doc + */ + public static String prettyJson(String jsonStr) { + try { + JSONObject jsonObj = new JSONObject(jsonStr); + return jsonObj.toString(MSOJsonIndentFactor); + } catch (Exception e) { + logger.debug("prettyJson(): unable to parse/format json input. Exception was: {}", e.toString(), e); + return null; + } + } - // only attempt to remove the key/value pair if it exists - if (jsonValueExists(jsonStr, keys)) { - // passing a null value results in a delete - return putJsonValue(jsonStr, keys, null); - } else { - logger.debug("delJsonValue(): JSON delete failed, no value exists for key={}", keys); - return jsonStr; - } - } + /** + * Returns an Iterator over the JSON keys in the specified JSON doc. + * + * @param jsonStr String containing the JSON doc + * @return Iterator over the JSON keys + * @throws JSONException if the doc cannot be parsed + */ + public static Iterator<String> getJsonIterator(String jsonStr) throws JSONException { + return new JSONObject(jsonStr).keys(); + } - /** - * Walks the JSON doc using the full key path to retrieve the associated - * value. All but the last key points to the 'parent' object name(s) in order - * in the JSON hierarchy with the last key pointing to the target value. - * The value returned is a Java object. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @return Object field value associated with keys - */ - private static Object getJsonRawValue(String jsonStr, String keys) { - return getJsonRawValue(jsonStr, keys, false); - } + /** + * Returns the name of the "root" property in the specified JSON doc. The "root" property is the single top-level + * property in the JSON doc. An exception is thrown if the doc is empty or if it contains more than one top-level + * property. + * + * @param jsonStr String containing the JSON doc + * @return the name of the "root" property + * @throws JSONException if the doc cannot be parsed, or if it is empty, or if it contains more than one top-level + * property + */ + public static String getJsonRootProperty(String jsonStr) throws JSONException { + Iterator<String> iter = getJsonIterator(jsonStr); + + if (!iter.hasNext()) { + throw new JSONException("Empty JSON object"); + } + + String rootPropertyName = iter.next(); + + if (iter.hasNext()) { + throw new JSONException("JSON object has more than one root property"); + } + + return rootPropertyName; + } - /** - * Walks the JSON doc using the full key path to retrieve the associated - * value. All but the last key points to the 'parent' object name(s) in order - * in the JSON hierarchy with the last key pointing to the target value. - * The value returned is a Java object. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @param wrap Boolean which determines if returned JSONObjects sould be "wrapped" - * Note: wrap does not apply to returned scalar values - * @return Object field value associated with keys - */ - private static Object getJsonRawValue(String jsonStr, String keys, Boolean wrap) { + /** + * Invokes the getJsonRawValue() method and returns the String equivalent of the object returned. + * + * TBD: May need separate methods for boolean, float, and integer fields if the String representation is not + * sufficient to meet client needs. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return String field value associated with keys + */ + public static String getJsonValue(String jsonStr, String keys) { + try { + Object rawValue = getJsonRawValue(jsonStr, keys); + if (rawValue == null) { + return null; + } else { + if (rawValue instanceof String) { + logger.debug("getJsonValue(): the raw value is a String Object={}", rawValue); + return (String) rawValue; + } else { + logger.debug("getJsonValue(): the raw value is NOT a String Object={}", rawValue.toString()); + return rawValue.toString(); + } + } + } catch (Exception e) { + logger.debug("getJsonValue(): unable to parse json to retrieve value for field={}. Exception was: {}", keys, + e.toString(), e); + } + return null; + } - String keyStr = ""; - try { - JSONObject jsonObj = new JSONObject(jsonStr); - StringTokenizer keyTokens = new StringTokenizer(keys, "."); - while (keyTokens.hasMoreElements()) { - keyStr = keyTokens.nextToken(); - Object keyValue = jsonObj.get(keyStr); - if (keyValue instanceof JSONObject) { - jsonObj = (JSONObject) keyValue; - } else { - if (keyTokens.hasMoreElements()) { - logger.debug("getJsonRawValue(): value found prior to last key for key={}", keyStr); - } - return keyValue; - } - } - // return the json 'node' that the key points to - // note: since this is a json object and not a scalar value, - // use the wrap flag to determine if the object should - // be wrapped with a root node value - // (the last key in the keys String) - if (wrap) { - JSONObject wrappedJsonObj = new JSONObject(); - wrappedJsonObj.put(keyStr, jsonObj); - return wrappedJsonObj.toString(); - } else { - return jsonObj.toString(); - } + /** + * Invokes the getJsonRawValue() method with the wrap flag set to true and returns the String equivalent of the json + * node object returned. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return String field value associated with keys + */ + public static String getJsonNodeValue(String jsonStr, String keys) { + try { + Object rawValue = getJsonRawValue(jsonStr, keys, true); + if (rawValue == null) { + return null; + } else { + if (rawValue instanceof String) { + logger.debug("getJsonNodeValue(): the raw value is a String Object={}", rawValue); + return (String) rawValue; + } else { + logger.debug("getJsonNodeValue(): the raw value is NOT a String Object={}", rawValue.toString()); + return rawValue.toString(); + } + } + } catch (Exception e) { + logger.debug("getJsonNodeValue(): unable to parse json to retrieve node for field={}. Exception was: {}", + keys, e.toString(), e); + } + return null; + } - } catch (Exception e) { - // JSONObject::get() throws a "not found" exception if one of the specified keys is not found - if (e.getMessage().contains("not found")) { - logger.debug("getJsonRawValue(): failed to retrieve param value for key={}: {}", keyStr, e.getMessage()); - } else { - logger.debug("getJsonRawValue(): unable to parse json to retrieve value for field={}. Exception was: {}", keys, - e.toString(), e); - } - } - return null; - } + /** + * Invokes the getJsonRawValue() method and returns the String equivalent of the object returned. + * + * TBD: May need separate methods for boolean, float, and integer fields if the String representation is not + * sufficient to meet client needs. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return String field value associated with keys + */ + public static int getJsonIntValue(String jsonStr, String keys) { + try { + Object rawValue = getJsonRawValue(jsonStr, keys); + if (rawValue == null) { + return 0; + } else { + if (rawValue instanceof Integer) { + logger.debug("getJsonIntValue(): the raw value is an Integer Object={}", + ((String) rawValue).toString()); + return (Integer) rawValue; + } else { + logger.debug("getJsonIntValue(): the raw value is NOT an Integer Object={}", rawValue.toString()); + return 0; + } + } + } catch (Exception e) { + logger.debug("getJsonIntValue(): unable to parse json to retrieve value for field={}. Exception was: {}", + keys, e.toString(), e); + } + return 0; + } - /** - * Private method invoked by the public add, update, and delete methods. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..." - * @return String containing the updated JSON doc - */ - private static String putJsonValue(String jsonStr, String keys, String value) { + /** + * Invokes the getJsonRawValue() method and returns the boolean equivalent of the object returned. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return boolean field value associated with keys - default is false + */ + public static boolean getJsonBooleanValue(String jsonStr, String keys) { + try { + Object rawValue = getJsonRawValue(jsonStr, keys); + if (rawValue == null) { + return false; + } else { + if (rawValue instanceof Boolean) { + logger.debug("getJsonBooleanValue(): the raw value is a Boolean Object={}", rawValue); + return (Boolean) rawValue; + } else { + logger.debug("getJsonBooleanValue(): the raw value is NOT an Boolean Object={}", + rawValue.toString()); + return false; + } + } + } catch (Exception e) { + logger.debug( + "getJsonBooleanValue(): unable to parse json to retrieve value for field={}. Exception was: {}", + keys, e.toString(), e); + } + return false; + } - String keyStr = ""; - try { - JSONObject jsonObj = new JSONObject(jsonStr); - JSONObject jsonObjOut = jsonObj; - StringTokenizer keyTokens = new StringTokenizer(keys, "."); - while (keyTokens.hasMoreElements()) { - keyStr = keyTokens.nextToken(); - if (keyTokens.hasMoreElements()) { - Object keyValue = jsonObj.get(keyStr); - if (keyValue instanceof JSONObject) { - jsonObj = (JSONObject) keyValue; - } else { - logger.debug("putJsonValue(): key={} not the last key but points to non-json object: {}", keyStr, keyValue); - return null; - } - } else { // at the last/new key value - jsonObj.put(keyStr, value); - return jsonObjOut.toString(3); - } - } - // should not hit this point if the key points to a valid key value - return null; + /** + * Invokes the getJsonParamValue() method to obtain the JSONArray associated with the specified keys. The JSONArray + * is then walked to retrieve the first array value associated with the specified field name (index=0). + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @param name field name for the param to be retrieved + * @return String param value associated with field name + */ + public static String getJsonParamValue(String jsonStr, String keys, String name) { + return getJsonParamValue(jsonStr, keys, name, 0); + } - } catch (Exception e) { - // JSONObject::get() throws a "not found" exception if one of the specified keys is not found - if (e.getMessage().contains("not found")) { - logger.debug("putJsonValue(): failed to put param value for key={}: {}", keyStr, e.getMessage()); - } else { - logger.debug("putJsonValue(): unable to parse json to put value for key={}. Exception was: {}", keys, e.toString(), - e); - } - } - return null; - } + /** + * Invokes the getJsonRawValue() method to obtain the JSONArray associated with the specified keys. The JSONArray is + * then walked to retrieve the nth array value associated with the specified field name and index. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @param name field name for the param to be retrieved + * @param index the nth param associated with name starting at 0 + * @return String param value associated with field name + */ + public static String getJsonParamValue(String jsonStr, String keys, String name, int index) { + try { + Object rawValue = getJsonRawValue(jsonStr, keys); + if (rawValue == null) { + return null; + } else { + if (rawValue instanceof JSONArray) { + logger.debug("getJsonParamValue(): keys={} points to JSONArray: {}", keys, rawValue.toString()); + int arrayLen = ((JSONArray) rawValue).length(); + if (index < 0 || arrayLen < index + 1) { + logger.debug("getJsonParamValue(): index: {} is out of bounds for array size of {}", index, + arrayLen); + return null; + } + int foundCnt = 0; + for (int i = 0; i < arrayLen; i++) { + logger.debug("getJsonParamValue(): index: {}, value: {}", i, + ((JSONArray) rawValue).get(i).toString()); + if (((JSONArray) rawValue).get(i) instanceof JSONObject) { + JSONObject jsonObj = (JSONObject) ((JSONArray) rawValue).get(i); + String parmValue = jsonObj.get(name).toString(); + if (parmValue != null) { + logger.debug("getJsonParamValue(): found value: {} for name: {} and index: {}", + parmValue, name, i); + if (foundCnt == index) { + return parmValue; + } else { + foundCnt++; + continue; + } + } else { + continue; + } + } else { + logger.debug("getJsonParamValue(): the JSONArray element is NOT a JSONObject={}", + rawValue.toString()); + return null; + } + } + logger.debug("getJsonParamValue(): content value NOT found for name: {}", name); + return null; + } else { + logger.debug("getJsonParamValue(): the raw value is NOT a JSONArray Object={}", + rawValue.toString()); + return null; + } + } + } catch (Exception e) { + if (e.getMessage().contains("not found")) { + logger.debug("getJsonParamValue(): failed to retrieve param value for keys:{}, name={} : {}", keys, + name, e.getMessage()); + } else { + logger.debug( + "getJsonParamValue(): unable to parse json to retrieve value for field={}. Exception was: {}", + keys, e.toString(), e); + } + } + return null; + } - /** - * This json util method converts a json array of Key Value - * pair objects into a Java Map. - * - * @param execution - * @param entryArray - the getJsonValue of a json Array of key/value pairs - * - * @return Map - a Map containing the entries - */ - public Map<String, String> jsonStringToMap(DelegateExecution execution, String entry) { - logger.debug("Started Json String To Map Method"); + /** + * Wrapper to generate the JSONObject to pass to the getJsonValueForKey(JSONObject, String) method so that recursion + * over the subobjects can be supported there + * + * @param jsonStr String containing the JSON doc + * @param key key to the target value + * @return String field value associated with key + */ + public static String getJsonValueForKey(String jsonStr, String key) { + + try { + JSONObject jsonObj = new JSONObject(jsonStr); + return getJsonValueForKey(jsonObj, key); + } catch (Exception e) { + logger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field={}. Exception was: {}", + key, e.toString(), e); + } + return null; + } - Map<String, String> map = new HashMap<>(); + /** + * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the single + * key/field name specified. Returns the associated value if found or null if the key is not found + * + * @param jsonObj JSONObject representation of the the JSON doc + * @param key key to the target value + * @return String field value associated with key + */ + public static String getJsonValueForKey(JSONObject jsonObj, String key) { + + String keyValue = null; + try { + if (jsonObj.has(key)) { + Object value = jsonObj.get(key); + logger.debug("getJsonValueForKey(): found value={}, for key={}", (String) value, key); + if (value == null) { + return null; + } else { + return ((String) value); + } + } else { + Iterator<String> itr = jsonObj.keys(); + while (itr.hasNext()) { + String nextKey = itr.next(); + Object obj = jsonObj.get(nextKey); + if (obj instanceof JSONObject) { + keyValue = getJsonValueForKey((JSONObject) obj, key); + if (keyValue != null) { + break; + } + } else { + logger.debug("getJsonValueForKey(): key={}, does not point to a JSONObject, next key", nextKey); + } + } + } + } catch (Exception e) { + // JSONObject::get() throws a "not found" exception if one of the specified keys is not found + if (e.getMessage().contains("not found")) { + logger.debug("getJsonValueForKey(): failed to retrieve param value for key={}: {}", key, + e.getMessage()); + } else { + logger.debug( + "getJsonValueForKey(): unable to parse json to retrieve value for field={}. Exception was {}", + key, e.toString(), e); + } + keyValue = null; + } + return keyValue; + } - //Populate Map - JSONObject obj = new JSONObject(entry); + /** + * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the single + * key/field name specified. Returns the associated value if found or null if the key is not found + * + * @param jsonObj JSONObject representation of the the JSON doc + * @param key key to the target value + * @return String field value associated with key + */ + public static Integer getJsonIntValueForKey(JSONObject jsonObj, String key) { + Integer keyValue = null; + try { + if (jsonObj.has(key)) { + Integer value = (Integer) jsonObj.get(key); + logger.debug("getJsonIntValueForKey(): found value={}, for key={}", value, key); + return value; + } else { + Iterator<String> itr = jsonObj.keys(); + while (itr.hasNext()) { + String nextKey = itr.next(); + Object obj = jsonObj.get(nextKey); + if (obj instanceof JSONObject) { + keyValue = getJsonIntValueForKey((JSONObject) obj, key); + if (keyValue != null) { + break; + } + } else { + logger.debug("getJsonIntValueForKey(): key={}, does not point to a JSONObject, next key", + nextKey); + } + } + } + } catch (Exception e) { + // JSONObject::get() throws a "not found" exception if one of the specified keys is not found + if (e.getMessage().contains("not found")) { + logger.debug("getJsonIntValueForKey(): failed to retrieve param value for key={}: {}", key, + e.getMessage()); + } else { + logger.debug( + "getJsonIntValueForKey(): unable to parse json to retrieve value for field={}. Exception was: {}", + key, e.toString(), e); + } + keyValue = null; + } + return keyValue; + } - /* Wildfly is pushing a version of org.json which does not - * auto cast to string. Leaving it as an object prevents - * a method not found exception at runtime. - */ - final Iterator<String> keys = obj.keys(); - while (keys.hasNext()) { - final String key = keys.next(); - map.put(key, obj.getString(key)); - } - logger.debug("Outgoing Map is: {}", map); - logger.debug("Completed Json String To Map Method"); - return map; - } + /** + * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the single + * key/field name specified. Returns the associated value if found or null if the key is not found + * + * @param jsonObj JSONObject representation of the the JSON doc + * @param key key to the target value + * @return String field value associated with key + */ + public static Boolean getJsonBooleanValueForKey(JSONObject jsonObj, String key) { + Boolean keyValue = null; + try { + if (jsonObj.has(key)) { + Boolean value = (Boolean) jsonObj.get(key); + logger.debug("getJsonBooleanValueForKey(): found value={}, for key={}", value, key); + return value; + } else { + Iterator<String> itr = jsonObj.keys(); + while (itr.hasNext()) { + String nextKey = itr.next(); + Object obj = jsonObj.get(nextKey); + if (obj instanceof JSONObject) { + keyValue = getJsonBooleanValueForKey((JSONObject) obj, key); + if (keyValue != null) { + break; + } + } else { + logger.debug("getJsonBooleanValueForKey(): key={}, does not point to a JSONObject, next key", + nextKey); + } + } + } + } catch (Exception e) { + // JSONObject::get() throws a "not found" exception if one of the specified keys is not found + if (e.getMessage().contains("not found")) { + logger.debug("getJsonBooleanValueForKey(): failed to retrieve param value for key={}: {}", key, + e.getMessage()); + } else { + logger.debug( + "getJsonBooleanValueForKey(): unable to parse json to retrieve value for field={}. Exception was: {}", + key, e.toString(), e); + } + keyValue = null; + } + return keyValue; + } - /** - * This json util method converts a json array of Key Value - * pair objects into a Java Map. - * - * @param execution - * @param entryArray - the getJsonValue of a json Array of key/value pairs - * @param keyNode - the name of the node that represents the key - * @param valueNode - the name of the node that represents the value - * @return Map - a Map containing the entries - * - */ - public Map<String, String> entryArrayToMap(DelegateExecution execution, String entryArray, String keyNode, String valueNode) { - logger.debug("Started Entry Array To Map Util Method"); + /** + * Boolean method to determine if a key path is valid for the JSON doc. Invokes getJsonValue(). + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return Boolean true if keys points to value in the JSON doc + */ + public static Boolean jsonValueExists(String jsonStr, String keys) { + if (getJsonRawValue(jsonStr, keys) == null) { + return false; + } else { + return true; + } + } - Map<String, String> map = new HashMap<>(); - //Populate Map - String entryListJson = "{ \"wrapper\":" + entryArray + "}"; - JSONObject obj = new JSONObject(entryListJson); - JSONArray arr = obj.getJSONArray("wrapper"); - for (int i = 0; i < arr.length(); i++){ - JSONObject jo = arr.getJSONObject(i); - String key = jo.getString(keyNode); - String value = jo.get(valueNode).toString(); - map.put(key, value); - } - logger.debug("Completed Entry Array To Map Util Method"); - return map; - } + /** + * Inserts the new key/value pair at the appropriate location in the JSON document after first determining if keyed + * field already exists. If it does exist, return the JSON unmodified, otherwise return the new JSON Note: this + * method currently only supports String value inserts. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the value to be added in the format of "key1.key2.key3..." + * @return String containing the updated JSON doc + */ + public static String addJsonValue(String jsonStr, String keys, String value) { + + // only attempt to insert the key/value pair if it does not exist + if (!jsonValueExists(jsonStr, keys)) { + return putJsonValue(jsonStr, keys, value); + } else { + logger.debug("addJsonValue(): JSON add failed, key={}/value={} already exists", keys, value); + return jsonStr; + } + } - /** - * This json util method converts a json array of Key Value pair objects into a Java Map. - * - * @param entryArray - the json Array of key/value pairs objects - * @param keyNode - the name of the node that represents the key - * @param valueNode - the name of the node that represents the value - * @return Map - a Map containing the entries - * @author cb645j - * - */ - public Map<String, String> entryArrayToMap(String entryArray, String keyNode, String valueNode){ - logger.debug("Started Entry Array To Map Util Method"); + /** + * Updates the value for the specified key in the JSON document after first determining if keyed field exists. If it + * does not exist, return the JSON unmodified, otherwise return the updated JSON. Note: this method currently only + * supports String value updates. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the value to be updated in the format of "key1.key2.key3..." + * @return String containing the updated JSON doc + */ + public static String updJsonValue(String jsonStr, String keys, String newValue) { + // only attempt to modify the key/value pair if it exists + if (jsonValueExists(jsonStr, keys)) { + return putJsonValue(jsonStr, keys, newValue); + } else { + logger.debug("updJsonValue(): JSON update failed, no value exists for key={}", keys); + return jsonStr; + } + } - Map<String, String> map = new HashMap<>(); - String entryListJson = "{ \"wrapper\":" + entryArray + "}"; - JSONObject obj = new JSONObject(entryListJson); // TODO just put in json array - JSONArray arr = obj.getJSONArray("wrapper"); - for(int i = 0; i < arr.length(); i++){ - JSONObject jo = arr.getJSONObject(i); - String key = jo.getString(keyNode); - String value = jo.get(valueNode).toString(); - map.put(key, value); - } - logger.debug("Completed Entry Array To Map Util Method"); - return map; - } + /** + * Deletes the value for the specified key in the JSON document after first determining if keyed field exists. If it + * does not exist, return the JSON unmodified, otherwise return the updated JSON + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..." + * @return String containing the updated JSON doc + */ + public static String delJsonValue(String jsonStr, String keys) { + + // only attempt to remove the key/value pair if it exists + if (jsonValueExists(jsonStr, keys)) { + // passing a null value results in a delete + return putJsonValue(jsonStr, keys, null); + } else { + logger.debug("delJsonValue(): JSON delete failed, no value exists for key={}", keys); + return jsonStr; + } + } - /** - * This json util method converts a json Array of Strings to a Java List. It takes each - * String in the json Array and puts it in a Java List<String>. - * - * @param execution - * @param jsonArray - string value of a json array - * @return List - a java list containing the strings - * - * @author cb645j - */ - public List<String> StringArrayToList(Execution execution, String jsonArray){ - logger.debug("Started String Array To List Util Method"); + /** + * Walks the JSON doc using the full key path to retrieve the associated value. All but the last key points to the + * 'parent' object name(s) in order in the JSON hierarchy with the last key pointing to the target value. The value + * returned is a Java object. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return Object field value associated with keys + */ + private static Object getJsonRawValue(String jsonStr, String keys) { + return getJsonRawValue(jsonStr, keys, false); + } - List<String> list = new ArrayList<>(); - // Populate List - // TODO - String stringListJson = "{ \"strings\":" + jsonArray + "}"; - JSONObject obj = new JSONObject(stringListJson); - JSONArray arr = obj.getJSONArray("strings"); - for(int i = 0; i < arr.length(); i++){ - String s = arr.get(i).toString(); - list.add(s); - } - logger.debug("Outgoing List is: {}", list); - logger.debug("Completed String Array To List Util Method"); - return list; - } + /** + * Walks the JSON doc using the full key path to retrieve the associated value. All but the last key points to the + * 'parent' object name(s) in order in the JSON hierarchy with the last key pointing to the target value. The value + * returned is a Java object. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @param wrap Boolean which determines if returned JSONObjects sould be "wrapped" Note: wrap does not apply to + * returned scalar values + * @return Object field value associated with keys + */ + private static Object getJsonRawValue(String jsonStr, String keys, Boolean wrap) { + + String keyStr = ""; + try { + JSONObject jsonObj = new JSONObject(jsonStr); + StringTokenizer keyTokens = new StringTokenizer(keys, "."); + while (keyTokens.hasMoreElements()) { + keyStr = keyTokens.nextToken(); + Object keyValue = jsonObj.get(keyStr); + if (keyValue instanceof JSONObject) { + jsonObj = (JSONObject) keyValue; + } else { + if (keyTokens.hasMoreElements()) { + logger.debug("getJsonRawValue(): value found prior to last key for key={}", keyStr); + } + return keyValue; + } + } + // return the json 'node' that the key points to + // note: since this is a json object and not a scalar value, + // use the wrap flag to determine if the object should + // be wrapped with a root node value + // (the last key in the keys String) + if (wrap) { + JSONObject wrappedJsonObj = new JSONObject(); + wrappedJsonObj.put(keyStr, jsonObj); + return wrappedJsonObj.toString(); + } else { + return jsonObj.toString(); + } + + } catch (Exception e) { + // JSONObject::get() throws a "not found" exception if one of the specified keys is not found + if (e.getMessage().contains("not found")) { + logger.debug("getJsonRawValue(): failed to retrieve param value for key={}: {}", keyStr, + e.getMessage()); + } else { + logger.debug( + "getJsonRawValue(): unable to parse json to retrieve value for field={}. Exception was: {}", + keys, e.toString(), e); + } + } + return null; + } - /** - * This json util method converts a json Array of Strings to a Java List. It takes each - * String in the json Array and puts it in a Java List<String>. - * - * @param jsonArray - string value of a json array - * @return List - a java list containing the strings - * - * @author cb645j - */ - public List<String> StringArrayToList(String jsonArray){ - logger.debug("Started Json Util String Array To List"); - List<String> list = new ArrayList<>(); + /** + * Private method invoked by the public add, update, and delete methods. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..." + * @return String containing the updated JSON doc + */ + private static String putJsonValue(String jsonStr, String keys, String value) { + + String keyStr = ""; + try { + JSONObject jsonObj = new JSONObject(jsonStr); + JSONObject jsonObjOut = jsonObj; + StringTokenizer keyTokens = new StringTokenizer(keys, "."); + while (keyTokens.hasMoreElements()) { + keyStr = keyTokens.nextToken(); + if (keyTokens.hasMoreElements()) { + Object keyValue = jsonObj.get(keyStr); + if (keyValue instanceof JSONObject) { + jsonObj = (JSONObject) keyValue; + } else { + logger.debug("putJsonValue(): key={} not the last key but points to non-json object: {}", + keyStr, keyValue); + return null; + } + } else { // at the last/new key value + jsonObj.put(keyStr, value); + return jsonObjOut.toString(3); + } + } + // should not hit this point if the key points to a valid key value + return null; + + } catch (Exception e) { + // JSONObject::get() throws a "not found" exception if one of the specified keys is not found + if (e.getMessage().contains("not found")) { + logger.debug("putJsonValue(): failed to put param value for key={}: {}", keyStr, e.getMessage()); + } else { + logger.debug("putJsonValue(): unable to parse json to put value for key={}. Exception was: {}", keys, + e.toString(), e); + } + } + return null; + } - JSONArray arr = new JSONArray(jsonArray); - for(int i = 0; i < arr.length(); i++){ - String s = arr.get(i).toString(); - list.add(s); - } - logger.debug("Completed Json Util String Array To List"); - return list; - } + /** + * This json util method converts a json array of Key Value pair objects into a Java Map. + * + * @param execution + * @param entryArray - the getJsonValue of a json Array of key/value pairs + * + * @return Map - a Map containing the entries + */ + public Map<String, String> jsonStringToMap(DelegateExecution execution, String entry) { + logger.debug("Started Json String To Map Method"); + + Map<String, String> map = new HashMap<>(); + + // Populate Map + JSONObject obj = new JSONObject(entry); + + /* + * Wildfly is pushing a version of org.json which does not auto cast to string. Leaving it as an object prevents + * a method not found exception at runtime. + */ + final Iterator<String> keys = obj.keys(); + while (keys.hasNext()) { + final String key = keys.next(); + map.put(key, obj.getString(key)); + } + logger.debug("Outgoing Map is: {}", map); + logger.debug("Completed Json String To Map Method"); + return map; + } - /** - * This json util method converts a json Array of Strings to a Java List. It takes each - * String in the json Array and puts it in a Java List<String>. - * - * @param jsonArray - json array - * @return List - a java list containing the strings - * - * @author cb645j - */ - public List<String> StringArrayToList(JSONArray jsonArray){ - logger.debug("Started Json Util String Array To List"); - List<String> list = new ArrayList<>(); + /** + * This json util method converts a json array of Key Value pair objects into a Java Map. + * + * @param execution + * @param entryArray - the getJsonValue of a json Array of key/value pairs + * @param keyNode - the name of the node that represents the key + * @param valueNode - the name of the node that represents the value + * @return Map - a Map containing the entries + * + */ + public Map<String, String> entryArrayToMap(DelegateExecution execution, String entryArray, String keyNode, + String valueNode) { + logger.debug("Started Entry Array To Map Util Method"); + + Map<String, String> map = new HashMap<>(); + // Populate Map + String entryListJson = "{ \"wrapper\":" + entryArray + "}"; + JSONObject obj = new JSONObject(entryListJson); + JSONArray arr = obj.getJSONArray("wrapper"); + for (int i = 0; i < arr.length(); i++) { + JSONObject jo = arr.getJSONObject(i); + String key = jo.getString(keyNode); + String value = jo.get(valueNode).toString(); + map.put(key, value); + } + logger.debug("Completed Entry Array To Map Util Method"); + return map; + } - for(int i = 0; i < jsonArray.length(); i++){ - String s = jsonArray.get(i).toString(); - list.add(s); - } - logger.debug("Completed Json Util String Array To List"); - return list; - } + /** + * This json util method converts a json array of Key Value pair objects into a Java Map. + * + * @param entryArray - the json Array of key/value pairs objects + * @param keyNode - the name of the node that represents the key + * @param valueNode - the name of the node that represents the value + * @return Map - a Map containing the entries + * @author cb645j + * + */ + public Map<String, String> entryArrayToMap(String entryArray, String keyNode, String valueNode) { + logger.debug("Started Entry Array To Map Util Method"); + + Map<String, String> map = new HashMap<>(); + String entryListJson = "{ \"wrapper\":" + entryArray + "}"; + JSONObject obj = new JSONObject(entryListJson); // TODO just put in json array + JSONArray arr = obj.getJSONArray("wrapper"); + for (int i = 0; i < arr.length(); i++) { + JSONObject jo = arr.getJSONObject(i); + String key = jo.getString(keyNode); + String value = jo.get(valueNode).toString(); + map.put(key, value); + } + logger.debug("Completed Entry Array To Map Util Method"); + return map; + } - /** - * - * Invokes the getJsonRawValue() method to determine if the json element/variable exist. - * Returns true if the json element exist - * - * @param jsonStr - String containing the JSON doc - * @param keys - full key path to the target value in the format of "key1.key2.key3..." - * @return boolean field value associated with keys - * - */ - public static boolean jsonElementExist(String jsonStr, String keys){ + /** + * This json util method converts a json Array of Strings to a Java List. It takes each String in the json Array and + * puts it in a Java List<String>. + * + * @param execution + * @param jsonArray - string value of a json array + * @return List - a java list containing the strings + * + * @author cb645j + */ + public List<String> StringArrayToList(Execution execution, String jsonArray) { + logger.debug("Started String Array To List Util Method"); + + List<String> list = new ArrayList<>(); + // Populate List + // TODO + String stringListJson = "{ \"strings\":" + jsonArray + "}"; + JSONObject obj = new JSONObject(stringListJson); + JSONArray arr = obj.getJSONArray("strings"); + for (int i = 0; i < arr.length(); i++) { + String s = arr.get(i).toString(); + list.add(s); + } + logger.debug("Outgoing List is: {}", list); + logger.debug("Completed String Array To List Util Method"); + return list; + } - try{ - Object rawValue = getJsonRawValue(jsonStr, keys); + /** + * This json util method converts a json Array of Strings to a Java List. It takes each String in the json Array and + * puts it in a Java List<String>. + * + * @param jsonArray - string value of a json array + * @return List - a java list containing the strings + * + * @author cb645j + */ + public List<String> StringArrayToList(String jsonArray) { + logger.debug("Started Json Util String Array To List"); + List<String> list = new ArrayList<>(); + + JSONArray arr = new JSONArray(jsonArray); + for (int i = 0; i < arr.length(); i++) { + String s = arr.get(i).toString(); + list.add(s); + } + logger.debug("Completed Json Util String Array To List"); + return list; + } - return !(rawValue == null); + /** + * This json util method converts a json Array of Strings to a Java List. It takes each String in the json Array and + * puts it in a Java List<String>. + * + * @param jsonArray - json array + * @return List - a java list containing the strings + * + * @author cb645j + */ + public List<String> StringArrayToList(JSONArray jsonArray) { + logger.debug("Started Json Util String Array To List"); + List<String> list = new ArrayList<>(); + + for (int i = 0; i < jsonArray.length(); i++) { + String s = jsonArray.get(i).toString(); + list.add(s); + } + logger.debug("Completed Json Util String Array To List"); + return list; + } - } catch(Exception e){ - logger.debug("jsonElementExist(): unable to determine if json element exist. Exception is: {}", e.toString(), e); - } - return true; - } + /** + * + * Invokes the getJsonRawValue() method to determine if the json element/variable exist. Returns true if the json + * element exist + * + * @param jsonStr - String containing the JSON doc + * @param keys - full key path to the target value in the format of "key1.key2.key3..." + * @return boolean field value associated with keys + * + */ + public static boolean jsonElementExist(String jsonStr, String keys) { + + try { + Object rawValue = getJsonRawValue(jsonStr, keys); + + return !(rawValue == null); + + } catch (Exception e) { + logger.debug("jsonElementExist(): unable to determine if json element exist. Exception is: {}", + e.toString(), e); + } + return true; + } - /** - * - * Validates the JSON document against a schema file. - * - * @param jsonStr String containing the JSON doc - * @param jsonSchemaPath full path to a valid JSON schema file - * - */ + /** + * + * Validates the JSON document against a schema file. + * + * @param jsonStr String containing the JSON doc + * @param jsonSchemaPath full path to a valid JSON schema file + * + */ public static String jsonSchemaValidation(String jsonStr, String jsonSchemaPath) throws ValidationException { - try { - logger.debug("JSON document to be validated: {}", jsonStr); - JsonNode document = JsonLoader.fromString(jsonStr); - JsonNode schema = JsonLoader.fromPath(jsonSchemaPath); - - JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); - JsonValidator validator = factory.getValidator(); - - ProcessingReport report = validator.validate(schema, document); - logger.debug("JSON schema validation report: {}", report.toString()); - return report.toString(); - } catch (IOException e) { - logger.debug("IOException performing JSON schema validation on document: {}", e.toString()); - throw new ValidationException(e.getMessage()); - } catch (ProcessingException e) { - logger.debug("ProcessingException performing JSON schema validation on document: {}", e.toString()); - throw new ValidationException(e.getMessage()); - } + try { + logger.debug("JSON document to be validated: {}", jsonStr); + JsonNode document = JsonLoader.fromString(jsonStr); + JsonNode schema = JsonLoader.fromPath(jsonSchemaPath); + + JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); + JsonValidator validator = factory.getValidator(); + + ProcessingReport report = validator.validate(schema, document); + logger.debug("JSON schema validation report: {}", report.toString()); + return report.toString(); + } catch (IOException e) { + logger.debug("IOException performing JSON schema validation on document: {}", e.toString()); + throw new ValidationException(e.getMessage()); + } catch (ProcessingException e) { + logger.debug("ProcessingException performing JSON schema validation on document: {}", e.toString()); + throw new ValidationException(e.getMessage()); + } } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/xml/XmlTool.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/xml/XmlTool.java index 6c8070f9bd..da096e5461 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/xml/XmlTool.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/xml/XmlTool.java @@ -32,7 +32,6 @@ import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import java.util.Optional; - import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -49,7 +48,6 @@ import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; - import org.apache.commons.lang3.StringEscapeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -64,193 +62,194 @@ import org.xml.sax.SAXException; */ public final class XmlTool { - private static final Map<String, Integer> ENTITIES = new HashMap<>(); - private static final Logger logger = LoggerFactory.getLogger(XmlTool.class); - static { - ENTITIES.put("amp", 38); - ENTITIES.put("quot", 34); - ENTITIES.put("lt", 60); - ENTITIES.put("gt", 62); - } + private static final Map<String, Integer> ENTITIES = new HashMap<>(); + private static final Logger logger = LoggerFactory.getLogger(XmlTool.class); + static { + ENTITIES.put("amp", 38); + ENTITIES.put("quot", 34); + ENTITIES.put("lt", 60); + ENTITIES.put("gt", 62); + } - /** + /** * Instantiation is not allowed. */ - private XmlTool() { + private XmlTool() {} + + /** + * Normalizes and formats XML. This method consolidates and moves all namespace declarations to the root element. + * The result will not have an XML prolog or a trailing newline. + * + * @param xml the XML to normalize + * @throws IOException + * @throws TransformerException + * @throws ParserConfigurationException + * @throws SAXException + * @throws XPathExpressionException + */ + public static String normalize(Object xml) throws IOException, TransformerException, ParserConfigurationException, + SAXException, XPathExpressionException { + + if (xml == null) { + return null; + } + + Source xsltSource = new StreamSource(new StringReader(readResourceFile("normalize-namespaces.xsl"))); + + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + dbFactory.setNamespaceAware(true); + dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); + dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + DocumentBuilder db = dbFactory.newDocumentBuilder(); + InputSource source = new InputSource(new StringReader(String.valueOf(xml))); + Document doc = db.parse(source); + + // Start of code to remove whitespace outside of tags + XPath xPath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", doc, XPathConstants.NODESET); + + for (int i = 0; i < nodeList.getLength(); ++i) { + Node node = nodeList.item(i); + node.getParentNode().removeChild(node); + } + // End of code to remove whitespace outside of tags + + // the factory pattern supports different XSLT processors + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + Transformer transformer = transformerFactory.newTransformer(xsltSource); + + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + + StringWriter writer = new StringWriter(); + transformer.transform(new DOMSource(doc), new StreamResult(writer)); + return writer.toString().trim(); } - - /** - * Normalizes and formats XML. This method consolidates and moves all namespace - * declarations to the root element. The result will not have an XML prolog or - * a trailing newline. - * @param xml the XML to normalize - * @throws IOException - * @throws TransformerException - * @throws ParserConfigurationException - * @throws SAXException - * @throws XPathExpressionException - */ - public static String normalize(Object xml) throws IOException, TransformerException, - ParserConfigurationException, SAXException, XPathExpressionException { - - if (xml == null) { - return null; - } - - Source xsltSource = new StreamSource(new StringReader( - readResourceFile("normalize-namespaces.xsl"))); - - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - dbFactory.setNamespaceAware(true); - dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); - dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); - DocumentBuilder db = dbFactory.newDocumentBuilder(); - InputSource source = new InputSource(new StringReader(String.valueOf(xml))); - Document doc = db.parse(source); - - // Start of code to remove whitespace outside of tags - XPath xPath = XPathFactory.newInstance().newXPath(); - NodeList nodeList = (NodeList) xPath.evaluate( - "//text()[normalize-space()='']", doc, XPathConstants.NODESET); - - for (int i = 0; i < nodeList.getLength(); ++i) { - Node node = nodeList.item(i); - node.getParentNode().removeChild(node); - } - // End of code to remove whitespace outside of tags - - // the factory pattern supports different XSLT processors - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - Transformer transformer = transformerFactory.newTransformer(xsltSource); - - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); - - StringWriter writer = new StringWriter(); - transformer.transform(new DOMSource(doc), new StreamResult(writer)); - return writer.toString().trim(); - } - - /** - * Encodes a value so it can be used inside an XML text element. - * @param value the string to encode - * @return the encoded string - */ - public static String encode(Object value) { - if (value == null) { - return null; - } - return StringEscapeUtils.escapeXml11(value.toString()); - } - - /** - * Removes the preamble, if present, from an XML document. - * @param xml the XML document - * @return a possibly modified document - */ - public static String removePreamble(Object xml) { - if (xml == null) { - return null; - } - - return String.valueOf(xml).replaceAll("(<\\?[^<]*\\?>\\s*[\\r\\n]*)?", ""); - } - /** - * Removes namespaces and namespace declarations from an XML document. - * @param xml the XML document - * @return a possibly modified document - */ - public static String removeNamespaces(Object xml) { - if (xml == null) { - logger.debug("removeNamespaces input object is null , returning null"); - return null; - } - - String text = String.valueOf(xml); - - // remove xmlns declaration - text = text.replaceAll("xmlns.*?(\"|\').*?(\"|\')", ""); - // remove opening tag prefix - text = text.replaceAll("(<)(\\w+:)(.*?>)", "$1$3"); - // remove closing tags prefix - text = text.replaceAll("(</)(\\w+:)(.*?>)", "$1$3"); - // remove extra spaces left when xmlns declarations are removed - text = text.replaceAll("\\s+>", ">"); - - return text; - } + /** + * Encodes a value so it can be used inside an XML text element. + * + * @param value the string to encode + * @return the encoded string + */ + public static String encode(Object value) { + if (value == null) { + return null; + } + return StringEscapeUtils.escapeXml11(value.toString()); + } + /** + * Removes the preamble, if present, from an XML document. + * + * @param xml the XML document + * @return a possibly modified document + */ + public static String removePreamble(Object xml) { + if (xml == null) { + return null; + } - /** - * Reads the specified resource file and return the contents as a string. - * @param file Name of the resource file - * @return the contents of the resource file as a String - * @throws IOException if there is a problem reading the file - */ - private static String readResourceFile(String file) throws IOException { + return String.valueOf(xml).replaceAll("(<\\?[^<]*\\?>\\s*[\\r\\n]*)?", ""); + } - try (InputStream stream = XmlTool.class.getClassLoader().getResourceAsStream(file); - Reader reader = new InputStreamReader(stream, "UTF-8")) { + /** + * Removes namespaces and namespace declarations from an XML document. + * + * @param xml the XML document + * @return a possibly modified document + */ + public static String removeNamespaces(Object xml) { + if (xml == null) { + logger.debug("removeNamespaces input object is null , returning null"); + return null; + } + + String text = String.valueOf(xml); + + // remove xmlns declaration + text = text.replaceAll("xmlns.*?(\"|\').*?(\"|\')", ""); + // remove opening tag prefix + text = text.replaceAll("(<)(\\w+:)(.*?>)", "$1$3"); + // remove closing tags prefix + text = text.replaceAll("(</)(\\w+:)(.*?>)", "$1$3"); + // remove extra spaces left when xmlns declarations are removed + text = text.replaceAll("\\s+>", ">"); + + return text; + } - StringBuilder out = new StringBuilder(); - char[] buf = new char[1024]; - int n; - while ((n = reader.read(buf)) >= 0) { - out.append(buf, 0, n); - } - return out.toString(); - } catch (Exception e) { - logger.debug("Exception at readResourceFile stream: " + e); - return null; - } - } - - /** - * Parses the XML document String for the first occurrence of the specified element tag. - * If found, the value associated with that element tag is replaced with the new value - * and a String containing the modified XML document is returned. If the XML passed is - * null or the element tag is not found in the document, null will be returned. - * @param xml String containing the original XML document. - * @param elementTag String containing the tag of the element to be modified. - * @param newValue String containing the new value to be used to modify the corresponding element. - * @return the contents of the modified XML document as a String or null/empty if the modification failed. - * @throws IOException, TransformerException, ParserConfigurationException, SAXException - */ - public static Optional<String> modifyElement(String xml, String elementTag, String newValue) throws IOException, TransformerException, - ParserConfigurationException, SAXException { + /** + * Reads the specified resource file and return the contents as a string. + * + * @param file Name of the resource file + * @return the contents of the resource file as a String + * @throws IOException if there is a problem reading the file + */ + private static String readResourceFile(String file) throws IOException { + + try (InputStream stream = XmlTool.class.getClassLoader().getResourceAsStream(file); + Reader reader = new InputStreamReader(stream, "UTF-8")) { + + StringBuilder out = new StringBuilder(); + char[] buf = new char[1024]; + int n; + + while ((n = reader.read(buf)) >= 0) { + out.append(buf, 0, n); + } + return out.toString(); + } catch (Exception e) { + logger.debug("Exception at readResourceFile stream: " + e); + return null; + } + } - if (xml == null || xml.isEmpty()) { - // no XML content to be modified, return empty - return Optional.empty(); - } - - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - dbFactory.setNamespaceAware(true); - dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); - dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); - DocumentBuilder db = dbFactory.newDocumentBuilder(); - InputSource source = new InputSource(new StringReader(xml)); - Document doc = db.parse(source); - - Node modNode = doc.getElementsByTagName(elementTag).item(0); - if (modNode == null) { - // did not find the specified element to be modified, return empty - //System.out.println("Did not find element tag " + elementTag + " in XML"); - return Optional.empty(); - } else { - modNode.setTextContent(newValue); - } - - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - StringWriter writer = new StringWriter(); - transformer.transform(new DOMSource(doc), new StreamResult(writer)); - // return the modified String representation of the XML - return Optional.of(writer.toString().trim()); - } + /** + * Parses the XML document String for the first occurrence of the specified element tag. If found, the value + * associated with that element tag is replaced with the new value and a String containing the modified XML document + * is returned. If the XML passed is null or the element tag is not found in the document, null will be returned. + * + * @param xml String containing the original XML document. + * @param elementTag String containing the tag of the element to be modified. + * @param newValue String containing the new value to be used to modify the corresponding element. + * @return the contents of the modified XML document as a String or null/empty if the modification failed. + * @throws IOException, TransformerException, ParserConfigurationException, SAXException + */ + public static Optional<String> modifyElement(String xml, String elementTag, String newValue) + throws IOException, TransformerException, ParserConfigurationException, SAXException { + + if (xml == null || xml.isEmpty()) { + // no XML content to be modified, return empty + return Optional.empty(); + } + + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + dbFactory.setNamespaceAware(true); + dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); + dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + DocumentBuilder db = dbFactory.newDocumentBuilder(); + InputSource source = new InputSource(new StringReader(xml)); + Document doc = db.parse(source); + + Node modNode = doc.getElementsByTagName(elementTag).item(0); + if (modNode == null) { + // did not find the specified element to be modified, return empty + // System.out.println("Did not find element tag " + elementTag + " in XML"); + return Optional.empty(); + } else { + modNode.setTextContent(newValue); + } + + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + StringWriter writer = new StringWriter(); + transformer.transform(new DOMSource(doc), new StreamResult(writer)); + // return the modified String representation of the XML + return Optional.of(writer.toString().trim()); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BadInjectedFiledExceptionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BadInjectedFiledExceptionTest.java index b35e65485f..67b33602dd 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BadInjectedFiledExceptionTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BadInjectedFiledExceptionTest.java @@ -1,22 +1,17 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 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 + * 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. + * 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.so.bpmn.core; @@ -25,22 +20,22 @@ import org.junit.Test; public class BadInjectedFiledExceptionTest { - private BadInjectedFieldException badInjectedFieldException; - - @Test - public void test() { - String fieldName = "anyFieldName"; - String taskName = "anyTask"; - Object info = new String("info"); - - String expectedMessage1 = taskName+" injected field '"+fieldName+"' is bad: "+(String)info; - badInjectedFieldException = new BadInjectedFieldException(fieldName, taskName, info); - assertEquals(expectedMessage1, badInjectedFieldException.getMessage()); - - String expectedMessage2 = "java.lang.Throwable: anyCause"; - Throwable cause = new Throwable("anyCause"); - badInjectedFieldException = new BadInjectedFieldException(fieldName, taskName, info, cause); - assertEquals(expectedMessage2, badInjectedFieldException.getCause().toString()); - - } + private BadInjectedFieldException badInjectedFieldException; + + @Test + public void test() { + String fieldName = "anyFieldName"; + String taskName = "anyTask"; + Object info = new String("info"); + + String expectedMessage1 = taskName + " injected field '" + fieldName + "' is bad: " + (String) info; + badInjectedFieldException = new BadInjectedFieldException(fieldName, taskName, info); + assertEquals(expectedMessage1, badInjectedFieldException.getMessage()); + + String expectedMessage2 = "java.lang.Throwable: anyCause"; + Throwable cause = new Throwable("anyCause"); + badInjectedFieldException = new BadInjectedFieldException(fieldName, taskName, info, cause); + assertEquals(expectedMessage2, badInjectedFieldException.getCause().toString()); + + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java index 40fcb982c1..49f373c01e 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java @@ -1,22 +1,17 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 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 + * 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. + * 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.so.bpmn.core; @@ -24,7 +19,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import org.camunda.bpm.engine.ProcessEngineServices; import org.camunda.bpm.engine.RepositoryService; import org.camunda.bpm.engine.delegate.DelegateExecution; @@ -33,215 +27,215 @@ import org.camunda.bpm.engine.repository.ProcessDefinition; import org.junit.Before; import org.junit.Rule; import org.junit.Test; - import org.junit.rules.ExpectedException; public class BaseTaskTest { - private String prefix = "PRE_"; - private String processKey = "AnyProcessKey"; - private String definitionId = "100"; - private String anyVariable = "anyVariable"; - private String anyValueString = "anyValue"; - private String badValueString = "123abc"; - private int anyValueInt = 123; - private Integer anyValueInteger = new Integer(anyValueInt); - private long anyValuelong = 123L; - private Long anyValueLong = new Long(anyValuelong); - - private DelegateExecution mockExecution; - private Expression mockExpression; - private BaseTask baseTask; - private Object obj1; - private Object obj2; - private Object objectString; - private Object objectInteger; - private Object objectLong; - private Object objectBoolean; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Before - public void before() throws Exception { - baseTask = new BaseTask(); - ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class); - when(mockProcessDefinition.getKey()).thenReturn(processKey); - RepositoryService mockRepositoryService = mock(RepositoryService.class); - when(mockRepositoryService.getProcessDefinition(definitionId)).thenReturn(mockProcessDefinition); - ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class); - when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService); - mockExecution = mock(DelegateExecution.class); - when(mockExecution.getId()).thenReturn(definitionId); - when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices); - when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition); - when(mockExecution.getVariable("prefix")).thenReturn(prefix); - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true"); - mockExpression = mock(Expression.class); - } - - @Test - public void testExecution() throws Exception{ - baseTask.execute(mockExecution); - assertEquals("BaseTask", baseTask.getTaskName()); - } - - @Test - public void testGetFieldAndMissingInjectedException() throws Exception{ - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj1 = baseTask.getField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueString, obj1.toString()); - - expectedException.expect(MissingInjectedFieldException.class); - obj2 = baseTask.getField(null, mockExecution, anyVariable); - } - - @Test - public void testGetFieldAndBadInjectedFieldException() throws Exception{ - expectedException.expect(BadInjectedFieldException.class); - obj1 = baseTask.getField(mockExpression, mockExecution, null); - } - - @Test - public void testGetOptionalField() throws Exception{ - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj1 = baseTask.getOptionalField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueString, obj1.toString()); - } - - @Test - public void testGetStringFieldAndMissingInjectedFieldException() throws Exception{ - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj1 = baseTask.getStringField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueString, obj1.toString()); - - expectedException.expect(MissingInjectedFieldException.class); - Object objectBoolean = new Boolean(true); // bad data - when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean); - obj2 = baseTask.getStringField(null, mockExecution, anyVariable); - } - - @Test - public void testGetStringFieldAndBadInjectedFieldException() throws Exception{ - expectedException.expect(BadInjectedFieldException.class); - obj1 = baseTask.getStringField(mockExpression, mockExecution, null); - } - - @Test - public void testGetOptionalStringField() throws Exception{ - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj1 = baseTask.getOptionalStringField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueString, obj1.toString()); - } - - @Test - public void testGetIntegerFieldAndMissingInjectedFieldException() throws Exception{ - objectInteger = new Integer(anyValueInt); - when(mockExpression.getValue(mockExecution)).thenReturn(objectInteger); - obj1 = baseTask.getIntegerField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueInteger, (Integer)obj1); - - expectedException.expect(MissingInjectedFieldException.class); - objectString = new String(badValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj2 = baseTask.getIntegerField(null, mockExecution, anyVariable); - } - - @Test - public void testGetIntegerFieldAndBadInjectedFieldException() throws Exception{ - expectedException.expect(BadInjectedFieldException.class); - obj1 = baseTask.getIntegerField(mockExpression, mockExecution, null); - } - - - @Test - public void testGetOptionalIntegerField() throws Exception{ - objectInteger = new Integer(anyValueInt); - when(mockExpression.getValue(mockExecution)).thenReturn(objectInteger); - obj1 = baseTask.getOptionalIntegerField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueInteger, (Integer)obj1); - } - - @Test - public void testGetOptionalIntegerFieldAndBadInjectedFieldException() throws Exception{ - expectedException.expect(BadInjectedFieldException.class); - objectBoolean = new Boolean(true); - when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean); - obj1 = baseTask.getOptionalIntegerField(mockExpression, mockExecution, anyVariable); - } - - @Test - public void testGetLongFieldAndMissingInjectedFieldException() throws Exception{ - objectLong = new Long(anyValuelong); - when(mockExpression.getValue(mockExecution)).thenReturn(objectLong); - obj1 = baseTask.getLongField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueLong, (Long)obj1); - - expectedException.expect(MissingInjectedFieldException.class); - objectString = new String(badValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj2 = baseTask.getLongField(null, mockExecution, anyVariable); - } - - @Test - public void testGetLongFieldAndBadInjectedFieldException() throws Exception{ - expectedException.expect(BadInjectedFieldException.class); - obj2 = baseTask.getLongField(mockExpression, mockExecution, null); - } - - @Test - public void testGetOptionalLongField() throws Exception{ - objectLong = new Long(anyValuelong); - when(mockExpression.getValue(mockExecution)).thenReturn(objectLong); - obj1 = baseTask.getOptionalLongField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueLong, (Long)obj1); - } - - @Test - public void testGetOptionalLongFieldAndBadInjectedFieldException() throws Exception{ - expectedException.expect(BadInjectedFieldException.class); - objectBoolean = new Boolean(true); - when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean); - obj1 = baseTask.getOptionalLongField(mockExpression, mockExecution, anyVariable); - } - - @Test - public void testGetOutputAndMissingInjectedFieldException() throws Exception{ - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj1 = baseTask.getOutputField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueString, obj1.toString()); - - expectedException.expect(MissingInjectedFieldException.class); - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj2 = baseTask.getOutputField(null, mockExecution, anyVariable); - } - - @Test - public void testGetOutputAndBadInjectedFieldException() throws Exception{ - expectedException.expect(BadInjectedFieldException.class); - obj2 = baseTask.getOutputField(null, mockExecution, anyVariable); - } - - @Test - public void testGetOptionalOutputField() throws Exception{ - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj1 = baseTask.getOptionalOutputField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueString, obj1.toString()); - } - - @Test - public void testGetOptionalOutputFieldAndBadInjectedFieldException() throws Exception{ - expectedException.expect(BadInjectedFieldException.class); - objectBoolean = new Boolean(true); - when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean); - obj1 = baseTask.getOptionalOutputField(mockExpression, mockExecution, anyVariable); - } - + private String prefix = "PRE_"; + private String processKey = "AnyProcessKey"; + private String definitionId = "100"; + private String anyVariable = "anyVariable"; + private String anyValueString = "anyValue"; + private String badValueString = "123abc"; + private int anyValueInt = 123; + private Integer anyValueInteger = new Integer(anyValueInt); + private long anyValuelong = 123L; + private Long anyValueLong = new Long(anyValuelong); + + private DelegateExecution mockExecution; + private Expression mockExpression; + private BaseTask baseTask; + private Object obj1; + private Object obj2; + private Object objectString; + private Object objectInteger; + private Object objectLong; + private Object objectBoolean; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void before() throws Exception { + baseTask = new BaseTask(); + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class); + when(mockProcessDefinition.getKey()).thenReturn(processKey); + RepositoryService mockRepositoryService = mock(RepositoryService.class); + when(mockRepositoryService.getProcessDefinition(definitionId)).thenReturn(mockProcessDefinition); + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class); + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService); + mockExecution = mock(DelegateExecution.class); + when(mockExecution.getId()).thenReturn(definitionId); + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices); + when(mockExecution.getProcessEngineServices().getRepositoryService() + .getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition); + when(mockExecution.getVariable("prefix")).thenReturn(prefix); + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true"); + mockExpression = mock(Expression.class); + } + + @Test + public void testExecution() throws Exception { + baseTask.execute(mockExecution); + assertEquals("BaseTask", baseTask.getTaskName()); + } + + @Test + public void testGetFieldAndMissingInjectedException() throws Exception { + objectString = new String(anyValueString); + when(mockExpression.getValue(mockExecution)).thenReturn(objectString); + obj1 = baseTask.getField(mockExpression, mockExecution, anyVariable); + assertEquals(anyValueString, obj1.toString()); + + expectedException.expect(MissingInjectedFieldException.class); + obj2 = baseTask.getField(null, mockExecution, anyVariable); + } + + @Test + public void testGetFieldAndBadInjectedFieldException() throws Exception { + expectedException.expect(BadInjectedFieldException.class); + obj1 = baseTask.getField(mockExpression, mockExecution, null); + } + + @Test + public void testGetOptionalField() throws Exception { + objectString = new String(anyValueString); + when(mockExpression.getValue(mockExecution)).thenReturn(objectString); + obj1 = baseTask.getOptionalField(mockExpression, mockExecution, anyVariable); + assertEquals(anyValueString, obj1.toString()); + } + + @Test + public void testGetStringFieldAndMissingInjectedFieldException() throws Exception { + objectString = new String(anyValueString); + when(mockExpression.getValue(mockExecution)).thenReturn(objectString); + obj1 = baseTask.getStringField(mockExpression, mockExecution, anyVariable); + assertEquals(anyValueString, obj1.toString()); + + expectedException.expect(MissingInjectedFieldException.class); + Object objectBoolean = new Boolean(true); // bad data + when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean); + obj2 = baseTask.getStringField(null, mockExecution, anyVariable); + } + + @Test + public void testGetStringFieldAndBadInjectedFieldException() throws Exception { + expectedException.expect(BadInjectedFieldException.class); + obj1 = baseTask.getStringField(mockExpression, mockExecution, null); + } + + @Test + public void testGetOptionalStringField() throws Exception { + objectString = new String(anyValueString); + when(mockExpression.getValue(mockExecution)).thenReturn(objectString); + obj1 = baseTask.getOptionalStringField(mockExpression, mockExecution, anyVariable); + assertEquals(anyValueString, obj1.toString()); + } + + @Test + public void testGetIntegerFieldAndMissingInjectedFieldException() throws Exception { + objectInteger = new Integer(anyValueInt); + when(mockExpression.getValue(mockExecution)).thenReturn(objectInteger); + obj1 = baseTask.getIntegerField(mockExpression, mockExecution, anyVariable); + assertEquals(anyValueInteger, (Integer) obj1); + + expectedException.expect(MissingInjectedFieldException.class); + objectString = new String(badValueString); + when(mockExpression.getValue(mockExecution)).thenReturn(objectString); + obj2 = baseTask.getIntegerField(null, mockExecution, anyVariable); + } + + @Test + public void testGetIntegerFieldAndBadInjectedFieldException() throws Exception { + expectedException.expect(BadInjectedFieldException.class); + obj1 = baseTask.getIntegerField(mockExpression, mockExecution, null); + } + + + @Test + public void testGetOptionalIntegerField() throws Exception { + objectInteger = new Integer(anyValueInt); + when(mockExpression.getValue(mockExecution)).thenReturn(objectInteger); + obj1 = baseTask.getOptionalIntegerField(mockExpression, mockExecution, anyVariable); + assertEquals(anyValueInteger, (Integer) obj1); + } + + @Test + public void testGetOptionalIntegerFieldAndBadInjectedFieldException() throws Exception { + expectedException.expect(BadInjectedFieldException.class); + objectBoolean = new Boolean(true); + when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean); + obj1 = baseTask.getOptionalIntegerField(mockExpression, mockExecution, anyVariable); + } + + @Test + public void testGetLongFieldAndMissingInjectedFieldException() throws Exception { + objectLong = new Long(anyValuelong); + when(mockExpression.getValue(mockExecution)).thenReturn(objectLong); + obj1 = baseTask.getLongField(mockExpression, mockExecution, anyVariable); + assertEquals(anyValueLong, (Long) obj1); + + expectedException.expect(MissingInjectedFieldException.class); + objectString = new String(badValueString); + when(mockExpression.getValue(mockExecution)).thenReturn(objectString); + obj2 = baseTask.getLongField(null, mockExecution, anyVariable); + } + + @Test + public void testGetLongFieldAndBadInjectedFieldException() throws Exception { + expectedException.expect(BadInjectedFieldException.class); + obj2 = baseTask.getLongField(mockExpression, mockExecution, null); + } + + @Test + public void testGetOptionalLongField() throws Exception { + objectLong = new Long(anyValuelong); + when(mockExpression.getValue(mockExecution)).thenReturn(objectLong); + obj1 = baseTask.getOptionalLongField(mockExpression, mockExecution, anyVariable); + assertEquals(anyValueLong, (Long) obj1); + } + + @Test + public void testGetOptionalLongFieldAndBadInjectedFieldException() throws Exception { + expectedException.expect(BadInjectedFieldException.class); + objectBoolean = new Boolean(true); + when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean); + obj1 = baseTask.getOptionalLongField(mockExpression, mockExecution, anyVariable); + } + + @Test + public void testGetOutputAndMissingInjectedFieldException() throws Exception { + objectString = new String(anyValueString); + when(mockExpression.getValue(mockExecution)).thenReturn(objectString); + obj1 = baseTask.getOutputField(mockExpression, mockExecution, anyVariable); + assertEquals(anyValueString, obj1.toString()); + + expectedException.expect(MissingInjectedFieldException.class); + objectString = new String(anyValueString); + when(mockExpression.getValue(mockExecution)).thenReturn(objectString); + obj2 = baseTask.getOutputField(null, mockExecution, anyVariable); + } + + @Test + public void testGetOutputAndBadInjectedFieldException() throws Exception { + expectedException.expect(BadInjectedFieldException.class); + obj2 = baseTask.getOutputField(null, mockExecution, anyVariable); + } + + @Test + public void testGetOptionalOutputField() throws Exception { + objectString = new String(anyValueString); + when(mockExpression.getValue(mockExecution)).thenReturn(objectString); + obj1 = baseTask.getOptionalOutputField(mockExpression, mockExecution, anyVariable); + assertEquals(anyValueString, obj1.toString()); + } + + @Test + public void testGetOptionalOutputFieldAndBadInjectedFieldException() throws Exception { + expectedException.expect(BadInjectedFieldException.class); + objectBoolean = new Boolean(true); + when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean); + obj1 = baseTask.getOptionalOutputField(mockExpression, mockExecution, anyVariable); + } + } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BeansTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BeansTest.java index 2415e619d7..965a9cc04d 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BeansTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BeansTest.java @@ -24,17 +24,14 @@ import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.onap.so.openpojo.rules.HasAnnotationMatcher.hasAnnotation; import static org.onap.so.openpojo.rules.HasAnnotationPropertyWithValueMatcher.hasAnnotationPropertyWithValue; - import javax.persistence.Column; import javax.persistence.Temporal; - import org.junit.Test; import org.onap.so.openpojo.rules.CustomSetterMustExistRule; import org.onap.so.openpojo.rules.EqualsAndHashCodeTester; import org.onap.so.openpojo.rules.HasEqualsAndHashCodeRule; import org.onap.so.openpojo.rules.HasToStringRule; import org.onap.so.openpojo.rules.ToStringTester; - import com.openpojo.reflection.PojoClass; import com.openpojo.reflection.PojoClassFilter; import com.openpojo.reflection.filters.FilterEnum; @@ -55,37 +52,35 @@ import com.openpojo.validation.test.impl.SetterTester; public class BeansTest { - private PojoClassFilter filterTestClasses = new FilterTestClasses(); - - private PojoClassFilter enumFilter = new FilterEnum(); - - - - @Test - public void pojoStructure() { - test("org.onap.so.bpmn.core.domain"); - - } - - private void test(String pojoPackage) { - Validator validator = ValidatorBuilder.create() - .with(new GetterMustExistRule()) - .with(new NoNestedClassRule()) - .with(new SerializableMustHaveSerialVersionUIDRule()) - .with(new NoPublicFieldsExceptStaticFinalRule()) - .with(new SetterTester()) - .with(new GetterTester()) - - - - .build(); - - - validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses,enumFilter,new FilterNonConcrete()); - } - private static class FilterTestClasses implements PojoClassFilter { - public boolean include(PojoClass pojoClass) { - return !pojoClass.getSourcePath().contains("/test-classes/"); - } - } + private PojoClassFilter filterTestClasses = new FilterTestClasses(); + + private PojoClassFilter enumFilter = new FilterEnum(); + + + + @Test + public void pojoStructure() { + test("org.onap.so.bpmn.core.domain"); + + } + + private void test(String pojoPackage) { + Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new NoNestedClassRule()) + .with(new SerializableMustHaveSerialVersionUIDRule()).with(new NoPublicFieldsExceptStaticFinalRule()) + .with(new SetterTester()).with(new GetterTester()) + + + + .build(); + + + validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, enumFilter, + new FilterNonConcrete()); + } + + private static class FilterTestClasses implements PojoClassFilter { + public boolean include(PojoClass pojoClass) { + return !pojoClass.getSourcePath().contains("/test-classes/"); + } + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/MissingInjectedFiledExceptionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/MissingInjectedFiledExceptionTest.java index b0aa41b05d..1bc0153956 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/MissingInjectedFiledExceptionTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/MissingInjectedFiledExceptionTest.java @@ -1,22 +1,17 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 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 + * 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. + * 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.so.bpmn.core; @@ -25,15 +20,15 @@ import org.junit.Test; public class MissingInjectedFiledExceptionTest { - private MissingInjectedFieldException missingInjectedFieldException; - - @Test - public void test() { - String fieldName = "anyFieldName"; - String taskName = "anyTask"; - String info = "missing required field"; - String expectedMessage1 = taskName+" injected field '"+fieldName+"' is bad: "+info; - missingInjectedFieldException = new MissingInjectedFieldException(fieldName, taskName); - assertEquals(expectedMessage1, missingInjectedFieldException.getMessage()); - } + private MissingInjectedFieldException missingInjectedFieldException; + + @Test + public void test() { + String fieldName = "anyFieldName"; + String taskName = "anyTask"; + String info = "missing required field"; + String expectedMessage1 = taskName + " injected field '" + fieldName + "' is bad: " + info; + missingInjectedFieldException = new MissingInjectedFieldException(fieldName, taskName); + assertEquals(expectedMessage1, missingInjectedFieldException.getMessage()); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/ResponseBuilderTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/ResponseBuilderTest.java index b605209739..b06837aa0d 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/ResponseBuilderTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/ResponseBuilderTest.java @@ -1,29 +1,23 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 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 + * 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. + * 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.so.bpmn.core; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import org.camunda.bpm.engine.ProcessEngineServices; import org.camunda.bpm.engine.RepositoryService; import org.camunda.bpm.engine.delegate.DelegateExecution; @@ -33,78 +27,79 @@ import org.junit.Test; public class ResponseBuilderTest { - private String prefix = "PRE_"; - private String processKey = "AnyProcessKey"; - private String definitionId = "100"; - private int errorCode_200 = 200; - private int errorCode_404 = 404; - private String errorMessage = "any error message!"; - private String errorMessageXML = "<ErrorMessage>any error message!</ErrorMessage><ErrorCode>200</ErrorCode>"; - private String response = "<WorkflowResponse>bad</WorkflowResponse>"; - - private DelegateExecution mockExecution; - private ResponseBuilder responseBuilder; - private WorkflowException workflowException; - private Object obj; - - @Before - public void before() throws Exception { - responseBuilder = new ResponseBuilder(); - ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class); - when(mockProcessDefinition.getKey()).thenReturn(processKey); - RepositoryService mockRepositoryService = mock(RepositoryService.class); - when(mockRepositoryService.getProcessDefinition(definitionId)).thenReturn(mockProcessDefinition); - ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class); - when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService); - mockExecution = mock(DelegateExecution.class); - when(mockExecution.getId()).thenReturn(definitionId); - when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices); - when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition); - when(mockExecution.getVariable("prefix")).thenReturn(prefix); - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true"); - } - - @Test - public void buildWorkflowException_WorkflowException_2000_Test() { - when(mockExecution.getVariable(prefix+"ErrorResponse")).thenReturn(errorMessage); - when(mockExecution.getVariable(prefix+"ResponseCode")).thenReturn(errorCode_200); - workflowException = responseBuilder.buildWorkflowException(mockExecution); - assertEquals(2000, workflowException.getErrorCode()); - assertEquals("any error message!", workflowException.getErrorMessage()); - } + private String prefix = "PRE_"; + private String processKey = "AnyProcessKey"; + private String definitionId = "100"; + private int errorCode_200 = 200; + private int errorCode_404 = 404; + private String errorMessage = "any error message!"; + private String errorMessageXML = "<ErrorMessage>any error message!</ErrorMessage><ErrorCode>200</ErrorCode>"; + private String response = "<WorkflowResponse>bad</WorkflowResponse>"; + + private DelegateExecution mockExecution; + private ResponseBuilder responseBuilder; + private WorkflowException workflowException; + private Object obj; + + @Before + public void before() throws Exception { + responseBuilder = new ResponseBuilder(); + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class); + when(mockProcessDefinition.getKey()).thenReturn(processKey); + RepositoryService mockRepositoryService = mock(RepositoryService.class); + when(mockRepositoryService.getProcessDefinition(definitionId)).thenReturn(mockProcessDefinition); + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class); + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService); + mockExecution = mock(DelegateExecution.class); + when(mockExecution.getId()).thenReturn(definitionId); + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices); + when(mockExecution.getProcessEngineServices().getRepositoryService() + .getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition); + when(mockExecution.getVariable("prefix")).thenReturn(prefix); + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true"); + } + + @Test + public void buildWorkflowException_WorkflowException_2000_Test() { + when(mockExecution.getVariable(prefix + "ErrorResponse")).thenReturn(errorMessage); + when(mockExecution.getVariable(prefix + "ResponseCode")).thenReturn(errorCode_200); + workflowException = responseBuilder.buildWorkflowException(mockExecution); + assertEquals(2000, workflowException.getErrorCode()); + assertEquals("any error message!", workflowException.getErrorMessage()); + } + + @Test + public void buildWorkflowException_WorkflowException_XML_2000_Test() { + when(mockExecution.getVariable(prefix + "ErrorResponse")).thenReturn(errorMessageXML); + when(mockExecution.getVariable(prefix + "ResponseCode")).thenReturn(errorCode_200); + workflowException = responseBuilder.buildWorkflowException(mockExecution); + assertEquals(2000, workflowException.getErrorCode()); + assertEquals("any error message!", workflowException.getErrorMessage()); + } + + @Test + public void buildWorkflowException_WorkflowException_NULL_Test() { + when(mockExecution.getVariable(prefix + "ErrorResponse")).thenReturn(null); + when(mockExecution.getVariable(prefix + "ResponseCode")).thenReturn(null); + workflowException = responseBuilder.buildWorkflowException(mockExecution); + assertEquals(null, workflowException); + } + + @Test + public void buildWorkflowException_Response_1002_Test() { + when(mockExecution.getVariable(processKey + "Response")).thenReturn(response); + when(mockExecution.getVariable(prefix + "ResponseCode")).thenReturn(errorCode_404); + workflowException = responseBuilder.buildWorkflowException(mockExecution); + assertEquals(response, workflowException.getErrorMessage()); + assertEquals(1002, workflowException.getErrorCode()); + } + + @Test + public void buildWorkflowResponse_Object_Test() { + String workflowResponse = "<WorkflowResponse>good</WorkflowResponse>"; + when(mockExecution.getVariable("WorkflowResponse")).thenReturn(workflowResponse); + obj = responseBuilder.buildWorkflowResponse(mockExecution); + assertEquals(workflowResponse, obj); + } - @Test - public void buildWorkflowException_WorkflowException_XML_2000_Test() { - when(mockExecution.getVariable(prefix+"ErrorResponse")).thenReturn(errorMessageXML); - when(mockExecution.getVariable(prefix+"ResponseCode")).thenReturn(errorCode_200); - workflowException = responseBuilder.buildWorkflowException(mockExecution); - assertEquals(2000, workflowException.getErrorCode()); - assertEquals("any error message!", workflowException.getErrorMessage()); - } - - @Test - public void buildWorkflowException_WorkflowException_NULL_Test() { - when(mockExecution.getVariable(prefix+"ErrorResponse")).thenReturn(null); - when(mockExecution.getVariable(prefix+"ResponseCode")).thenReturn(null); - workflowException = responseBuilder.buildWorkflowException(mockExecution); - assertEquals(null, workflowException); - } - - @Test - public void buildWorkflowException_Response_1002_Test() { - when(mockExecution.getVariable(processKey+"Response")).thenReturn(response); - when(mockExecution.getVariable(prefix+"ResponseCode")).thenReturn(errorCode_404); - workflowException = responseBuilder.buildWorkflowException(mockExecution); - assertEquals(response, workflowException.getErrorMessage()); - assertEquals(1002, workflowException.getErrorCode()); - } - - @Test - public void buildWorkflowResponse_Object_Test() { - String workflowResponse = "<WorkflowResponse>good</WorkflowResponse>"; - when(mockExecution.getVariable("WorkflowResponse")).thenReturn(workflowResponse); - obj = responseBuilder.buildWorkflowResponse(mockExecution); - assertEquals(workflowResponse, obj); - } - } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/RollbackDataTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/RollbackDataTest.java index 875df6cf94..86a9ecf57e 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/RollbackDataTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/RollbackDataTest.java @@ -29,7 +29,6 @@ import static org.junit.Assert.assertTrue; import static org.hamcrest.Matchers.isIn; import java.util.Arrays; import java.util.Collections; - import org.junit.Test; public class RollbackDataTest { @@ -48,11 +47,11 @@ public class RollbackDataTest { data.put(TYPE_A, "key2", "value2"); data.put(TYPE_B, "key3", "value3"); // when, then - assertThat(data.toString(), isIn(Arrays.asList( - "[typeB{key3=value3},typeA{key1=value1, key2=value2}]", - "[typeB{key3=value3},typeA{key2=value2, key1=value1}]", - "[typeA{key1=value1, key2=value2},typeB{key3=value3}]", - "[typeA{key2=value2, key1=value1},typeB{key3=value3}]"))); + assertThat(data.toString(), + isIn(Arrays.asList("[typeB{key3=value3},typeA{key1=value1, key2=value2}]", + "[typeB{key3=value3},typeA{key2=value2, key1=value1}]", + "[typeA{key1=value1, key2=value2},typeB{key3=value3}]", + "[typeA{key2=value2, key1=value1},typeB{key3=value3}]"))); } @Test @@ -89,4 +88,4 @@ public class RollbackDataTest { assertEquals(VALUE_2, data.get(TYPE_B, KEY_1)); assertThat(data.get(TYPE_B), is(Collections.singletonMap(KEY_1, VALUE_2))); } -}
\ No newline at end of file +} diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/UrnPropertiesReaderTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/UrnPropertiesReaderTest.java index 5d9a1d61f2..f0c3d39625 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/UrnPropertiesReaderTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/UrnPropertiesReaderTest.java @@ -24,36 +24,35 @@ import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity; import org.junit.Assert; import org.junit.Test; import org.springframework.core.env.Environment; - import static org.mockito.Mockito.*; public class UrnPropertiesReaderTest { @Test - public void testGetVariableFromExecution() { + public void testGetVariableFromExecution() { ExecutionEntity mockExecution = mock(ExecutionEntity.class); when(mockExecution.getVariable("testKey")).thenReturn("testValue"); - String value = UrnPropertiesReader.getVariable("testKey",mockExecution); + String value = UrnPropertiesReader.getVariable("testKey", mockExecution); Assert.assertEquals("testValue", value); verify(mockExecution).getVariable("testKey"); verify(mockExecution, never()).setVariable("testKey", value); } @Test - public void testGetVariableFromEnvironment() { + public void testGetVariableFromEnvironment() { ExecutionEntity mockExecution = mock(ExecutionEntity.class); Environment mockEnvironment = mock(Environment.class); when(mockEnvironment.getProperty("testKey")).thenReturn("testValue"); UrnPropertiesReader urnPropertiesReader = new UrnPropertiesReader(); urnPropertiesReader.setEnvironment(mockEnvironment); - String value = UrnPropertiesReader.getVariable("testKey",mockExecution); - Assert.assertEquals("testValue",value); + String value = UrnPropertiesReader.getVariable("testKey", mockExecution); + Assert.assertEquals("testValue", value); verify(mockExecution).getVariable("testKey"); verify(mockExecution).setVariable("testKey", value); } @Test - public void testGetVariableNotExist() { + public void testGetVariableNotExist() { ExecutionEntity mockExecution = mock(ExecutionEntity.class); String value = UrnPropertiesReader.getVariable("notExist", mockExecution); Assert.assertEquals(null, value); diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/WorkflowExceptionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/WorkflowExceptionTest.java index c1e9b8776b..2792b1bd73 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/WorkflowExceptionTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/WorkflowExceptionTest.java @@ -1,47 +1,41 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 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 + * 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. + * 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.so.bpmn.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; - import org.junit.Test; public class WorkflowExceptionTest { - private WorkflowException workflowException; - - @Test - public void test() { - String processKey = "AnyProcessKey"; - int errorCode = 200; - String errorMessage = "any error message!"; - workflowException = new WorkflowException(processKey, errorCode, errorMessage); - assertEquals(errorCode, workflowException.getErrorCode()); - assertEquals(errorMessage, workflowException.getErrorMessage()); - assertEquals(processKey, workflowException.getProcessKey()); - assertEquals("*", workflowException.getWorkStep()); - String workStep = "one"; - workflowException = new WorkflowException(processKey, errorCode, errorMessage, workStep); - assertEquals(workStep, workflowException.getWorkStep()); - assertNotEquals(null, workflowException.toString()); - } + private WorkflowException workflowException; + + @Test + public void test() { + String processKey = "AnyProcessKey"; + int errorCode = 200; + String errorMessage = "any error message!"; + workflowException = new WorkflowException(processKey, errorCode, errorMessage); + assertEquals(errorCode, workflowException.getErrorCode()); + assertEquals(errorMessage, workflowException.getErrorMessage()); + assertEquals(processKey, workflowException.getProcessKey()); + assertEquals("*", workflowException.getWorkStep()); + String workStep = "one"; + workflowException = new WorkflowException(processKey, errorCode, errorMessage, workStep); + assertEquals(workStep, workflowException.getWorkStep()); + assertNotEquals(null, workflowException.toString()); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/AllottedResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/AllottedResourceTest.java index cca28d411f..fcd502f982 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/AllottedResourceTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/AllottedResourceTest.java @@ -1,66 +1,59 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; - import java.io.IOException; public class AllottedResourceTest { - private AllottedResource ar = new AllottedResource(); - - @Test - public void testAllottedResource() { - ar.setAllottedResourceType("allottedResourceType"); - ar.setAllottedResourceRole("allottedResourceRole"); - ar.setProvidingServiceModelName("providingServiceModelName"); - ar.setProvidingServiceModelInvariantUuid("providingServiceModelInvariantUuid"); - ar.setProvidingServiceModelUuid("providingServiceModelUuid"); - ar.setNfFunction("nfFunction"); - ar.setNfType("nfType"); - ar.setNfRole("nfRole"); - ar.setNfNamingCode("nfNamingCode"); - ar.setOrchestrationStatus("orchestrationStatus"); - assertEquals(ar.getAllottedResourceType(), "allottedResourceType"); - assertEquals(ar.getAllottedResourceRole(), "allottedResourceRole"); - assertEquals(ar.getProvidingServiceModelName(), "providingServiceModelName"); - assertEquals(ar.getProvidingServiceModelInvariantUuid(), "providingServiceModelInvariantUuid"); - assertEquals(ar.getProvidingServiceModelUuid(), "providingServiceModelUuid"); - assertEquals(ar.getNfFunction(), "nfFunction"); - assertEquals(ar.getNfType(), "nfType"); - assertEquals(ar.getNfRole(), "nfRole"); - assertEquals(ar.getNfNamingCode(), "nfNamingCode"); - assertEquals(ar.getOrchestrationStatus(), "orchestrationStatus"); - - } - - @Test - public void allottedResourceMapperTest() throws IOException { - String jsonStr = "{\"allottedResourceType\": \"code123\", \"resourceInput\": \"sample\"}"; - ObjectMapper objectMapper = new ObjectMapper(); - AllottedResource vnfResource = objectMapper.readValue(jsonStr, AllottedResource.class); - - assertTrue(vnfResource != null); - } + private AllottedResource ar = new AllottedResource(); + + @Test + public void testAllottedResource() { + ar.setAllottedResourceType("allottedResourceType"); + ar.setAllottedResourceRole("allottedResourceRole"); + ar.setProvidingServiceModelName("providingServiceModelName"); + ar.setProvidingServiceModelInvariantUuid("providingServiceModelInvariantUuid"); + ar.setProvidingServiceModelUuid("providingServiceModelUuid"); + ar.setNfFunction("nfFunction"); + ar.setNfType("nfType"); + ar.setNfRole("nfRole"); + ar.setNfNamingCode("nfNamingCode"); + ar.setOrchestrationStatus("orchestrationStatus"); + assertEquals(ar.getAllottedResourceType(), "allottedResourceType"); + assertEquals(ar.getAllottedResourceRole(), "allottedResourceRole"); + assertEquals(ar.getProvidingServiceModelName(), "providingServiceModelName"); + assertEquals(ar.getProvidingServiceModelInvariantUuid(), "providingServiceModelInvariantUuid"); + assertEquals(ar.getProvidingServiceModelUuid(), "providingServiceModelUuid"); + assertEquals(ar.getNfFunction(), "nfFunction"); + assertEquals(ar.getNfType(), "nfType"); + assertEquals(ar.getNfRole(), "nfRole"); + assertEquals(ar.getNfNamingCode(), "nfNamingCode"); + assertEquals(ar.getOrchestrationStatus(), "orchestrationStatus"); + + } + + @Test + public void allottedResourceMapperTest() throws IOException { + String jsonStr = "{\"allottedResourceType\": \"code123\", \"resourceInput\": \"sample\"}"; + ObjectMapper objectMapper = new ObjectMapper(); + AllottedResource vnfResource = objectMapper.readValue(jsonStr, AllottedResource.class); + + assertTrue(vnfResource != null); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CompareModelsResultTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CompareModelsResultTest.java index af9c7a7fa6..4c371d3cff 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CompareModelsResultTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CompareModelsResultTest.java @@ -1,83 +1,76 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import java.util.ArrayList; import java.util.List; - import org.junit.Before; import org.junit.Test; public class CompareModelsResultTest { - - private CompareModelsResult modelsResult; - private List<ResourceModelInfo> addedResourceList; - private List<ResourceModelInfo> deletedResourceList; - private ResourceModelInfo resourceModelInfo1; - private ResourceModelInfo resourceModelInfo2; - private List<String> requestInputs; - - @Before - public void before() { - resourceModelInfo1 = new ResourceModelInfo(); - resourceModelInfo1.setResourceCustomizationUuid("f1d563e8-e714-4393-8f99-cc480144a05e"); - resourceModelInfo1.setResourceInvariantUuid("e1d563e8-e714-4393-8f99-cc480144a05f"); - resourceModelInfo1.setResourceName("resourceName1"); - resourceModelInfo1.setResourceUuid("f1d563e8-e714-4393-8f99-cc480144a05g"); - resourceModelInfo2 = new ResourceModelInfo(); - resourceModelInfo2.setResourceCustomizationUuid("a1d563e8-e714-4393-8f99-cc480144a05d"); - resourceModelInfo2.setResourceInvariantUuid("b1d563e8-e714-4393-8f99-cc480144a05e"); - resourceModelInfo2.setResourceName("resourceName2"); - resourceModelInfo2.setResourceUuid("c1d563e8-e714-4393-8f99-cc480144a05f"); - } - - @Test - public void testSetAddedResourceList() { - addedResourceList = new ArrayList<ResourceModelInfo>(); - addedResourceList.add(resourceModelInfo1); - addedResourceList.add(resourceModelInfo2); - modelsResult = new CompareModelsResult(); - modelsResult.setAddedResourceList(addedResourceList); - assertEquals(addedResourceList, modelsResult.getAddedResourceList()); - } - @Test - public void testSetDeletedResourceList() { - deletedResourceList = new ArrayList<ResourceModelInfo>(); - deletedResourceList.add(resourceModelInfo1); - deletedResourceList.add(resourceModelInfo2); - modelsResult = new CompareModelsResult(); - modelsResult.setDeletedResourceList(deletedResourceList); - assertEquals(deletedResourceList, modelsResult.getDeletedResourceList()); - } + private CompareModelsResult modelsResult; + private List<ResourceModelInfo> addedResourceList; + private List<ResourceModelInfo> deletedResourceList; + private ResourceModelInfo resourceModelInfo1; + private ResourceModelInfo resourceModelInfo2; + private List<String> requestInputs; + + @Before + public void before() { + resourceModelInfo1 = new ResourceModelInfo(); + resourceModelInfo1.setResourceCustomizationUuid("f1d563e8-e714-4393-8f99-cc480144a05e"); + resourceModelInfo1.setResourceInvariantUuid("e1d563e8-e714-4393-8f99-cc480144a05f"); + resourceModelInfo1.setResourceName("resourceName1"); + resourceModelInfo1.setResourceUuid("f1d563e8-e714-4393-8f99-cc480144a05g"); + resourceModelInfo2 = new ResourceModelInfo(); + resourceModelInfo2.setResourceCustomizationUuid("a1d563e8-e714-4393-8f99-cc480144a05d"); + resourceModelInfo2.setResourceInvariantUuid("b1d563e8-e714-4393-8f99-cc480144a05e"); + resourceModelInfo2.setResourceName("resourceName2"); + resourceModelInfo2.setResourceUuid("c1d563e8-e714-4393-8f99-cc480144a05f"); + } + + @Test + public void testSetAddedResourceList() { + addedResourceList = new ArrayList<ResourceModelInfo>(); + addedResourceList.add(resourceModelInfo1); + addedResourceList.add(resourceModelInfo2); + modelsResult = new CompareModelsResult(); + modelsResult.setAddedResourceList(addedResourceList); + assertEquals(addedResourceList, modelsResult.getAddedResourceList()); + } + + @Test + public void testSetDeletedResourceList() { + deletedResourceList = new ArrayList<ResourceModelInfo>(); + deletedResourceList.add(resourceModelInfo1); + deletedResourceList.add(resourceModelInfo2); + modelsResult = new CompareModelsResult(); + modelsResult.setDeletedResourceList(deletedResourceList); + assertEquals(deletedResourceList, modelsResult.getDeletedResourceList()); + } + + @Test + public void testSetRequestInputs() { + requestInputs = new ArrayList<String>(); + requestInputs.add("requestInput1"); + requestInputs.add("requestInput2"); + modelsResult = new CompareModelsResult(); + modelsResult.setRequestInputs(requestInputs); + assertEquals(requestInputs, modelsResult.getRequestInputs()); + } - @Test - public void testSetRequestInputs() { - requestInputs = new ArrayList<String>(); - requestInputs.add("requestInput1"); - requestInputs.add("requestInput2"); - modelsResult = new CompareModelsResult(); - modelsResult.setRequestInputs(requestInputs); - assertEquals(requestInputs, modelsResult.getRequestInputs()); - } - } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigResourceTest.java index 13a30d26ee..1e1595f048 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigResourceTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigResourceTest.java @@ -1,39 +1,34 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import org.junit.Test; public class ConfigResourceTest { - private ConfigResource configresource = new ConfigResource();{ - configresource.resourceType = ResourceType.CONFIGURATION; - } + private ConfigResource configresource = new ConfigResource(); + { + configresource.resourceType = ResourceType.CONFIGURATION; + } + + @Test + public void testConfigResource() { + configresource.setToscaNodeType("toscaNodeType"); + assertEquals(configresource.getToscaNodeType(), "toscaNodeType"); + - @Test - public void testConfigResource() { - configresource.setToscaNodeType("toscaNodeType"); - assertEquals(configresource.getToscaNodeType(), "toscaNodeType"); - - - } + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigurationTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigurationTest.java index fe84a1b5a7..68839a7ad6 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigurationTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigurationTest.java @@ -1,47 +1,41 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import org.junit.Test; public class ConfigurationTest { - private Configuration configuration = new Configuration(); + private Configuration configuration = new Configuration(); - @Test - public void testConfigurationTest() { - configuration.setId("id"); - configuration.setName("name"); - configuration.setType("type"); - configuration.setOrchestrationStatus("orchestrationStatus"); - configuration.setTunnelBandwidth("tunnelBandwidth"); - configuration.setVendorAllowedMaxBandwidth("vendorAllowedMaxBandwidth"); - configuration.setResourceVersion("resourceVersion"); - assertEquals(configuration.getId(), "id"); - assertEquals(configuration.getName(), "name"); - assertEquals(configuration.getType(), "type"); - assertEquals(configuration.getOrchestrationStatus(), "orchestrationStatus"); - assertEquals(configuration.getTunnelBandwidth(), "tunnelBandwidth"); - assertEquals(configuration.getVendorAllowedMaxBandwidth(), "vendorAllowedMaxBandwidth"); - assertEquals(configuration.getResourceVersion(), "resourceVersion"); - } + @Test + public void testConfigurationTest() { + configuration.setId("id"); + configuration.setName("name"); + configuration.setType("type"); + configuration.setOrchestrationStatus("orchestrationStatus"); + configuration.setTunnelBandwidth("tunnelBandwidth"); + configuration.setVendorAllowedMaxBandwidth("vendorAllowedMaxBandwidth"); + configuration.setResourceVersion("resourceVersion"); + assertEquals(configuration.getId(), "id"); + assertEquals(configuration.getName(), "name"); + assertEquals(configuration.getType(), "type"); + assertEquals(configuration.getOrchestrationStatus(), "orchestrationStatus"); + assertEquals(configuration.getTunnelBandwidth(), "tunnelBandwidth"); + assertEquals(configuration.getVendorAllowedMaxBandwidth(), "vendorAllowedMaxBandwidth"); + assertEquals(configuration.getResourceVersion(), "resourceVersion"); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CustomerTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CustomerTest.java index 86eb717664..9640cfce07 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CustomerTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CustomerTest.java @@ -1,38 +1,32 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import org.junit.Test; public class CustomerTest { - private Customer customer = new Customer(); + private Customer customer = new Customer(); + + @Test + public void testCustomer() { + customer.setSubscriptionServiceType("subscriptionServiceType"); + customer.setGlobalSubscriberId("globalSubscriberId"); + assertEquals(customer.getSubscriptionServiceType(), "subscriptionServiceType"); + assertEquals(customer.getGlobalSubscriberId(), "globalSubscriberId"); - @Test - public void testCustomer() { - customer.setSubscriptionServiceType("subscriptionServiceType"); - customer.setGlobalSubscriberId("globalSubscriberId"); - assertEquals(customer.getSubscriptionServiceType(), "subscriptionServiceType"); - assertEquals(customer.getGlobalSubscriberId(), "globalSubscriberId"); - - } + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/DomainPojoTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/DomainPojoTest.java index b4860c6323..ae1aff7275 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/DomainPojoTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/DomainPojoTest.java @@ -21,7 +21,6 @@ package org.onap.so.bpmn.core.domain; import org.junit.Test; - import com.openpojo.reflection.PojoClass; import com.openpojo.reflection.PojoClassFilter; import com.openpojo.reflection.filters.FilterNonConcrete; @@ -33,24 +32,21 @@ import com.openpojo.validation.test.impl.SetterTester; public class DomainPojoTest { - private PojoClassFilter filterTestClasses = new FilterTestClasses(); - - @Test - public void pojoStructure() { - test("org.onap.so.bpmn.core.domain"); - } - - private void test(String pojoPackage) { - Validator validator = ValidatorBuilder.create() - .with(new SetterTester()) - .with(new GetterTester()) - .build(); - validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, new FilterNonConcrete()); - } - - private static class FilterTestClasses implements PojoClassFilter { - public boolean include(PojoClass pojoClass) { - return !pojoClass.getSourcePath().contains("/test-classes/"); - } - } + private PojoClassFilter filterTestClasses = new FilterTestClasses(); + + @Test + public void pojoStructure() { + test("org.onap.so.bpmn.core.domain"); + } + + private void test(String pojoPackage) { + Validator validator = ValidatorBuilder.create().with(new SetterTester()).with(new GetterTester()).build(); + validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, new FilterNonConcrete()); + } + + private static class FilterTestClasses implements PojoClassFilter { + public boolean include(PojoClass pojoClass) { + return !pojoClass.getSourcePath().contains("/test-classes/"); + } + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/HomingSolutionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/HomingSolutionTest.java index 9750e03b4c..249307cbbc 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/HomingSolutionTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/HomingSolutionTest.java @@ -1,58 +1,52 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import org.junit.Test; public class HomingSolutionTest { - - private HomingSolution homingsolution = new HomingSolution(); - InventoryType inventory = InventoryType.cloud; - VnfResource vnfresource = new VnfResource(); - License license = new License(); - @Test - public void testHomingSolution() { - homingsolution.setInventoryType(inventory); - homingsolution.setRehome(true); - homingsolution.setServiceInstanceId("serviceInstanceId"); - homingsolution.setCloudOwner("cloudOwner"); - homingsolution.setCloudRegionId("cloudRegionId"); - homingsolution.setAicClli("aicClli"); - homingsolution.setAicVersion("aicVersion"); - homingsolution.setTenant("tenant"); - homingsolution.setVnf(vnfresource); - homingsolution.setLicense(license); - assertEquals(homingsolution.getInventoryType(), inventory); - assertEquals(homingsolution.isRehome(), true); - assertEquals(homingsolution.getServiceInstanceId(), "serviceInstanceId"); - assertEquals(homingsolution.getCloudOwner(), "cloudOwner"); - assertEquals(homingsolution.getCloudRegionId(), "cloudRegionId"); - assertEquals(homingsolution.getAicClli(), "aicClli"); - assertEquals(homingsolution.getAicVersion(), "aicVersion"); - assertEquals(homingsolution.getTenant(), "tenant"); - assertEquals(homingsolution.getVnf(), vnfresource); - assertEquals(homingsolution.getLicense(), license); - - } + private HomingSolution homingsolution = new HomingSolution(); + InventoryType inventory = InventoryType.cloud; + VnfResource vnfresource = new VnfResource(); + License license = new License(); + + @Test + public void testHomingSolution() { + homingsolution.setInventoryType(inventory); + homingsolution.setRehome(true); + homingsolution.setServiceInstanceId("serviceInstanceId"); + homingsolution.setCloudOwner("cloudOwner"); + homingsolution.setCloudRegionId("cloudRegionId"); + homingsolution.setAicClli("aicClli"); + homingsolution.setAicVersion("aicVersion"); + homingsolution.setTenant("tenant"); + homingsolution.setVnf(vnfresource); + homingsolution.setLicense(license); + assertEquals(homingsolution.getInventoryType(), inventory); + assertEquals(homingsolution.isRehome(), true); + assertEquals(homingsolution.getServiceInstanceId(), "serviceInstanceId"); + assertEquals(homingsolution.getCloudOwner(), "cloudOwner"); + assertEquals(homingsolution.getCloudRegionId(), "cloudRegionId"); + assertEquals(homingsolution.getAicClli(), "aicClli"); + assertEquals(homingsolution.getAicVersion(), "aicVersion"); + assertEquals(homingsolution.getTenant(), "tenant"); + assertEquals(homingsolution.getVnf(), vnfresource); + assertEquals(homingsolution.getLicense(), license); + + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/LicenseTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/LicenseTest.java index f3a96bf4eb..bacaaf77c9 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/LicenseTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/LicenseTest.java @@ -1,54 +1,47 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.assertEquals; - import java.util.ArrayList; import java.util.List; - import org.junit.Test; -public class LicenseTest { - - private License license= new License(); - List<String> entitlementPoolList = new ArrayList<String>(); - private List<String> licenseKeyGroupList = new ArrayList<String>(); - - Long serialVersionUID = 333L; - - @Test - public void testLicense() { - license.setEntitlementPoolList(entitlementPoolList); - license.setLicenseKeyGroupList(licenseKeyGroupList); - license.addLicenseKeyGroup("licenseKeyGroupUuid"); - assertEquals(license.getEntitlementPoolList(), entitlementPoolList); - assertEquals(license.getLicenseKeyGroupList(), licenseKeyGroupList); - assert(license.getEntitlementPoolListAsString()!= null); - assert(license.getLicenseKeyGroupListAsString()!=null); - license.addEntitlementPool("entitlementPoolUuid"); - - - } - +public class LicenseTest { + + private License license = new License(); + List<String> entitlementPoolList = new ArrayList<String>(); + private List<String> licenseKeyGroupList = new ArrayList<String>(); + + Long serialVersionUID = 333L; + + @Test + public void testLicense() { + license.setEntitlementPoolList(entitlementPoolList); + license.setLicenseKeyGroupList(licenseKeyGroupList); + license.addLicenseKeyGroup("licenseKeyGroupUuid"); + assertEquals(license.getEntitlementPoolList(), entitlementPoolList); + assertEquals(license.getLicenseKeyGroupList(), licenseKeyGroupList); + assert (license.getEntitlementPoolListAsString() != null); + assert (license.getLicenseKeyGroupListAsString() != null); + license.addEntitlementPool("entitlementPoolUuid"); + + + } + } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModelInfoTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModelInfoTest.java index 3d07f85c04..807338745f 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModelInfoTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModelInfoTest.java @@ -1,47 +1,41 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import org.junit.Test; public class ModelInfoTest { - private ModelInfo modelinfo = new ModelInfo(); + private ModelInfo modelinfo = new ModelInfo(); - @Test - public void testModelInfo() { - modelinfo.setModelName("modelName"); - modelinfo.setModelUuid("modelUuid"); - modelinfo.setModelInvariantUuid("modelInvariantUuid"); - modelinfo.setModelVersion("modelVersion"); - modelinfo.setModelCustomizationUuid("modelCustomizationUuid"); - modelinfo.setModelInstanceName("modelInstanceName"); - modelinfo.setModelType("modelType"); - assertEquals(modelinfo.getModelName(), "modelName"); - assertEquals(modelinfo.getModelUuid(), "modelUuid"); - assertEquals(modelinfo.getModelInvariantUuid(), "modelInvariantUuid"); - assertEquals(modelinfo.getModelVersion(), "modelVersion"); - assertEquals(modelinfo.getModelCustomizationUuid(), "modelCustomizationUuid"); - assertEquals(modelinfo.getModelInstanceName(), "modelInstanceName"); - assertEquals(modelinfo.getModelType(), "modelType"); - } + @Test + public void testModelInfo() { + modelinfo.setModelName("modelName"); + modelinfo.setModelUuid("modelUuid"); + modelinfo.setModelInvariantUuid("modelInvariantUuid"); + modelinfo.setModelVersion("modelVersion"); + modelinfo.setModelCustomizationUuid("modelCustomizationUuid"); + modelinfo.setModelInstanceName("modelInstanceName"); + modelinfo.setModelType("modelType"); + assertEquals(modelinfo.getModelName(), "modelName"); + assertEquals(modelinfo.getModelUuid(), "modelUuid"); + assertEquals(modelinfo.getModelInvariantUuid(), "modelInvariantUuid"); + assertEquals(modelinfo.getModelVersion(), "modelVersion"); + assertEquals(modelinfo.getModelCustomizationUuid(), "modelCustomizationUuid"); + assertEquals(modelinfo.getModelInstanceName(), "modelInstanceName"); + assertEquals(modelinfo.getModelType(), "modelType"); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModuleResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModuleResourceTest.java index dcb62cfc40..6e915b2a60 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModuleResourceTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModuleResourceTest.java @@ -1,48 +1,42 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import org.junit.Test; public class ModuleResourceTest { - private ModuleResource moduleresource = new ModuleResource(); + private ModuleResource moduleresource = new ModuleResource(); + + @Test + public void testModuleResource() { - @Test - public void testModuleResource() { - - moduleresource.setVfModuleName("vfModuleName"); - moduleresource.setHeatStackId("heatStackId"); - moduleresource.setIsBase(true); - moduleresource.setVfModuleLabel("vfModuleLabel"); - moduleresource.setInitialCount(0); - moduleresource.setVfModuleType("vfModuleType"); - moduleresource.setHasVolumeGroup(true); - assertEquals(moduleresource.getVfModuleName(), "vfModuleName"); - assertEquals(moduleresource.getHeatStackId(), "heatStackId"); - assertEquals(moduleresource.getIsBase(), true); - assertEquals(moduleresource.getVfModuleLabel(), "vfModuleLabel"); - assertEquals(moduleresource.getInitialCount(), 0); - assertEquals(moduleresource.getVfModuleType(), "vfModuleType"); - assertEquals(moduleresource.isHasVolumeGroup(), true); - } + moduleresource.setVfModuleName("vfModuleName"); + moduleresource.setHeatStackId("heatStackId"); + moduleresource.setIsBase(true); + moduleresource.setVfModuleLabel("vfModuleLabel"); + moduleresource.setInitialCount(0); + moduleresource.setVfModuleType("vfModuleType"); + moduleresource.setHasVolumeGroup(true); + assertEquals(moduleresource.getVfModuleName(), "vfModuleName"); + assertEquals(moduleresource.getHeatStackId(), "heatStackId"); + assertEquals(moduleresource.getIsBase(), true); + assertEquals(moduleresource.getVfModuleLabel(), "vfModuleLabel"); + assertEquals(moduleresource.getInitialCount(), 0); + assertEquals(moduleresource.getVfModuleType(), "vfModuleType"); + assertEquals(moduleresource.isHasVolumeGroup(), true); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/NetworkResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/NetworkResourceTest.java index ee23ebd438..668d6dc1de 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/NetworkResourceTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/NetworkResourceTest.java @@ -1,54 +1,47 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; - import java.io.IOException; public class NetworkResourceTest { - private NetworkResource nr = new NetworkResource(); - - @Test - public void testNetworkResource() { - nr.setNetworkType("networkType"); - nr.setNetworkRole("networkRole"); - nr.setNetworkTechnology("networkTechnology"); - nr.setNetworkScope("networkScope"); - assertEquals(nr.getNetworkType(), "networkType"); - assertEquals(nr.getNetworkRole(), "networkRole"); - assertEquals(nr.getNetworkTechnology(), "networkTechnology"); - assertEquals(nr.getNetworkScope(), "networkScope"); - - } - - @Test - public void networkResourceMapperTest() throws IOException { - String jsonStr = "{\"networkScope\": \"code123\", \"resourceInput\": \"sample\"}"; - ObjectMapper objectMapper = new ObjectMapper(); - NetworkResource networkResource = objectMapper.readValue(jsonStr, NetworkResource.class); - - assertTrue(networkResource != null); - } + private NetworkResource nr = new NetworkResource(); + + @Test + public void testNetworkResource() { + nr.setNetworkType("networkType"); + nr.setNetworkRole("networkRole"); + nr.setNetworkTechnology("networkTechnology"); + nr.setNetworkScope("networkScope"); + assertEquals(nr.getNetworkType(), "networkType"); + assertEquals(nr.getNetworkRole(), "networkRole"); + assertEquals(nr.getNetworkTechnology(), "networkTechnology"); + assertEquals(nr.getNetworkScope(), "networkScope"); + + } + + @Test + public void networkResourceMapperTest() throws IOException { + String jsonStr = "{\"networkScope\": \"code123\", \"resourceInput\": \"sample\"}"; + ObjectMapper objectMapper = new ObjectMapper(); + NetworkResource networkResource = objectMapper.readValue(jsonStr, NetworkResource.class); + + assertTrue(networkResource != null); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/OwningEntityTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/OwningEntityTest.java index 396d866446..23a1d866a2 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/OwningEntityTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/OwningEntityTest.java @@ -1,39 +1,33 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import org.junit.Test; public class OwningEntityTest { - private OwningEntity oe = new OwningEntity(); + private OwningEntity oe = new OwningEntity(); + + @Test + public void testOwingEntity() { + oe.setOwningEntityId("owningEntityId"); + oe.setOwningEntityName("owningEntityName"); + assertEquals(oe.getOwningEntityId(), "owningEntityId"); + assertEquals(oe.getOwningEntityName(), "owningEntityName"); - @Test - public void testOwingEntity() { - oe.setOwningEntityId("owningEntityId"); - oe.setOwningEntityName("owningEntityName"); - assertEquals(oe.getOwningEntityId(), "owningEntityId"); - assertEquals(oe.getOwningEntityName(), "owningEntityName"); - - } + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ProjectTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ProjectTest.java index 9081f9dd14..47ce61b8fe 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ProjectTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ProjectTest.java @@ -1,36 +1,30 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import org.junit.Test; public class ProjectTest { - - private Project project = new Project(); - @Test - public void testProject() { - project.setProjectName("projectName"); - assertEquals(project.getProjectName(), "projectName"); - } + private Project project = new Project(); + + @Test + public void testProject() { + project.setProjectName("projectName"); + assertEquals(project.getProjectName(), "projectName"); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/RequestTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/RequestTest.java index 0c552ce19e..a890289943 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/RequestTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/RequestTest.java @@ -1,44 +1,38 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import org.junit.Test; public class RequestTest { - - private Request request = new Request(); - ModelInfo model = new ModelInfo(); - @Test - public void testRequest() { - request.setSdncRequestId("sdncRequestId"); - request.setRequestId("requestId"); - request.setModelInfo(model); - request.setProductFamilyId("productFamilyId"); - assertEquals(request.getSdncRequestId(), "sdncRequestId"); - assertEquals(request.getRequestId(), "requestId"); - assertEquals(request.getModelInfo(), model); - assertEquals(request.getProductFamilyId(), "productFamilyId"); - - } + private Request request = new Request(); + ModelInfo model = new ModelInfo(); + + @Test + public void testRequest() { + request.setSdncRequestId("sdncRequestId"); + request.setRequestId("requestId"); + request.setModelInfo(model); + request.setProductFamilyId("productFamilyId"); + assertEquals(request.getSdncRequestId(), "sdncRequestId"); + assertEquals(request.getRequestId(), "requestId"); + assertEquals(request.getModelInfo(), model); + assertEquals(request.getProductFamilyId(), "productFamilyId"); + + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceDecompositionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceDecompositionTest.java index 573ffab4aa..112139ce95 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceDecompositionTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceDecompositionTest.java @@ -1,50 +1,44 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import org.junit.Test; public class ResourceDecompositionTest { - - private ResourceDecomposition rd = new ResourceDecomposition() { - private static final long serialVersionUID = 1L; - }; - ModelInfo model = new ModelInfo(); - ResourceInstance ri = new ResourceInstance(); - - - @Test - public void testResourceDecomposition() { - rd.setModelInfo(model); - rd.setInstanceData(ri); - rd.setResourceType("resourceType"); - rd.setResourceInstanceId("newInstanceId"); - rd.setResourceInstanceName("newInstanceName"); - assertEquals(rd.getResourceModel(), model); - assertEquals(rd.getModelInfo(), model); - assertEquals(rd.getInstanceData(), ri); - assertEquals(rd.getResourceInstanceId(), "newInstanceId"); - assertEquals(rd.getResourceInstanceName(), "newInstanceName"); - } + private ResourceDecomposition rd = new ResourceDecomposition() { + private static final long serialVersionUID = 1L; + }; + ModelInfo model = new ModelInfo(); + ResourceInstance ri = new ResourceInstance(); + + + + @Test + public void testResourceDecomposition() { + rd.setModelInfo(model); + rd.setInstanceData(ri); + rd.setResourceType("resourceType"); + rd.setResourceInstanceId("newInstanceId"); + rd.setResourceInstanceName("newInstanceName"); + assertEquals(rd.getResourceModel(), model); + assertEquals(rd.getModelInfo(), model); + assertEquals(rd.getInstanceData(), ri); + assertEquals(rd.getResourceInstanceId(), "newInstanceId"); + assertEquals(rd.getResourceInstanceName(), "newInstanceName"); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceTest.java index afdbcd9f98..271ed6b32e 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceTest.java @@ -1,68 +1,60 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import org.junit.Test; public class ResourceTest { - private Resource resource = new Resource() { - private static final long serialVersionUID = 1L; - - - }; - ModelInfo model = new ModelInfo(); - ResourceInstance ri = new ResourceInstance(); - HomingSolution hs = new HomingSolution(); - ResourceType rt = ResourceType.VNF; - public long concurrencyCounter = 1L; - long initval = resource.getConcurrencyCounter(); + private Resource resource = new Resource() { + private static final long serialVersionUID = 1L; + + + }; + ModelInfo model = new ModelInfo(); + ResourceInstance ri = new ResourceInstance(); + HomingSolution hs = new HomingSolution(); + ResourceType rt = ResourceType.VNF; + public long concurrencyCounter = 1L; + long initval = resource.getConcurrencyCounter(); + + @Test + public void testResource() { + resource.setResourceId("resourceId"); + resource.setModelInfo(model); + resource.setResourceInstance(ri); + resource.setHomingSolution(hs); + resource.setCurrentHomingSolution(hs); + resource.setResourceType(rt); + resource.setToscaNodeType("toscaNodeType"); + resource.setResourceInstanceId("newInstanceId"); + resource.setResourceInstanceName("newInstanceName"); + resource.incrementConcurrencyCounter(); + assertEquals(resource.getResourceId(), "resourceId"); + assertEquals(resource.getModelInfo(), model); + assertEquals(resource.getResourceInstance(), ri); + assertEquals(resource.getHomingSolution(), hs); + assertEquals(resource.getCurrentHomingSolution(), hs); + assertEquals(resource.getResourceType(), rt); + assertEquals(resource.getToscaNodeType(), "toscaNodeType"); + assertEquals(resource.getResourceInstanceId(), "newInstanceId"); + assertEquals(resource.getResourceInstanceName(), "newInstanceName"); + assertEquals(resource.getConcurrencyCounter(), initval + 1); + + - @Test - public void testResource() { - resource.setResourceId("resourceId"); - resource.setModelInfo(model); - resource.setResourceInstance(ri); - resource.setHomingSolution(hs); - resource.setCurrentHomingSolution(hs); - resource.setResourceType(rt); - resource.setToscaNodeType("toscaNodeType"); - resource.setResourceInstanceId("newInstanceId"); - resource.setResourceInstanceName("newInstanceName"); - resource.incrementConcurrencyCounter(); - assertEquals(resource.getResourceId(), "resourceId"); - assertEquals(resource.getModelInfo(), model); - assertEquals(resource.getResourceInstance(), ri); - assertEquals(resource.getHomingSolution(), hs); - assertEquals(resource.getCurrentHomingSolution(), hs); - assertEquals(resource.getResourceType(), rt); - assertEquals(resource.getToscaNodeType(), "toscaNodeType"); - assertEquals(resource.getResourceInstanceId(), "newInstanceId"); - assertEquals(resource.getResourceInstanceName(), "newInstanceName"); - assertEquals(resource.getConcurrencyCounter(), initval+1); - - - - - - } + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java index 5d8d55152c..5db277628e 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java @@ -1,22 +1,17 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static com.shazam.shazamcrest.MatcherAssert.assertThat; @@ -24,104 +19,109 @@ import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; - import org.junit.Before; import org.junit.Test; - import com.fasterxml.jackson.core.JsonProcessingException; public class ServiceDecompositionTest { - private static final String RESOURCE_PATH = "src/test/resources/json-examples/"; - - VnfResource vnfResource; - NetworkResource networkResource; - AllottedResource allottedResource; - ConfigResource configResource; - - @Before - public void before() { - vnfResource = new VnfResource(); - vnfResource.setResourceId("vnfResourceId"); - vnfResource.setModules(new ArrayList<>()); - - networkResource = new NetworkResource(); - networkResource.setResourceId("networkResourceId"); - - allottedResource = new AllottedResource(); - allottedResource.setResourceId("allottedResourceId"); - - configResource = new ConfigResource(); - configResource.setResourceId("configResourceId"); - } - - @Test - public void serviceDecompositionTest() throws JsonProcessingException, IOException { - // covering methods not covered by openpojo test - String catalogRestOutput = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceDecomposition.json"))); - - ServiceDecomposition serviceDecomp = new ServiceDecomposition(catalogRestOutput); - serviceDecomp.addVnfResource(vnfResource); - serviceDecomp.addNetworkResource(networkResource); - serviceDecomp.addAllottedResource(allottedResource); - serviceDecomp.addConfigResource(configResource); - - assertThat(serviceDecomp.getServiceResource(vnfResource.getResourceId()), sameBeanAs(vnfResource)); - assertThat(serviceDecomp.getServiceResource(networkResource.getResourceId()), sameBeanAs(networkResource)); - assertThat(serviceDecomp.getServiceResource(allottedResource.getResourceId()), sameBeanAs(allottedResource)); - assertThat(serviceDecomp.getServiceResource(configResource.getResourceId()), sameBeanAs(configResource)); - - VnfResource vnfResourceReplace = new VnfResource(); - vnfResourceReplace.setResourceId(vnfResource.getResourceId()); - vnfResourceReplace.setResourceInstanceName("vnfResourceReplaceInstanceName"); - - assertTrue(serviceDecomp.replaceResource(vnfResourceReplace)); - assertTrue(serviceDecomp.getVnfResources().contains(vnfResourceReplace)); - - assertTrue(serviceDecomp.deleteResource(vnfResourceReplace)); - assertFalse(serviceDecomp.deleteResource(vnfResourceReplace)); - assertFalse(serviceDecomp.deleteResource(new VnfResource())); - } - - @Test - public void serviceDecompositionJsonTest() throws IOException { - String catalogRestOutput = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceDecomposition.json"))); - String expectedCatalogRestOutput = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceDecompositionExpected.json"))); - String vnfResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "VnfResource.json"))); - String networkResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "NetworkResource.json"))); - String allottedResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "AllottedResource.json"))); - String configResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ConfigResource.json"))); - - ServiceDecomposition serviceDecomp = new ServiceDecomposition(catalogRestOutput, "serviceInstanceId"); - serviceDecomp.addResource(vnfResource); - serviceDecomp.addResource(networkResource); - serviceDecomp.addResource(allottedResource); - serviceDecomp.addResource(configResource); - - System.out.println(serviceDecomp.toJsonString()); - - assertThat(serviceDecomp.getServiceResource(vnfResource.getResourceId()), sameBeanAs(vnfResource)); - assertThat(serviceDecomp.getServiceResource(networkResource.getResourceId()), sameBeanAs(networkResource)); - assertThat(serviceDecomp.getServiceResource(allottedResource.getResourceId()), sameBeanAs(allottedResource)); - assertThat(serviceDecomp.getServiceResource(configResource.getResourceId()), sameBeanAs(configResource)); - - serviceDecomp = new ServiceDecomposition(catalogRestOutput, "serviceInstanceId"); - serviceDecomp.addVnfResource(vnfResourceJson); - serviceDecomp.addNetworkResource(networkResourceJson); - serviceDecomp.addAllottedResource(allottedResourceJson); - serviceDecomp.addConfigResource(configResourceJson); - - ServiceDecomposition expectedServiceDecomp = new ServiceDecomposition(expectedCatalogRestOutput, "serviceInstanceId"); - - assertThat(serviceDecomp, sameBeanAs(expectedServiceDecomp)); - assertEquals(serviceDecomp.listToJson(Arrays.asList(networkResource)) + serviceDecomp.listToJson(Arrays.asList(vnfResource)) + - serviceDecomp.listToJson(Arrays.asList(allottedResource)) + serviceDecomp.listToJson(Arrays.asList(configResource)), - serviceDecomp.getServiceResourcesJsonString()); - } + private static final String RESOURCE_PATH = "src/test/resources/json-examples/"; + + VnfResource vnfResource; + NetworkResource networkResource; + AllottedResource allottedResource; + ConfigResource configResource; + + @Before + public void before() { + vnfResource = new VnfResource(); + vnfResource.setResourceId("vnfResourceId"); + vnfResource.setModules(new ArrayList<>()); + + networkResource = new NetworkResource(); + networkResource.setResourceId("networkResourceId"); + + allottedResource = new AllottedResource(); + allottedResource.setResourceId("allottedResourceId"); + + configResource = new ConfigResource(); + configResource.setResourceId("configResourceId"); + } + + @Test + public void serviceDecompositionTest() throws JsonProcessingException, IOException { + // covering methods not covered by openpojo test + String catalogRestOutput = + new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceDecomposition.json"))); + + ServiceDecomposition serviceDecomp = new ServiceDecomposition(catalogRestOutput); + serviceDecomp.addVnfResource(vnfResource); + serviceDecomp.addNetworkResource(networkResource); + serviceDecomp.addAllottedResource(allottedResource); + serviceDecomp.addConfigResource(configResource); + + assertThat(serviceDecomp.getServiceResource(vnfResource.getResourceId()), sameBeanAs(vnfResource)); + assertThat(serviceDecomp.getServiceResource(networkResource.getResourceId()), sameBeanAs(networkResource)); + assertThat(serviceDecomp.getServiceResource(allottedResource.getResourceId()), sameBeanAs(allottedResource)); + assertThat(serviceDecomp.getServiceResource(configResource.getResourceId()), sameBeanAs(configResource)); + + VnfResource vnfResourceReplace = new VnfResource(); + vnfResourceReplace.setResourceId(vnfResource.getResourceId()); + vnfResourceReplace.setResourceInstanceName("vnfResourceReplaceInstanceName"); + + assertTrue(serviceDecomp.replaceResource(vnfResourceReplace)); + assertTrue(serviceDecomp.getVnfResources().contains(vnfResourceReplace)); + + assertTrue(serviceDecomp.deleteResource(vnfResourceReplace)); + assertFalse(serviceDecomp.deleteResource(vnfResourceReplace)); + assertFalse(serviceDecomp.deleteResource(new VnfResource())); + } + + @Test + public void serviceDecompositionJsonTest() throws IOException { + String catalogRestOutput = + new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceDecomposition.json"))); + String expectedCatalogRestOutput = + new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceDecompositionExpected.json"))); + String vnfResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "VnfResource.json"))); + String networkResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "NetworkResource.json"))); + String allottedResourceJson = + new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "AllottedResource.json"))); + String configResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ConfigResource.json"))); + + ServiceDecomposition serviceDecomp = new ServiceDecomposition(catalogRestOutput, "serviceInstanceId"); + serviceDecomp.addResource(vnfResource); + serviceDecomp.addResource(networkResource); + serviceDecomp.addResource(allottedResource); + serviceDecomp.addResource(configResource); + + System.out.println(serviceDecomp.toJsonString()); + + assertThat(serviceDecomp.getServiceResource(vnfResource.getResourceId()), sameBeanAs(vnfResource)); + assertThat(serviceDecomp.getServiceResource(networkResource.getResourceId()), sameBeanAs(networkResource)); + assertThat(serviceDecomp.getServiceResource(allottedResource.getResourceId()), sameBeanAs(allottedResource)); + assertThat(serviceDecomp.getServiceResource(configResource.getResourceId()), sameBeanAs(configResource)); + + serviceDecomp = new ServiceDecomposition(catalogRestOutput, "serviceInstanceId"); + serviceDecomp.addVnfResource(vnfResourceJson); + serviceDecomp.addNetworkResource(networkResourceJson); + serviceDecomp.addAllottedResource(allottedResourceJson); + serviceDecomp.addConfigResource(configResourceJson); + + ServiceDecomposition expectedServiceDecomp = + new ServiceDecomposition(expectedCatalogRestOutput, "serviceInstanceId"); + + assertThat(serviceDecomp, sameBeanAs(expectedServiceDecomp)); + assertEquals( + serviceDecomp.listToJson(Arrays.asList(networkResource)) + + serviceDecomp.listToJson(Arrays.asList(vnfResource)) + + serviceDecomp.listToJson(Arrays.asList(allottedResource)) + + serviceDecomp.listToJson(Arrays.asList(configResource)), + serviceDecomp.getServiceResourcesJsonString()); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceInstanceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceInstanceTest.java index c04dc9d601..1fb51412f6 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceInstanceTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceInstanceTest.java @@ -1,71 +1,64 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import java.io.IOException; import java.util.Map; - import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; public class ServiceInstanceTest { - - private ServiceInstance si= new ServiceInstance(); - Map serviceParams; - Configuration config= new Configuration(); - ModelInfo model= new ModelInfo(); - @Test - public void testServiceInstance() { - si.setServiceType("serviceType"); - si.setServiceId("serviceId"); - si.setServiceParams(serviceParams); - si.setInstanceId("instanceId"); - si.setInstanceName("instanceName"); - si.setOrchestrationStatus("orchestrationStatus"); - si.setConfiguration(config); - si.setModelInfo(model); - si.setEnvironmentContext("environmentContext"); - si.setWorkloadContext("workloadContext"); - assertEquals(si.getServiceType(), "serviceType"); - assertEquals(si.getServiceId(), "serviceId"); - assertEquals(si.getServiceParams(), serviceParams); - assertEquals(si.getInstanceId(), "instanceId"); - assertEquals(si.getInstanceName(), "instanceName"); - assertEquals(si.getOrchestrationStatus(), "orchestrationStatus"); - assertEquals(si.getConfiguration(), config); - assertEquals(si.getModelInfo(), model); - assertEquals(si.getEnvironmentContext(), "environmentContext"); - assertEquals(si.getWorkloadContext(), "workloadContext"); - - - } + private ServiceInstance si = new ServiceInstance(); + Map serviceParams; + Configuration config = new Configuration(); + ModelInfo model = new ModelInfo(); + + @Test + public void testServiceInstance() { + si.setServiceType("serviceType"); + si.setServiceId("serviceId"); + si.setServiceParams(serviceParams); + si.setInstanceId("instanceId"); + si.setInstanceName("instanceName"); + si.setOrchestrationStatus("orchestrationStatus"); + si.setConfiguration(config); + si.setModelInfo(model); + si.setEnvironmentContext("environmentContext"); + si.setWorkloadContext("workloadContext"); + assertEquals(si.getServiceType(), "serviceType"); + assertEquals(si.getServiceId(), "serviceId"); + assertEquals(si.getServiceParams(), serviceParams); + assertEquals(si.getInstanceId(), "instanceId"); + assertEquals(si.getInstanceName(), "instanceName"); + assertEquals(si.getOrchestrationStatus(), "orchestrationStatus"); + assertEquals(si.getConfiguration(), config); + assertEquals(si.getModelInfo(), model); + assertEquals(si.getEnvironmentContext(), "environmentContext"); + assertEquals(si.getWorkloadContext(), "workloadContext"); + + + } - @Test - public void serviceInstanceMapperTest() throws IOException { - String jsonStr = "{\"workloadContext\": \"code123\", \"resourceOrder\": \"sample\"}"; - ObjectMapper objectMapper = new ObjectMapper(); - ServiceInstance serviceInstance = objectMapper.readValue(jsonStr, ServiceInstance.class); - assertTrue(serviceInstance != null); - } + @Test + public void serviceInstanceMapperTest() throws IOException { + String jsonStr = "{\"workloadContext\": \"code123\", \"resourceOrder\": \"sample\"}"; + ObjectMapper objectMapper = new ObjectMapper(); + ServiceInstance serviceInstance = objectMapper.readValue(jsonStr, ServiceInstance.class); + assertTrue(serviceInstance != null); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/SubscriberTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/SubscriberTest.java index b862c8704f..8f1b666d0b 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/SubscriberTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/SubscriberTest.java @@ -1,41 +1,35 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import org.junit.Test; public class SubscriberTest { - Subscriber subscriber= new Subscriber("globalId", "name", "commonSiteId"); + Subscriber subscriber = new Subscriber("globalId", "name", "commonSiteId"); + + @Test + public void testSubscriber() { + subscriber.setGlobalId("globalId"); + subscriber.setName("name"); + subscriber.setCommonSiteId("commonSiteId"); + assertEquals(subscriber.getGlobalId(), "globalId"); + assertEquals(subscriber.getName(), "name"); + assertEquals(subscriber.getCommonSiteId(), "commonSiteId"); + - @Test - public void testSubscriber() { - subscriber.setGlobalId("globalId"); - subscriber.setName("name"); - subscriber.setCommonSiteId("commonSiteId"); - assertEquals(subscriber.getGlobalId(), "globalId"); - assertEquals(subscriber.getName(), "name"); - assertEquals(subscriber.getCommonSiteId(), "commonSiteId"); - - - } + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java index 5271bb3c53..09bcfe8470 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java @@ -1,100 +1,93 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 TechMahindra + * ================================================================================ 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 + * 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. + * 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.so.bpmn.core.domain; import static org.junit.Assert.*; - import java.io.IOException; import java.util.ArrayList; import java.util.List; - import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; public class VnfResourceTest { - private final static String ALL_VF_MODULES_JSON = - "{\"ArrayList\":[{\"resourceType\":\"MODULE\",\"resourceInstance\":{},\"homingSolution\":{\"license\":{},\"rehome\":false},\"vfModuleName\":\"vfModuleName\",\"vfModuleType\":\"vfModuleType\",\"heatStackId\":\"heatStackId\",\"hasVolumeGroup\":true,\"isBase\":true,\"vfModuleLabel\":\"vfModuleLabel\",\"initialCount\":0},{\"resourceType\":\"MODULE\",\"resourceInstance\":{},\"homingSolution\":{\"license\":{},\"rehome\":false},\"vfModuleName\":\"vfModuleName\",\"vfModuleType\":\"vfModuleType\",\"heatStackId\":\"heatStackId\",\"hasVolumeGroup\":true,\"isBase\":true,\"vfModuleLabel\":\"vfModuleLabel\",\"initialCount\":0}]}"; - - private VnfResource vnf= new VnfResource(); - List<ModuleResource> moduleResources; - - @Test - public void testVnfResource() { - vnf.setModules(moduleResources); - vnf.setVnfHostname("vnfHostname"); - vnf.setVnfType("vnfType"); - vnf.setNfFunction("nfFunction"); - vnf.setNfType("nfType"); - vnf.setNfRole("nfRole"); - vnf.setNfNamingCode("nfNamingCode"); - vnf.setMultiStageDesign("multiStageDesign"); - assertEquals(vnf.getVfModules(), moduleResources); - assertEquals(vnf.getVnfHostname(), "vnfHostname"); - assertEquals(vnf.getVnfType(), "vnfType"); - assertEquals(vnf.getNfFunction(), "nfFunction"); - assertEquals(vnf.getNfType(), "nfType"); - assertEquals(vnf.getNfRole(), "nfRole"); - assertEquals(vnf.getNfNamingCode(), "nfNamingCode"); - assertEquals(vnf.getMultiStageDesign(), "multiStageDesign"); - - - } - - @Test - public void vnfResourceMapperTest() throws IOException { - String jsonStr = "{\"vnfHostname\": \"home\", \"resourceInput\": \"sample\"}"; - ObjectMapper objectMapper = new ObjectMapper(); - VnfResource vnfResource = objectMapper.readValue(jsonStr, VnfResource.class); - - assertTrue(vnfResource != null); - } - - @Test - public void testVfModules() { - - moduleResources = new ArrayList<>(); - - ModuleResource moduleresource = new ModuleResource(); - moduleresource.setVfModuleName("vfModuleName"); - moduleresource.setHeatStackId("heatStackId"); - moduleresource.setIsBase(true); - moduleresource.setVfModuleLabel("vfModuleLabel"); - moduleresource.setInitialCount(0); - moduleresource.setVfModuleType("vfModuleType"); - moduleresource.setHasVolumeGroup(true); - - moduleResources.add(moduleresource); - - vnf.setModules(moduleResources); - assertEquals(vnf.getVfModules(), moduleResources); - - List<ModuleResource> moduleResources = vnf.getAllVfModuleObjects(); - assertEquals(1, moduleResources.size()); - - vnf.addVfModule(moduleresource); - moduleResources = vnf.getAllVfModuleObjects(); - assertEquals(2, moduleResources.size()); - - assertEquals(ALL_VF_MODULES_JSON, vnf.getAllVfModulesJson()); - - } + private final static String ALL_VF_MODULES_JSON = + "{\"ArrayList\":[{\"resourceType\":\"MODULE\",\"resourceInstance\":{},\"homingSolution\":{\"license\":{},\"rehome\":false},\"vfModuleName\":\"vfModuleName\",\"vfModuleType\":\"vfModuleType\",\"heatStackId\":\"heatStackId\",\"hasVolumeGroup\":true,\"isBase\":true,\"vfModuleLabel\":\"vfModuleLabel\",\"initialCount\":0},{\"resourceType\":\"MODULE\",\"resourceInstance\":{},\"homingSolution\":{\"license\":{},\"rehome\":false},\"vfModuleName\":\"vfModuleName\",\"vfModuleType\":\"vfModuleType\",\"heatStackId\":\"heatStackId\",\"hasVolumeGroup\":true,\"isBase\":true,\"vfModuleLabel\":\"vfModuleLabel\",\"initialCount\":0}]}"; + + private VnfResource vnf = new VnfResource(); + List<ModuleResource> moduleResources; + + @Test + public void testVnfResource() { + vnf.setModules(moduleResources); + vnf.setVnfHostname("vnfHostname"); + vnf.setVnfType("vnfType"); + vnf.setNfFunction("nfFunction"); + vnf.setNfType("nfType"); + vnf.setNfRole("nfRole"); + vnf.setNfNamingCode("nfNamingCode"); + vnf.setMultiStageDesign("multiStageDesign"); + assertEquals(vnf.getVfModules(), moduleResources); + assertEquals(vnf.getVnfHostname(), "vnfHostname"); + assertEquals(vnf.getVnfType(), "vnfType"); + assertEquals(vnf.getNfFunction(), "nfFunction"); + assertEquals(vnf.getNfType(), "nfType"); + assertEquals(vnf.getNfRole(), "nfRole"); + assertEquals(vnf.getNfNamingCode(), "nfNamingCode"); + assertEquals(vnf.getMultiStageDesign(), "multiStageDesign"); + + + } + + @Test + public void vnfResourceMapperTest() throws IOException { + String jsonStr = "{\"vnfHostname\": \"home\", \"resourceInput\": \"sample\"}"; + ObjectMapper objectMapper = new ObjectMapper(); + VnfResource vnfResource = objectMapper.readValue(jsonStr, VnfResource.class); + + assertTrue(vnfResource != null); + } + + @Test + public void testVfModules() { + + moduleResources = new ArrayList<>(); + + ModuleResource moduleresource = new ModuleResource(); + moduleresource.setVfModuleName("vfModuleName"); + moduleresource.setHeatStackId("heatStackId"); + moduleresource.setIsBase(true); + moduleresource.setVfModuleLabel("vfModuleLabel"); + moduleresource.setInitialCount(0); + moduleresource.setVfModuleType("vfModuleType"); + moduleresource.setHasVolumeGroup(true); + + moduleResources.add(moduleresource); + + vnf.setModules(moduleResources); + assertEquals(vnf.getVfModules(), moduleResources); + + List<ModuleResource> moduleResources = vnf.getAllVfModuleObjects(); + assertEquals(1, moduleResources.size()); + + vnf.addVfModule(moduleresource); + moduleResources = vnf.getAllVfModuleObjects(); + assertEquals(2, moduleResources.size()); + + assertEquals(ALL_VF_MODULES_JSON, vnf.getAllVfModulesJson()); + + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/internal/VariableNameExtractorTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/internal/VariableNameExtractorTest.java index 14b8c49655..e62ff09545 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/internal/VariableNameExtractorTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/internal/VariableNameExtractorTest.java @@ -19,10 +19,10 @@ */ package org.onap.so.bpmn.core.internal; + import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.contains; - import java.util.Optional; import org.junit.Test; @@ -86,4 +86,4 @@ public class VariableNameExtractorTest { // then assertFalse(extracted.isPresent()); } -}
\ No newline at end of file +} diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/DecomposeJsonUtilTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/DecomposeJsonUtilTest.java index c1f7cce30b..3a8948c00d 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/DecomposeJsonUtilTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/DecomposeJsonUtilTest.java @@ -1,27 +1,21 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 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 + * 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. + * 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.so.bpmn.core.json; import static org.junit.Assert.assertEquals; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -34,137 +28,140 @@ import org.onap.so.bpmn.core.domain.VnfResource; public class DecomposeJsonUtilTest { - private VnfResource vnfResource; - private NetworkResource networkResource; - private AllottedResource allottedResource; - private ConfigResource configResource; - private ServiceDecomposition serviceDecomposition; - - private String serviceInstanceId = "serviceInstanceId"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Before - public void before() throws Exception { - - } - - @Test - public void testJsonToServiceDecomposition_twoParams() throws JsonDecomposingException { - serviceDecomposition = createServiceDecompositionData(); - ServiceDecomposition serviceDecompositionObj = DecomposeJsonUtil.jsonToServiceDecomposition(serviceDecomposition.toString(), "serviceInstanceId"); - assertEquals(serviceInstanceId, serviceDecompositionObj.getServiceInstance().getInstanceId()); - } - - @Test - public void testJsonToServiceDecomposition() throws JsonDecomposingException { - serviceDecomposition = createServiceDecompositionData(); - ServiceDecomposition serviceDecompositionObj = DecomposeJsonUtil.jsonToServiceDecomposition(serviceDecomposition.toString()); - assertEquals(serviceDecomposition.getServiceType(), serviceDecompositionObj.getServiceType()); - } - - @Test - public void testJsonToServiceDecomposition_JsonDecomposingException() throws JsonDecomposingException { - expectedException.expect(JsonDecomposingException.class); - vnfResource = createVnfResourceData(); // wrong object - ServiceDecomposition serviceDecompositionObj = DecomposeJsonUtil.jsonToServiceDecomposition(vnfResource.toString()); - } - - @Test - public void testJsonToVnfResource() throws JsonDecomposingException { - vnfResource = createVnfResourceData(); - VnfResource vnfResourceObj = DecomposeJsonUtil.jsonToVnfResource(vnfResource.toString()); - assertEquals(vnfResource.getResourceId(), vnfResourceObj.getResourceId()); - } - - @Test - public void testJsonToVnfResource_JsonDecomposingException() throws JsonDecomposingException { - expectedException.expect(JsonDecomposingException.class); - networkResource = createNetworkResourceData(); // wrong object - VnfResource vnfResourceObj = DecomposeJsonUtil.jsonToVnfResource(networkResource.toString()); - } - - @Test - public void testJsonToNetworkResource() throws JsonDecomposingException { - networkResource = createNetworkResourceData(); - NetworkResource networkResourceObj = DecomposeJsonUtil.jsonToNetworkResource(networkResource.toString()); - assertEquals(networkResource.getResourceId(), networkResourceObj.getResourceId()); - } - - @Test - public void testJsonToNetworkResource_JsonDecomposingException() throws JsonDecomposingException { - expectedException.expect(JsonDecomposingException.class); - vnfResource = createVnfResourceData(); // wrong object - NetworkResource networkResourceObj = DecomposeJsonUtil.jsonToNetworkResource(vnfResource.toString()); - } - - @Test - public void testJsonToAllottedResource() throws JsonDecomposingException { - allottedResource = createAllottedResourceData(); - AllottedResource allottedResourceObj = DecomposeJsonUtil.jsonToAllottedResource(allottedResource.toString()); - assertEquals(allottedResource.getResourceId(), allottedResourceObj.getResourceId()); - } - - @Test - public void testJsonToAllottedResource_JsonDecomposingException() throws JsonDecomposingException { - expectedException.expect(JsonDecomposingException.class); - configResource = createConfigResourceData(); // wrong object - AllottedResource allottedResourceObj = DecomposeJsonUtil.jsonToAllottedResource(configResource.toString()); - } - - @Test - public void testJsonToConfigResource() throws JsonDecomposingException { - configResource = createConfigResourceData(); - ConfigResource configResourceObj = DecomposeJsonUtil.jsonToConfigResource(configResource.toString()); - assertEquals(configResource.getResourceId(), configResourceObj.getResourceId()); - } - - @Test - public void testJsonToConfigResource_JsonDecomposingException() throws JsonDecomposingException { - expectedException.expect(JsonDecomposingException.class); - allottedResource = createAllottedResourceData(); // wrong object - ConfigResource configResourceObj = DecomposeJsonUtil.jsonToConfigResource(allottedResource.toString()); - } - - // data creation section - private VnfResource createVnfResourceData() { - vnfResource = new VnfResource(); - vnfResource.setResourceId("resourceId"); - vnfResource.setNfFunction("nfFunction"); - vnfResource.setNfNamingCode("nfNamingCode"); - vnfResource.setNfRole("nfRole"); - return vnfResource; - } - - private NetworkResource createNetworkResourceData() { - networkResource = new NetworkResource(); - networkResource.setNetworkRole("networkRole"); - networkResource.setResourceId("resourceId"); - return networkResource; - } - - private AllottedResource createAllottedResourceData() { - allottedResource = new AllottedResource(); - allottedResource.setResourceId("resourceId"); - allottedResource.setNfFunction("nfFunction"); - allottedResource.setNfNamingCode("nfNamingCode"); - allottedResource.setNfRole("nfRole"); - return allottedResource; - } - - private ConfigResource createConfigResourceData() { - configResource = new ConfigResource(); - configResource.setResourceId("resourceId"); - configResource.setToscaNodeType("toscaNodeType"); - return configResource; - } - - private ServiceDecomposition createServiceDecompositionData() { - serviceDecomposition = new ServiceDecomposition(); - serviceDecomposition.setSdncVersion("sdncVersion"); - serviceDecomposition.setServiceRole("serviceRole"); - serviceDecomposition.setServiceType("serviceType"); - return serviceDecomposition; - } + private VnfResource vnfResource; + private NetworkResource networkResource; + private AllottedResource allottedResource; + private ConfigResource configResource; + private ServiceDecomposition serviceDecomposition; + + private String serviceInstanceId = "serviceInstanceId"; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void before() throws Exception { + + } + + @Test + public void testJsonToServiceDecomposition_twoParams() throws JsonDecomposingException { + serviceDecomposition = createServiceDecompositionData(); + ServiceDecomposition serviceDecompositionObj = + DecomposeJsonUtil.jsonToServiceDecomposition(serviceDecomposition.toString(), "serviceInstanceId"); + assertEquals(serviceInstanceId, serviceDecompositionObj.getServiceInstance().getInstanceId()); + } + + @Test + public void testJsonToServiceDecomposition() throws JsonDecomposingException { + serviceDecomposition = createServiceDecompositionData(); + ServiceDecomposition serviceDecompositionObj = + DecomposeJsonUtil.jsonToServiceDecomposition(serviceDecomposition.toString()); + assertEquals(serviceDecomposition.getServiceType(), serviceDecompositionObj.getServiceType()); + } + + @Test + public void testJsonToServiceDecomposition_JsonDecomposingException() throws JsonDecomposingException { + expectedException.expect(JsonDecomposingException.class); + vnfResource = createVnfResourceData(); // wrong object + ServiceDecomposition serviceDecompositionObj = + DecomposeJsonUtil.jsonToServiceDecomposition(vnfResource.toString()); + } + + @Test + public void testJsonToVnfResource() throws JsonDecomposingException { + vnfResource = createVnfResourceData(); + VnfResource vnfResourceObj = DecomposeJsonUtil.jsonToVnfResource(vnfResource.toString()); + assertEquals(vnfResource.getResourceId(), vnfResourceObj.getResourceId()); + } + + @Test + public void testJsonToVnfResource_JsonDecomposingException() throws JsonDecomposingException { + expectedException.expect(JsonDecomposingException.class); + networkResource = createNetworkResourceData(); // wrong object + VnfResource vnfResourceObj = DecomposeJsonUtil.jsonToVnfResource(networkResource.toString()); + } + + @Test + public void testJsonToNetworkResource() throws JsonDecomposingException { + networkResource = createNetworkResourceData(); + NetworkResource networkResourceObj = DecomposeJsonUtil.jsonToNetworkResource(networkResource.toString()); + assertEquals(networkResource.getResourceId(), networkResourceObj.getResourceId()); + } + + @Test + public void testJsonToNetworkResource_JsonDecomposingException() throws JsonDecomposingException { + expectedException.expect(JsonDecomposingException.class); + vnfResource = createVnfResourceData(); // wrong object + NetworkResource networkResourceObj = DecomposeJsonUtil.jsonToNetworkResource(vnfResource.toString()); + } + + @Test + public void testJsonToAllottedResource() throws JsonDecomposingException { + allottedResource = createAllottedResourceData(); + AllottedResource allottedResourceObj = DecomposeJsonUtil.jsonToAllottedResource(allottedResource.toString()); + assertEquals(allottedResource.getResourceId(), allottedResourceObj.getResourceId()); + } + + @Test + public void testJsonToAllottedResource_JsonDecomposingException() throws JsonDecomposingException { + expectedException.expect(JsonDecomposingException.class); + configResource = createConfigResourceData(); // wrong object + AllottedResource allottedResourceObj = DecomposeJsonUtil.jsonToAllottedResource(configResource.toString()); + } + + @Test + public void testJsonToConfigResource() throws JsonDecomposingException { + configResource = createConfigResourceData(); + ConfigResource configResourceObj = DecomposeJsonUtil.jsonToConfigResource(configResource.toString()); + assertEquals(configResource.getResourceId(), configResourceObj.getResourceId()); + } + + @Test + public void testJsonToConfigResource_JsonDecomposingException() throws JsonDecomposingException { + expectedException.expect(JsonDecomposingException.class); + allottedResource = createAllottedResourceData(); // wrong object + ConfigResource configResourceObj = DecomposeJsonUtil.jsonToConfigResource(allottedResource.toString()); + } + + // data creation section + private VnfResource createVnfResourceData() { + vnfResource = new VnfResource(); + vnfResource.setResourceId("resourceId"); + vnfResource.setNfFunction("nfFunction"); + vnfResource.setNfNamingCode("nfNamingCode"); + vnfResource.setNfRole("nfRole"); + return vnfResource; + } + + private NetworkResource createNetworkResourceData() { + networkResource = new NetworkResource(); + networkResource.setNetworkRole("networkRole"); + networkResource.setResourceId("resourceId"); + return networkResource; + } + + private AllottedResource createAllottedResourceData() { + allottedResource = new AllottedResource(); + allottedResource.setResourceId("resourceId"); + allottedResource.setNfFunction("nfFunction"); + allottedResource.setNfNamingCode("nfNamingCode"); + allottedResource.setNfRole("nfRole"); + return allottedResource; + } + + private ConfigResource createConfigResourceData() { + configResource = new ConfigResource(); + configResource.setResourceId("resourceId"); + configResource.setToscaNodeType("toscaNodeType"); + return configResource; + } + + private ServiceDecomposition createServiceDecompositionData() { + serviceDecomposition = new ServiceDecomposition(); + serviceDecomposition.setSdncVersion("sdncVersion"); + serviceDecomposition.setServiceRole("serviceRole"); + serviceDecomposition.setServiceType("serviceType"); + return serviceDecomposition; + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonDecomposingExceptionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonDecomposingExceptionTest.java index 6c8b7326e2..a9df2d9ea6 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonDecomposingExceptionTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonDecomposingExceptionTest.java @@ -1,22 +1,17 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 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 + * 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. + * 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.so.bpmn.core.json; @@ -25,14 +20,14 @@ import org.junit.Test; public class JsonDecomposingExceptionTest { - private JsonDecomposingException jsonDecomposingException; - - @Test - public void test() { - String expectedMessage = "java.lang.Throwable: anyCause"; - String message = "java.lang.Throwable: anyCause"; - Throwable cause = new Throwable("anyCause"); - jsonDecomposingException = new JsonDecomposingException(message, cause); - assertEquals(expectedMessage, jsonDecomposingException.getMessage()); - } + private JsonDecomposingException jsonDecomposingException; + + @Test + public void test() { + String expectedMessage = "java.lang.Throwable: anyCause"; + String message = "java.lang.Throwable: anyCause"; + Throwable cause = new Throwable("anyCause"); + jsonDecomposingException = new JsonDecomposingException(message, cause); + assertEquals(expectedMessage, jsonDecomposingException.getMessage()); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtils2Test.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtils2Test.java index 667027f8de..1a2ceb5b39 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtils2Test.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtils2Test.java @@ -22,12 +22,10 @@ package org.onap.so.bpmn.core.json; import static org.junit.Assert.*; - import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; - import org.json.JSONObject; import org.junit.Assert; import org.junit.BeforeClass; @@ -46,102 +44,78 @@ import org.xmlunit.diff.ElementSelectors; public class JsonUtils2Test { private static final String EOL = "\n"; - private static final String XML_REQ = - "<vnf-request xmlns=\"http://org.onap/so/infra/vnf-request/v1\">" + EOL + - " <request-info>" + EOL + - " <request-id>DEV-VF-0021</request-id>" + EOL + - " <action>CREATE_VF_MODULE</action>" + EOL + - " <source>PORTAL</source>" + EOL + - " </request-info>" + EOL + - " <vnf-inputs>" + EOL + - " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL + - " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + - " <vnf-type>asc_heat-int</vnf-type>" + EOL + - " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL + - " <vf-module-model-name>STMTN5MMSC21-MMSC::model-1-0</vf-module-model-name>" + EOL + - " <is-base-module>true</is-base-module>" + EOL + - " <persona-model-id>00000000-0000-0000-0000-000000000000</persona-model-id>" + EOL + - " <persona-model-version>1.0</persona-model-version>" + EOL + - " <vnf-persona-model-id>999999999-0000-0000-0000-000000000000</vnf-persona-model-id>" + EOL + - " <vnf-persona-model-version>1.5</vnf-persona-model-version>" + EOL + - " <service-id>00000000-0000-0000-0000-000000000000</service-id>" + EOL + - " <service-type>SDN-ETHERNET-INTERNET</service-type>" + EOL + - " <tenant-id>fba1bd1e195a404cacb9ce17a9b2b421</tenant-id>" + EOL + - " <orchestration-status>pending-delete</orchestration-status>" + EOL + - " <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region>" + EOL + - " <asdc-service-model-version>1</asdc-service-model-version>" + EOL + - " </vnf-inputs>" + EOL + - " <vnf-params xmlns:tns=\"http://org.onap/so/infra/vnf-request/v1\">" + EOL + - " <param name=\"network\">network1111</param>" + EOL + - " <param name=\"server\">server1111</param>" + EOL + - " </vnf-params> " + EOL + - "</vnf-request>" + EOL; - - private static final String XML_REQ_NO_ATTRS = - "<vnf-request xmlns=\"http://org.onap/so/infra/vnf-request/v1\">" + EOL + - " <request-info>" + EOL + - " <action>DELETE_VF_MODULE</action>" + EOL + - " <source>PORTAL</source>" + EOL + - " </request-info>" + EOL + - " <vnf-inputs>" + EOL + - " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL + - " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + - " <vnf-type>asc_heat-int</vnf-type>" + EOL + - " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL + - " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL + - " <service-id>00000000-0000-0000-0000-000000000000</service-id>" + EOL + - " <service-type>SDN-ETHERNET-INTERNET</service-type>" + EOL + - " <tenant-id>fba1bd1e195a404cacb9ce17a9b2b421</tenant-id>" + EOL + - " <orchestration-status>pending-delete</orchestration-status>" + EOL + - " <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region>" + EOL + - " </vnf-inputs>" + EOL + - " <vnf-params xmlns:tns=\"http://org.onap/so/infra/vnf-request/v1\"/>" + EOL + - "</vnf-request>" + EOL; + private static final String XML_REQ = "<vnf-request xmlns=\"http://org.onap/so/infra/vnf-request/v1\">" + EOL + + " <request-info>" + EOL + " <request-id>DEV-VF-0021</request-id>" + EOL + + " <action>CREATE_VF_MODULE</action>" + EOL + " <source>PORTAL</source>" + EOL + " </request-info>" + + EOL + " <vnf-inputs>" + EOL + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + " <vnf-type>asc_heat-int</vnf-type>" + EOL + + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL + + " <vf-module-model-name>STMTN5MMSC21-MMSC::model-1-0</vf-module-model-name>" + EOL + + " <is-base-module>true</is-base-module>" + EOL + + " <persona-model-id>00000000-0000-0000-0000-000000000000</persona-model-id>" + EOL + + " <persona-model-version>1.0</persona-model-version>" + EOL + + " <vnf-persona-model-id>999999999-0000-0000-0000-000000000000</vnf-persona-model-id>" + EOL + + " <vnf-persona-model-version>1.5</vnf-persona-model-version>" + EOL + + " <service-id>00000000-0000-0000-0000-000000000000</service-id>" + EOL + + " <service-type>SDN-ETHERNET-INTERNET</service-type>" + EOL + + " <tenant-id>fba1bd1e195a404cacb9ce17a9b2b421</tenant-id>" + EOL + + " <orchestration-status>pending-delete</orchestration-status>" + EOL + + " <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region>" + EOL + + " <asdc-service-model-version>1</asdc-service-model-version>" + EOL + " </vnf-inputs>" + EOL + + " <vnf-params xmlns:tns=\"http://org.onap/so/infra/vnf-request/v1\">" + EOL + + " <param name=\"network\">network1111</param>" + EOL + " <param name=\"server\">server1111</param>" + + EOL + " </vnf-params> " + EOL + "</vnf-request>" + EOL; + + private static final String XML_REQ_NO_ATTRS = "<vnf-request xmlns=\"http://org.onap/so/infra/vnf-request/v1\">" + + EOL + " <request-info>" + EOL + " <action>DELETE_VF_MODULE</action>" + EOL + + " <source>PORTAL</source>" + EOL + " </request-info>" + EOL + " <vnf-inputs>" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + " <vnf-type>asc_heat-int</vnf-type>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL + + " <service-id>00000000-0000-0000-0000-000000000000</service-id>" + EOL + + " <service-type>SDN-ETHERNET-INTERNET</service-type>" + EOL + + " <tenant-id>fba1bd1e195a404cacb9ce17a9b2b421</tenant-id>" + EOL + + " <orchestration-status>pending-delete</orchestration-status>" + EOL + + " <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region>" + EOL + " </vnf-inputs>" + EOL + + " <vnf-params xmlns:tns=\"http://org.onap/so/infra/vnf-request/v1\"/>" + EOL + "</vnf-request>" + EOL; private static final String XML_ARRAY_REQ = - "<ucpeInfo>" + EOL + - " <outOfBandManagementModem>BROADBAND</outOfBandManagementModem>" + EOL + - " <internetTopology>IVLAN</internetTopology>" + EOL + - " <ucpeAliasHostName>SHELLUCPE31</ucpeAliasHostName>" + EOL + - " <wanList>" + EOL + - " <wanInfo>" + EOL + - " <wanType>AVPN</wanType>" + EOL + - " <interfaceType>1000BASE-T</interfaceType>" + EOL + - " <transportProviderName>ATT</transportProviderName>" + EOL + - " <circuitId>BT/SLIR/70911</circuitId>" + EOL + - " <dualMode>Active</dualMode>" + EOL + - " <wanPortNumber>WAN1</wanPortNumber>" + EOL + - " <transportManagementOption>ATT</transportManagementOption>" + EOL + - " <transportVendorTotalBandwidth>100</transportVendorTotalBandwidth>" + EOL + - " <mediaType>ELECTRICAL</mediaType>" + EOL + - " </wanInfo>" + EOL + - " <wanInfo>" + EOL + - " <wanType>AVPN</wanType>" + EOL + - " <interfaceType>10/100/1000BASE-T</interfaceType>" + EOL + - " <transportProviderName>ATT</transportProviderName>" + EOL + - " <circuitId>AS/KRFN/34611</circuitId>" + EOL + - " <dualMode>Active</dualMode>" + EOL + - " <wanPortNumber>WAN2</wanPortNumber>" + EOL + - " <transportManagementOption>ATT</transportManagementOption>" + EOL + - " <transportVendorTotalBandwidth>10000</transportVendorTotalBandwidth>" + EOL + - " <mediaType>MMF</mediaType>" + EOL + - " </wanInfo>" + EOL + - " </wanList>" + EOL + - " <ucpeActivationCode>ASD-987-M31</ucpeActivationCode>" + EOL + - " <ucpeHostName>USOSTCDALTX0101UJZZ31</ucpeHostName>" + EOL + - " <ucpePartNumber>FG-VM00*</ucpePartNumber>" + EOL + - "</ucpeInfo>"; + "<ucpeInfo>" + EOL + " <outOfBandManagementModem>BROADBAND</outOfBandManagementModem>" + EOL + + " <internetTopology>IVLAN</internetTopology>" + EOL + + " <ucpeAliasHostName>SHELLUCPE31</ucpeAliasHostName>" + EOL + " <wanList>" + EOL + + " <wanInfo>" + EOL + " <wanType>AVPN</wanType>" + EOL + + " <interfaceType>1000BASE-T</interfaceType>" + EOL + + " <transportProviderName>ATT</transportProviderName>" + EOL + + " <circuitId>BT/SLIR/70911</circuitId>" + EOL + + " <dualMode>Active</dualMode>" + EOL + + " <wanPortNumber>WAN1</wanPortNumber>" + EOL + + " <transportManagementOption>ATT</transportManagementOption>" + EOL + + " <transportVendorTotalBandwidth>100</transportVendorTotalBandwidth>" + EOL + + " <mediaType>ELECTRICAL</mediaType>" + EOL + " </wanInfo>" + EOL + + " <wanInfo>" + EOL + " <wanType>AVPN</wanType>" + EOL + + " <interfaceType>10/100/1000BASE-T</interfaceType>" + EOL + + " <transportProviderName>ATT</transportProviderName>" + EOL + + " <circuitId>AS/KRFN/34611</circuitId>" + EOL + + " <dualMode>Active</dualMode>" + EOL + + " <wanPortNumber>WAN2</wanPortNumber>" + EOL + + " <transportManagementOption>ATT</transportManagementOption>" + EOL + + " <transportVendorTotalBandwidth>10000</transportVendorTotalBandwidth>" + EOL + + " <mediaType>MMF</mediaType>" + EOL + " </wanInfo>" + EOL + + " </wanList>" + EOL + " <ucpeActivationCode>ASD-987-M31</ucpeActivationCode>" + EOL + + " <ucpeHostName>USOSTCDALTX0101UJZZ31</ucpeHostName>" + EOL + + " <ucpePartNumber>FG-VM00*</ucpePartNumber>" + EOL + "</ucpeInfo>"; // JSON request w/ embedded XML will be read from a file private static String jsonReq; private static String jsonReqArray; - + @BeforeClass public static void initialize() throws Exception { jsonReq = readFileToString("src/test/resources/request.json"); jsonReqArray = readFileToString("src/test/resources/requestArray.json"); - } - + } + private static String readFileToString(String path) throws IOException { File file = new File(path); return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); @@ -149,16 +123,16 @@ public class JsonUtils2Test { @Test public void shouldConvertXmlToJsonAndBackToSameXml() throws Exception { - // Note: the current version of the JsonUtils.json2xml() method - // does not support converting the JSONObject representation - // of XML attributes (JSONArray) back to XML. So this test will - // only succeed if the original XML does not contain attributes - + // Note: the current version of the JsonUtils.json2xml() method + // does not support converting the JSONObject representation + // of XML attributes (JSONArray) back to XML. So this test will + // only succeed if the original XML does not contain attributes + // given String xmlIn = XmlTool.removeNamespaces(XML_REQ_NO_ATTRS); // when String json = JsonUtils.xml2json(XML_REQ_NO_ATTRS); - String xmlOut = JsonUtils.json2xml(json); + String xmlOut = JsonUtils.json2xml(json); // then Diff diffXml = DiffBuilder.compare(xmlIn).withTest(xmlOut).ignoreWhitespace() .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)).checkForSimilar().build(); @@ -214,7 +188,7 @@ public class JsonUtils2Test { assertNull(JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "badParam")); assertNull(JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "name", 2)); } - + @Test public void shouldAddJsonValue() throws Exception { // given @@ -265,11 +239,11 @@ public class JsonUtils2Test { // then String extractedValue = JsonUtils.getJsonValue(jsonUpd, key); assertNull(extractedValue); - JSONObject jsonObj = new JSONObject(json); - Integer intValue = JsonUtils.getJsonIntValueForKey(jsonObj, "persona-model-version"); - Assert.assertTrue(intValue == 1); - Boolean boolValue = JsonUtils.getJsonBooleanValueForKey(jsonObj, "is-base-module"); - Assert.assertTrue(boolValue); + JSONObject jsonObj = new JSONObject(json); + Integer intValue = JsonUtils.getJsonIntValueForKey(jsonObj, "persona-model-version"); + Assert.assertTrue(intValue == 1); + Boolean boolValue = JsonUtils.getJsonBooleanValueForKey(jsonObj, "is-base-module"); + Assert.assertTrue(boolValue); } @Test @@ -282,26 +256,26 @@ public class JsonUtils2Test { // then assertEquals(json, jsonUpd); } - + @Test public void shouldConvertXmlToJsonAndBackToSameXmlExtractedFromTheRequest() throws Exception { // given - String value = JsonUtils.getJsonValue(jsonReq, "variables.bpmnRequest.value"); - String xmlReq = XmlTool.removeNamespaces(XmlTool.normalize(value)); + String value = JsonUtils.getJsonValue(jsonReq, "variables.bpmnRequest.value"); + String xmlReq = XmlTool.removeNamespaces(XmlTool.normalize(value)); // when - String json = JsonUtils.xml2json(xmlReq); - String xmlOut = JsonUtils.json2xml(json); + String json = JsonUtils.xml2json(xmlReq); + String xmlOut = JsonUtils.json2xml(json); // then Diff diffXml = DiffBuilder.compare(xmlReq).withTest(xmlOut).ignoreWhitespace() .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)).checkForSimilar().build(); assertFalse(diffXml.hasDifferences()); - } - + } + @Test public void shouldConvertJsonContainingArrayToXml() throws Exception { // when - String jsonParm = JsonUtils.getJsonNodeValue(jsonReqArray, "requestDetails.requestParameters.ucpeInfo"); - String xmlOut = JsonUtils.json2xml(jsonParm); + String jsonParm = JsonUtils.getJsonNodeValue(jsonReqArray, "requestDetails.requestParameters.ucpeInfo"); + String xmlOut = JsonUtils.json2xml(jsonParm); // then Diff diffXml = DiffBuilder.compare(XML_ARRAY_REQ).withTest(xmlOut).ignoreWhitespace() .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)).checkForSimilar().build(); @@ -311,19 +285,19 @@ public class JsonUtils2Test { @Test // Tests the jsonSchemaValidation() method public void testJsonSchemaValidation() { - try { - String myReqArray = jsonReqArray; - String result = JsonUtils.jsonSchemaValidation(myReqArray, "src/test/resources/requestSchema.json"); - System.out.println("Schema Validation Result: " + result); - Assert.assertTrue(result.contains("success")); - // remove a required parameter from the JSON doc so that validation fails - myReqArray = JsonUtils.delJsonValue(myReqArray, "requestDetails.requestParameters.ucpeInfo.ucpeHostName"); - result = JsonUtils.jsonSchemaValidation(myReqArray, "src/test/resources/requestSchema.json"); - System.out.println("Schema Validation Result: " + result); - Assert.assertTrue(result.contains("failure")); - Assert.assertTrue(result.contains("error: object has missing required properties ([\"ucpeHostName\"])")); - } catch (ValidationException e) { - e.printStackTrace(); - } + try { + String myReqArray = jsonReqArray; + String result = JsonUtils.jsonSchemaValidation(myReqArray, "src/test/resources/requestSchema.json"); + System.out.println("Schema Validation Result: " + result); + Assert.assertTrue(result.contains("success")); + // remove a required parameter from the JSON doc so that validation fails + myReqArray = JsonUtils.delJsonValue(myReqArray, "requestDetails.requestParameters.ucpeInfo.ucpeHostName"); + result = JsonUtils.jsonSchemaValidation(myReqArray, "src/test/resources/requestSchema.json"); + System.out.println("Schema Validation Result: " + result); + Assert.assertTrue(result.contains("failure")); + Assert.assertTrue(result.contains("error: object has missing required properties ([\"ucpeHostName\"])")); + } catch (ValidationException e) { + e.printStackTrace(); + } } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtilsTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtilsTest.java index 067ae9806d..36ffc0b04d 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtilsTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtilsTest.java @@ -23,13 +23,11 @@ package org.onap.so.bpmn.core.json; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; - import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.runtime.Execution; import org.json.JSONArray; @@ -43,203 +41,232 @@ import org.onap.so.exceptions.ValidationException; public class JsonUtilsTest { - @Mock public DelegateExecution execution; - @Mock public Execution mockEexecution; - private final String fileLocation = "src/test/resources/json-examples/"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void jsonStringToMapTest() throws IOException { - - JsonUtils utils = new JsonUtils(); - String response = this.getJson("SDNCServiceResponseExample.json"); - String entry = JsonUtils.getJsonValue(response, "SDNCServiceResponse.params"); - Map<String, String> map = utils.jsonStringToMap(execution, entry); - assertEquals(map.get("e2e-vpn-key"), "my-key"); - } - - @Test - public void entryArrayToMapTest() throws IOException { - JsonUtils utils = new JsonUtils(); - String response = this.getJson("SNIROExample.json"); - String entry = JsonUtils.getJsonValue(response, "solutionInfo.placementInfo"); - JSONArray arr = new JSONArray(entry); - JSONObject homingDataJson = arr.getJSONObject(0); - JSONArray assignmentInfo = homingDataJson.getJSONArray("assignmentInfo"); - Map<String, String> map = utils.entryArrayToMap(execution, assignmentInfo.toString(), "variableName", "variableValue"); - assertEquals(map.get("cloudOwner"), "CloudOwner"); - } - @Test - public void entryArrayToMapStringTest() throws IOException { - JsonUtils utils = new JsonUtils(); - String response = this.getJson("SNIROExample.json"); - String entry = JsonUtils.getJsonValue(response, "solutionInfo.placementInfo"); - JSONArray arr = new JSONArray(entry); - JSONObject homingDataJson = arr.getJSONObject(0); - JSONArray assignmentInfo = homingDataJson.getJSONArray("assignmentInfo"); - Map<String, String> map = utils.entryArrayToMap(assignmentInfo.toString(), "variableName", "variableValue"); - assertEquals(map.get("cloudOwner"), "CloudOwner"); - } - @Test - public void entryArrayToMapStringTestOof() throws IOException { - JsonUtils utils = new JsonUtils(); - String response = this.getJson("OofExample.json"); - String entry = JsonUtils.getJsonValue(response, "solutions.placementSolutions"); - JSONArray arr = new JSONArray(entry); - JSONArray arr2 = arr.getJSONArray(0); - JSONObject homingDataJson = arr2.getJSONObject(0); - JSONArray assignmentInfo = homingDataJson.getJSONArray("assignmentInfo"); - Map<String, String> map = utils.entryArrayToMap(assignmentInfo.toString(), "key", "value"); - assertEquals(map.get("cloudOwner"), "HPA-cloud"); - } - @Test - public void getJsonRootPropertyTest() throws IOException { - String response = this.getJson("SDNCServiceResponseExample.json"); - assertEquals("SDNCServiceResponse",JsonUtils.getJsonRootProperty(response)); - } - @Test - public void getJsonRootProperty_ExceptionTest() throws IOException { - expectedException.expect(JSONException.class); - String response = this.getJson("SNIROExample.json"); - String root = JsonUtils.getJsonRootProperty(response); - } - @Test - public void getJsonNodeValueTest() throws IOException { - String response = this.getJson("SDNCServiceResponseExample.json"); - String code = JsonUtils.getJsonNodeValue(response,"SDNCServiceResponse.responseCode"); - assertEquals("200", code); - } - @Test - public void stringArrayToList_jsonStringTest() throws IOException { - String response = this.getJson("SNIROExample.json"); - String licenseInfo = JsonUtils.getJsonNodeValue(response,"solutionInfo.licenseInfo"); - JsonUtils utils = new JsonUtils(); - List<String> listString = utils.StringArrayToList(licenseInfo); - assertNotNull(listString.get(0)); - } - @Test - public void stringArrayToList_JSONArrayTest() throws IOException { - String response = this.getJson("SNIROExample.json"); - String licenseInfo = JsonUtils.getJsonNodeValue(response,"solutionInfo.licenseInfo"); - JSONArray jsonArray = new JSONArray(licenseInfo); - JsonUtils utils = new JsonUtils(); - List<String> listString = utils.StringArrayToList(jsonArray); - assertNotNull(listString.get(0)); - } - @Test - public void stringArrayToList_withExecutionTest() throws IOException { - String response = this.getJson("SNIROExample.json"); - String licenseInfo = JsonUtils.getJsonNodeValue(response,"solutionInfo.licenseInfo"); - JsonUtils utils = new JsonUtils(); - List<String> listString = utils.StringArrayToList(mockEexecution, licenseInfo); - assertNotNull(listString.get(0)); - } - @Test - public void jsonElementExist_trueTest() throws IOException { - String response = this.getJson("SDNCServiceResponseExample.json"); - boolean isExist = JsonUtils.jsonElementExist(response,"SDNCServiceResponse.responseCode"); - assertEquals(true, isExist); - } - @Test - public void jsonElementExist_falseTest() throws IOException { - String response = this.getJson("SDNCServiceResponseExample.json"); - boolean isExist = JsonUtils.jsonElementExist(response,"SDNCServiceResponse.responseX"); - assertEquals(false, isExist); - } - @Test - public void jsonElementExist_NullTest() throws IOException { - String response = this.getJson("SDNCServiceResponseExample.json"); - boolean isExist = JsonUtils.jsonElementExist(response, null); - assertEquals(true, isExist); - } - @Test - public void jsonSchemaValidation_ExceptionTest() throws IOException, ValidationException { - expectedException.expect(ValidationException.class); - String response = this.getJson("SDNCServiceResponseExample.json"); - String isExist = JsonUtils.jsonSchemaValidation(response, fileLocation); - } - @Test - public void getJsonIntValueTest() throws IOException { - String response = this.getJson("SDNCServiceResponseExample.json"); - int intValue = JsonUtils.getJsonIntValue(response,"SDNCServiceResponse.responseCode"); - assertEquals(0, intValue); - } - @Test - public void getJsonBooleanValueTest() throws IOException { - String response = this.getJson("SDNCServiceResponseExample.json"); - boolean isBoolean = JsonUtils.getJsonBooleanValue(response,"SDNCServiceResponse.responseCode"); - assertEquals(false, isBoolean); - } - @Test - public void prettyJsonTest() throws IOException { - String response = this.getJson("SNIROExample.json"); - assertNotNull(JsonUtils.prettyJson(response)); - String malformedJson = "{\"name\" \"myName\"}"; - assertNull(JsonUtils.prettyJson(malformedJson)); - } - @Test - public void xml2jsonTest() throws IOException { - String expectedJson = "{\"name\":\"myName\"}"; - String xml = "<name>myName</name>"; - assertEquals(expectedJson, JsonUtils.xml2json(xml,false)); - } - @Test - public void xml2jsonErrorTest() throws IOException { - String malformedXml = "<name>myName<name>"; - assertNull(JsonUtils.xml2json(malformedXml)); - } - @Test - public void json2xmlTest() throws IOException { - String expectedXml = "<name>myName</name>"; - String malformedJson = "{\"name\":\"myName\"}"; - assertEquals(expectedXml, JsonUtils.json2xml(malformedJson, false)); - } - @Test - public void json2xmlErrorTest() throws IOException { - String malformedJson = "{\"name\" \"myName\"}"; - assertNull(JsonUtils.json2xml(malformedJson)); - } - @Test - public void getJsonValueErrorTest() throws IOException { - String response = this.getJson("SDNCServiceResponseExample.json"); - assertNull(JsonUtils.getJsonValue(response,null)); - } - @Test - public void getJsonNodeValueErrorTest() throws IOException { - String response = this.getJson("SDNCServiceResponseExample.json"); - assertNull(JsonUtils.getJsonNodeValue(response,null)); - } - @Test - public void getJsonIntValueErrorTest() throws IOException { - String response = this.getJson("SDNCServiceResponseExample.json"); - assertEquals(0, JsonUtils.getJsonIntValue(response,null)); - } - @Test - public void getJsonBooleanValueErrorTest() throws IOException { - String response = this.getJson("SDNCServiceResponseExample.json"); - assertEquals(false, JsonUtils.getJsonBooleanValue(response,null)); - } - @Test - public void getJsonValueForKeyErrorTest() throws IOException { - String malformedJson = "{\"name\" \"myName\"}"; - assertNull(JsonUtils.getJsonValueForKey(malformedJson, "name")); - } - @Test - public void updJsonValueTest() throws IOException { - String expectedJson = "{\"name\": \"yourName\"}"; - String json = "{\"name\":\"myName\"}"; - assertEquals(expectedJson, JsonUtils.updJsonValue(json, "name", "yourName")); - } - @Test - public void updJsonValueErrorTest() throws IOException { - String expectedJson = "{\"name\" \"myName\"}"; - String json = "{\"name\" \"myName\"}"; - assertEquals(expectedJson, JsonUtils.updJsonValue(json, "name", "yourName")); - } - - private String getJson(String filename) throws IOException { - return new String(Files.readAllBytes(Paths.get(fileLocation + filename))); - } + @Mock + public DelegateExecution execution; + @Mock + public Execution mockEexecution; + private final String fileLocation = "src/test/resources/json-examples/"; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void jsonStringToMapTest() throws IOException { + + JsonUtils utils = new JsonUtils(); + String response = this.getJson("SDNCServiceResponseExample.json"); + String entry = JsonUtils.getJsonValue(response, "SDNCServiceResponse.params"); + Map<String, String> map = utils.jsonStringToMap(execution, entry); + assertEquals(map.get("e2e-vpn-key"), "my-key"); + } + + @Test + public void entryArrayToMapTest() throws IOException { + JsonUtils utils = new JsonUtils(); + String response = this.getJson("SNIROExample.json"); + String entry = JsonUtils.getJsonValue(response, "solutionInfo.placementInfo"); + JSONArray arr = new JSONArray(entry); + JSONObject homingDataJson = arr.getJSONObject(0); + JSONArray assignmentInfo = homingDataJson.getJSONArray("assignmentInfo"); + Map<String, String> map = + utils.entryArrayToMap(execution, assignmentInfo.toString(), "variableName", "variableValue"); + assertEquals(map.get("cloudOwner"), "CloudOwner"); + } + + @Test + public void entryArrayToMapStringTest() throws IOException { + JsonUtils utils = new JsonUtils(); + String response = this.getJson("SNIROExample.json"); + String entry = JsonUtils.getJsonValue(response, "solutionInfo.placementInfo"); + JSONArray arr = new JSONArray(entry); + JSONObject homingDataJson = arr.getJSONObject(0); + JSONArray assignmentInfo = homingDataJson.getJSONArray("assignmentInfo"); + Map<String, String> map = utils.entryArrayToMap(assignmentInfo.toString(), "variableName", "variableValue"); + assertEquals(map.get("cloudOwner"), "CloudOwner"); + } + + @Test + public void entryArrayToMapStringTestOof() throws IOException { + JsonUtils utils = new JsonUtils(); + String response = this.getJson("OofExample.json"); + String entry = JsonUtils.getJsonValue(response, "solutions.placementSolutions"); + JSONArray arr = new JSONArray(entry); + JSONArray arr2 = arr.getJSONArray(0); + JSONObject homingDataJson = arr2.getJSONObject(0); + JSONArray assignmentInfo = homingDataJson.getJSONArray("assignmentInfo"); + Map<String, String> map = utils.entryArrayToMap(assignmentInfo.toString(), "key", "value"); + assertEquals(map.get("cloudOwner"), "HPA-cloud"); + } + + @Test + public void getJsonRootPropertyTest() throws IOException { + String response = this.getJson("SDNCServiceResponseExample.json"); + assertEquals("SDNCServiceResponse", JsonUtils.getJsonRootProperty(response)); + } + + @Test + public void getJsonRootProperty_ExceptionTest() throws IOException { + expectedException.expect(JSONException.class); + String response = this.getJson("SNIROExample.json"); + String root = JsonUtils.getJsonRootProperty(response); + } + + @Test + public void getJsonNodeValueTest() throws IOException { + String response = this.getJson("SDNCServiceResponseExample.json"); + String code = JsonUtils.getJsonNodeValue(response, "SDNCServiceResponse.responseCode"); + assertEquals("200", code); + } + + @Test + public void stringArrayToList_jsonStringTest() throws IOException { + String response = this.getJson("SNIROExample.json"); + String licenseInfo = JsonUtils.getJsonNodeValue(response, "solutionInfo.licenseInfo"); + JsonUtils utils = new JsonUtils(); + List<String> listString = utils.StringArrayToList(licenseInfo); + assertNotNull(listString.get(0)); + } + + @Test + public void stringArrayToList_JSONArrayTest() throws IOException { + String response = this.getJson("SNIROExample.json"); + String licenseInfo = JsonUtils.getJsonNodeValue(response, "solutionInfo.licenseInfo"); + JSONArray jsonArray = new JSONArray(licenseInfo); + JsonUtils utils = new JsonUtils(); + List<String> listString = utils.StringArrayToList(jsonArray); + assertNotNull(listString.get(0)); + } + + @Test + public void stringArrayToList_withExecutionTest() throws IOException { + String response = this.getJson("SNIROExample.json"); + String licenseInfo = JsonUtils.getJsonNodeValue(response, "solutionInfo.licenseInfo"); + JsonUtils utils = new JsonUtils(); + List<String> listString = utils.StringArrayToList(mockEexecution, licenseInfo); + assertNotNull(listString.get(0)); + } + + @Test + public void jsonElementExist_trueTest() throws IOException { + String response = this.getJson("SDNCServiceResponseExample.json"); + boolean isExist = JsonUtils.jsonElementExist(response, "SDNCServiceResponse.responseCode"); + assertEquals(true, isExist); + } + + @Test + public void jsonElementExist_falseTest() throws IOException { + String response = this.getJson("SDNCServiceResponseExample.json"); + boolean isExist = JsonUtils.jsonElementExist(response, "SDNCServiceResponse.responseX"); + assertEquals(false, isExist); + } + + @Test + public void jsonElementExist_NullTest() throws IOException { + String response = this.getJson("SDNCServiceResponseExample.json"); + boolean isExist = JsonUtils.jsonElementExist(response, null); + assertEquals(true, isExist); + } + + @Test + public void jsonSchemaValidation_ExceptionTest() throws IOException, ValidationException { + expectedException.expect(ValidationException.class); + String response = this.getJson("SDNCServiceResponseExample.json"); + String isExist = JsonUtils.jsonSchemaValidation(response, fileLocation); + } + + @Test + public void getJsonIntValueTest() throws IOException { + String response = this.getJson("SDNCServiceResponseExample.json"); + int intValue = JsonUtils.getJsonIntValue(response, "SDNCServiceResponse.responseCode"); + assertEquals(0, intValue); + } + + @Test + public void getJsonBooleanValueTest() throws IOException { + String response = this.getJson("SDNCServiceResponseExample.json"); + boolean isBoolean = JsonUtils.getJsonBooleanValue(response, "SDNCServiceResponse.responseCode"); + assertEquals(false, isBoolean); + } + + @Test + public void prettyJsonTest() throws IOException { + String response = this.getJson("SNIROExample.json"); + assertNotNull(JsonUtils.prettyJson(response)); + String malformedJson = "{\"name\" \"myName\"}"; + assertNull(JsonUtils.prettyJson(malformedJson)); + } + + @Test + public void xml2jsonTest() throws IOException { + String expectedJson = "{\"name\":\"myName\"}"; + String xml = "<name>myName</name>"; + assertEquals(expectedJson, JsonUtils.xml2json(xml, false)); + } + + @Test + public void xml2jsonErrorTest() throws IOException { + String malformedXml = "<name>myName<name>"; + assertNull(JsonUtils.xml2json(malformedXml)); + } + + @Test + public void json2xmlTest() throws IOException { + String expectedXml = "<name>myName</name>"; + String malformedJson = "{\"name\":\"myName\"}"; + assertEquals(expectedXml, JsonUtils.json2xml(malformedJson, false)); + } + + @Test + public void json2xmlErrorTest() throws IOException { + String malformedJson = "{\"name\" \"myName\"}"; + assertNull(JsonUtils.json2xml(malformedJson)); + } + + @Test + public void getJsonValueErrorTest() throws IOException { + String response = this.getJson("SDNCServiceResponseExample.json"); + assertNull(JsonUtils.getJsonValue(response, null)); + } + + @Test + public void getJsonNodeValueErrorTest() throws IOException { + String response = this.getJson("SDNCServiceResponseExample.json"); + assertNull(JsonUtils.getJsonNodeValue(response, null)); + } + + @Test + public void getJsonIntValueErrorTest() throws IOException { + String response = this.getJson("SDNCServiceResponseExample.json"); + assertEquals(0, JsonUtils.getJsonIntValue(response, null)); + } + + @Test + public void getJsonBooleanValueErrorTest() throws IOException { + String response = this.getJson("SDNCServiceResponseExample.json"); + assertEquals(false, JsonUtils.getJsonBooleanValue(response, null)); + } + + @Test + public void getJsonValueForKeyErrorTest() throws IOException { + String malformedJson = "{\"name\" \"myName\"}"; + assertNull(JsonUtils.getJsonValueForKey(malformedJson, "name")); + } + + @Test + public void updJsonValueTest() throws IOException { + String expectedJson = "{\"name\": \"yourName\"}"; + String json = "{\"name\":\"myName\"}"; + assertEquals(expectedJson, JsonUtils.updJsonValue(json, "name", "yourName")); + } + + @Test + public void updJsonValueErrorTest() throws IOException { + String expectedJson = "{\"name\" \"myName\"}"; + String json = "{\"name\" \"myName\"}"; + assertEquals(expectedJson, JsonUtils.updJsonValue(json, "name", "yourName")); + } + + private String getJson(String filename) throws IOException { + return new String(Files.readAllBytes(Paths.get(fileLocation + filename))); + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/utils/CamundaDBSetup.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/utils/CamundaDBSetup.java index 15f6fbe008..b6a2e789ba 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/utils/CamundaDBSetup.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/utils/CamundaDBSetup.java @@ -25,7 +25,6 @@ package org.onap.so.bpmn.core.utils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,43 +32,42 @@ import org.slf4j.LoggerFactory; * Sets up the unit test (H2) database for Camunda. */ public class CamundaDBSetup { - private static boolean isDBConfigured = false; - private static final Logger logger = LoggerFactory.getLogger(CamundaDBSetup.class); - - private CamundaDBSetup() { - } - - public static synchronized void configure() throws SQLException { - if (isDBConfigured) { - return; - } + private static boolean isDBConfigured = false; + private static final Logger logger = LoggerFactory.getLogger(CamundaDBSetup.class); + + private CamundaDBSetup() {} + + public static synchronized void configure() throws SQLException { + if (isDBConfigured) { + return; + } + + logger.debug("Configuring the Camunda H2 database for MSO"); - logger.debug ("Configuring the Camunda H2 database for MSO"); + Connection connection = null; + PreparedStatement stmt = null; - Connection connection = null; - PreparedStatement stmt = null; + try { - try { + isDBConfigured = true; - isDBConfigured = true; - - } finally { - if (stmt != null) { - try { - stmt.close(); - } catch (Exception e) { - logger.debug("Exception :",e); - } - } + } finally { + if (stmt != null) { + try { + stmt.close(); + } catch (Exception e) { + logger.debug("Exception :", e); + } + } - if (connection != null) { - try { - connection.close(); - } catch (Exception e) { - logger.debug("Exception :",e); - } - } - } - } + if (connection != null) { + try { + connection.close(); + } catch (Exception e) { + logger.debug("Exception :", e); + } + } + } + } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/xml/XmlToolTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/xml/XmlToolTest.java index 6bad0c6c29..d099cbebcc 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/xml/XmlToolTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/xml/XmlToolTest.java @@ -1,82 +1,72 @@ /* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 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 + * ============LICENSE_START======================================================= ONAP : SO + * ================================================================================ Copyright (C) 2018 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 + * 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. + * 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.so.bpmn.core.xml; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import java.util.Optional; - import org.junit.Test; public class XmlToolTest { - private String response = "<Response>good</Response>"; - private String responseModified = "<Response>veryGood</Response>"; - private String encodeResponse = "<Response>good</Response>"; - private String encodeResponseNamespace = "<Response xmlns:ns2=\"http://ecomp.att.com/mso/request/types/v1\">good</Response>"; - private String attribute = "<Response>good&\"bad\"</Response>"; - private String updatedAttribute = "<Response>good&"bad"</Response>"; + private String response = "<Response>good</Response>"; + private String responseModified = "<Response>veryGood</Response>"; + private String encodeResponse = "<Response>good</Response>"; + private String encodeResponseNamespace = + "<Response xmlns:ns2=\"http://ecomp.att.com/mso/request/types/v1\">good</Response>"; + private String attribute = "<Response>good&\"bad\"</Response>"; + private String updatedAttribute = "<Response>good&"bad"</Response>"; + + private String content = "<dummy><configuration-event>" + "<event-type>test</event-type>" + + "<event-correlator-type>test</event-correlator-type>" + "<event-correlator>123</event-correlator>" + + "<event-parameters><event-parameter>" + "<tag-name>test</tag-name>" + + "<tag-value>test</tag-value></event-parameter></event-parameters>" + "</configuration-event></dummy>"; + + @Test + public void test() throws Exception { + Object xmlMessage = new String(response); + String xmlResponse = XmlTool.normalize(xmlMessage); + assertEquals(response, xmlResponse.toString()); + String xmlEncode = XmlTool.encode(xmlMessage); + assertEquals(encodeResponse, xmlEncode.toString()); + Optional<String> optXml = XmlTool.modifyElement(response, "Response", "veryGood"); + Object obj1 = new String(optXml.get().toString()); + String noPreamble = XmlTool.removePreamble(obj1); + assertEquals(responseModified, noPreamble.toString()); + Object obj2 = new String(encodeResponseNamespace); + String noNamespace = XmlTool.removeNamespaces(obj2); + assertEquals(response, noNamespace.toString()); + Object obj3 = new String(attribute); - private String content = "<dummy><configuration-event>" + - "<event-type>test</event-type>" + - "<event-correlator-type>test</event-correlator-type>" + - "<event-correlator>123</event-correlator>" + - "<event-parameters><event-parameter>" + - "<tag-name>test</tag-name>" + - "<tag-value>test</tag-value></event-parameter></event-parameters>" + - "</configuration-event></dummy>"; - - @Test - public void test() throws Exception { - Object xmlMessage = new String(response); - String xmlResponse = XmlTool.normalize(xmlMessage); - assertEquals(response, xmlResponse.toString()); - String xmlEncode = XmlTool.encode(xmlMessage); - assertEquals(encodeResponse, xmlEncode.toString()); - Optional<String> optXml = XmlTool.modifyElement(response, "Response", "veryGood"); - Object obj1 = new String(optXml.get().toString()); - String noPreamble = XmlTool.removePreamble(obj1); - assertEquals(responseModified, noPreamble.toString()); - Object obj2 = new String(encodeResponseNamespace); - String noNamespace = XmlTool.removeNamespaces(obj2); - assertEquals(response, noNamespace.toString()); - Object obj3 = new String(attribute); - - assertEquals(null, XmlTool.normalize(null)); - assertEquals(null, XmlTool.encode(null)); - assertEquals(null, XmlTool.removePreamble(null)); - assertEquals(null, XmlTool.removeNamespaces(null)); - assertEquals(Optional.empty(), XmlTool.modifyElement(null, "Response", "veryGood")); - } + assertEquals(null, XmlTool.normalize(null)); + assertEquals(null, XmlTool.encode(null)); + assertEquals(null, XmlTool.removePreamble(null)); + assertEquals(null, XmlTool.removeNamespaces(null)); + assertEquals(Optional.empty(), XmlTool.modifyElement(null, "Response", "veryGood")); + } - @Test - public void normalizeTest() throws Exception { - String response = XmlTool.normalize(content); - assertNotNull(response); - } + @Test + public void normalizeTest() throws Exception { + String response = XmlTool.normalize(content); + assertNotNull(response); + } - @Test - public void modifyElementTest() throws Exception { - String response = XmlTool.modifyElement(content, "event-type", "uCPE-VMS").get(); - assertNotNull(response); - } + @Test + public void modifyElementTest() throws Exception { + String response = XmlTool.modifyElement(content, "event-type", "uCPE-VMS").get(); + assertNotNull(response); + } } |