Add activity spec code 39/59339/4
authortalig <talig@amdocs.com>
Thu, 9 Aug 2018 10:13:23 +0000 (13:13 +0300)
committertalig <talig@amdocs.com>
Thu, 9 Aug 2018 10:13:23 +0000 (13:13 +0300)
Move code from sdc repository and:
1. place according to this project structure
2. refactor DTOs and use mapstruct
3. change errorResponse to be a json instead of a string (for all workflow code)

Change-Id: Ia85590b53ab59ff7600e05b8a6d52e06b1773220
Issue-ID: SDC-1606
Signed-off-by: talig <talig@amdocs.com>
72 files changed:
workflow-bdd/config.json
workflow-bdd/features/ActivitySpec.feature [new file with mode: 0644]
workflow-bdd/features/ActivitySpecStatus.feature [new file with mode: 0644]
workflow-bdd/features/examples/ResponseDataChecks.feature
workflow-bdd/resources/json/createActivitySpec.json [new file with mode: 0644]
workflow-bdd/stepDefinitions/ActivitySpec_steps.js [new file with mode: 0644]
workflow-bdd/stepDefinitions/General_Steps.js
workflow-bdd/stepDefinitions/Utils.js
workflow-bdd/stepDefinitions/world.js
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/ActivitySpecController.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/ExceptionsHandler.java [moved from workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/exceptionshandlers/CustomizedResponseEntityExceptionHandler.java with 57% similarity]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/WorkflowController.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/WorkflowVersionController.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/mappers/ActivitySpecDtoMapper.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/ErrorResponse.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/VersionStateDto.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/VersionStatesFormatter.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecAction.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecActionRequest.java [moved from workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/exceptions/InvalidPaginationParameterException.java with 54% similarity]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecBase.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecCreateResponse.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecDataResponse.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecRequest.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecResponse.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/InternalEmptyObject.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/ActivitySpecRepository.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/impl/ActivitySpecRepositoryImpl.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/impl/ArtifactRepositoryImpl.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/impl/ParameterRepositoryImpl.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/impl/types/ActivitySpecData.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/impl/types/ActivitySpecElementType.java [moved from workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/types/WorkflowProperty.java with 65% similarity]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/impl/types/ParameterPropertyName.java [moved from workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/types/ParameterPropertyName.java with 89% similarity]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/impl/types/WorkflowElementType.java [moved from workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/types/WorkflowElementType.java with 92% similarity]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/types/ActivitySpecEntity.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/types/ActivitySpecParameter.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/server/config/SwaggerConfig.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/ActivitySpecConstant.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/ActivitySpecManager.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/UniqueValueService.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/WorkflowManager.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/WorkflowVersionManager.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/exceptions/VersionStateModificationException.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/exceptions/VersionStatusModificationException.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/ActivitySpecManagerImpl.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/CollaborationConfiguration.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/ItemType.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/WorkflowManagerImpl.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/WorkflowVersionManagerImpl.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/mappers/ActivitySpecMapper.java [new file with mode: 0644]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/mappers/VersionMapper.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/mappers/VersionStateMapper.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/mappers/WorkflowMapper.java
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/types/Workflow.java [moved from workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/types/Workflow.java with 96% similarity]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/types/WorkflowVersion.java [moved from workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/types/WorkflowVersion.java with 93% similarity]
workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/types/WorkflowVersionState.java [moved from workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/types/WorkflowVersionState.java with 95% similarity]
workflow-designer-be/src/main/resources/application-dev.properties
workflow-designer-be/src/main/resources/application.properties
workflow-designer-be/src/test/java/org/onap/sdc/workflow/RestPath.java
workflow-designer-be/src/test/java/org/onap/sdc/workflow/TestUtil.java
workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/WorkflowControllerTest.java
workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/WorkflowVersionControllerTest.java
workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/types/VersionStatesFormatterTest.java
workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ActivitySpecRepositoryImplTest.java [new file with mode: 0644]
workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ArtifactRepositoryTest.java
workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ParameterRepositoryTest.java
workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/UniqueValueServiceTest.java
workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/ActivitySpecManagerImplTest.java [new file with mode: 0644]
workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/WorkflowManagerImplTest.java
workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/WorkflowVersionManagerImplTest.java
workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/mappers/VersionMapperTest.java
workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/mappers/VersionStateMapperTest.java
workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/mappers/WorkflowMapperTest.java

index 260f285..5d38d09 100644 (file)
   "workflow" : {
     "port" : 8080,
     "prefix" : "wf",
-    "server" : "",
+    "server": "wf.server",
     "user" : "user"
   },
   "activity_spec" : {
     "port" : 8080,
-    "prefix" : "activity-spec-api/v1.0",
-    "server" : "activity_spec.server",
+    "prefix": "v1.0",
+    "server": "wf.server",
     "user" : "user"
   }
 }
diff --git a/workflow-bdd/features/ActivitySpec.feature b/workflow-bdd/features/ActivitySpec.feature
new file mode 100644 (file)
index 0000000..7d9a754
--- /dev/null
@@ -0,0 +1,61 @@
+Feature: Activity Spec
+
+   #SDC-6350
+  Scenario: Create
+    When I want to set the input data to file "resources/json/createActivitySpec.json"
+    Then I want to update the input property "name" with a random value
+    When I want to create an ActivitySpec
+
+    Then I want to check property "id" exists
+    And I want to check property "versionId" exists
+
+    And I want to list ActivitySpecs with status "Draft"
+    And I want to check property "total" exists
+
+    And I want to get the ActivitySpec for the current item
+    And I want to check property "status" for value "Draft"
+
+    And I want to call action "CERTIFY" on this ActivitySpec item
+    And I want to get the ActivitySpec for the current item
+    And I want to check property "status" for value "Certified"
+
+    And I want to call action "DEPRECATE" on this ActivitySpec item
+    And I want to get the ActivitySpec for the current item
+    And I want to check property "status" for value "Deprecated"
+
+    And I want to call action "DELETE" on this ActivitySpec item
+    And I want to get the ActivitySpec for the current item
+    And I want to check property "status" for value "Deleted"
+
+  Scenario: Get with invalid Id
+    Then I want to set property "item.id" to value "invalidId"
+    Then I want the following to fail with error message "No Activity Spec found for the given identifiers"
+    And I want to get the ActivitySpec for the current item
+
+   #SDC-6353
+  Scenario: Create with duplicate name - invalid
+    Given I want to set property "duplicateName" with a random value
+    And I want to set the input data to file "resources/json/createActivitySpec.json"
+    And I want to update the input property "name" with value of property "duplicateName"
+    And I want to create an ActivitySpec
+    And I want to check property "id" exists
+    And I want to check property "versionId" exists
+
+    When I want to set the input data to file "resources/json/createActivitySpec.json"
+    And I want to update the input property "name" with value of property "duplicateName"
+    Then I want the following to fail with response status code 422
+    And I want to create an ActivitySpec
+
+   #SDC-6354
+  Scenario: Create with invalid name - invalid
+    Given I want to set the input data to file "resources/json/createActivitySpec.json"
+    And I want to update the input property "name" with value "test!@"
+    Then I want the following to fail with response status code 400
+    When I want to create an ActivitySpec
+
+   #SDC-6355
+  Scenario: Create with null/blank name - invalid
+    Given I want to set the input data to file "resources/json/createActivitySpec.json"
+    And I want to update the input property "name" with value ""
+    Then I want the following to fail with response status code 400
+    When I want to create an ActivitySpec
\ No newline at end of file
diff --git a/workflow-bdd/features/ActivitySpecStatus.feature b/workflow-bdd/features/ActivitySpecStatus.feature
new file mode 100644 (file)
index 0000000..c908701
--- /dev/null
@@ -0,0 +1,21 @@
+Feature: Activity Spec Status
+
+  Scenario: Invalid Status Transition
+    When I want to set the input data to file "resources/json/createActivitySpec.json"
+    Then I want to update the input property "name" with a random value
+    When I want to create an ActivitySpec
+    Then I want to check property "id" exists
+    And I want to check property "versionId" exists
+
+    When I want to get the ActivitySpec for the current item
+    Then I want to check property "status" for value "Draft"
+
+    Then I want the following to fail with response status code 422
+    When I want to call action "DEPRECATE" on this ActivitySpec item
+
+    Then I want the following to fail with response status code 422
+    When I want to call action "DELETE" on this ActivitySpec item
+
+    When I want to call action "CERTIFY" on this ActivitySpec item
+    Then I want the following to fail with response status code 422
+    When I want to call action "CERTIFY" on this ActivitySpec item
\ No newline at end of file
index 2f8ff52..7956e65 100644 (file)
@@ -35,7 +35,7 @@ Feature: Example for checking response data
     }
     """
     # printing out for test purposes
-    Then I want to print the context data
+    #Then I want to print the context data
 
     # running the different options of checking the respone data
     Then I want to check property "field1" for value "string field"
diff --git a/workflow-bdd/resources/json/createActivitySpec.json b/workflow-bdd/resources/json/createActivitySpec.json
new file mode 100644 (file)
index 0000000..bf1b601
--- /dev/null
@@ -0,0 +1,23 @@
+{
+  "name": "RANDOM",
+  "description": "Start Server",
+  "categoryList": [
+    "Server"
+  ],
+  "inputs": [
+    {
+      "name": "host",
+      "type": "string",
+      "value": "10.1.2.3"
+    }
+  ],
+  "outputs": [
+    {
+      "name": "status",
+      "type": "string",
+      "value": "started"
+    }
+  ],
+  "type": "string",
+  "content": "test"
+}
\ No newline at end of file
diff --git a/workflow-bdd/stepDefinitions/ActivitySpec_steps.js b/workflow-bdd/stepDefinitions/ActivitySpec_steps.js
new file mode 100644 (file)
index 0000000..7fe8ddf
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const {Then, When} = require('cucumber');
+const assert = require('assert');
+const util = require('./Utils.js');
+const _ = require('lodash');
+
+When('I want to create an ActivitySpec', function () {
+  let path = '/activity-spec';
+  return util.request(this.context, 'POST', path, this.context.inputData, false, 'activity_spec').then((result)=> {
+    this.context.item = {id : result.data.id, versionId: result.data.versionId};
+    this.context.activityspec = {id : result.data.id, versionId: result.data.versionId};
+  });
+});
+
+When('I want to list ActivitySpecs with status {string}', function (string) {
+  let path = '/activity-spec?status='+string;
+  return util.request(this.context, 'GET', path, null, false, 'activity_spec').then((result)=> {
+    this.context.listCount = result.data.listCount;
+  });
+});
+
+When('I want to get the ActivitySpec for the current item', function () {
+  let path = '/activity-spec/'+ this.context.item.id+'/versions/'+this.context.item.versionId ;
+  return util.request(this.context, 'GET', path, null, false, 'activity_spec').then((result)=> {
+  });
+});
+
+Then('I want to call action {string} on this ActivitySpec item', function(string)  {
+  let path = '/activity-spec/'+ this.context.item.id+'/versions/'+this.context.item.versionId+'/actions' ;
+  let inputData = JSON.parse('{"action" : "' +string+ '"}');
+  return util.request(this.context, 'PUT', path, inputData, false, 'activity_spec')
+});
\ No newline at end of file
index 69a703c..5968d40 100644 (file)
@@ -80,6 +80,16 @@ Then('I want to set property {string} to value {string}', function(string, strin
        _.set(this.context, string, string2);
 });
 
+/**
+ * @module ContextData
+ * @description sets context property to a random value
+ * @exampleFile Example_Rest_Calls.feature
+ * @step I want to update the input property {string} with a random value
+ **/
+Then('I want to set property {string} with a random value', function (string) {
+    _.set(this.context, string, util.random());
+});
+
 /**
  * @module ResponseData
  * @description Will check the output data for a property and a value. property can be a path (example: results[0].id)
index 6f8a7a5..9f39816 100644 (file)
@@ -17,7 +17,7 @@ const request = require('request');
 const fs = require('fs');
 require('node-zip');
 
-function _request(context, method, path, data, isBinary=false, type='onboarding') {
+function _request(context, method, path, data, isBinary=false, type='workflow') {
        let server = context.getUrlForType(type);
 
        let options = {
@@ -106,7 +106,7 @@ function _request(context, method, path, data, isBinary=false, type='onboarding'
        });
 }
 
-function download(context, path, filePath,  callback, type='onboarding') {
+function download(context, path, filePath, callback, type='workflow') {
        let server = context.getUrlForType(type);
        let options = {
                        method: 'GET',
index cf749e6..4c50b0c 100644 (file)
@@ -70,7 +70,7 @@ class CustomWorld {
                        var _server = context.server;
                        var _config = config;
                        return function(type) {
-                               let typeData = _config["workflow"];
+                let typeData = _config[type];
                                let _url = _config.protocol + '://' +
                                        typeData.server + ':' +
                                        typeData.port + '/' +
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/ActivitySpecController.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/ActivitySpecController.java
new file mode 100644 (file)
index 0000000..dca6c69
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.api;
+
+import static org.onap.sdc.workflow.api.RestParams.USER_ID_HEADER;
+import static org.onap.sdc.workflow.services.ActivitySpecConstant.VERSION_ID_DEFAULT_VALUE;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import javax.validation.Valid;
+import org.onap.sdc.workflow.api.mappers.ActivitySpecDtoMapper;
+import org.onap.sdc.workflow.api.types.CollectionResponse;
+import org.onap.sdc.workflow.api.types.activityspec.ActivitySpecActionRequest;
+import org.onap.sdc.workflow.api.types.activityspec.ActivitySpecCreateResponse;
+import org.onap.sdc.workflow.api.types.activityspec.ActivitySpecDataResponse;
+import org.onap.sdc.workflow.api.types.activityspec.ActivitySpecRequest;
+import org.onap.sdc.workflow.api.types.activityspec.ActivitySpecResponse;
+import org.onap.sdc.workflow.persistence.types.ActivitySpecEntity;
+import org.onap.sdc.workflow.services.ActivitySpecManager;
+import org.openecomp.sdc.versioning.dao.types.Version;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+@RequestMapping(value = "/v1.0/activity-spec")
+@Api("Activity Specs")
+@RestController("activitySpecController")
+@Validated
+public class ActivitySpecController {
+
+    private final ActivitySpecManager activitySpecManager;
+    private final ActivitySpecDtoMapper activitySpecDtoMapper;
+
+    @Autowired
+    public ActivitySpecController(@Qualifier("activitySpecManager") ActivitySpecManager activitySpecManager,
+            ActivitySpecDtoMapper activitySpecDtoMapper) {
+        this.activitySpecManager = activitySpecManager;
+        this.activitySpecDtoMapper = activitySpecDtoMapper;
+    }
+
+    @GetMapping
+    @ApiOperation(value = "List activity specs", responseContainer = "List")
+    @ApiImplicitParam(name = USER_ID_HEADER, required = true, dataType = "string", paramType = "header")
+    public CollectionResponse<ActivitySpecResponse> list(@ApiParam(value = "List activity specs based on status filter",
+            allowableValues = "Draft,Certified,Deprecated,Deleted") @RequestParam(name = "status", required = false)
+                                                                 String versionStatus) {
+        return new CollectionResponse<>(
+                activitySpecManager.list(versionStatus).stream().map(activitySpecDtoMapper::toActivitySpecResponse)
+                        .collect(Collectors.toList()));
+    }
+
+    @PostMapping
+    @ApiOperation(value = "Create Activity Spec")
+    @ApiImplicitParam(name = USER_ID_HEADER, required = true, dataType = "string", paramType = "header")
+    public ResponseEntity<ActivitySpecCreateResponse> create(@Valid @RequestBody ActivitySpecRequest request) {
+        ActivitySpecEntity activitySpec =
+                activitySpecManager.createActivitySpec(activitySpecDtoMapper.fromActivitySpecRequest(request));
+        return new ResponseEntity<>(new ActivitySpecCreateResponse(activitySpec.getId(),
+                Objects.nonNull(activitySpec.getVersion()) ? activitySpec.getVersion().getId() : null),
+                HttpStatus.CREATED);
+    }
+
+    @GetMapping("/{id}/versions/{versionId}")
+    @ApiOperation(value = "Get Activity Spec")
+    @ApiImplicitParam(name = USER_ID_HEADER, required = true, dataType = "string", paramType = "header")
+    public ActivitySpecDataResponse get(@ApiParam(value = "Activity Spec Id") @PathVariable("id") String activitySpecId,
+            @ApiParam(value = "Version Id", defaultValue = VERSION_ID_DEFAULT_VALUE) @PathVariable("versionId")
+                    String versionId) {
+        return activitySpecDtoMapper.toActivitySpecDataResponse(
+                activitySpecManager.get(new ActivitySpecEntity(activitySpecId, new Version(versionId))));
+    }
+
+    @PutMapping("/{id}/versions/{versionId}")
+    @ApiOperation(value = "Update Activity Spec")
+    @ApiImplicitParam(name = USER_ID_HEADER, required = true, dataType = "string", paramType = "header")
+    public void update(@Valid @RequestBody ActivitySpecRequest request,
+            @ApiParam(value = "Activity Spec Id") @PathVariable("id") String activitySpecId,
+            @ApiParam(value = "Version Id", defaultValue = VERSION_ID_DEFAULT_VALUE) @PathVariable("versionId")
+                    String versionId) {
+        ActivitySpecEntity activitySpec = activitySpecDtoMapper.fromActivitySpecRequest(request);
+        activitySpec.setId(activitySpecId);
+        activitySpec.setVersion(new Version(versionId));
+
+        activitySpecManager.update(activitySpec);
+    }
+
+    @PutMapping("/{id}/versions/{versionId}/actions")
+    @ApiOperation(value = "Actions on a activity spec",
+            notes = "Performs one of the following actions on a activity spec: |" + "CERTIFY: Certifies activity spec.|"
+                            + "DEPRECATE: Deprecates activity spec.|" + "DELETE: Deletes activity spec.")
+    @ApiImplicitParam(name = USER_ID_HEADER, required = true, dataType = "string", paramType = "header")
+    public void actOn(@Valid @RequestBody ActivitySpecActionRequest request,
+            @ApiParam(value = "Activity Spec Id") @PathVariable("id") String activitySpecId,
+            @ApiParam(value = "Version Id", defaultValue = VERSION_ID_DEFAULT_VALUE) @PathVariable("versionId")
+                    String versionId) {
+        activitySpecManager
+                .actOnAction(new ActivitySpecEntity(activitySpecId, new Version(versionId)), request.getAction());
+    }
+}
  * limitations under the License.
  */
 
-package org.onap.sdc.workflow.api.exceptionshandlers;
+package org.onap.sdc.workflow.api;
 
 import static org.springframework.http.HttpStatus.BAD_REQUEST;
 import static org.springframework.http.HttpStatus.FORBIDDEN;
+import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
 import static org.springframework.http.HttpStatus.NOT_FOUND;
 import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY;
 
+import org.onap.sdc.workflow.api.types.ErrorResponse;
 import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException;
 import org.onap.sdc.workflow.services.exceptions.InvalidArtifactException;
-import org.onap.sdc.workflow.services.exceptions.InvalidPaginationParameterException;
 import org.onap.sdc.workflow.services.exceptions.UniqueValueViolationException;
 import org.onap.sdc.workflow.services.exceptions.VersionCreationException;
 import org.onap.sdc.workflow.services.exceptions.VersionModificationException;
 import org.onap.sdc.workflow.services.exceptions.VersionStateModificationException;
+import org.onap.sdc.workflow.services.exceptions.VersionStatusModificationException;
 import org.springframework.context.support.DefaultMessageSourceResolvable;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
-import org.springframework.validation.FieldError;
 import org.springframework.web.bind.MethodArgumentNotValidException;
 import org.springframework.web.bind.ServletRequestBindingException;
 import org.springframework.web.bind.annotation.ControllerAdvice;
 import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.ResponseStatus;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.context.request.WebRequest;
 import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
 
 @ControllerAdvice
 @RestController
-public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
-
-    @ExceptionHandler(UniqueValueViolationException.class)
-    public final ResponseEntity<String> handleUniqueValueViolationException(
-            UniqueValueViolationException exception) {
-        return new ResponseEntity<>(exception.getMessage(), UNPROCESSABLE_ENTITY);
-    }
+public class ExceptionsHandler extends ResponseEntityExceptionHandler {
 
     @ExceptionHandler(EntityNotFoundException.class)
-    public final ResponseEntity<String> handleWorkflowNotFoundException(
-            Exception exception) {
-        return new ResponseEntity<>(exception.getMessage(), NOT_FOUND);
+    public final ResponseEntity<ErrorResponse> handleNotFoundException(Exception exception) {
+        return new ResponseEntity<>(new ErrorResponse(exception.getMessage()), NOT_FOUND);
     }
 
-    @ExceptionHandler({InvalidPaginationParameterException.class})
-    public final ResponseEntity<String> handlePaginationException(InvalidPaginationParameterException exception) {
-        return new ResponseEntity<>(exception.getMessage(), BAD_REQUEST);
+    @ExceptionHandler({InvalidArtifactException.class, VersionModificationException.class,
+            VersionStateModificationException.class, VersionStatusModificationException.class,
+            UniqueValueViolationException.class})
+    public final ResponseEntity<ErrorResponse> handleUnprocessableEntityException(Exception exception) {
+        return new ResponseEntity<>(new ErrorResponse(exception.getMessage()), UNPROCESSABLE_ENTITY);
     }
 
-    @Override
-    protected final ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException exception,
-            final HttpHeaders headers,
-            final HttpStatus status,
-            final WebRequest request) {
-
-        String errorMsg = exception.getBindingResult().getFieldErrors().stream()
-                                   .map(DefaultMessageSourceResolvable::getDefaultMessage)
-                                   .findFirst()
-                                   .orElse(exception.getMessage());
+    @ExceptionHandler(VersionCreationException.class)
+    public final ResponseEntity<ErrorResponse> handleVersioningErrorException(VersionCreationException exception) {
+        return new ResponseEntity<>(new ErrorResponse(exception.getMessage()), FORBIDDEN);
+    }
 
-        return new ResponseEntity<>(errorMsg, BAD_REQUEST);
+    @ExceptionHandler(Exception.class)
+    public final ResponseEntity<ErrorResponse> handleUnexpectedException(Exception exception) {
+        return new ResponseEntity<>(new ErrorResponse(exception.getMessage()), INTERNAL_SERVER_ERROR);
     }
 
     //For missing header exceptions
     @Override
     public ResponseEntity<Object> handleServletRequestBindingException(ServletRequestBindingException ex,
-                                                                       HttpHeaders headers, HttpStatus status,
-                                                                       WebRequest request) {
-        return new ResponseEntity<>(ex.getMessage(), BAD_REQUEST);
-    }
-
-
-    @ExceptionHandler({InvalidArtifactException.class, VersionModificationException.class,
-            VersionStateModificationException.class})
-    public final ResponseEntity<String> handleInvalidArtifactException(
-            Exception exception) {
-        return new ResponseEntity<>(exception.getMessage(), UNPROCESSABLE_ENTITY);
+            HttpHeaders headers, HttpStatus status, WebRequest request) {
+        return new ResponseEntity<>(new ErrorResponse(ex.getMessage()), BAD_REQUEST);
     }
 
+    @Override
+    protected final ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException exception,
+            final HttpHeaders headers,
+            final HttpStatus status,
+            final WebRequest request) {
 
-    @ExceptionHandler(VersionCreationException.class)
-    public final ResponseEntity<String> handleVersioningErrorException(
-            VersionCreationException exception) {
-        return new ResponseEntity<>(exception.getMessage(), FORBIDDEN);
+        String errorMsg = exception.getBindingResult().getFieldErrors().stream()
+                                  .map(DefaultMessageSourceResolvable::getDefaultMessage).findFirst()
+                                  .orElse(exception.getMessage());
+        return new ResponseEntity<>(new ErrorResponse(errorMsg), BAD_REQUEST);
     }
 }
index 690b207..18288e2 100644 (file)
@@ -31,13 +31,13 @@ import io.swagger.annotations.ApiParam;
 import org.onap.sdc.workflow.api.types.Paging;
 import org.onap.sdc.workflow.api.types.Sorting;
 import org.onap.sdc.workflow.api.types.VersionStatesFormatter;
-import org.onap.sdc.workflow.persistence.types.Workflow;
 import org.onap.sdc.workflow.services.WorkflowManager;
 import org.onap.sdc.workflow.services.WorkflowVersionManager;
 import org.onap.sdc.workflow.services.types.Page;
 import org.onap.sdc.workflow.services.types.PagingRequest;
 import org.onap.sdc.workflow.services.types.RequestSpec;
 import org.onap.sdc.workflow.services.types.SortingRequest;
+import org.onap.sdc.workflow.services.types.Workflow;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.http.HttpStatus;
@@ -55,10 +55,11 @@ import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.RestController;
 import springfox.documentation.annotations.ApiIgnore;
 
-@RequestMapping("/workflows")
+@RequestMapping("/wf/workflows")
 @Api("Workflows")
 @RestController("workflowController")
 public class WorkflowController {
+
     private final WorkflowManager workflowManager;
     private final WorkflowVersionManager workflowVersionManager;
 
@@ -71,9 +72,8 @@ public class WorkflowController {
 
     @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
     @ApiOperation("List workflows")
-    @ApiImplicitParams({
-            @ApiImplicitParam(name = "versionState", dataType = "string", paramType = "query",
-                    allowableValues = "DRAFT,CERTIFIED", value = "Filter by version state"),
+    @ApiImplicitParams({@ApiImplicitParam(name = "versionState", dataType = "string", paramType = "query",
+            allowableValues = "DRAFT,CERTIFIED", value = "Filter by version state"),
             @ApiImplicitParam(name = OFFSET, dataType = "string", paramType = "query", defaultValue = "0",
                     value = "Index of the starting item"),
             @ApiImplicitParam(name = LIMIT, dataType = "string", paramType = "query", defaultValue = "200",
@@ -81,10 +81,8 @@ public class WorkflowController {
             @ApiImplicitParam(name = SORT, dataType = "string", paramType = "query", defaultValue = "name:asc",
                     value = "Sorting criteria in the format: property:(asc|desc). Default sort order is ascending.",
                     allowableValues = "name:asc,name:desc")})
-    public Page<Workflow> list(@ApiIgnore VersionStatesFormatter versionStateFilter,
-            @ApiIgnore Paging paging,
-            @ApiIgnore Sorting sorting,
-            @RequestHeader(USER_ID_HEADER) String user) {
+    public Page<Workflow> list(@ApiIgnore VersionStatesFormatter versionStateFilter, @ApiIgnore Paging paging,
+            @ApiIgnore Sorting sorting, @RequestHeader(USER_ID_HEADER) String user) {
         return workflowManager.list(versionStateFilter.getVersionStates(), initRequestSpec(paging, sorting));
     }
 
@@ -104,8 +102,8 @@ public class WorkflowController {
         Workflow workflow = new Workflow();
         workflow.setId(workflowId);
         Workflow retrievedWorkflow = workflowManager.get(workflow);
-        if("versions".equals(expand)){
-            retrievedWorkflow.setVersions(workflowVersionManager.list(workflowId,null));
+        if ("versions".equals(expand)) {
+            retrievedWorkflow.setVersions(workflowVersionManager.list(workflowId, null));
         }
         return retrievedWorkflow;
     }
index 35b4959..f869ce0 100644 (file)
@@ -21,15 +21,14 @@ import static org.onap.sdc.workflow.api.RestParams.USER_ID_HEADER;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiImplicitParam;
 import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
 import javax.validation.Valid;
 import org.onap.sdc.workflow.api.types.CollectionResponse;
 import org.onap.sdc.workflow.api.types.VersionStateDto;
-import org.onap.sdc.workflow.api.types.dto.ArtifactDeliveriesRequestDto;
 import org.onap.sdc.workflow.api.types.VersionStatesFormatter;
+import org.onap.sdc.workflow.api.types.dto.ArtifactDeliveriesRequestDto;
 import org.onap.sdc.workflow.persistence.types.ArtifactEntity;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersion;
 import org.onap.sdc.workflow.services.WorkflowVersionManager;
+import org.onap.sdc.workflow.services.types.WorkflowVersion;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.core.io.InputStreamResource;
@@ -51,7 +50,7 @@ import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.multipart.MultipartFile;
 import springfox.documentation.annotations.ApiIgnore;
 
-@RequestMapping("/workflows/{workflowId}/versions")
+@RequestMapping("/wf/workflows/{workflowId}/versions")
 @Api("Workflow versions")
 @RestController("workflowsVersionController")
 public class WorkflowVersionController {
@@ -60,17 +59,16 @@ public class WorkflowVersionController {
     private final ArtifactAssociationService associationHandler;
 
     @Autowired
-    public WorkflowVersionController(
-            @Qualifier("workflowVersionManager") WorkflowVersionManager workflowVersionManager,
+    public WorkflowVersionController(@Qualifier("workflowVersionManager") WorkflowVersionManager workflowVersionManager,
             @Qualifier("ArtifactAssociationHandler") ArtifactAssociationService artifatcAssociationHandler) {
         this.workflowVersionManager = workflowVersionManager;
         this.associationHandler = artifatcAssociationHandler;
     }
 
-    @ApiImplicitParam(name = "state", dataType = "string", paramType = "query", allowableValues = "DRAFT,CERTIFIED",
-            value = "Filter by state")
     @GetMapping
     @ApiOperation("List workflow versions")
+    @ApiImplicitParam(name = "state", dataType = "string", paramType = "query", allowableValues = "DRAFT,CERTIFIED",
+            value = "Filter by state")
     public CollectionResponse<WorkflowVersion> list(@PathVariable("workflowId") String workflowId,
             @ApiIgnore VersionStatesFormatter stateFilter, @RequestHeader(USER_ID_HEADER) String user) {
         return new CollectionResponse<>(workflowVersionManager.list(workflowId, stateFilter.getVersionStates()));
@@ -119,10 +117,11 @@ public class WorkflowVersionController {
 
     @PostMapping("/{versionId}/artifact-deliveries")
     @ApiOperation("upload of artifact to VF operation workflow")
-    public ResponseEntity<String> artifactDeliveries(@RequestBody ArtifactDeliveriesRequestDto deliveriesRequestDto, @PathVariable("workflowId") String workflowId,
-            @PathVariable("versionId") String versionId, @RequestHeader(USER_ID_HEADER) String user) {
-        return associationHandler.execute(user, deliveriesRequestDto,
-                workflowVersionManager.getArtifact(workflowId, versionId));
+    public ResponseEntity<String> artifactDeliveries(@RequestBody ArtifactDeliveriesRequestDto deliveriesRequestDto,
+            @PathVariable("workflowId") String workflowId, @PathVariable("versionId") String versionId,
+            @RequestHeader(USER_ID_HEADER) String user) {
+        return associationHandler
+                       .execute(user, deliveriesRequestDto, workflowVersionManager.getArtifact(workflowId, versionId));
     }
 
     @PutMapping("/{versionId}/artifact")
@@ -139,9 +138,9 @@ public class WorkflowVersionController {
         ArtifactEntity artifact = workflowVersionManager.getArtifact(workflowId, versionId);
 
         return ResponseEntity.ok()
-                             .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + artifact.getFileName())
-                             .contentType(MediaType.APPLICATION_OCTET_STREAM)
-                             .body(new InputStreamResource(artifact.getArtifactData()));
+                       .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + artifact.getFileName())
+                       .contentType(MediaType.APPLICATION_OCTET_STREAM)
+                       .body(new InputStreamResource(artifact.getArtifactData()));
     }
 
     @DeleteMapping("/{versionId}/artifact")
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/mappers/ActivitySpecDtoMapper.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/mappers/ActivitySpecDtoMapper.java
new file mode 100644 (file)
index 0000000..cea7c87
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright © 2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.api.mappers;
+
+import org.mapstruct.Mapper;
+import org.onap.sdc.workflow.api.types.activityspec.ActivitySpecDataResponse;
+import org.onap.sdc.workflow.api.types.activityspec.ActivitySpecRequest;
+import org.onap.sdc.workflow.api.types.activityspec.ActivitySpecResponse;
+import org.onap.sdc.workflow.persistence.types.ActivitySpecEntity;
+
+@Mapper(componentModel = "spring")
+public interface ActivitySpecDtoMapper {
+
+    ActivitySpecResponse toActivitySpecResponse(ActivitySpecEntity activitySpec);
+
+    ActivitySpecDataResponse toActivitySpecDataResponse(ActivitySpecEntity activitySpec);
+
+    ActivitySpecEntity fromActivitySpecRequest(ActivitySpecRequest request);
+
+}
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/ErrorResponse.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/ErrorResponse.java
new file mode 100644 (file)
index 0000000..1b8fb3c
--- /dev/null
@@ -0,0 +1,11 @@
+package org.onap.sdc.workflow.api.types;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+@Getter
+@AllArgsConstructor
+public class ErrorResponse {
+
+    private String message;
+}
index a7f43cd..147ca50 100644 (file)
@@ -18,7 +18,7 @@ package org.onap.sdc.workflow.api.types;
 
 import java.util.List;
 import lombok.Data;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
+import org.onap.sdc.workflow.services.types.WorkflowVersionState;
 
 @Data
 public class VersionStateDto {
index c9d3bf1..18ed50c 100644 (file)
@@ -5,7 +5,7 @@ import java.util.Collections;
 import java.util.Set;
 import java.util.stream.Collectors;
 import lombok.Getter;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
+import org.onap.sdc.workflow.services.types.WorkflowVersionState;
 import org.openecomp.sdc.logging.api.Logger;
 import org.openecomp.sdc.logging.api.LoggerFactory;
 
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecAction.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecAction.java
new file mode 100644 (file)
index 0000000..87a97ff
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.api.types.activityspec;
+
+public enum ActivitySpecAction {
+    CERTIFY, DEPRECATE, DELETE
+}
\ No newline at end of file
@@ -1,11 +1,11 @@
 /*
- * Copyright © 2018 European Support Limited
+ * Copyright © 2016-2018 European Support Limited
  *
  * 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,
  * limitations under the License.
  */
 
-package org.onap.sdc.workflow.services.exceptions;
+package org.onap.sdc.workflow.api.types.activityspec;
 
-public class InvalidPaginationParameterException extends RuntimeException {
+import javax.validation.constraints.NotNull;
 
-    public InvalidPaginationParameterException(String parameterName, String parameterValue, String message) {
-        super(String.format("Requested %s: %s %s", parameterName, parameterValue, message));
-    }
-}
\ No newline at end of file
+@lombok.Data
+public class ActivitySpecActionRequest {
+
+    @NotNull
+    private ActivitySpecAction action;
+}
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecBase.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecBase.java
new file mode 100644 (file)
index 0000000..aa2a0ab
--- /dev/null
@@ -0,0 +1,15 @@
+package org.onap.sdc.workflow.api.types.activityspec;
+
+import java.util.List;
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.Pattern;
+import lombok.Data;
+
+@Data
+abstract class ActivitySpecBase {
+
+    @NotBlank(message = "Mandatory name field is missing")
+    @Pattern(regexp = "^[a-zA-Z0-9-]*$", message = "name should match with \"^[a-zA-Z0-9-]*$\" pattern")
+    private String name;
+    private List<String> categoryList;
+}
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecCreateResponse.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecCreateResponse.java
new file mode 100644 (file)
index 0000000..895c74e
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.api.types.activityspec;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+@Getter
+@AllArgsConstructor
+public class ActivitySpecCreateResponse {
+
+    private String id;
+    private String versionId;
+}
+
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecDataResponse.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecDataResponse.java
new file mode 100644 (file)
index 0000000..d4b1003
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.api.types.activityspec;
+
+import lombok.EqualsAndHashCode;
+
+@lombok.Data
+@EqualsAndHashCode(callSuper = true)
+public class ActivitySpecDataResponse extends ActivitySpecRequest {
+
+    private String id;
+    private String status;
+}
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecRequest.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecRequest.java
new file mode 100644 (file)
index 0000000..fd29fdf
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.api.types.activityspec;
+
+import io.swagger.annotations.ApiModel;
+import java.util.List;
+import lombok.EqualsAndHashCode;
+import org.onap.sdc.workflow.persistence.types.ActivitySpecParameter;
+
+@ApiModel(value = "ActivitySpecRequest")
+@lombok.Data
+@EqualsAndHashCode(callSuper = true)
+public class ActivitySpecRequest extends ActivitySpecBase {
+
+    private String description;
+    private List<ActivitySpecParameter> inputs;
+    private List<ActivitySpecParameter> outputs;
+    private String type;
+    private String content;
+}
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecResponse.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/ActivitySpecResponse.java
new file mode 100644 (file)
index 0000000..a061b3f
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.api.types.activityspec;
+
+import lombok.EqualsAndHashCode;
+
+@lombok.Data
+@EqualsAndHashCode(callSuper = true)
+public class ActivitySpecResponse extends ActivitySpecBase {
+
+    private String id;
+    private String status;
+}
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/InternalEmptyObject.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/types/activityspec/InternalEmptyObject.java
new file mode 100644 (file)
index 0000000..efbd440
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.api.types.activityspec;
+
+import org.codehaus.jackson.annotate.JsonAutoDetect;
+
+/**
+ * Object of this class can be used to create empty Response body like "{}".
+ */
+@JsonAutoDetect
+public class InternalEmptyObject {
+
+}
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/ActivitySpecRepository.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/ActivitySpecRepository.java
new file mode 100644 (file)
index 0000000..f8f1d9a
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.persistence;
+
+import org.onap.sdc.workflow.persistence.types.ActivitySpecEntity;
+
+public interface ActivitySpecRepository {
+
+    void create(ActivitySpecEntity activitySpec);
+
+    ActivitySpecEntity get(ActivitySpecEntity activitySpec);
+
+    void update(ActivitySpecEntity activitySpec);
+}
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/impl/ActivitySpecRepositoryImpl.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/impl/ActivitySpecRepositoryImpl.java
new file mode 100644 (file)
index 0000000..05f2031
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.persistence.impl;
+
+import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement;
+import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext;
+
+import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element;
+import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement;
+import com.amdocs.zusammen.datatypes.SessionContext;
+import com.amdocs.zusammen.datatypes.item.Action;
+import com.amdocs.zusammen.datatypes.item.ElementContext;
+import com.amdocs.zusammen.datatypes.item.Info;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.util.Objects;
+import java.util.Optional;
+import org.onap.sdc.workflow.persistence.ActivitySpecRepository;
+import org.onap.sdc.workflow.persistence.impl.types.ActivitySpecData;
+import org.onap.sdc.workflow.persistence.impl.types.ActivitySpecElementType;
+import org.onap.sdc.workflow.persistence.types.ActivitySpecEntity;
+import org.onap.sdc.workflow.services.ActivitySpecConstant;
+import org.openecomp.core.utilities.json.JsonUtil;
+import org.openecomp.core.zusammen.api.ZusammenAdaptor;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public class ActivitySpecRepositoryImpl implements ActivitySpecRepository {
+
+    private final ZusammenAdaptor zusammenAdaptor;
+
+    @Autowired
+    public ActivitySpecRepositoryImpl(ZusammenAdaptor zusammenAdaptor) {
+        this.zusammenAdaptor = zusammenAdaptor;
+    }
+
+    @Override
+    public void create(ActivitySpecEntity activitySpec) {
+        SessionContext context = createSessionContext();
+        ZusammenElement generalElement = mapActivityDetailsToZusammenElement(activitySpec, Action.CREATE);
+
+        ElementContext elementContext = new ElementContext(activitySpec.getId(), activitySpec.getVersion().getId());
+        zusammenAdaptor
+                .saveElement(context, elementContext, generalElement, "Create Activity Spec General Info Element");
+    }
+
+    @Override
+    public ActivitySpecEntity get(ActivitySpecEntity entity) {
+        SessionContext context = createSessionContext();
+
+        ElementContext elementContext = new ElementContext(entity.getId(), entity.getVersion().getId());
+        Optional<Element> element =
+                zusammenAdaptor.getElementByName(context, elementContext, null, ActivitySpecElementType.ACTIVITYSPEC.name());
+        return element.map(this::mapZusammenElementToActivityDetails).orElse(null);
+    }
+
+    @Override
+    public void update(ActivitySpecEntity entity) {
+        SessionContext context = createSessionContext();
+        ZusammenElement generalElement = mapActivityDetailsToZusammenElement(entity, Action.UPDATE);
+
+        ElementContext elementContext = new ElementContext(entity.getId(), entity.getVersion().getId());
+        zusammenAdaptor
+                .saveElement(context, elementContext, generalElement, "Update Activity Spec General Info Element");
+    }
+
+    private ZusammenElement mapActivityDetailsToZusammenElement(ActivitySpecEntity entity, Action action) {
+        ZusammenElement generalElement = buildStructuralElement(ActivitySpecElementType.ACTIVITYSPEC.name(), action);
+
+        enrichElementInfoFromEntity(generalElement, entity);
+        enrichElementDataFromEntity(generalElement, entity);
+        return generalElement;
+    }
+
+    private void enrichElementInfoFromEntity(ZusammenElement element, ActivitySpecEntity entity) {
+        element.getInfo().addProperty(InfoPropertyName.DESCRIPTION.getValue(), entity.getDescription());
+        element.getInfo().addProperty(InfoPropertyName.NAME.getValue(), entity.getName());
+        element.getInfo().addProperty(InfoPropertyName.CATEGORY.getValue(), entity.getCategoryList());
+    }
+
+    private void enrichElementDataFromEntity(ZusammenElement element, ActivitySpecEntity entity) {
+        ActivitySpecData activitySpecData = new ActivitySpecData();
+        activitySpecData.setInputs(entity.getInputs());
+        activitySpecData.setOutputs(entity.getOutputs());
+        activitySpecData.setType(entity.getType());
+        activitySpecData.setContent(entity.getContent());
+        element.setData(new ByteArrayInputStream(JsonUtil.object2Json(activitySpecData).getBytes()));
+    }
+
+    private ActivitySpecEntity mapZusammenElementToActivityDetails(Element element) {
+        ActivitySpecEntity entity = new ActivitySpecEntity();
+        entity.setId(element.getElementId().getValue());
+        enrichEntityFromElementData(entity, element.getData());
+        enrichEntityFromElementInfo(entity, element.getInfo());
+        return entity;
+    }
+
+    private void enrichEntityFromElementData(ActivitySpecEntity entity, InputStream data) {
+        ActivitySpecData activitySpecData = JsonUtil.json2Object(data, ActivitySpecData.class);
+        if (Objects.nonNull(activitySpecData)) {
+            entity.setInputs(activitySpecData.getInputs());
+            entity.setOutputs(activitySpecData.getOutputs());
+            entity.setType(activitySpecData.getType());
+            entity.setContent(activitySpecData.getContent());
+        }
+    }
+
+    private void enrichEntityFromElementInfo(ActivitySpecEntity entity, Info info) {
+        entity.setName(info.getProperty(InfoPropertyName.NAME.getValue()));
+        entity.setDescription(info.getProperty(InfoPropertyName.DESCRIPTION.getValue()));
+        entity.setCategoryList(info.getProperty(InfoPropertyName.CATEGORY.getValue()));
+    }
+
+    public enum InfoPropertyName {
+        DESCRIPTION("description"), NAME("name"), CATEGORY(ActivitySpecConstant.CATEGORY_ATTRIBUTE_NAME);
+
+        private final String value;
+
+        InfoPropertyName(String value) {
+            this.value = value;
+        }
+
+        public String getValue() {
+            return value;
+        }
+    }
+
+}
index b49433c..06e2a63 100644 (file)
@@ -33,9 +33,9 @@ import java.util.Optional;
 import org.apache.commons.io.IOUtils;
 import org.onap.sdc.workflow.persistence.ArtifactRepository;
 import org.onap.sdc.workflow.persistence.types.ArtifactEntity;
-import org.onap.sdc.workflow.persistence.types.WorkflowElementType;
+import org.onap.sdc.workflow.persistence.impl.types.WorkflowElementType;
 import org.openecomp.core.zusammen.api.ZusammenAdaptor;
-import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Repository;
 
 @Repository
@@ -43,8 +43,13 @@ public class ArtifactRepositoryImpl implements ArtifactRepository {
 
     private static final String FILE_NAME_PROPERTY = "fileName";
     private static final String EMPTY_DATA = "{}";
-    private ZusammenAdaptor zusammenAdaptor = ZusammenAdaptorFactory.getInstance().createInterface();
 
+    private final ZusammenAdaptor zusammenAdaptor;
+
+    @Autowired
+    public ArtifactRepositoryImpl(ZusammenAdaptor zusammenAdaptor) {
+        this.zusammenAdaptor = zusammenAdaptor;
+    }
 
     @Override
     public void update(String workflowId, String versionId, ArtifactEntity artifactEntity) {
@@ -113,8 +118,7 @@ public class ArtifactRepositoryImpl implements ArtifactRepository {
         artifactElement.setData(new ByteArrayInputStream(EMPTY_DATA.getBytes()));
         artifactElement.getInfo().getProperties().remove(FILE_NAME_PROPERTY);
 
-        zusammenAdaptor
-                .saveElement(context, elementContext, artifactElement, "Delete WorkflowVersion Artifact Data");
+        zusammenAdaptor.saveElement(context, elementContext, artifactElement, "Delete WorkflowVersion Artifact Data");
 
     }
 
index 468e93f..483c709 100644 (file)
@@ -33,19 +33,24 @@ import java.util.Optional;
 import java.util.stream.Collectors;
 import org.onap.sdc.workflow.persistence.ParameterRepository;
 import org.onap.sdc.workflow.persistence.types.ParameterEntity;
-import org.onap.sdc.workflow.persistence.types.ParameterPropertyName;
+import org.onap.sdc.workflow.persistence.impl.types.ParameterPropertyName;
 import org.onap.sdc.workflow.persistence.types.ParameterRole;
 import org.onap.sdc.workflow.persistence.types.ParameterType;
-import org.onap.sdc.workflow.persistence.types.WorkflowElementType;
+import org.onap.sdc.workflow.persistence.impl.types.WorkflowElementType;
 import org.openecomp.core.zusammen.api.ZusammenAdaptor;
-import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory;
 import org.openecomp.types.ElementPropertyName;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Repository;
 
 @Repository
 public class ParameterRepositoryImpl implements ParameterRepository {
 
-    private ZusammenAdaptor zusammenAdaptor = ZusammenAdaptorFactory.getInstance().createInterface();
+    private final ZusammenAdaptor zusammenAdaptor;
+
+    @Autowired
+    public ParameterRepositoryImpl(ZusammenAdaptor zusammenAdaptor) {
+        this.zusammenAdaptor = zusammenAdaptor;
+    }
 
     @Override
     public void createStructure(String id, String versionId) {
@@ -150,7 +155,7 @@ public class ParameterRepositoryImpl implements ParameterRepository {
         info.setName(parameter.getName());
         info.addProperty(ElementPropertyName.elementType.name(), WorkflowElementType.valueOf(role.name()));
         info.addProperty(ParameterPropertyName.TYPE.name(), parameter.getType());
-        info.addProperty(ParameterPropertyName.mandatory.name(), parameter.isMandatory());
+        info.addProperty(ParameterPropertyName.MANDATORY.name(), parameter.isMandatory());
         parameterElement.setInfo(info);
 
         return parameterElement;
@@ -162,7 +167,7 @@ public class ParameterRepositoryImpl implements ParameterRepository {
         parameterEntity.setName(elementInfo.getInfo().getName());
         parameterEntity
                 .setType(ParameterType.valueOf(elementInfo.getInfo().getProperty(ParameterPropertyName.TYPE.name())));
-        parameterEntity.setMandatory(elementInfo.getInfo().getProperty(ParameterPropertyName.mandatory.name()));
+        parameterEntity.setMandatory(elementInfo.getInfo().getProperty(ParameterPropertyName.MANDATORY.name()));
         return parameterEntity;
     }
 
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/impl/types/ActivitySpecData.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/impl/types/ActivitySpecData.java
new file mode 100644 (file)
index 0000000..5daba8d
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.persistence.impl.types;
+
+import java.util.Collections;
+import java.util.List;
+import org.onap.sdc.workflow.persistence.types.ActivitySpecParameter;
+
+@lombok.Data
+public class ActivitySpecData {
+
+    private List<ActivitySpecParameter> inputs = Collections.emptyList();
+    private List<ActivitySpecParameter> outputs = Collections.emptyList();
+    private String type;
+    private String content;
+}
+
@@ -1,11 +1,11 @@
 /*
- * Copyright © 2018 European Support Limited
+ * Copyright © 2016-2018 European Support Limited
  *
  * 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,
  * limitations under the License.
  */
 
-package org.onap.sdc.workflow.persistence.types;
+package org.onap.sdc.workflow.persistence.impl.types;
 
-public final class WorkflowProperty {
-
-    private WorkflowProperty() {
-    }
-
-    public static final String CATEGORY = "category";
+public enum ActivitySpecElementType {
+    ACTIVITYSPEC
 }
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/types/ActivitySpecEntity.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/types/ActivitySpecEntity.java
new file mode 100644 (file)
index 0000000..cf2db9a
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.persistence.types;
+
+import java.util.List;
+import lombok.NoArgsConstructor;
+import org.openecomp.sdc.versioning.dao.types.Version;
+
+@lombok.Data
+@NoArgsConstructor
+public class ActivitySpecEntity {
+
+    private String id;
+    private Version version;
+    private String name;
+    private String description;
+
+    private List<String> categoryList;
+    private List<ActivitySpecParameter> inputs;
+    private List<ActivitySpecParameter> outputs;
+    private String type;
+    private String content;
+
+    //Not to be maintained in activityspec element
+    private String status;
+
+    public ActivitySpecEntity(String id, Version version) {
+        this.id = id;
+        this.version = version;
+    }
+}
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/types/ActivitySpecParameter.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/persistence/types/ActivitySpecParameter.java
new file mode 100644 (file)
index 0000000..3f2562e
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.persistence.types;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class ActivitySpecParameter {
+
+    private String name;
+    private String type;
+    private String value;
+}
index 5105114..f17cea1 100644 (file)
@@ -16,9 +16,8 @@ public class SwaggerConfig {
     @Bean
     public Docket api() {
         return new Docket(DocumentationType.SWAGGER_2)
-                       .select()
-                       .apis(RequestHandlerSelectors.basePackage("org.onap.sdc.workflow.api"))
-                       .paths(regex("/workflows.*"))
+                       .select().apis(RequestHandlerSelectors.basePackage("org.onap.sdc.workflow.api"))
+                       .paths(regex("/(wf/workflows|v1.0/activity-spec).*"))
                        .build();
     }
 }
\ No newline at end of file
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/ActivitySpecConstant.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/ActivitySpecConstant.java
new file mode 100644 (file)
index 0000000..bee916a
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.services;
+
+public class ActivitySpecConstant {
+
+    public static final String CATEGORY_ATTRIBUTE_NAME = "category";
+    public static final String VERSION_ID_DEFAULT_VALUE = "latest";
+    public static final String ACTIVITY_SPEC_NOT_FOUND = "No Activity Spec found for the given identifiers";
+
+    private ActivitySpecConstant() {
+        //Utility Class declaring constants does not require instantiation.
+    }
+}
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/ActivitySpecManager.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/ActivitySpecManager.java
new file mode 100644 (file)
index 0000000..b93a8dc
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.services;
+
+import java.util.Collection;
+import org.onap.sdc.workflow.api.types.activityspec.ActivitySpecAction;
+import org.onap.sdc.workflow.persistence.types.ActivitySpecEntity;
+
+public interface ActivitySpecManager {
+
+    ActivitySpecEntity createActivitySpec(ActivitySpecEntity activitySpec);
+
+    ActivitySpecEntity get(ActivitySpecEntity activitySpec);
+
+    void update(ActivitySpecEntity activitySpec);
+
+    void actOnAction(ActivitySpecEntity activitySpec, ActivitySpecAction action);
+
+    Collection<ActivitySpecEntity> list(String versionStatus);
+}
index 0a8b640..0a78982 100644 (file)
 package org.onap.sdc.workflow.services;
 
 import java.util.Optional;
-import org.apache.commons.lang.ArrayUtils;
+import org.apache.commons.lang3.ArrayUtils;
 import org.onap.sdc.workflow.persistence.UniqueValueRepository;
 import org.onap.sdc.workflow.persistence.types.UniqueValueEntity;
 import org.onap.sdc.workflow.services.exceptions.UniqueValueViolationException;
-import org.openecomp.core.utilities.CommonMethods; // todo get rid of
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 @Service("uniqueValueService")
 public class UniqueValueService {
 
-    private static final char FORMATTED_UNIQUE_VALUE_SEPARATOR = '_';
+    private static final String FORMATTED_UNIQUE_VALUE_SEPARATOR = "_";
 
     private final UniqueValueRepository uniqueValueRepository;
 
@@ -43,7 +42,7 @@ public class UniqueValueService {
      * @param type              the type
      * @param uniqueCombination the unique combination
      */
-    public void createUniqueValue(String type, String[] uniqueCombination) {
+    public void createUniqueValue(String type, String... uniqueCombination) {
         formatValue(uniqueCombination).ifPresent(formattedValue -> {
             validateUniqueValue(type, formattedValue, uniqueCombination);
             uniqueValueRepository.insert(new UniqueValueEntity(type, formattedValue));
@@ -56,7 +55,7 @@ public class UniqueValueService {
      * @param type              the type
      * @param uniqueCombination the unique combination
      */
-    public void deleteUniqueValue(String type, String[] uniqueCombination) {
+    public void deleteUniqueValue(String type, String... uniqueCombination) {
         formatValue(uniqueCombination)
                 .ifPresent(formattedValue -> uniqueValueRepository.delete(new UniqueValueEntity(type, formattedValue)));
 
@@ -70,10 +69,10 @@ public class UniqueValueService {
      * @param newValue      the new value
      * @param uniqueContext the unique context
      */
-    public void updateUniqueValue(String type, String oldValue, String newValue, String ... uniqueContext) {
+    public void updateUniqueValue(String type, String oldValue, String newValue, String... uniqueContext) {
         if (newValue == null || !newValue.equalsIgnoreCase(oldValue)) {
-            createUniqueValue(type, CommonMethods.concat(uniqueContext, new String[] {newValue}));
-            deleteUniqueValue(type, CommonMethods.concat(uniqueContext, new String[] {oldValue}));
+            createUniqueValue(type, ArrayUtils.addAll(uniqueContext, newValue));
+            deleteUniqueValue(type, ArrayUtils.addAll(uniqueContext, oldValue));
         }
     }
 
@@ -83,19 +82,18 @@ public class UniqueValueService {
      * @param type              the type
      * @param uniqueCombination the unique combination
      */
-    public void validateUniqueValue(String type, String[] uniqueCombination) {
+    public void validateUniqueValue(String type, String... uniqueCombination) {
         formatValue(uniqueCombination)
                 .ifPresent(formattedValue -> validateUniqueValue(type, formattedValue, uniqueCombination));
     }
 
-    /**
-     * Checks if a unique value is taken.
-     *
-     * @return true if the unique value is occupied, false otherwise
-     */
-    public boolean isUniqueValueOccupied(String type, String[] uniqueCombination) {
-        return formatValue(uniqueCombination).map(formattedValue -> isUniqueValueOccupied(type, formattedValue))
-                                             .orElse(false);
+    private Optional<String> formatValue(String[] uniqueCombination) {
+        if (ArrayUtils.isEmpty(uniqueCombination) || getValueWithoutContext(uniqueCombination) == null) {
+            return Optional.empty();
+        }
+
+        uniqueCombination[uniqueCombination.length - 1] = getValueWithoutContext(uniqueCombination).toLowerCase();
+        return Optional.of(String.join(FORMATTED_UNIQUE_VALUE_SEPARATOR, uniqueCombination));
     }
 
     private void validateUniqueValue(String type, String formattedValue, String[] uniqueCombination) {
@@ -108,13 +106,14 @@ public class UniqueValueService {
         return uniqueValueRepository.findById(new UniqueValueEntity(type, formattedValue)).isPresent();
     }
 
-    private Optional<String> formatValue(String[] uniqueCombination) {
-        if (ArrayUtils.isEmpty(uniqueCombination) || getValueWithoutContext(uniqueCombination) == null) {
-            return Optional.empty();
-        }
-
-        uniqueCombination[uniqueCombination.length - 1] = getValueWithoutContext(uniqueCombination).toLowerCase();
-        return Optional.of(CommonMethods.arrayToSeparatedString(uniqueCombination, FORMATTED_UNIQUE_VALUE_SEPARATOR));
+    /**
+     * Checks if a unique value is taken.
+     *
+     * @return true if the unique value is occupied, false otherwise
+     */
+    public boolean isUniqueValueOccupied(String type, String... uniqueCombination) {
+        return formatValue(uniqueCombination).map(formattedValue -> isUniqueValueOccupied(type, formattedValue))
+                                             .orElse(false);
     }
 
     private String getValueWithoutContext(String[] uniqueCombination) {
index fcae232..3ef38d7 100644 (file)
 
 package org.onap.sdc.workflow.services;
 
-import java.util.Collection;
 import java.util.Set;
-import org.onap.sdc.workflow.persistence.types.Workflow;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
+import org.onap.sdc.workflow.services.types.Workflow;
+import org.onap.sdc.workflow.services.types.WorkflowVersionState;
 import org.onap.sdc.workflow.services.types.Page;
 import org.onap.sdc.workflow.services.types.RequestSpec;
 
index 8effb64..a7f5c42 100644 (file)
@@ -19,8 +19,8 @@ package org.onap.sdc.workflow.services;
 import java.util.Collection;
 import java.util.Set;
 import org.onap.sdc.workflow.persistence.types.ArtifactEntity;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersion;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
+import org.onap.sdc.workflow.services.types.WorkflowVersion;
+import org.onap.sdc.workflow.services.types.WorkflowVersionState;
 import org.springframework.web.multipart.MultipartFile;
 
 
index 87027a5..011b274 100644 (file)
@@ -16,7 +16,7 @@
 
 package org.onap.sdc.workflow.services.exceptions;
 
-import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
+import org.onap.sdc.workflow.services.types.WorkflowVersionState;
 
 public class VersionStateModificationException extends RuntimeException {
 
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/exceptions/VersionStatusModificationException.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/exceptions/VersionStatusModificationException.java
new file mode 100644 (file)
index 0000000..7264682
--- /dev/null
@@ -0,0 +1,12 @@
+package org.onap.sdc.workflow.services.exceptions;
+
+import org.openecomp.sdc.versioning.dao.types.VersionStatus;
+
+public class VersionStatusModificationException extends RuntimeException {
+
+    public VersionStatusModificationException(String activitySpecId, String versionId, VersionStatus sourceState,
+            VersionStatus targetState) {
+        super(String.format("Activity spec %s, version %s: status can not be changed from %s to %s", activitySpecId,
+                versionId, sourceState.name(), targetState.name()));
+    }
+}
\ No newline at end of file
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/ActivitySpecManagerImpl.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/ActivitySpecManagerImpl.java
new file mode 100644 (file)
index 0000000..3cfaf4a
--- /dev/null
@@ -0,0 +1,248 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.services.impl;
+
+import static org.onap.sdc.workflow.services.ActivitySpecConstant.ACTIVITY_SPEC_NOT_FOUND;
+import static org.onap.sdc.workflow.services.ActivitySpecConstant.VERSION_ID_DEFAULT_VALUE;
+import static org.openecomp.sdc.versioning.dao.types.VersionStatus.Certified;
+import static org.openecomp.sdc.versioning.dao.types.VersionStatus.Deleted;
+import static org.openecomp.sdc.versioning.dao.types.VersionStatus.Deprecated;
+import static org.openecomp.sdc.versioning.dao.types.VersionStatus.Draft;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import org.onap.sdc.workflow.api.types.activityspec.ActivitySpecAction;
+import org.onap.sdc.workflow.persistence.ActivitySpecRepository;
+import org.onap.sdc.workflow.persistence.types.ActivitySpecEntity;
+import org.onap.sdc.workflow.services.ActivitySpecManager;
+import org.onap.sdc.workflow.services.UniqueValueService;
+import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException;
+import org.onap.sdc.workflow.services.exceptions.VersionStatusModificationException;
+import org.onap.sdc.workflow.services.impl.mappers.ActivitySpecMapper;
+import org.openecomp.sdc.common.errors.SdcRuntimeException;
+import org.openecomp.sdc.logging.api.Logger;
+import org.openecomp.sdc.logging.api.LoggerFactory;
+import org.openecomp.sdc.versioning.ItemManager;
+import org.openecomp.sdc.versioning.VersioningManager;
+import org.openecomp.sdc.versioning.dao.types.Version;
+import org.openecomp.sdc.versioning.dao.types.VersionStatus;
+import org.openecomp.sdc.versioning.types.Item;
+import org.openecomp.sdc.versioning.types.VersionCreationMethod;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Service;
+
+@Service("activitySpecManager")
+public class ActivitySpecManagerImpl implements ActivitySpecManager {
+
+    private static final String ACTIVITY_SPEC_NAME = "ActivitySpec.Name";
+    private static final Logger LOGGER = LoggerFactory.getLogger(ActivitySpecManagerImpl.class);
+    private static final Map<VersionStatus, VersionStatus> EXPECTED_PREV_STATUS;
+
+    static {
+        EXPECTED_PREV_STATUS = new EnumMap<>(VersionStatus.class);
+        EXPECTED_PREV_STATUS.put(Certified, Draft);
+        EXPECTED_PREV_STATUS.put(Deprecated, Certified);
+        EXPECTED_PREV_STATUS.put(Deleted, Deprecated);
+    }
+
+    private final ItemManager itemManager;
+    private final VersioningManager versioningManager;
+    private final ActivitySpecRepository activitySpecDao;
+    private final UniqueValueService uniqueValueService;
+    private final ActivitySpecMapper activitySpecMapper;
+
+
+    @Autowired
+    public ActivitySpecManagerImpl(ItemManager itemManager, VersioningManager versioningManager,
+            ActivitySpecRepository activitySpecDao,
+            @Qualifier("uniqueValueService") UniqueValueService uniqueValueService,
+            ActivitySpecMapper activitySpecMapper) {
+        this.itemManager = itemManager;
+        this.versioningManager = versioningManager;
+        this.activitySpecDao = activitySpecDao;
+        this.uniqueValueService = uniqueValueService;
+        this.activitySpecMapper = activitySpecMapper;
+    }
+
+    @Override
+    public ActivitySpecEntity createActivitySpec(ActivitySpecEntity activitySpec) {
+
+        uniqueValueService.validateUniqueValue(ACTIVITY_SPEC_NAME, activitySpec.getName());
+
+        Item item = activitySpecMapper.activitySpecToItem(activitySpec);
+        item = itemManager.create(item);
+
+        Version version = getActivitySpecVersion(activitySpec);
+        versioningManager.create(item.getId(), version, VersionCreationMethod.major);
+
+        enrichActivitySpec(item, version, activitySpec);
+        activitySpecDao.create(activitySpec);
+
+        uniqueValueService.createUniqueValue(ACTIVITY_SPEC_NAME, activitySpec.getName());
+        return activitySpec;
+    }
+
+    @Override
+    public ActivitySpecEntity get(ActivitySpecEntity activitySpec) {
+        activitySpec.setVersion(calculateLatestVersion(activitySpec));
+        ActivitySpecEntity retrieved;
+        try {
+            retrieved = activitySpecDao.get(activitySpec);
+        } catch (SdcRuntimeException runtimeException) {
+            LOGGER.debug(
+                    "Failed to retrieve activity spec for activitySpecId: " + activitySpec.getId() + " and version: "
+                            + activitySpec.getVersion().getId(), runtimeException);
+            throw new EntityNotFoundException(ACTIVITY_SPEC_NOT_FOUND);
+        }
+        if (retrieved != null) {
+            final Version retrievedVersion = versioningManager.get(activitySpec.getId(), activitySpec.getVersion());
+            retrieved.setStatus(Objects.nonNull(retrievedVersion) ? retrievedVersion.getStatus().name() : null);
+        }
+        return retrieved;
+    }
+
+    @Override
+    public void update(ActivitySpecEntity activitySpec) {
+        Item retrievedItem = itemManager.get(activitySpec.getId());
+        if (retrievedItem == null) {
+            LOGGER.error(String.format("Activity Spec with id %s was not found", activitySpec.getId()));
+            throw new EntityNotFoundException(ACTIVITY_SPEC_NOT_FOUND);
+        }
+        uniqueValueService.updateUniqueValue(ACTIVITY_SPEC_NAME, retrievedItem.getName(), activitySpec.getName());
+
+        Item item = activitySpecMapper.activitySpecToItem(activitySpec);
+        item.setId(activitySpec.getId());
+        item.setStatus(retrievedItem.getStatus());
+        item.setVersionStatusCounters(retrievedItem.getVersionStatusCounters());
+        itemManager.update(item);
+
+        activitySpec.setVersion(calculateLatestVersion(activitySpec));
+        activitySpecDao.update(activitySpec);
+    }
+
+    @Override
+    public void actOnAction(ActivitySpecEntity activitySpec, ActivitySpecAction action) {
+        Version version = calculateLatestVersion(activitySpec);
+        if (action == ActivitySpecAction.CERTIFY) {
+            version.setStatus(Certified);
+        }
+        if (action == ActivitySpecAction.DEPRECATE) {
+            version.setStatus(Deprecated);
+        }
+        if (action == ActivitySpecAction.DELETE) {
+            version.setStatus(Deleted);
+        }
+
+        updateVersionStatus(activitySpec.getId(), action, version);
+        if (action == ActivitySpecAction.DELETE) {
+            final String activitySpecName = get(new ActivitySpecEntity(activitySpec.getId(), version)).getName();
+            uniqueValueService.deleteUniqueValue(ACTIVITY_SPEC_NAME, activitySpecName);
+        }
+    }
+
+    private void updateVersionStatus(String activitySpecId, ActivitySpecAction action, Version version) {
+        VersionStatus prevVersionStatus = null;
+        Version retrievedVersion;
+        try {
+            retrievedVersion = versioningManager.get(activitySpecId, version);
+        } catch (SdcRuntimeException exception) {
+            LOGGER.debug(
+                    "Failed to get version for activitySpecId: " + activitySpecId + " and version: " + version.getId(),
+                    exception);
+            throw new EntityNotFoundException(ACTIVITY_SPEC_NOT_FOUND);
+
+        }
+
+        VersionStatus status = version.getStatus();
+        VersionStatus expectedPrevStatus = EXPECTED_PREV_STATUS.get(status);
+        if (expectedPrevStatus != null) {
+
+            VersionStatus retrievedStatus = Objects.nonNull(retrievedVersion) ? retrievedVersion.getStatus() : null;
+            if (retrievedStatus != expectedPrevStatus) {
+                LOGGER.debug("Failed to " + version.getStatus() + " since activity spec is in " + retrievedStatus);
+                throw new VersionStatusModificationException(activitySpecId, version.getId(), retrievedStatus, status);
+            }
+            prevVersionStatus = expectedPrevStatus;
+        }
+
+        if (Objects.nonNull(retrievedVersion)) {
+            retrievedVersion.setStatus(status);
+            versioningManager.updateVersion(activitySpecId, retrievedVersion);
+            itemManager.updateVersionStatus(activitySpecId, status, prevVersionStatus);
+            versioningManager.publish(activitySpecId, retrievedVersion, "actionOnActivitySpec :" + action.name());
+        }
+    }
+
+    @Override
+    public Collection<ActivitySpecEntity> list(String versionStatus) {
+        Predicate<Item> itemPredicate;
+        if (Objects.nonNull(versionStatus)) {
+            VersionStatus statusEnumValue;
+
+            try {
+                statusEnumValue = VersionStatus.valueOf(versionStatus);
+            } catch (IllegalArgumentException e) {
+                LOGGER.debug("Unexpected value of VersionStatus {}", versionStatus);
+                return Collections.emptyList();
+            }
+            itemPredicate =
+                    item -> ItemType.ACTIVITYSPEC.name().equals(item.getType()) && item.getVersionStatusCounters()
+                                                                                           .containsKey(
+                                                                                                   statusEnumValue);
+        } else {
+            itemPredicate = item -> ItemType.ACTIVITYSPEC.name().equals(item.getType());
+        }
+
+        return itemManager.list(itemPredicate).stream()
+                       .sorted(Comparator.comparing(Item::getModificationTime).reversed())
+                       .map(activitySpecMapper::itemToActivitySpec).collect(Collectors.toList());
+    }
+
+    private Version calculateLatestVersion(ActivitySpecEntity activitySpec) {
+        if (VERSION_ID_DEFAULT_VALUE.equalsIgnoreCase(activitySpec.getVersion().getId())) {
+            List<Version> list;
+            try {
+                list = versioningManager.list(activitySpec.getId());
+            } catch (SdcRuntimeException runtimeException) {
+                LOGGER.debug("Failed to list versions for activitySpecId " + activitySpec.getId(), runtimeException);
+                throw new EntityNotFoundException(ACTIVITY_SPEC_NOT_FOUND);
+            }
+            if (Objects.nonNull(list) && !list.isEmpty()) {
+                return list.get(0);
+            }
+        }
+        return activitySpec.getVersion();
+    }
+
+    private Version getActivitySpecVersion(ActivitySpecEntity activitySpecEntity) {
+        return activitySpecEntity.getVersion() == null ? new Version() : activitySpecEntity.getVersion();
+
+    }
+
+    private void enrichActivitySpec(Item item, Version version, ActivitySpecEntity activitySpecEntity) {
+        activitySpecEntity.setId(item.getId());
+        activitySpecEntity.setVersion(version);
+    }
+}
index 80b969c..c061243 100644 (file)
@@ -16,6 +16,8 @@
 
 package org.onap.sdc.workflow.services.impl;
 
+import org.openecomp.core.zusammen.api.ZusammenAdaptor;
+import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory;
 import org.openecomp.sdc.versioning.ItemManager;
 import org.openecomp.sdc.versioning.ItemManagerFactory;
 import org.openecomp.sdc.versioning.VersioningManager;
@@ -35,4 +37,9 @@ public class CollaborationConfiguration {
     public VersioningManager versioningManager() {
         return VersioningManagerFactory.getInstance().createInterface();
     }
+
+    @Bean
+    public ZusammenAdaptor zusammenAdaptor() {
+        return ZusammenAdaptorFactory.getInstance().createInterface();
+    }
 }
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/ItemType.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/ItemType.java
new file mode 100644 (file)
index 0000000..8a05d88
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.services.impl;
+
+public enum ItemType {
+    WORKFLOW, ACTIVITYSPEC
+}
index a309204..e16c7b4 100644 (file)
@@ -16,6 +16,7 @@
 
 package org.onap.sdc.workflow.services.impl;
 
+import static org.onap.sdc.workflow.services.impl.ItemType.WORKFLOW;
 import static org.onap.sdc.workflow.services.types.PagingConstants.DEFAULT_LIMIT;
 import static org.onap.sdc.workflow.services.types.PagingConstants.DEFAULT_OFFSET;
 import static org.onap.sdc.workflow.services.types.PagingConstants.MAX_LIMIT;
@@ -26,8 +27,8 @@ import java.util.List;
 import java.util.Set;
 import java.util.function.Predicate;
 import java.util.stream.Collectors;
-import org.onap.sdc.workflow.persistence.types.Workflow;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
+import org.onap.sdc.workflow.services.types.Workflow;
+import org.onap.sdc.workflow.services.types.WorkflowVersionState;
 import org.onap.sdc.workflow.services.UniqueValueService;
 import org.onap.sdc.workflow.services.WorkflowManager;
 import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException;
@@ -51,10 +52,9 @@ import org.springframework.stereotype.Service;
 @Service("workflowManager")
 public class WorkflowManagerImpl implements WorkflowManager {
 
-    public static final String WORKFLOW_TYPE = "WORKFLOW";
     private static final String WORKFLOW_NOT_FOUND_ERROR_MSG = "Workflow with id '%s' does not exist";
     private static final String WORKFLOW_NAME_UNIQUE_TYPE = "WORKFLOW_NAME";
-    private static final Predicate<Item> WORKFLOW_ITEM_FILTER = item -> WORKFLOW_TYPE.equals(item.getType());
+    private static final Predicate<Item> WORKFLOW_ITEM_FILTER = item -> WORKFLOW.name().equals(item.getType());
     private static final String WORKSPACES_SORT_PROPERTY = "name";
     private static final RequestSpec WORKSPACES_DEFAULT_REQUEST_SPEC =
             new RequestSpec(new PagingRequest(DEFAULT_OFFSET, DEFAULT_LIMIT),
@@ -84,7 +84,7 @@ public class WorkflowManagerImpl implements WorkflowManager {
         Set<VersionStatus> versionStatusesFilter =
                 versionStatesFilter == null ? null :
                         versionStatesFilter.stream().map(versionStateMapper::workflowVersionStateToVersionStatus)
-                                           .collect(Collectors.toSet());
+                                .collect(Collectors.toSet());
 
         Collection<Item> workflowItems = itemManager.list(getFilter(versionStatusesFilter));
 
@@ -111,9 +111,9 @@ public class WorkflowManagerImpl implements WorkflowManager {
         Item item = workflowMapper.workflowToItem(workflow);
         item.setStatus(ItemStatus.ACTIVE);
 
-        uniqueValueService.validateUniqueValue(WORKFLOW_NAME_UNIQUE_TYPE, new String[] {workflow.getName()});
+        uniqueValueService.validateUniqueValue(WORKFLOW_NAME_UNIQUE_TYPE, workflow.getName());
         Item createdItem = itemManager.create(item);
-        uniqueValueService.createUniqueValue(WORKFLOW_NAME_UNIQUE_TYPE, new String[] {workflow.getName()});
+        uniqueValueService.createUniqueValue(WORKFLOW_NAME_UNIQUE_TYPE, workflow.getName());
 
         return workflowMapper.itemToWorkflow(createdItem);
     }
@@ -163,8 +163,8 @@ public class WorkflowManagerImpl implements WorkflowManager {
 
     private static Comparator<Workflow> getWorkflowComparator(SortingRequest sorting) {
         Boolean byNameAscending = sorting.getSorts().stream()
-                                  .filter(sort -> WORKSPACES_SORT_PROPERTY.equalsIgnoreCase(sort.getProperty()))
-                                  .findFirst().map(Sort::isAscendingOrder).orElse(true);
+                                         .filter(sort -> WORKSPACES_SORT_PROPERTY.equalsIgnoreCase(sort.getProperty()))
+                                         .findFirst().map(Sort::isAscendingOrder).orElse(true);
         Comparator<Workflow> byName = Comparator.comparing(Workflow::getName);
 
         return byNameAscending ? byName : byName.reversed();
index 14e2874..14a6722 100644 (file)
@@ -16,7 +16,7 @@
 
 package org.onap.sdc.workflow.services.impl;
 
-import static org.onap.sdc.workflow.persistence.types.WorkflowVersionState.CERTIFIED;
+import static org.onap.sdc.workflow.services.types.WorkflowVersionState.CERTIFIED;
 
 import java.io.IOException;
 import java.io.InputStream;
@@ -34,8 +34,8 @@ import org.onap.sdc.workflow.persistence.ParameterRepository;
 import org.onap.sdc.workflow.persistence.types.ArtifactEntity;
 import org.onap.sdc.workflow.persistence.types.ParameterEntity;
 import org.onap.sdc.workflow.persistence.types.ParameterRole;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersion;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
+import org.onap.sdc.workflow.services.types.WorkflowVersion;
+import org.onap.sdc.workflow.services.types.WorkflowVersionState;
 import org.onap.sdc.workflow.services.WorkflowVersionManager;
 import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException;
 import org.onap.sdc.workflow.services.exceptions.InvalidArtifactException;
diff --git a/workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/mappers/ActivitySpecMapper.java b/workflow-designer-be/src/main/java/org/onap/sdc/workflow/services/impl/mappers/ActivitySpecMapper.java
new file mode 100644 (file)
index 0000000..d9e5a10
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Copyright © 2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.services.impl.mappers;
+
+import static org.onap.sdc.workflow.services.ActivitySpecConstant.CATEGORY_ATTRIBUTE_NAME;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.mapstruct.InheritInverseConfiguration;
+import org.mapstruct.Mapper;
+import org.mapstruct.Mapping;
+import org.mapstruct.Mappings;
+import org.onap.sdc.workflow.persistence.types.ActivitySpecEntity;
+import org.onap.sdc.workflow.services.ActivitySpecConstant;
+import org.onap.sdc.workflow.services.impl.ItemType;
+import org.openecomp.sdc.versioning.dao.types.VersionStatus;
+import org.openecomp.sdc.versioning.types.Item;
+
+@Mapper(componentModel = "spring", imports = {ItemType.class, ActivitySpecConstant.class})
+public interface ActivitySpecMapper {
+
+    @Mappings({@Mapping(source = "versionStatusCounters", target = "status"),
+            @Mapping(source = "properties", target = "categoryList")})
+    ActivitySpecEntity itemToActivitySpec(Item item);
+
+    @InheritInverseConfiguration
+    @Mappings({@Mapping(expression = "java(ItemType.ACTIVITYSPEC.name())", target = "type"),
+            @Mapping(target = "versionStatusCounters", ignore = true), @Mapping(target = "status", ignore = true),
+            @Mapping(source = "categoryList", target = "properties")})
+    Item activitySpecToItem(ActivitySpecEntity activitySpec);
+
+    default String versionStatusCountersToStatus(Map<VersionStatus, Integer> versionStatusCounters) {
+        return versionStatusCounters.keySet().stream().findFirst().map(Enum::name).orElse(null);
+    }
+
+    default Map<String, Object> categoriesToProperties(List<String> categories) {
+        Map<String, Object> properties = new HashMap<>();
+        properties.put(CATEGORY_ATTRIBUTE_NAME, categories);
+        return properties;
+    }
+
+    default List<String> propertiesToCategories(Map<String, Object> properties) {
+        return (List<String>) properties.get(CATEGORY_ATTRIBUTE_NAME);
+    }
+}
index a3a1cdc..6dffb36 100644 (file)
@@ -19,7 +19,7 @@ package org.onap.sdc.workflow.services.impl.mappers;
 import org.mapstruct.InheritInverseConfiguration;
 import org.mapstruct.Mapper;
 import org.mapstruct.Mapping;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersion;
+import org.onap.sdc.workflow.services.types.WorkflowVersion;
 import org.openecomp.sdc.versioning.dao.types.Version;
 
 @Mapper(componentModel = "spring", uses = VersionStateMapper.class)
index 45012b5..82f5814 100644 (file)
@@ -23,7 +23,7 @@ import org.mapstruct.InheritInverseConfiguration;
 import org.mapstruct.Mapper;
 import org.mapstruct.ValueMapping;
 import org.mapstruct.ValueMappings;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
+import org.onap.sdc.workflow.services.types.WorkflowVersionState;
 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
 
 @Mapper(componentModel = "spring")
index 5cfcd7e..1ca7c71 100644 (file)
@@ -20,18 +20,18 @@ import org.mapstruct.InheritInverseConfiguration;
 import org.mapstruct.Mapper;
 import org.mapstruct.Mapping;
 import org.mapstruct.Mappings;
-import org.onap.sdc.workflow.persistence.types.Workflow;
-import org.onap.sdc.workflow.services.impl.WorkflowManagerImpl;
+import org.onap.sdc.workflow.services.types.Workflow;
+import org.onap.sdc.workflow.services.impl.ItemType;
 import org.openecomp.sdc.versioning.types.Item;
 
-@Mapper(componentModel = "spring", imports = WorkflowManagerImpl.class, uses = VersionStateMapper.class)
+@Mapper(componentModel = "spring", imports = ItemType.class, uses = VersionStateMapper.class)
 public interface WorkflowMapper {
 
     @Mapping(source = "versionStatusCounters", target = "versionStates")
     Workflow itemToWorkflow(Item item);
 
     @InheritInverseConfiguration
-    @Mappings({@Mapping(expression = "java(WorkflowManagerImpl.WORKFLOW_TYPE)", target = "type"),
+    @Mappings({@Mapping(expression = "java(ItemType.WORKFLOW.name())", target = "type"),
             @Mapping(target = "versionStatusCounters", ignore = true)})
     Item workflowToItem(Workflow workflow);
 
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package org.onap.sdc.workflow.persistence.types;
+package org.onap.sdc.workflow.services.types;
 
 import java.util.Collection;
 import java.util.Collections;
@@ -22,6 +22,8 @@ import java.util.Date;
 import javax.validation.Valid;
 import lombok.Data;
 import org.onap.sdc.workflow.api.validation.NoDuplicates;
+import org.onap.sdc.workflow.persistence.types.ParameterEntity;
+
 
 
 @Data
index de62ead..897b042 100644 (file)
@@ -13,8 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #/
-
-server.servlet.context-path=/wf
+server.servlet.context-path=/
 server.port=${SERVER_PORT:8080}
 
 #CASSANDRA
index 5149bdf..64b58fd 100644 (file)
@@ -13,8 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #/
-
-server.servlet.context-path=/wf
+server.servlet.context-path=/
 server.port=${SERVER_PORT:8080}
 sdc.be.protocol=${SDC_PROTOCOL:}
 sdc.be.endpoint=${SDC_ENDPOINT:}
index 4301feb..6c825f9 100644 (file)
@@ -10,8 +10,7 @@ public class RestPath {
         //Hiding implicit constructor
     }
 
-    private static final String WORKFLOWS_URL = "/workflows";
-    public static final String WORKFLOWS_WITH_VERSION_STATE_FILTER_URL = WORKFLOWS_URL + "?versionState=%s";
+    private static final String WORKFLOWS_URL = "/wf/workflows";
     private static final String WORKFLOW_URL_FORMATTER = WORKFLOWS_URL + "/%s";
     private static final String VERSIONS_URL_FORMATTER = WORKFLOWS_URL + "/%s/versions";
     private static final String VERSION_URL_FORMATTER = WORKFLOWS_URL + "/%s/versions/%s";
@@ -21,8 +20,6 @@ public class RestPath {
     private static final String WORKFLOW_URL_FORMATTER_QUERY_PARAMS_ALL =
             WORKFLOWS_URL + "?" + SORT_QUERY_STRING_FORMATTER+ "&" +  LIMIT_QUERY_STRING_FORMATTER + "&" +
                     OFFSET_QUERY_STRING_FORMATTER;
-    private static final String WORKFLOW_URL_FORMATTER_QUERY_PARAMS_NO_SORT =
-            WORKFLOWS_URL + "?" + LIMIT_QUERY_STRING_FORMATTER + "&" + OFFSET_QUERY_STRING_FORMATTER;
     private static final String WORKFLOW_URL_FORMATTER_QUERY_PARAMS_NO_SORT_AND_LIMIT =
             WORKFLOWS_URL + "?" + OFFSET_QUERY_STRING_FORMATTER;
     private static final String WORKFLOW_URL_FORMATTER_QUERY_PARAMS_NO_SORT_AND_OFFSET =
@@ -32,10 +29,6 @@ public class RestPath {
         return String.format(WORKFLOW_URL_FORMATTER_QUERY_PARAMS_ALL, sort, limit, offset);
     }
 
-    public static String getWorkflowsPathNoSort(String limit, String offset){
-        return String.format(WORKFLOW_URL_FORMATTER_QUERY_PARAMS_NO_SORT, limit, offset);
-    }
-
     public static String getWorkflowsPathNoSortAndLimit(String offset){
         return String.format(WORKFLOW_URL_FORMATTER_QUERY_PARAMS_NO_SORT_AND_LIMIT, offset);
     }
index e2a566a..0a8355c 100644 (file)
@@ -1,12 +1,12 @@
 package org.onap.sdc.workflow;
 
-import org.onap.sdc.workflow.persistence.types.Workflow;
+import static org.onap.sdc.workflow.services.impl.ItemType.WORKFLOW;
+
+import org.onap.sdc.workflow.services.types.Workflow;
 import org.openecomp.sdc.versioning.types.Item;
 
 public class TestUtil {
 
-    private static final String WORKFLOW_TYPE = "WORKFLOW";
-
     public static Workflow createWorkflow(int workflowNum, boolean createId) {
         Workflow workflow = new Workflow();
         if (createId) {
@@ -26,7 +26,7 @@ public class TestUtil {
         item.setName("Workflow_" + itemNum);
         item.setDescription("Description_" + itemNum);
         if (setType) {
-            item.setType(WORKFLOW_TYPE);
+            item.setType(WORKFLOW.name());
         }
         return item;
     }
index f8d2aec..3438093 100644 (file)
@@ -32,15 +32,13 @@ import org.mockito.InjectMocks;
 import org.mockito.Mock;
 import org.mockito.junit.MockitoJUnitRunner;
 import org.onap.sdc.workflow.RestPath;
-import org.onap.sdc.workflow.api.exceptionshandlers.CustomizedResponseEntityExceptionHandler;
-import org.onap.sdc.workflow.persistence.types.Workflow;
+import org.onap.sdc.workflow.services.types.Workflow;
 import org.onap.sdc.workflow.services.WorkflowManager;
 import org.onap.sdc.workflow.services.types.Page;
 import org.onap.sdc.workflow.services.types.PagingRequest;
 import org.onap.sdc.workflow.services.types.RequestSpec;
 import org.onap.sdc.workflow.services.types.Sort;
 import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
-import org.springframework.mock.web.MockHttpServletResponse;
 import org.springframework.test.web.servlet.MockMvc;
 import org.springframework.test.web.servlet.ResultActions;
 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@@ -48,16 +46,14 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
 @RunWith(MockitoJUnitRunner.class)
 public class WorkflowControllerTest {
 
-
-    private static final String MISSING_REQUEST_HEADER_ERRROR_FORMAT =
-            "Missing request header '%s' for method parameter of type String";
     private static final String USER_ID = "userId";
+    private static final String MISSING_USER_HEADER_ERROR =
+            "Missing request header 'USER_ID' for method parameter of type String";
     private static final Gson GSON = new Gson();
     private static final String DEFAULT_SORT_VALUE = "name:asc";
 
     private MockMvc mockMvc;
 
-
     @Mock
     private WorkflowManager workflowManagerMock;
     @Captor
@@ -65,23 +61,19 @@ public class WorkflowControllerTest {
     @InjectMocks
     private WorkflowController workflowController;
 
-
     @Before
     public void setUp() {
         mockMvc = MockMvcBuilders.standaloneSetup(workflowController)
                                  .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
-                                 .setControllerAdvice(new CustomizedResponseEntityExceptionHandler()).build();
+                                 .setControllerAdvice(new ExceptionsHandler()).build();
     }
 
     @Test
     public void shouldReturnErrorWhenMissingUserIdInGetReqHeader() throws Exception {
         Workflow workflowMock = createWorkflow(1, true);
-        MockHttpServletResponse response =
-                mockMvc.perform(get(RestPath.getWorkflowPath(workflowMock.getId())).contentType(APPLICATION_JSON))
-                       .andDo(print()).andExpect(status().isBadRequest()).andExpect(status().is(400)).andReturn()
-                       .getResponse();
-        assertEquals(String.format(MISSING_REQUEST_HEADER_ERRROR_FORMAT, USER_ID_HEADER),
-                response.getContentAsString());
+        mockMvc.perform(get(RestPath.getWorkflowPath(workflowMock.getId())).contentType(APPLICATION_JSON))
+               .andDo(print()).andExpect(status().isBadRequest())
+               .andExpect(jsonPath("$.message", is(MISSING_USER_HEADER_ERROR)));
     }
 
     @Test
@@ -96,11 +88,8 @@ public class WorkflowControllerTest {
 
     @Test
     public void shouldReturnErrorWhenMissingUserIdInListReqHeader() throws Exception {
-        MockHttpServletResponse response =
-                mockMvc.perform(get(RestPath.getWorkflowsPath()).contentType(APPLICATION_JSON)).andDo(print())
-                       .andExpect(status().isBadRequest()).andExpect(status().is(400)).andReturn().getResponse();
-        assertEquals(String.format(MISSING_REQUEST_HEADER_ERRROR_FORMAT, USER_ID_HEADER),
-                response.getContentAsString());
+        mockMvc.perform(get(RestPath.getWorkflowsPath()).contentType(APPLICATION_JSON)).andDo(print())
+               .andExpect(status().isBadRequest()).andExpect(jsonPath("$.message", is(MISSING_USER_HEADER_ERROR)));
     }
 
     @Test
@@ -205,23 +194,17 @@ public class WorkflowControllerTest {
 
     @Test
     public void shouldThrowExceptionWhenWorkflowNameInvalid() throws Exception {
-
         Workflow reqWorkflow = new Workflow();
         reqWorkflow.setName("Invalid workflow name %");
-        MockHttpServletResponse response = mockMvc.perform(
-                post(RestPath.getWorkflowsPath()).header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON)
-                                                 .content(GSON.toJson(reqWorkflow))).andDo(print())
-                                                  .andExpect(status().isBadRequest()).andReturn().getResponse();
-        assertEquals("Workflow name must contain only letters, digits and underscores", response.getContentAsString());
+        mockMvc.perform(post(RestPath.getWorkflowsPath()).header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON)
+                                                         .content(GSON.toJson(reqWorkflow))).andDo(print())
+               .andExpect(status().isBadRequest())
+               .andExpect(jsonPath("$.message", is("Workflow name must contain only letters, digits and underscores")));
     }
 
     private void mockManagerList3() {
-        doReturn(new Page<>(Arrays.asList(
-                createWorkflow(1, true),
-                createWorkflow(2, true),
-                createWorkflow(3, true)),
-                new PagingRequest(DEFAULT_OFFSET, DEFAULT_LIMIT), 3))
-                .when(workflowManagerMock).list(any(), any());
+        doReturn(new Page<>(Arrays.asList(createWorkflow(1, true), createWorkflow(2, true), createWorkflow(3, true)),
+                new PagingRequest(DEFAULT_OFFSET, DEFAULT_LIMIT), 3)).when(workflowManagerMock).list(any(), any());
     }
 
     private static void assertRequestSpec(RequestSpec actual, int expectedOffset, int expectedLimit,
index 65dae72..2b3c49c 100644 (file)
@@ -1,5 +1,6 @@
 package org.onap.sdc.workflow.api;
 
+import static org.hamcrest.Matchers.hasSize;
 import static org.hamcrest.Matchers.is;
 import static org.junit.Assert.assertEquals;
 import static org.mockito.Mockito.doReturn;
@@ -16,7 +17,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
 import com.google.gson.Gson;
 import java.util.Arrays;
 import java.util.Collection;
-import java.util.List;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -26,8 +26,8 @@ import org.mockito.junit.MockitoJUnitRunner;
 import org.onap.sdc.workflow.RestPath;
 import org.onap.sdc.workflow.persistence.types.ParameterEntity;
 import org.onap.sdc.workflow.persistence.types.ParameterType;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersion;
 import org.onap.sdc.workflow.services.WorkflowVersionManager;
+import org.onap.sdc.workflow.services.types.WorkflowVersion;
 import org.openecomp.sdc.versioning.dao.types.Version;
 import org.springframework.http.HttpStatus;
 import org.springframework.mock.web.MockHttpServletResponse;
@@ -57,15 +57,27 @@ public class WorkflowVersionControllerTest {
         mockMvc = MockMvcBuilders.standaloneSetup(workflowVersionController).build();
     }
 
+    @Test
+    public void shouldReturnWorkflowVersionListWhenCallingVersionGetREST() throws Exception {
+        doReturn(Arrays.asList(new Version(VERSION1_ID), new Version(VERSION2_ID))).when(workflowVersionManagerMock)
+                .list(ITEM1_ID, null);
+        mockMvc.perform(get(RestPath.getWorkflowVersions(ITEM1_ID)).header(RestParams.USER_ID_HEADER, USER_ID)
+                                .contentType(APPLICATION_JSON)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.items", hasSize(2))).andExpect(jsonPath("$.items[0].id", is(VERSION1_ID)))
+                .andExpect(jsonPath("$.items[1].id", is(VERSION2_ID)));
+
+        verify(workflowVersionManagerMock, times(1)).list(ITEM1_ID, null);
+    }
+
+
     @Test
     public void shouldCreateWorkflowVersionWhenCallingVersionsPostREST() throws Exception {
 
         WorkflowVersion version = new WorkflowVersion();
         version.setDescription("VersionDescription");
         mockMvc.perform(post(RestPath.getWorkflowVersions(ITEM1_ID)).header(RestParams.USER_ID_HEADER, USER_ID)
-                                                                    .contentType(APPLICATION_JSON)
-                                                                    .content(GSON.toJson(version)))
-               .andExpect(status().isCreated());
+                                .contentType(APPLICATION_JSON).content(GSON.toJson(version)))
+                .andExpect(status().isCreated());
 
         verify(workflowVersionManagerMock, times(1)).create(ITEM1_ID, null, version);
     }
@@ -79,9 +91,8 @@ public class WorkflowVersionControllerTest {
         version.setInputs(inputs);
         version.setDescription("VersionDescription");
         mockMvc.perform(post(RestPath.getWorkflowVersions(ITEM1_ID)).header(RestParams.USER_ID_HEADER, USER_ID)
-                                                                    .contentType(APPLICATION_JSON)
-                                                                    .content(GSON.toJson(version)))
-               .andExpect(status().isBadRequest());
+                                .contentType(APPLICATION_JSON).content(GSON.toJson(version)))
+                .andExpect(status().isBadRequest());
 
     }
 
@@ -92,8 +103,8 @@ public class WorkflowVersionControllerTest {
         doReturn(version).when(workflowVersionManagerMock).get(ITEM1_ID, VERSION1_ID);
         mockMvc.perform(
                 get(RestPath.getWorkflowVersion(ITEM1_ID, VERSION1_ID)).header(RestParams.USER_ID_HEADER, USER_ID)
-                                                                       .contentType(APPLICATION_JSON)).andDo(print())
-               .andExpect(status().isOk()).andExpect(jsonPath("$.id", is(version.getId())));
+                        .contentType(APPLICATION_JSON)).andDo(print()).andExpect(status().isOk())
+                .andExpect(jsonPath("$.id", is(version.getId())));
         verify(workflowVersionManagerMock, times(1)).get(ITEM1_ID, VERSION1_ID);
     }
 
@@ -104,9 +115,7 @@ public class WorkflowVersionControllerTest {
 
         MockHttpServletResponse result = mockMvc.perform(
                 put(RestPath.getWorkflowVersion(ITEM1_ID, VERSION1_ID)).header(RestParams.USER_ID_HEADER, USER_ID)
-                                                                       .contentType(APPLICATION_JSON)
-                                                                       .content(GSON.toJson(version))).andReturn()
-                                                .getResponse();
+                        .contentType(APPLICATION_JSON).content(GSON.toJson(version))).andReturn().getResponse();
 
         assertEquals(HttpStatus.OK.value(), result.getStatus());
         version.setId(VERSION1_ID);
index 423c5e6..c40aef3 100644 (file)
@@ -2,8 +2,8 @@ package org.onap.sdc.workflow.api.types;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
-import static org.onap.sdc.workflow.persistence.types.WorkflowVersionState.CERTIFIED;
-import static org.onap.sdc.workflow.persistence.types.WorkflowVersionState.DRAFT;
+import static org.onap.sdc.workflow.services.types.WorkflowVersionState.CERTIFIED;
+import static org.onap.sdc.workflow.services.types.WorkflowVersionState.DRAFT;
 
 import java.util.Collections;
 import java.util.stream.Collectors;
diff --git a/workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ActivitySpecRepositoryImplTest.java b/workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ActivitySpecRepositoryImplTest.java
new file mode 100644 (file)
index 0000000..999097c
--- /dev/null
@@ -0,0 +1,365 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.persistence.impl;
+
+import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext;
+
+import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element;
+import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementConflict;
+import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo;
+import com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict;
+import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement;
+import com.amdocs.zusammen.commons.health.data.HealthInfo;
+import com.amdocs.zusammen.datatypes.Id;
+import com.amdocs.zusammen.datatypes.SessionContext;
+import com.amdocs.zusammen.datatypes.item.Action;
+import com.amdocs.zusammen.datatypes.item.ElementContext;
+import com.amdocs.zusammen.datatypes.item.Info;
+import com.amdocs.zusammen.datatypes.item.Item;
+import com.amdocs.zusammen.datatypes.item.ItemVersion;
+import com.amdocs.zusammen.datatypes.item.ItemVersionData;
+import com.amdocs.zusammen.datatypes.item.ItemVersionStatus;
+import com.amdocs.zusammen.datatypes.item.Resolution;
+import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions;
+import com.amdocs.zusammen.datatypes.itemversion.Tag;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.onap.sdc.workflow.persistence.impl.ActivitySpecRepositoryImpl.InfoPropertyName;
+import org.onap.sdc.workflow.persistence.impl.types.ActivitySpecData;
+import org.onap.sdc.workflow.persistence.impl.types.ActivitySpecElementType;
+import org.onap.sdc.workflow.persistence.types.ActivitySpecEntity;
+import org.onap.sdc.workflow.persistence.types.ActivitySpecParameter;
+import org.openecomp.core.utilities.json.JsonUtil;
+import org.openecomp.core.zusammen.api.ZusammenAdaptor;
+import org.openecomp.sdc.common.session.SessionContextProviderFactory;
+import org.openecomp.sdc.versioning.dao.types.Version;
+import org.openecomp.types.ElementPropertyName;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+public class ActivitySpecRepositoryImplTest {
+
+    private static final Version version = new Version();
+    private static final String versionId = "1234";
+    private static final String itemId = "5678";
+    private static final String tenant = "dox";
+
+    private ZusammenAdaptorMock zusammenAdaptor;
+    private ActivitySpecRepositoryImpl daoImpl;
+    private ActivitySpecEntity entity;
+
+
+    @Before
+    public void setUp() {
+        SessionContextProviderFactory.getInstance().createInterface().create("test", tenant);
+        zusammenAdaptor = new ZusammenAdaptorMock();
+        daoImpl = new ActivitySpecRepositoryImpl(zusammenAdaptor);
+        entity = new ActivitySpecEntity();
+        entity = new ActivitySpecEntity();
+
+        entity.setId(itemId);
+        version.setId(versionId);
+        entity.setVersion(version);
+        entity.setName("activitySpec");
+        List<String> categoryList = new ArrayList<>();
+        categoryList.add("category1");
+        entity.setCategoryList(categoryList);
+        ActivitySpecParameter inputParams = new ActivitySpecParameter("dbhost", "String", null);
+        inputParams.setValue("localhost");
+        List<ActivitySpecParameter> inputs = new ArrayList<>();
+        inputs.add(inputParams);
+        entity.setInputs(inputs);
+    }
+
+    @After
+    public void tearDown() {
+        SessionContextProviderFactory.getInstance().createInterface().close();
+    }
+
+    @Test
+    public void testCreate() {
+        ItemVersion itemVersionmock = new ItemVersion();
+        itemVersionmock.setId(new Id());
+
+        daoImpl.create(entity);
+        SessionContext context = createSessionContext();
+        ElementContext elementContext = new ElementContext(entity.getId(), entity.getVersion().getId());
+        Optional<ElementInfo> testElementInfo = zusammenAdaptor.getElementInfoByName(context, elementContext, Id.ZERO,
+                ActivitySpecElementType.ACTIVITYSPEC.name());
+        Assert.assertTrue(testElementInfo.isPresent());
+        Assert.assertEquals(testElementInfo.get().getInfo().getName(), ActivitySpecElementType.ACTIVITYSPEC.name());
+        Assert.assertEquals(testElementInfo.get().getInfo()
+                                    .getProperty(ActivitySpecRepositoryImpl.InfoPropertyName.DESCRIPTION.getValue()),
+                entity.getDescription());
+        Assert.assertEquals(testElementInfo.get().getInfo().getProperty(InfoPropertyName.CATEGORY.getValue()),
+                entity.getCategoryList());
+        Assert.assertEquals(testElementInfo.get().getInfo()
+                                    .getProperty(ActivitySpecRepositoryImpl.InfoPropertyName.NAME.getValue()),
+                entity.getName());
+
+        final Optional<Element> testElement =
+                zusammenAdaptor.getElement(context, elementContext, zusammenAdaptor.elementId);
+        final InputStream data = testElement.get().getData();
+        final ActivitySpecData activitySpecData = JsonUtil.json2Object(data, ActivitySpecData.class);
+        Assert.assertEquals(activitySpecData.getInputs().get(0).getName(), entity.getInputs().get(0).getName());
+    }
+
+    @Test
+    public void testGet() {
+        final ActivitySpecEntity retrieved = daoImpl.get(entity);
+        Assert.assertEquals(retrieved.getName(), entity.getName());
+        Assert.assertEquals(retrieved.getDescription(), entity.getDescription());
+        Assert.assertEquals(retrieved.getCategoryList(), entity.getCategoryList());
+    }
+
+    @Test
+    public void testUpdate() {
+        entity.setDescription("Update AS version1");
+        daoImpl.update(entity);
+        final ActivitySpecEntity retrieved = daoImpl.get(entity);
+        Assert.assertEquals(retrieved.getName(), entity.getName());
+        Assert.assertEquals(retrieved.getDescription(), entity.getDescription());
+        Assert.assertEquals(retrieved.getCategoryList(), entity.getCategoryList());
+    }
+
+    private class ZusammenAdaptorMock implements ZusammenAdaptor {
+
+        private final Map<String, Element> elementMap = new HashMap<>();
+        String elementId;
+        private ItemVersion itemVersion;
+
+        @Override
+        public Collection<Item> listItems(SessionContext context) {
+            return null;
+        }
+
+        @Override
+        public Item getItem(SessionContext context, Id itemId) {
+            return null;
+        }
+
+        @Override
+        public void deleteItem(SessionContext context, Id itemId) {
+
+        }
+
+        @Override
+        public Id createItem(SessionContext context, Info info) {
+            return null;
+        }
+
+        @Override
+        public void updateItem(SessionContext context, Id itemId, Info info) {
+
+        }
+
+        @Override
+        public Optional<ItemVersion> getFirstVersion(SessionContext context, Id itemId) {
+
+            return Optional.ofNullable(itemVersion);
+        }
+
+        @Override
+        public Collection<ItemVersion> listPublicVersions(SessionContext context, Id itemId) {
+            return null;
+        }
+
+        @Override
+        public ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId) {
+            return null;
+        }
+
+        @Override
+        public Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData itemVersionData) {
+            return null;
+        }
+
+        @Override
+        public void updateVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData) {
+
+        }
+
+        @Override
+        public ItemVersion getVersion(SessionContext context, Id itemId, Id versionId) {
+            return null;
+        }
+
+        @Override
+        public ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId) {
+            return null;
+        }
+
+        @Override
+        public ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId) {
+            return null;
+        }
+
+        @Override
+        public void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag) {
+
+        }
+
+        @Override
+        public void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef) {
+
+        }
+
+        @Override
+        public void publishVersion(SessionContext context, Id itemId, Id versionId, String message) {
+
+        }
+
+        @Override
+        public void syncVersion(SessionContext sessionContext, Id itemId, Id versionId) {
+
+        }
+
+        @Override
+        public void forceSyncVersion(SessionContext context, Id itemId, Id versionId) {
+
+        }
+
+        @Override
+        public void cleanVersion(SessionContext sessionContext, Id itemId, Id versionId) {
+
+        }
+
+        @Override
+        public Optional<ElementInfo> getElementInfo(SessionContext context, ElementContext elementContext,
+                Id elementId) {
+            return Optional.empty();
+        }
+
+        @Override
+        public Optional<Element> getElement(SessionContext context, ElementContext elementContext, String elementId) {
+            return Optional.of(elementMap.get(elementId));
+        }
+
+        @Override
+        public Optional<Element> getElementByName(SessionContext context, ElementContext elementContext,
+                Id parentElementId, String elementName) {
+            //return Optional.empty();
+            ZusammenElement element = new ZusammenElement();
+            Info info = new Info();
+            element.setElementId(Id.ZERO);
+            info.addProperty("name", entity.getName());
+            info.addProperty("description", entity.getDescription());
+            info.addProperty("category", entity.getCategoryList());
+            element.setInfo(info);
+            return Optional.ofNullable(element);
+        }
+
+        @Override
+        public Collection<ElementInfo> listElements(SessionContext context, ElementContext elementContext,
+                Id parentElementId) {
+            return null;
+        }
+
+        @Override
+        public Collection<Element> listElementData(SessionContext context, ElementContext elementContext,
+                Id parentElementId) {
+            return elementMap.values();
+        }
+
+        @Override
+        public Collection<ElementInfo> listElementsByName(SessionContext context, ElementContext elementContext,
+                Id parentElementId, String elementName) {
+
+            return elementMap.values().stream().filter(element -> elementName.equals(element.getInfo().getProperty(
+                    ElementPropertyName.elementType.name()))).map(element -> {
+                ElementInfo elementInfo = new ElementInfo();
+                elementInfo.setId(element.getElementId());
+                elementInfo.setInfo(element.getInfo());
+                return elementInfo;
+            }).collect(Collectors.toList());
+
+        }
+
+        @Override
+        public Optional<ElementInfo> getElementInfoByName(SessionContext context, ElementContext elementContext,
+                Id parentElementId, String elementName) {
+
+
+            return elementMap.values().stream().filter(element -> elementName.equals(element.getInfo().getProperty(
+                    ElementPropertyName.elementType.name()))).map(element -> {
+                ElementInfo elementInfo = new ElementInfo();
+                elementInfo.setId(element.getElementId());
+                elementInfo.setInfo(element.getInfo());
+                return elementInfo;
+            }).findAny();
+
+
+        }
+
+        @Override
+        public Optional<ElementConflict> getElementConflict(SessionContext context, ElementContext elementContext,
+                Id id) {
+            return Optional.empty();
+        }
+
+        @Override
+        public Element saveElement(SessionContext context, ElementContext elementContext, ZusammenElement element,
+                String message) {
+            if (element.getAction().equals(Action.CREATE) || element.getAction().equals(Action.UPDATE)) {
+                element.setElementId(new Id(UUID.randomUUID().toString()));
+            }
+            elementMap.put(element.getElementId().getValue(), element);
+            elementId = element.getElementId().getValue();
+            return element;
+        }
+
+        @Override
+        public void resolveElementConflict(SessionContext context, ElementContext elementContext,
+                ZusammenElement element, Resolution resolution) {
+
+        }
+
+        @Override
+        public void revert(SessionContext sessionContext, Id itemId, Id versionId, Id revisionId) {
+
+        }
+
+        @Override
+        public ItemVersionRevisions listRevisions(SessionContext sessionContext, Id itemId, Id versionId) {
+            return null;
+        }
+
+        @Override
+        public Collection<HealthInfo> checkHealth(SessionContext context) {
+            return null;
+        }
+
+        @Override
+        public String getVersion(SessionContext sessionContext) {
+            return null;
+        }
+
+    }
+
+}
index b86b14b..9d202fc 100644 (file)
@@ -26,7 +26,7 @@ import org.mockito.InjectMocks;
 import org.mockito.Mock;
 import org.mockito.junit.MockitoJUnitRunner;
 import org.onap.sdc.workflow.persistence.types.ArtifactEntity;
-import org.onap.sdc.workflow.persistence.types.WorkflowElementType;
+import org.onap.sdc.workflow.persistence.impl.types.WorkflowElementType;
 import org.openecomp.core.zusammen.api.ZusammenAdaptor;
 import org.openecomp.sdc.common.session.SessionContextProviderFactory;
 
index 07a4265..546a3fe 100644 (file)
@@ -26,10 +26,10 @@ import org.mockito.Mock;
 import org.mockito.Spy;
 import org.mockito.junit.MockitoJUnitRunner;
 import org.onap.sdc.workflow.persistence.types.ParameterEntity;
-import org.onap.sdc.workflow.persistence.types.ParameterPropertyName;
+import org.onap.sdc.workflow.persistence.impl.types.ParameterPropertyName;
 import org.onap.sdc.workflow.persistence.types.ParameterRole;
 import org.onap.sdc.workflow.persistence.types.ParameterType;
-import org.onap.sdc.workflow.persistence.types.WorkflowElementType;
+import org.onap.sdc.workflow.persistence.impl.types.WorkflowElementType;
 import org.openecomp.core.zusammen.api.ZusammenAdaptor;
 import org.openecomp.sdc.common.session.SessionContextProviderFactory;
 
@@ -62,7 +62,7 @@ public class ParameterRepositoryTest {
         Info info = new Info();
         info.setName("testInput");
         info.addProperty(ParameterPropertyName.TYPE.name(), ParameterType.FLOAT.name());
-        info.addProperty(ParameterPropertyName.mandatory.name(), true);
+        info.addProperty(ParameterPropertyName.MANDATORY.name(), true);
         element.setInfo(info);
         doReturn(Optional.of(element)).when(zusammenAdaptorMock)
                                       .getElementInfo(any(SessionContext.class), any(ElementContext.class),
@@ -118,14 +118,14 @@ public class ParameterRepositoryTest {
         Info info1 = new Info();
         info1.setName("input1");
         info1.addProperty(ParameterPropertyName.TYPE.name(), "INTEGER");
-        info1.addProperty(ParameterPropertyName.mandatory.name(), true);
+        info1.addProperty(ParameterPropertyName.MANDATORY.name(), true);
         parameter1.setInfo(info1);
         ElementInfo parameter2 = new ElementInfo();
         parameter2.setId(new Id(PARAMETER2_ID));
         Info info2 = new Info();
         info2.setName("input2");
         info2.addProperty(ParameterPropertyName.TYPE.name(), "STRING");
-        info2.addProperty(ParameterPropertyName.mandatory.name(), false);
+        info2.addProperty(ParameterPropertyName.MANDATORY.name(), false);
         parameter2.setInfo(info2);
         Collection<ElementInfo> parameters = Collections.asSet(parameter1, parameter2);
         doReturn(parameters).when(zusammenAdaptorMock)
index 4911060..5c285c3 100644 (file)
@@ -38,45 +38,45 @@ public class UniqueValueServiceTest {
     }
 
     @Test
-    public void shouldCallRepositoryInsertIfValueUnique(){
+    public void shouldCallRepositoryInsertIfValueUnique() {
         doReturn(Optional.empty()).when(uniqueValueRepositoryMock).findById(any());
-        uniqueValueService.createUniqueValue(TYPE, new String[]{DUMMY_COMBINATION});
+        uniqueValueService.createUniqueValue(TYPE, DUMMY_COMBINATION);
         verify(uniqueValueRepositoryMock, times(1)).insert(any(UniqueValueEntity.class));
     }
 
     @Test
-    public void shouldNotCheckValueIfNoUniqueCombination(){
-        uniqueValueService.createUniqueValue(TYPE, null);
+    public void shouldNotCheckValueIfNoUniqueCombination() {
+        uniqueValueService.createUniqueValue(TYPE);
         verify(uniqueValueRepositoryMock, never()).findById(any(UniqueValueEntity.class));
     }
 
     @Test(expected = UniqueValueViolationException.class)
-    public void shouldThrowExceptionIfValueIsNotUnique(){
+    public void shouldThrowExceptionIfValueIsNotUnique() {
         doReturn(Optional.of("xxx")).when(uniqueValueRepositoryMock).findById(any());
-        uniqueValueService.createUniqueValue(TYPE, new String[]{DUMMY_COMBINATION});
+        uniqueValueService.createUniqueValue(TYPE, DUMMY_COMBINATION);
     }
 
     @Test
-    public void shouldCallRepositoryDeleteIfValueValid(){
-        uniqueValueService.deleteUniqueValue(TYPE, new String[]{DUMMY_COMBINATION});
+    public void shouldCallRepositoryDeleteIfValueValid() {
+        uniqueValueService.deleteUniqueValue(TYPE, DUMMY_COMBINATION);
         verify(uniqueValueRepositoryMock, times(1)).delete(any(UniqueValueEntity.class));
     }
 
     @Test
-    public void shouldNotCallRepositoryDeleteIfValueNouniqueCombination(){
-        uniqueValueService.deleteUniqueValue(TYPE, new String[]{});
+    public void shouldNotCallRepositoryDeleteIfValueNouniqueCombination() {
+        uniqueValueService.deleteUniqueValue(TYPE);
         verify(uniqueValueRepositoryMock, never()).delete(any(UniqueValueEntity.class));
     }
 
     @Test
-    public void shouldNotUpdateIfNewAndOldValueAreEqualsCaseIgnore(){
+    public void shouldNotUpdateIfNewAndOldValueAreEqualsCaseIgnore() {
         String value = "value";
         uniqueValueService.updateUniqueValue(TYPE, value, value.toUpperCase());
         verify(uniqueValueService, never()).createUniqueValue(anyString(), any());
     }
 
     @Test
-    public void shouldUpdateIfNewAndOldValueAreNotEqualsCaseIgnore(){
+    public void shouldUpdateIfNewAndOldValueAreNotEqualsCaseIgnore() {
         String oldValue = "oldValue";
         String newValue = "newValue";
         uniqueValueService.updateUniqueValue(TYPE, oldValue, newValue);
@@ -87,12 +87,12 @@ public class UniqueValueServiceTest {
     @Test
     public void shouldReturnTrueIfValueExist() {
         doReturn(Optional.of("xxx")).when(uniqueValueRepositoryMock).findById(any());
-        assertTrue(uniqueValueService.isUniqueValueOccupied(TYPE, new String[]{DUMMY_COMBINATION}));
+        assertTrue(uniqueValueService.isUniqueValueOccupied(TYPE, DUMMY_COMBINATION));
     }
 
     @Test
     public void shouldReturnFalseIfValueNotExist() {
         doReturn(Optional.empty()).when(uniqueValueRepositoryMock).findById(any());
-        assertFalse(uniqueValueService.isUniqueValueOccupied(TYPE, new String[]{DUMMY_COMBINATION}));
+        assertFalse(uniqueValueService.isUniqueValueOccupied(TYPE, DUMMY_COMBINATION));
     }
 }
diff --git a/workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/ActivitySpecManagerImplTest.java b/workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/ActivitySpecManagerImplTest.java
new file mode 100644 (file)
index 0000000..719531b
--- /dev/null
@@ -0,0 +1,301 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.sdc.workflow.services.impl;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.verify;
+import static org.onap.sdc.workflow.services.ActivitySpecConstant.ACTIVITY_SPEC_NOT_FOUND;
+import static org.onap.sdc.workflow.services.ActivitySpecConstant.VERSION_ID_DEFAULT_VALUE;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
+import org.onap.sdc.workflow.api.types.activityspec.ActivitySpecAction;
+import org.onap.sdc.workflow.persistence.ActivitySpecRepository;
+import org.onap.sdc.workflow.persistence.types.ActivitySpecEntity;
+import org.onap.sdc.workflow.persistence.types.ActivitySpecParameter;
+import org.onap.sdc.workflow.services.UniqueValueService;
+import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException;
+import org.onap.sdc.workflow.services.exceptions.VersionStatusModificationException;
+import org.onap.sdc.workflow.services.impl.mappers.ActivitySpecMapper;
+import org.openecomp.sdc.common.errors.SdcRuntimeException;
+import org.openecomp.sdc.versioning.ItemManager;
+import org.openecomp.sdc.versioning.VersioningManager;
+import org.openecomp.sdc.versioning.dao.types.Version;
+import org.openecomp.sdc.versioning.dao.types.VersionStatus;
+import org.openecomp.sdc.versioning.types.Item;
+
+public class ActivitySpecManagerImplTest {
+
+    private static final String STRING_TYPE = "String";
+    private static final String TEST_ERROR_MSG = "Test Error";
+    private static final String ID = "ID1";
+    private Version version01 = new Version("12345");
+    private ActivitySpecEntity input;
+
+    @Spy
+    @InjectMocks
+    private ActivitySpecManagerImpl activitySpecManager;
+    @Mock
+    private ItemManager itemManagerMock;
+    @Mock
+    private VersioningManager versionManagerMock;
+    @Mock
+    private ActivitySpecRepository activitySpecRepositoryMock;
+    @Mock
+    private UniqueValueService uniqueValueServiceMock;
+    @Mock
+    private ActivitySpecMapper activitySpecMapperMock;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+    }
+
+    @After
+    public void tearDown() {
+        activitySpecManager = null;
+    }
+
+    @Test
+    public void testCreate() {
+        ActivitySpecEntity activitySpecToCreate = new ActivitySpecEntity();
+        activitySpecToCreate.setName("startserver");
+        activitySpecToCreate.setDescription("start the server");
+        activitySpecToCreate.setVersion(version01);
+
+        List<String> categoryList = new ArrayList<>();
+        categoryList.add("category1");
+        categoryList.add("category2");
+        activitySpecToCreate.setCategoryList(categoryList);
+
+        ActivitySpecParameter inputParams = new ActivitySpecParameter("dbhost", STRING_TYPE, null);
+        inputParams.setValue("localhost");
+        ActivitySpecParameter inputParams1 = new ActivitySpecParameter("dbname", STRING_TYPE, null);
+        inputParams.setValue("prod");
+        List<ActivitySpecParameter> inputs = new ArrayList<>();
+        inputs.add(inputParams);
+        inputs.add(inputParams1);
+        activitySpecToCreate.setInputs(inputs);
+
+        ActivitySpecParameter outputParams = new ActivitySpecParameter("status", STRING_TYPE, null);
+        outputParams.setValue("started");
+        List<ActivitySpecParameter> outputs = new ArrayList<>();
+        outputs.add(outputParams);
+        activitySpecToCreate.setOutputs(outputs);
+
+        activitySpecToCreate.setId("ID1");
+        activitySpecToCreate.setVersion(version01);
+
+        Item mappedItem = new Item();
+        doReturn(mappedItem).when(activitySpecMapperMock).activitySpecToItem(activitySpecToCreate);
+        doReturn(new Item()).when(itemManagerMock).create(mappedItem);
+
+        ActivitySpecEntity activitySpec = activitySpecManager.createActivitySpec(activitySpecToCreate);
+
+        Assert.assertNotNull(activitySpec);
+        activitySpec.setId("ID1");
+        activitySpec.setStatus(VersionStatus.Draft.name());
+        assertActivitySpecEquals(activitySpec, activitySpecToCreate);
+    }
+
+    private void assertActivitySpecEquals(ActivitySpecEntity actual, ActivitySpecEntity expected) {
+        Assert.assertEquals(actual.getId(), expected.getId());
+        Assert.assertEquals(actual.getName(), expected.getName());
+        Assert.assertEquals(actual.getDescription(), expected.getDescription());
+        Assert.assertEquals(actual.getCategoryList(), expected.getCategoryList());
+        Assert.assertEquals(actual.getInputs(), expected.getInputs());
+        Assert.assertEquals(actual.getOutputs(), expected.getOutputs());
+    }
+
+    @Test
+    public void testList() {
+        Item item = new Item();
+        item.setId(ID);
+        doReturn(Collections.singletonList(item)).when(itemManagerMock).list(any());
+        doReturn(new ActivitySpecEntity(ID, null)).when(activitySpecMapperMock).itemToActivitySpec(item);
+
+        final Collection<ActivitySpecEntity> activitySpecs = activitySpecManager.list("Certified");
+        Assert.assertEquals(1, activitySpecs.size());
+        Assert.assertEquals(ID, activitySpecs.iterator().next().getId());
+    }
+
+    @Test
+    public void testListInvalidFilter() {
+        final Collection<ActivitySpecEntity> activitySpecs = activitySpecManager.list("invalid_status");
+        Assert.assertEquals(0, activitySpecs.size());
+    }
+
+    @Test
+    public void testListNoFilter() {
+        final Collection<ActivitySpecEntity> activitySpecs = activitySpecManager.list(null);
+        Assert.assertEquals(0, activitySpecs.size());
+    }
+
+    @Test
+    public void testGet() {
+        input = new ActivitySpecEntity();
+        input.setId(ID);
+        input.setVersion(version01);
+
+        mockListVersions();
+        doReturn(input).when(activitySpecRepositoryMock).get(any());
+        version01.setStatus(VersionStatus.Draft);
+        doReturn(version01).when(versionManagerMock).get(any(), any());
+        ActivitySpecEntity retrieved = activitySpecManager.get(input);
+        assertActivitySpecEquals(retrieved, input);
+        Assert.assertEquals(retrieved.getStatus(), VersionStatus.Draft.name());
+
+
+        input.setVersion(new Version(VERSION_ID_DEFAULT_VALUE));
+        retrieved = activitySpecManager.get(input);
+        assertActivitySpecEquals(retrieved, input);
+        Assert.assertEquals(retrieved.getStatus(), VersionStatus.Draft.name());
+    }
+
+    private void mockListVersions() {
+        doReturn(Collections.singletonList(version01)).when(versionManagerMock).list(any());
+    }
+
+    @Test
+    public void testGetActivitySpecDaoFail() {
+        input = new ActivitySpecEntity();
+        input.setId(ID);
+        input.setVersion(version01);
+        mockListVersions();
+        doReturn(input).when(activitySpecRepositoryMock).get(any());
+        Mockito.doThrow(new SdcRuntimeException(TEST_ERROR_MSG)).when(activitySpecRepositoryMock).get(any());
+        try {
+            activitySpecManager.get(input);
+            Assert.fail();
+        } catch (EntityNotFoundException exception) {
+            Assert.assertEquals(ACTIVITY_SPEC_NOT_FOUND, exception.getMessage());
+        }
+    }
+
+    @Test
+    public void testListVersionFail() {
+        input = new ActivitySpecEntity();
+        input.setId(ID);
+        input.setVersion(version01);
+        input.getVersion().setId(VERSION_ID_DEFAULT_VALUE);
+        Mockito.doThrow(new SdcRuntimeException(TEST_ERROR_MSG)).when(versionManagerMock).list(any());
+        try {
+            activitySpecManager.get(input);
+            Assert.fail();
+        } catch (EntityNotFoundException exception) {
+            Assert.assertEquals(ACTIVITY_SPEC_NOT_FOUND, exception.getMessage());
+        }
+    }
+
+    @Test(expected = VersionStatusModificationException.class)
+    public void testInvalidDeprecate() {
+        Version version = new Version(version01.getId());
+        version.setStatus(VersionStatus.Draft);
+        doReturn(version).when(versionManagerMock).get(ID, version01);
+        activitySpecManager.actOnAction(new ActivitySpecEntity(ID, version01), ActivitySpecAction.DEPRECATE);
+    }
+
+    @Test(expected = VersionStatusModificationException.class)
+    public void testInvalidDelete() {
+        mockCertifiedVersion();
+        activitySpecManager.actOnAction(new ActivitySpecEntity(ID, version01), ActivitySpecAction.DELETE);
+    }
+
+    private void mockCertifiedVersion() {
+        Version version = new Version(version01.getId());
+        version.setStatus(VersionStatus.Certified);
+        doReturn(version).when(versionManagerMock).get(ID, version01);
+    }
+
+    @Test(expected = VersionStatusModificationException.class)
+    public void testInvalidCertify() {
+        mockCertifiedVersion();
+        activitySpecManager.actOnAction(new ActivitySpecEntity(ID, version01), ActivitySpecAction.CERTIFY);
+    }
+
+    @Test
+    public void testCertify() {
+        Version retrievedVersion = new Version(version01.getId());
+        retrievedVersion.setStatus(VersionStatus.Draft);
+        doReturn(Collections.singletonList(retrievedVersion)).when(versionManagerMock).list(any());
+        doReturn(retrievedVersion).when(versionManagerMock).get(any(), any());
+
+        activitySpecManager.actOnAction(new ActivitySpecEntity(ID, version01), ActivitySpecAction.CERTIFY);
+
+        verify(versionManagerMock).updateVersion(ID, retrievedVersion);
+        verify(itemManagerMock).updateVersionStatus(ID, VersionStatus.Certified, VersionStatus.Draft);
+        verify(versionManagerMock).publish(ID, retrievedVersion, "actionOnActivitySpec :CERTIFY");
+    }
+
+    @Test
+    public void testGetVersionFailOnStatusChangeAction() {
+        mockListVersions();
+        Mockito.doThrow(new SdcRuntimeException(TEST_ERROR_MSG)).when(versionManagerMock).get(any(), any());
+        try {
+            activitySpecManager.actOnAction(new ActivitySpecEntity(ID, version01), ActivitySpecAction.CERTIFY);
+            Assert.fail();
+        } catch (EntityNotFoundException exception) {
+            Assert.assertEquals(ACTIVITY_SPEC_NOT_FOUND, exception.getMessage());
+        }
+    }
+
+    @Test
+    public void testDeprecate() {
+        version01.setStatus(VersionStatus.Certified);
+        Version retrivedVersion = new Version("12");
+        retrivedVersion.setStatus(VersionStatus.Certified);
+        mockListVersions();
+        doReturn(retrivedVersion).when(versionManagerMock).get(any(), any());
+        activitySpecManager.actOnAction(new ActivitySpecEntity(ID, new Version(VERSION_ID_DEFAULT_VALUE)), ActivitySpecAction.DEPRECATE);
+
+        verify(versionManagerMock).updateVersion(ID, retrivedVersion);
+        verify(itemManagerMock).updateVersionStatus(ID, VersionStatus.Deprecated, VersionStatus.Certified);
+        verify(versionManagerMock).publish(any(), any(), any());
+    }
+
+    @Test
+    public void testDelete() {
+        ActivitySpecEntity activitySpec = new ActivitySpecEntity();
+        version01.setStatus(VersionStatus.Deprecated);
+        activitySpec.setName("stopServer");
+        activitySpec.setVersion(version01);
+
+        Version retrivedVersion = new Version("12");
+        retrivedVersion.setStatus(VersionStatus.Deprecated);
+
+        mockListVersions();
+        doReturn(retrivedVersion).when(versionManagerMock).get(any(), any());
+        doReturn(activitySpec).when(activitySpecRepositoryMock).get(any());
+        activitySpecManager.actOnAction(new ActivitySpecEntity(ID, new Version(VERSION_ID_DEFAULT_VALUE)), ActivitySpecAction.DELETE);
+
+        verify(versionManagerMock).updateVersion(ID, version01);
+        verify(itemManagerMock).updateVersionStatus(ID, VersionStatus.Deleted, VersionStatus.Deprecated);
+        verify(versionManagerMock).publish(any(), any(), any());
+    }
+}
index de17a04..2b93075 100644 (file)
@@ -25,8 +25,8 @@ import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.InjectMocks;
 import org.mockito.Mock;
-import org.onap.sdc.workflow.persistence.types.Workflow;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
+import org.onap.sdc.workflow.services.types.Workflow;
+import org.onap.sdc.workflow.services.types.WorkflowVersionState;
 import org.onap.sdc.workflow.services.UniqueValueService;
 import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException;
 import org.onap.sdc.workflow.services.impl.mappers.VersionStateMapper;
index be6fe04..9640fa1 100644 (file)
@@ -7,15 +7,13 @@ import static org.mockito.ArgumentMatchers.argThat;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
-import static org.onap.sdc.workflow.persistence.types.WorkflowVersionState.CERTIFIED;
-import static org.onap.sdc.workflow.persistence.types.WorkflowVersionState.DRAFT;
+import static org.onap.sdc.workflow.services.types.WorkflowVersionState.CERTIFIED;
+import static org.onap.sdc.workflow.services.types.WorkflowVersionState.DRAFT;
 
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 import java.util.Optional;
@@ -32,8 +30,8 @@ import org.onap.sdc.workflow.persistence.ArtifactRepository;
 import org.onap.sdc.workflow.persistence.ParameterRepository;
 import org.onap.sdc.workflow.persistence.types.ArtifactEntity;
 import org.onap.sdc.workflow.persistence.types.ParameterRole;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersion;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
+import org.onap.sdc.workflow.services.types.WorkflowVersion;
+import org.onap.sdc.workflow.services.types.WorkflowVersionState;
 import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException;
 import org.onap.sdc.workflow.services.exceptions.VersionCreationException;
 import org.onap.sdc.workflow.services.exceptions.VersionStateModificationException;
index d979035..3ee3c07 100644 (file)
@@ -5,8 +5,8 @@ import static org.junit.Assert.assertEquals;
 import java.util.Date;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersion;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
+import org.onap.sdc.workflow.services.types.WorkflowVersion;
+import org.onap.sdc.workflow.services.types.WorkflowVersionState;
 import org.openecomp.sdc.versioning.dao.types.Version;
 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
 import org.springframework.beans.factory.annotation.Autowired;
index 070c433..b69b0f7 100644 (file)
@@ -4,7 +4,7 @@ import static org.junit.Assert.assertEquals;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
+import org.onap.sdc.workflow.services.types.WorkflowVersionState;
 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.ComponentScan;
index 55802cc..d6e16d5 100644 (file)
@@ -8,7 +8,7 @@ import static org.onap.sdc.workflow.TestUtil.createWorkflow;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.onap.sdc.workflow.persistence.types.Workflow;
+import org.onap.sdc.workflow.services.types.Workflow;
 import org.openecomp.sdc.versioning.types.Item;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.ComponentScan;