summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorStone, Avi (as206k) <as206k@att.com>2018-05-24 16:12:32 +0300
committerStone, Avi (as206k) <as206k@att.com>2018-05-24 16:12:32 +0300
commit1a0189f890e4ff65ee245be9b7ef67788ac53a61 (patch)
tree15c269d48d03ef35770763169bd85f4cf31398c0
parentcd0441658018dfbab0950f959c9b718ad9601f6d (diff)
Update code
Update to latest version after improving testing and sonar coverage Change-Id: I527f4bc38d3b4e1005d38e3a2584fa730857425d Issue-ID: SDC-1313 Signed-off-by: Stone, Avi (as206k) <as206k@att.com>
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BaseController.java60
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BlueprintController.java68
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/CompositionController.java212
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/ConfigurationController.java2
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/LifecycleController.java11
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/RuleEditorController.java9
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/VfcmtController.java3
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BaseBusinessLogic.java34
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BlueprintBusinessLogic.java12
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/CompositionBusinessLogic.java9
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/CompositionCatalogBusinessLogic.java205
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogic.java2
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogic.java1
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogic.java48
-rw-r--r--dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/RuleValidator.java4
-rw-r--r--dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/CompositionCatalogBusinessLogicTest.java74
-rw-r--r--dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogicTest.java406
-rw-r--r--dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDC.java802
-rw-r--r--dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCController.java0
-rw-r--r--dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtils.java276
-rw-r--r--dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/RequestError.java18
-rw-r--r--dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Action.java2
-rw-r--r--dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Future.java3
-rw-r--r--dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/FutureHandler.java2
-rw-r--r--dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Futures.java8
-rw-r--r--dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogController.java9
-rw-r--r--dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogError.java3
-rw-r--r--dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogRequest.java2
28 files changed, 717 insertions, 1568 deletions
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BaseController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BaseController.java
index 818a30d..131efad 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BaseController.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BaseController.java
@@ -1,37 +1,23 @@
package org.onap.sdc.dcae.composition.controller;
-import javax.servlet.http.HttpServletRequest;
-
+import com.google.gson.Gson;
+import org.onap.sdc.common.onaplog.Enums.LogLevel;
import org.onap.sdc.common.onaplog.OnapLoggerDebug;
import org.onap.sdc.common.onaplog.OnapLoggerError;
-import org.onap.sdc.common.onaplog.Enums.LogLevel;
import org.onap.sdc.dcae.composition.impl.BaseBusinessLogic;
-import org.onap.sdc.dcae.composition.restmodels.sdc.Asset;
-import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed;
-import org.onap.sdc.dcae.composition.util.DcaeBeConstants;
-import org.onap.sdc.dcae.composition.util.SystemProperties;
-import org.onap.sdc.dcae.enums.AssetType;
-import org.onap.sdc.dcae.enums.LifecycleOperationType;
-import org.onap.sdc.dcae.errormng.ActionStatus;
-import org.onap.sdc.dcae.errormng.DcaeException;
import org.onap.sdc.dcae.errormng.ErrConfMgr;
import org.onap.sdc.dcae.errormng.ErrConfMgr.ApiType;
-import org.onap.sdc.dcae.errormng.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
-import com.google.gson.Gson;
+import javax.servlet.http.HttpServletRequest;
public abstract class BaseController {
protected Gson gson = new Gson();
@Autowired
- protected SystemProperties systemProperties;
-
- @Autowired
protected BaseBusinessLogic baseBusinessLogic;
protected OnapLoggerError errLogger = OnapLoggerError.getInstance();
@@ -42,48 +28,8 @@ public abstract class BaseController {
return request.getAttribute("requestId").toString();
}
- ResourceDetailed checkoutVfcmt(String userId, String uuid, String requestId) {
- return baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, uuid, LifecycleOperationType.CHECKOUT.name(), null, requestId);
- }
-
- ResourceDetailed checkinVfcmt(String userId, String uuid, String requestId) {
- return baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, uuid, LifecycleOperationType.CHECKIN.name(), "checking in vfcmt" + uuid, requestId);
- }
-
-
- boolean isNeedToCheckOut(String lifecycleState) {
- return DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT != DcaeBeConstants.LifecycleStateEnum.findState(lifecycleState);
- }
-
- void checkUserIfResourceCheckedOut(String userId, Asset asset) {
- if (DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == DcaeBeConstants.LifecycleStateEnum.findState(asset.getLifecycleState())) {
- String lastUpdaterUserId = asset.getLastUpdaterUserId();
- if (lastUpdaterUserId != null && !lastUpdaterUserId.equals(userId)) {
- errLogger.log(LogLevel.ERROR, this.getClass().getName(), "User conflicts. Operation not allowed for user {} on resource checked out by {}", userId, lastUpdaterUserId);
- ResponseFormat responseFormat = ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.USER_CONFLICT, null, userId, asset.getName(), lastUpdaterUserId);
- throw new DcaeException(HttpStatus.FORBIDDEN, responseFormat.getRequestError());
- }
- }
- }
-
- void checkVfcmtType(ResourceDetailed vfcmt) {
- if (AssetType.VFCMT != getValidAssetTypeOrNull(vfcmt.getResourceType()) || !"Template".equals(vfcmt.getCategory())) {
- ResponseFormat responseFormat = ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.RESOURCE_NOT_VFCMT_ERROR, null, vfcmt.getUuid());
- throw new DcaeException(HttpStatus.BAD_REQUEST, responseFormat.getRequestError());
- }
- }
-
ResponseEntity handleException(Exception e, ApiType apiType, String... variables){
errLogger.log(LogLevel.ERROR, this.getClass().getName(), e.getMessage());
return ErrConfMgr.INSTANCE.handleException(e, apiType, variables);
}
-
- AssetType getValidAssetTypeOrNull(String type) {
- try {
- return AssetType.getAssetTypeByName(type);
- } catch (IllegalArgumentException e) {
- debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "invalid asset type: {}. Error: {}", type, e);
- return null;
- }
- }
}
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BlueprintController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BlueprintController.java
index 5f4cee7..0d638d9 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BlueprintController.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BlueprintController.java
@@ -7,48 +7,44 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
-import javax.annotation.PostConstruct;
-
@RestController
@EnableAutoConfiguration
@CrossOrigin
public class BlueprintController extends BaseController {
- @Autowired
- private BlueprintBusinessLogic blueprintBusinessLogic;
+ @Autowired
+ private BlueprintBusinessLogic blueprintBusinessLogic;
- @PostConstruct
- public void init(){
+ /***
+ * VFCMT - Resource, blueprint - as an artifact as an service.
+ * @param context
+ * @param userId
+ * @param vfcmtUuid
+ * @param serviceUuid
+ * @param instanceName
+ * @param requestId
+ * @return ResponseEntity
+ */
+ @RequestMapping(value = "{context}/createBluePrint/{VFCMTUuid}/{serviceUuid}/{instanceName}", method = RequestMethod.POST)
+ public ResponseEntity createBlueprint(
+ @RequestHeader("USER_ID") String userId,
+ @PathVariable String context,
+ @PathVariable("VFCMTUuid") String vfcmtUuid,
+ @PathVariable("serviceUuid") String serviceUuid,
+ @PathVariable("instanceName") String instanceName,
+ @ModelAttribute("requestId") String requestId) {
+ return blueprintBusinessLogic.generateAndSaveBlueprint(userId, context, vfcmtUuid, serviceUuid, instanceName, "", requestId);
}
- /***
- * VFCMT - Resource, blueprint - as an artifact as an service.
- * @param context
- * @param userId
- * @param vfcmtUuid
- * @param serviceUuid
- * @param instanceName
- * @param requestId
- * @return ResponseEntity
- */
- @RequestMapping(value = "{context}/createBluePrint/{VFCMTUuid}/{serviceUuid}/{instanceName}", method = RequestMethod.POST)
- public ResponseEntity createBlueprint(@RequestHeader("USER_ID") String userId,
- @PathVariable String context,
- @PathVariable("VFCMTUuid") String vfcmtUuid,
- @PathVariable("serviceUuid") String serviceUuid,
- @PathVariable("instanceName") String instanceName,
- @ModelAttribute("requestId") String requestId) {
- return blueprintBusinessLogic.generateAndSaveBlueprint(userId, context, vfcmtUuid, serviceUuid, instanceName, "", requestId);
- }
-
- @Deprecated
- @RequestMapping(value = "/createBluePrint/{VFCMTUuid}/{serviceUuid}/{instanceName}/{monitoringFlowType}", method = RequestMethod.POST)
- public ResponseEntity createBluePrintWithFlowType(@RequestHeader("USER_ID") String userId,
- @PathVariable("VFCMTUuid") String vfcmtUuid,
- @PathVariable("serviceUuid") String serviceUuid,
- @PathVariable("instanceName") String serviceInstanceName,
- @PathVariable("monitoringFlowType") String monitoringFlowType,
- @ModelAttribute("requestId") String requestId) {
- return blueprintBusinessLogic.generateAndSaveBlueprint(userId, AssetType.SERVICE.name(), vfcmtUuid, serviceUuid, serviceInstanceName, monitoringFlowType, requestId);
- }
+ @Deprecated
+ @RequestMapping(value = "/createBluePrint/{VFCMTUuid}/{serviceUuid}/{instanceName}/{monitoringFlowType}", method = RequestMethod.POST)
+ public ResponseEntity createBluePrintWithFlowType(
+ @RequestHeader("USER_ID") String userId,
+ @PathVariable("VFCMTUuid") String vfcmtUuid,
+ @PathVariable("serviceUuid") String serviceUuid,
+ @PathVariable("instanceName") String instanceName,
+ @PathVariable("monitoringFlowType") String monitoringFlowType,
+ @ModelAttribute("requestId") String requestId) {
+ return blueprintBusinessLogic.generateAndSaveBlueprint(userId, AssetType.SERVICE.name(), vfcmtUuid, serviceUuid, instanceName, monitoringFlowType, requestId);
+ }
}
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/CompositionController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/CompositionController.java
index 3261ddc..dbcbcc9 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/CompositionController.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/CompositionController.java
@@ -1,17 +1,15 @@
package org.onap.sdc.dcae.composition.controller;
-import org.json.JSONArray;
-import org.json.JSONException;
import org.onap.sdc.common.onaplog.Enums.LogLevel;
+import org.onap.sdc.dcae.catalog.engine.CatalogResponse;
+import org.onap.sdc.dcae.catalog.engine.ElementRequest;
+import org.onap.sdc.dcae.catalog.engine.ItemsRequest;
import org.onap.sdc.dcae.composition.impl.CompositionBusinessLogic;
+import org.onap.sdc.dcae.composition.impl.CompositionCatalogBusinessLogic;
import org.onap.sdc.dcae.composition.restmodels.MessageResponse;
import org.onap.sdc.dcae.composition.restmodels.ReferenceUUID;
import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact;
-import org.onap.sdc.dcae.composition.restmodels.sdc.Asset;
import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed;
-import org.onap.sdc.dcae.catalog.Catalog;
-import org.onap.sdc.dcae.catalog.Catalog.*;
-import org.onap.sdc.dcae.catalog.engine.*;
import org.onap.sdc.dcae.composition.util.DcaeBeConstants;
import org.onap.sdc.dcae.enums.LifecycleOperationType;
import org.onap.sdc.dcae.errormng.ActionStatus;
@@ -25,8 +23,6 @@ import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;
-import javax.annotation.PostConstruct;
-import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -38,22 +34,22 @@ import java.util.stream.Collectors;
@CrossOrigin
public class CompositionController extends BaseController {
- @Autowired private CatalogController catalogController;
+ @Autowired
+ private CompositionCatalogBusinessLogic compositionCatalogBusinessLogic;
- @Autowired private CompositionBusinessLogic compositionBusinessLogic;
+ @Autowired
+ private CompositionBusinessLogic compositionBusinessLogic;
- @PostConstruct public void init() {
- catalogController.setDefaultCatalog(URI.create(systemProperties.getProperties().getProperty(DcaeBeConstants.Config.ASDC_CATALOG_URL)));
- }
-
- @RequestMapping(value = { "/utils/clone/{assetType}/{sourceId}/{targetId}" }, method = { RequestMethod.GET }, produces = { "application/json" }) public ResponseEntity clone(@RequestHeader("USER_ID") String userId,
+ @Deprecated
+ @RequestMapping(value = { "/utils/clone/{assetType}/{sourceId}/{targetId}" }, method = { RequestMethod.GET }, produces = { "application/json" })
+ public ResponseEntity clone(@RequestHeader("USER_ID") String userId,
@PathVariable("assetType") String theAssetType, @PathVariable("sourceId") String theSourceId, @PathVariable("targetId") String theTargetId, @ModelAttribute("requestId") String requestId) {
MessageResponse response = new MessageResponse();
try {
// fetch the source and assert it is a vfcmt containing clone worthy artifacts (composition + rules)
ResourceDetailed sourceVfcmt = baseBusinessLogic.getSdcRestClient().getResource(theSourceId, requestId);
- checkVfcmtType(sourceVfcmt);
+ baseBusinessLogic.checkVfcmtType(sourceVfcmt);
List<Artifact> artifactsToClone = CollectionUtils.isEmpty(sourceVfcmt.getArtifacts()) ?
null :
sourceVfcmt.getArtifacts().stream().filter(p -> DcaeBeConstants.Composition.fileNames.COMPOSITION_YML.equals(p.getArtifactName()) || p.getArtifactName().endsWith(DcaeBeConstants.Composition.fileNames.MAPPING_RULE_POSTFIX))
@@ -66,9 +62,9 @@ public class CompositionController extends BaseController {
// fetch the target
ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(theTargetId, requestId);
debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), vfcmt.toString());
- checkVfcmtType(vfcmt);
- checkUserIfResourceCheckedOut(userId, vfcmt);
- boolean isTargetNeed2Checkout = isNeedToCheckOut(vfcmt.getLifecycleState());
+ baseBusinessLogic.checkVfcmtType(vfcmt);
+ baseBusinessLogic.checkUserIfResourceCheckedOut(userId, vfcmt);
+ boolean isTargetNeed2Checkout = baseBusinessLogic.isNeedToCheckOut(vfcmt.getLifecycleState());
if (isTargetNeed2Checkout) {
ResourceDetailed targetVfcmt = baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, theTargetId, LifecycleOperationType.CHECKOUT.name(), "checking out VFCMT before clone", requestId);
if (null == targetVfcmt) {
@@ -95,183 +91,39 @@ public class CompositionController extends BaseController {
}
}
- @RequestMapping(value = "/elements", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public DeferredResult<CatalogResponse> items(@RequestBody(required = false) ItemsRequest theRequest) {
-
- final ItemsRequest request = (theRequest == null) ? ItemsRequest.EMPTY_REQUEST : theRequest;
-
- Catalog catalog = catalogController.getCatalog(request.getCatalog());
- DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout());
-
- catalog.rootsByLabel(request.getStartingLabel()).setHandler(catalogController.new CatalogHandler<Folders>(request, result) {
- public CatalogResponse handleData(Folders theFolders) {
- JSONArray ja = new JSONArray();
- if (theFolders != null) {
- for (Folder folder : theFolders) {
- ja.put(catalogController.patchData(catalog, folder.data()));
- }
- }
- CatalogResponse response = new CatalogResponse(this.request);
- try {
- response.data().put("elements", ja);
- } catch (JSONException e) {
- errLogger.log(LogLevel.ERROR, this.getClass().getName(), "JSONException putting json elements to response {}", e);
- }
- return response;
- }
- });
- return result;
+ @RequestMapping(value = "/elements", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json")
+ public DeferredResult<CatalogResponse> items(@RequestBody(required = false) ItemsRequest theRequest) {
+ return compositionCatalogBusinessLogic.getItems(theRequest);
}
- @RequestMapping(value = "/{theItemId}/elements", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public DeferredResult<CatalogResponse> items(@RequestBody(required = false) ItemsRequest theRequest,
- @PathVariable String theItemId) {
-
- final ItemsRequest request = (theRequest == null) ? ItemsRequest.EMPTY_REQUEST : theRequest;
-
- Catalog catalog = catalogController.getCatalog(request.getCatalog());
- DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout());
-
- catalog
- // .fetchFolderByItemId(theItemId)
- .folder(theItemId).withParts().withPartAnnotations().withItems().withItemAnnotations().withItemModels().execute().setHandler(catalogController.new CatalogHandler<Folder>(request, result) {
- public CatalogResponse handleData(Folder theFolder) {
- CatalogResponse response = new CatalogResponse(this.request);
- if (theFolder == null) {
- return response;
- }
-
- try {
- Elements folders = theFolder.elements("parts", Folders.class);
- if (folders != null) {
- for (Object folder : folders) {
- catalogController.patchData(catalog, ((Element) folder).data());
- // lots of ephemere proxies created here ..
- Elements annotations = ((Element) folder).elements("annotations", Annotations.class);
- if (annotations != null) {
- for (Object a : annotations) {
- catalogController.patchData(catalog, ((Annotation) a).data());
- }
- }
- }
- }
- Elements items = theFolder.elements("items", Items.class);
- if (items != null) {
- for (Object i : items) {
- catalogController.patchData(catalog, ((Element) i).data());
- // lots of ephemere proxies created here ..
- Elements annotations = ((Element) i).elements("annotations", Annotations.class);
- if (annotations != null) {
- for (Object a : annotations) {
- catalogController.patchData(catalog, ((Annotation) a).data());
- }
- }
- }
- }
- } catch (Exception x) {
- errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Exception processing catalog {}", x);
- return new CatalogError(this.request, "", x);
- }
-
- try {
- response.data().put("element", theFolder.data());
- } catch (JSONException e) {
- errLogger.log(LogLevel.ERROR, this.getClass().getName(), "JSONException putting element to response {}", e);
- }
- return response;
- }
- });
-
- return result;
+ @RequestMapping(value = "/{theItemId}/elements", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json")
+ public DeferredResult<CatalogResponse> items(@RequestBody(required = false) ItemsRequest theRequest, @PathVariable String theItemId) {
+ return compositionCatalogBusinessLogic.getItemById(theRequest, theItemId);
}
- @RequestMapping(value = "/{theItemId}/model", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public DeferredResult model(@RequestBody(required = false) ElementRequest theRequest,
- @PathVariable String theItemId) {
- final ElementRequest request = (theRequest == null) ? ElementRequest.EMPTY_REQUEST : theRequest;
-
- Catalog catalog = catalogController.getCatalog(request.getCatalog());
- DeferredResult<CatalogResponse> result = new DeferredResult<>(request.getTimeout());
-
- catalog.item(theItemId).withModels().execute().setHandler(catalogController.new CatalogHandler<Item>(request, result) {
- public CatalogResponse handleData(Item theItem) {
- if (theItem == null) {
- return new CatalogError(this.request, "No such item");
- }
- Templates models = null;
- try {
- models = (Templates) theItem.elements("models", Templates.class);
- if (models == null || models.isEmpty()) {
- return new CatalogError(this.request, "Item has no models");
- }
- if (models.size() > 1) {
- return new CatalogError(this.request, "Item has more than one model !?");
- }
- catalog.template(models.get(0).id()).withInputs().withOutputs().withNodes().withNodeProperties().withNodePropertiesAssignments().withNodeRequirements().withNodeCapabilities().withNodeCapabilityProperties()
- .withNodeCapabilityPropertyAssignments().withPolicies().withPolicyProperties().withPolicyPropertiesAssignments().execute().setHandler(catalogController.new CatalogHandler<Template>(this.request, this.result) {
- public CatalogResponse handleData(Template theTemplate) {
- CatalogResponse response = new CatalogResponse(this.request);
- if (theTemplate != null) {
- try {
- response.data().put("model", catalogController.patchData(catalog, theTemplate.data()));
- } catch (JSONException e) {
- errLogger.log(LogLevel.ERROR, this.getClass().getName(), "JSONException putting model to response {}", e);
- }
- }
- return response;
- }
- });
- } catch (Exception e) {
- handleException(e, ApiType.GET_MODEL, models.get(0).name());
- }
- return null;
- }
- });
-
- return result;
+ @RequestMapping(value = "/{theItemId}/model", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json")
+ public DeferredResult model(@RequestBody(required = false) ElementRequest theRequest, @PathVariable String theItemId) {
+ return compositionCatalogBusinessLogic.getModelById(theRequest, theItemId);
}
- @RequestMapping(value = "/{theItemId}/type/{theTypeName}", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public DeferredResult<CatalogResponse> model(@RequestBody(required = false) ElementRequest theRequest,
- @PathVariable String theItemId, @PathVariable String theTypeName) {
- final ElementRequest request = (theRequest == null) ? ElementRequest.EMPTY_REQUEST : theRequest;
-
- Catalog catalog = catalogController.getCatalog(request.getCatalog());
- DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout());
-
- catalog.type(theItemId, theTypeName).withHierarchy().withCapabilities().withRequirements().execute().setHandler(catalogController.new CatalogHandler<Type>(request, result) {
- public CatalogResponse handleData(Type theType) {
- CatalogResponse response = new CatalogResponse(this.request);
- if (theType != null) {
- try {
- response.data().put("type", catalogController.patchData(catalog, theType.data()));
- } catch (JSONException e) {
- errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Exception processing catalog {}", e);
- }
- }
- return response;
- }
- });
-
- return result;
+ @RequestMapping(value = "/{theItemId}/type/{theTypeName}", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json")
+ public DeferredResult<CatalogResponse> model(@RequestBody(required = false) ElementRequest theRequest, @PathVariable String theItemId, @PathVariable String theTypeName) {
+ return compositionCatalogBusinessLogic.getTypeInfo(theRequest, theItemId, theTypeName);
}
- @RequestMapping(value = { "/getComposition/{vfcmtUuid}" }, method = { RequestMethod.GET }, produces = { "application/json" }) public ResponseEntity getComposition(@PathVariable("vfcmtUuid") String vfcmtUuid,
- @ModelAttribute("requestId") String requestId) {
+ @RequestMapping(value = { "/getComposition/{vfcmtUuid}" }, method = { RequestMethod.GET }, produces = { "application/json" })
+ public ResponseEntity getComposition(@PathVariable("vfcmtUuid") String vfcmtUuid, @ModelAttribute("requestId") String requestId) {
MessageResponse response = new MessageResponse();
try {
- ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId);
- debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), vfcmt.toString());
- checkVfcmtType(vfcmt);
-
- Artifact compositionArtifact = CollectionUtils.isEmpty(vfcmt.getArtifacts()) ? null : vfcmt.getArtifacts().stream().filter(a -> DcaeBeConstants.Composition.fileNames.COMPOSITION_YML.equals(a.getArtifactName())).findAny().orElse(null);
-
+ Artifact compositionArtifact = compositionBusinessLogic.getComposition(vfcmtUuid, requestId);
if (null == compositionArtifact) {
debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Couldn't find {} in VFCMT artifacts", DcaeBeConstants.Composition.fileNames.COMPOSITION_YML);
response.setErrorResponse("No Artifacts");
return new ResponseEntity<>(response, HttpStatus.NO_CONTENT);
}
- String artifact = baseBusinessLogic.getSdcRestClient().getResourceArtifact(vfcmtUuid, compositionArtifact.getArtifactUUID(), requestId);
-
- debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "ARTIFACT: {}", artifact);
- response.setSuccessResponse(artifact);
+ debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "ARTIFACT: {}", compositionArtifact.getPayloadData());
+ response.setSuccessResponse(compositionArtifact.getPayloadData());
return new ResponseEntity<>(response, HttpStatus.OK);
} catch (Exception e) {
return handleException(e, ApiType.GET_CDUMP);
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/ConfigurationController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/ConfigurationController.java
index 4f083ca..65663f6 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/ConfigurationController.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/ConfigurationController.java
@@ -26,7 +26,7 @@ import io.swagger.annotations.ApiResponses;
@EnableAutoConfiguration
@CrossOrigin
@RequestMapping("/conf")
-public class ConfigurationController extends BaseController{
+public class ConfigurationController extends BaseController {
@Autowired
private CompositionConfig compositionConfig;
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/LifecycleController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/LifecycleController.java
index 4fa8c18..1c90359 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/LifecycleController.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/LifecycleController.java
@@ -1,6 +1,5 @@
package org.onap.sdc.dcae.composition.controller;
-import org.onap.sdc.common.onaplog.Enums.LogLevel;
import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed;
import org.onap.sdc.dcae.enums.AssetType;
import org.onap.sdc.dcae.enums.LifecycleOperationType;
@@ -25,8 +24,8 @@ public class LifecycleController extends BaseController {
@ModelAttribute("requestId") String requestId) {
try {
- if (AssetType.VFCMT == getValidAssetTypeOrNull(assetType)) {
- ResourceDetailed resCheckin = checkinVfcmt(userId, uuid.toString(), requestId);
+ if (AssetType.VFCMT == baseBusinessLogic.getValidAssetTypeOrNull(assetType)) {
+ ResourceDetailed resCheckin = baseBusinessLogic.checkinVfcmt(userId, uuid.toString(), requestId);
return new ResponseEntity<>(resCheckin, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
@@ -44,8 +43,8 @@ public class LifecycleController extends BaseController {
@ModelAttribute("requestId") String requestId) {
try {
- if (AssetType.VFCMT == getValidAssetTypeOrNull(assetType)) {
- ResourceDetailed asset = checkoutVfcmt(userId, uuid.toString(), requestId);
+ if (AssetType.VFCMT == baseBusinessLogic.getValidAssetTypeOrNull(assetType)) {
+ ResourceDetailed asset = baseBusinessLogic.checkoutVfcmt(userId, uuid.toString(), requestId);
return new ResponseEntity<>(asset, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
@@ -63,7 +62,7 @@ public class LifecycleController extends BaseController {
@ModelAttribute("requestId") String requestId) {
try {
- if (AssetType.VFCMT == getValidAssetTypeOrNull(assetType)) {
+ if (AssetType.VFCMT == baseBusinessLogic.getValidAssetTypeOrNull(assetType)) {
ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, uuid, LifecycleOperationType.CERTIFY.name(), "certifying VFCMT", requestId);
return new ResponseEntity<>(vfcmt, HttpStatus.OK);
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/RuleEditorController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/RuleEditorController.java
index 8de8520..d7ddd6f 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/RuleEditorController.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/RuleEditorController.java
@@ -14,8 +14,6 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/rule-editor")
public class RuleEditorController extends BaseController {
- private static final String EXCEPTION = "Exception {}";
-
@Autowired
private RuleEditorBusinessLogic ruleEditorBusinessLogic;
@@ -70,7 +68,7 @@ public class RuleEditorController extends BaseController {
* @param configParam - the name of the DCAE Component configuration property the rule is linked to
* @return json representing the rule editor UI
*/
- @RequestMapping(value = "/rule/{vfcmtUuid}/{dcaeCompLabel}/{nid}/{configParam}", method = {RequestMethod.GET}, produces = "application/json")
+ @RequestMapping(value = "/rule/{vfcmtUuid}/{dcaeCompLabel}/{nid}/{configParam:.*}", method = {RequestMethod.GET}, produces = "application/json")
public ResponseEntity getRules(
@PathVariable("vfcmtUuid") String vfcmtUuid,
@PathVariable("dcaeCompLabel") String dcaeCompLabel,
@@ -119,9 +117,8 @@ public class RuleEditorController extends BaseController {
* 1. That the user is able to edit the VFCMT
* 2. That the cdump holds a dcae component with such nid (to avoid orphan rules)
* 3. Check that the fetched VFCMT is actually a VFCMT and not a regular VF
- * @throws Exception
*/
- @RequestMapping(value = "/rule/translate/{vfcmtUuid}/{dcaeCompLabel}/{nid}/{configParam}", method = {RequestMethod.GET}, produces = "application/json")
+ @RequestMapping(value = "/rule/translate/{vfcmtUuid}/{dcaeCompLabel}/{nid}/{configParam:.*}", method = {RequestMethod.GET}, produces = "application/json")
public ResponseEntity translateRules(@PathVariable("vfcmtUuid") String vfcmtUuid, @ModelAttribute("requestId") String requestId,
@PathVariable("dcaeCompLabel") String dcaeCompLabel,
@PathVariable("nid") String nid,
@@ -140,6 +137,4 @@ public class RuleEditorController extends BaseController {
debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Starting getExistingRuleTargets ", vfcmtUuid);
return ruleEditorBusinessLogic.getExistingRuleTargets(vfcmtUuid, requestId, dcaeCompLabel, nid);
}
-
-
}
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/VfcmtController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/VfcmtController.java
index 7d64dad..4fbce49 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/VfcmtController.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/VfcmtController.java
@@ -23,7 +23,6 @@ import java.util.List;
@CrossOrigin
public class VfcmtController extends BaseController{
-
@Autowired
private VfcmtBusinessLogic vfcmtBusinessLogic;
@Autowired
@@ -33,8 +32,6 @@ public class VfcmtController extends BaseController{
private static final String BASE_MONITORING_TEMPLATE = "Base Monitoring Template";
private static final String MONITORING_TEMPLATE = "Monitoring Template";
-
-
/***
* Get one resource information
* @param theResourceId retrieved resource id
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BaseBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BaseBusinessLogic.java
index bfec7ed..6779257 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BaseBusinessLogic.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BaseBusinessLogic.java
@@ -11,6 +11,7 @@ import org.onap.sdc.dcae.composition.restmodels.CreateMcResponse;
import org.onap.sdc.dcae.composition.restmodels.VfcmtData;
import org.onap.sdc.dcae.composition.restmodels.sdc.*;
import org.onap.sdc.dcae.composition.util.DcaeBeConstants;
+import org.onap.sdc.dcae.composition.util.SystemProperties;
import org.onap.sdc.dcae.enums.AssetType;
import org.onap.sdc.dcae.enums.LifecycleOperationType;
import org.onap.sdc.dcae.errormng.ActionStatus;
@@ -21,7 +22,6 @@ import org.onap.sdc.dcae.utils.Normalizers;
import org.onap.sdc.dcae.utils.SdcRestClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
@@ -29,6 +29,10 @@ import java.io.IOException;
@Component
public class BaseBusinessLogic {
+
+ @Autowired
+ protected SystemProperties systemProperties;
+
@Autowired
protected ISdcClient sdcRestClient;
@@ -39,6 +43,10 @@ public class BaseBusinessLogic {
return sdcRestClient;
}
+ public SystemProperties getSystemProperties() {
+ return systemProperties;
+ }
+
void setSdcRestClient(ISdcClient sdcRestClient) {
this.sdcRestClient = sdcRestClient;
}
@@ -85,7 +93,7 @@ public class BaseBusinessLogic {
return new CreateMcResponse(vfcmt, new ObjectMapper().readValue(cdumpPayload, Object.class));
}
- public Artifact fetchCdump(ResourceDetailed vfcmt, String requestId) {
+ Artifact fetchCdump(ResourceDetailed vfcmt, String requestId) {
Artifact cdumpArtifactData = findCdumpArtifactData(vfcmt);
if (null != cdumpArtifactData) {
String cdumpPayload = sdcRestClient.getResourceArtifact(vfcmt.getUuid(), cdumpArtifactData.getArtifactUUID(), requestId);
@@ -110,22 +118,19 @@ public class BaseBusinessLogic {
.filter(p -> Normalizers.normalizeComponentInstanceName(vfiName).equals(Normalizers.normalizeComponentInstanceName(p.getResourceInstanceName()))).findAny().orElse(null);
}
- public String extractFlowTypeFromCdump(String cdump) {
+ String extractFlowTypeFromCdump(String cdump) {
return StringUtils.substringBetween(cdump,"\"flowType\":\"","\"");
}
- // TODO - reuse
-
- ResourceDetailed checkinVfcmt(String userId, String uuid, String requestId) {
+ public ResourceDetailed checkinVfcmt(String userId, String uuid, String requestId) {
return getSdcRestClient().changeResourceLifecycleState(userId, uuid, LifecycleOperationType.CHECKIN.name(), "checking in vfcmt" + uuid, requestId);
}
- ResourceDetailed checkoutVfcmt(String userId, String uuid, String requestId) {
+ public ResourceDetailed checkoutVfcmt(String userId, String uuid, String requestId) {
return getSdcRestClient().changeResourceLifecycleState(userId, uuid, LifecycleOperationType.CHECKOUT.name(), null, requestId);
}
- // TODO - remove from BaseController
- void checkUserIfResourceCheckedOut(String userId, Asset asset) {
+ public void checkUserIfResourceCheckedOut(String userId, Asset asset) {
if (DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == DcaeBeConstants.LifecycleStateEnum.findState(asset.getLifecycleState())) {
String lastUpdaterUserId = asset.getLastUpdaterUserId();
if (lastUpdaterUserId != null && !lastUpdaterUserId.equals(userId)) {
@@ -136,18 +141,18 @@ public class BaseBusinessLogic {
}
}
- boolean isNeedToCheckOut(String lifecycleState) {
+ public boolean isNeedToCheckOut(String lifecycleState) {
return DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT != DcaeBeConstants.LifecycleStateEnum.findState(lifecycleState);
}
- void checkVfcmtType(ResourceDetailed vfcmt) {
+ public void checkVfcmtType(ResourceDetailed vfcmt) {
if (AssetType.VFCMT != getValidAssetTypeOrNull(vfcmt.getResourceType()) || !"Template".equals(vfcmt.getCategory())) {
ResponseFormat responseFormat = ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.RESOURCE_NOT_VFCMT_ERROR, null, vfcmt.getUuid());
throw new DcaeException(HttpStatus.BAD_REQUEST, responseFormat.getRequestError());
}
}
- AssetType getValidAssetTypeOrNull(String type) {
+ public AssetType getValidAssetTypeOrNull(String type) {
try {
return AssetType.getAssetTypeByName(type);
} catch (IllegalArgumentException e) {
@@ -156,9 +161,4 @@ public class BaseBusinessLogic {
}
}
- ResponseEntity handleException(Exception e, ErrConfMgr.ApiType apiType, String... variables){
- errLogger.log(LogLevel.ERROR, this.getClass().getName(), e.getMessage());
- return ErrConfMgr.INSTANCE.handleException(e, apiType, variables);
- }
-
}
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BlueprintBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BlueprintBusinessLogic.java
index 0ccb6d8..7a6f9a7 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BlueprintBusinessLogic.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BlueprintBusinessLogic.java
@@ -10,7 +10,6 @@ import org.onap.sdc.dcae.composition.restmodels.VfcmtData;
import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact;
import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed;
import org.onap.sdc.dcae.composition.util.DcaeBeConstants;
-import org.onap.sdc.dcae.composition.util.SystemProperties;
import org.onap.sdc.dcae.errormng.ActionStatus;
import org.onap.sdc.dcae.errormng.ErrConfMgr;
import org.springframework.beans.factory.annotation.Autowired;
@@ -23,15 +22,12 @@ import java.io.StringReader;
import java.net.URI;
@Component
-public class BlueprintBusinessLogic extends BaseBusinessLogic {
+public class BlueprintBusinessLogic extends CompositionBusinessLogic {
@Autowired
private Blueprinter blueprinter;
@Autowired
private ASDC asdc;
- @Autowired
- private SystemProperties systemProperties;
- @Autowired private CompositionBusinessLogic compositionBusinessLogic;
@PostConstruct
@@ -41,6 +37,7 @@ public class BlueprintBusinessLogic extends BaseBusinessLogic {
debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "SDC uri: {}", sdcUri);
}
+
public ResponseEntity generateAndSaveBlueprint(String userId, String context, String vfcmtUuid, String serviceUuid, String vfiName, String flowType, String requestId) {
try {
// prepare - fetch vfcmt and cdump
@@ -69,7 +66,7 @@ public class BlueprintBusinessLogic extends BaseBusinessLogic {
}
VfcmtData vfcmtData = new VfcmtData(vfcmt, vfiName, flowTypeFromCdump, serviceUuid);
- Artifact blueprintArtifactResult = compositionBusinessLogic.submitComposition(userId, context, vfcmtData, resultBlueprintCreation, requestId);
+ Artifact blueprintArtifactResult = submitComposition(userId, context, vfcmtData, resultBlueprintCreation, requestId);
if (null == blueprintArtifactResult) {
return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.SUBMIT_BLUEPRINT_ERROR);
}
@@ -78,7 +75,8 @@ public class BlueprintBusinessLogic extends BaseBusinessLogic {
response.setSuccessResponse("Blueprint build complete \n. Blueprint=" + blueprintArtifactResult.getArtifactName());
return new ResponseEntity<>(response, HttpStatus.OK);
} catch (Exception e) {
- return handleException(e, ErrConfMgr.ApiType.SUBMIT_BLUEPRINT);
+ errLogger.log(LogLevel.ERROR, this.getClass().getName(), e.getMessage());
+ return ErrConfMgr.INSTANCE.handleException(e, ErrConfMgr.ApiType.SUBMIT_BLUEPRINT);
}
}
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/CompositionBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/CompositionBusinessLogic.java
index e81ffe0..a3c68f6 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/CompositionBusinessLogic.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/CompositionBusinessLogic.java
@@ -31,6 +31,13 @@ public class CompositionBusinessLogic extends BaseBusinessLogic {
private static final String CREATE_DESC = "creating new artifact blueprint on the service vfi";
private static final String UPDATE_DESC = "updating artifact blueprint on the service vfi";
+ //canvas cdump as simple string
+ public Artifact getComposition(String vfcmtUuid, String requestId) {
+ ResourceDetailed vfcmt = sdcRestClient.getResource(vfcmtUuid, requestId);
+ return fetchCdump(vfcmt, requestId);
+ }
+
+ //cdump and vfcmt for monitoring configuration
public CreateMcResponse getDataAndComposition(String vfcmtUuid, String requestId) throws IOException {
ResourceDetailed vfcmt = sdcRestClient.getResource(vfcmtUuid, requestId);
Artifact composition = fetchCdump(vfcmt, requestId);
@@ -73,7 +80,7 @@ public class CompositionBusinessLogic extends BaseBusinessLogic {
}
}
- public Artifact submitComposition(String userId, String context, VfcmtData vfcmtData, String resultBlueprintCreation, String requestId) throws JsonProcessingException {
+ Artifact submitComposition(String userId, String context, VfcmtData vfcmtData, String resultBlueprintCreation, String requestId) throws JsonProcessingException {
// get service / find vfi
ServiceDetailed service = sdcRestClient.getAssetMetadata(context, vfcmtData.getServiceUuid(), requestId);
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/CompositionCatalogBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/CompositionCatalogBusinessLogic.java
new file mode 100644
index 0000000..ff596b5
--- /dev/null
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/CompositionCatalogBusinessLogic.java
@@ -0,0 +1,205 @@
+package org.onap.sdc.dcae.composition.impl;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.onap.sdc.common.onaplog.Enums.LogLevel;
+import org.onap.sdc.common.onaplog.OnapLoggerError;
+import org.onap.sdc.dcae.catalog.Catalog;
+import org.onap.sdc.dcae.catalog.engine.*;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.request.async.DeferredResult;
+
+@Component
+public class CompositionCatalogBusinessLogic {
+
+ @Autowired
+ private CatalogController catalogController;
+
+ protected OnapLoggerError errLogger = OnapLoggerError.getInstance();
+
+ public DeferredResult<CatalogResponse> getItems(ItemsRequest theRequest) {
+
+ final ItemsRequest request = (theRequest == null) ? ItemsRequest.EMPTY_REQUEST : theRequest;
+
+ Catalog catalog = catalogController.getCatalog(request.getCatalog());
+ DeferredResult<CatalogResponse> result = new DeferredResult<>(request.getTimeout());
+
+ catalog.rootsByLabel(request.getStartingLabel()).setHandler(catalogController.new CatalogHandler<Catalog.Folders>(request, result) {
+ public CatalogResponse handleData(Catalog.Folders theFolders) {
+ JSONArray ja = new JSONArray();
+ if (theFolders != null) {
+ for (Catalog.Folder folder : theFolders) {
+ ja.put(catalogController.patchData(catalog, folder.data()));
+ }
+ }
+ CatalogResponse response = new CatalogResponse(this.request);
+ try {
+ response.data().put("elements", ja);
+ } catch (JSONException e) {
+ errLogger.log(LogLevel.ERROR, this.getClass().getName(), "JSONException putting json elements to response {}", e);
+ }
+ return response;
+ }
+ });
+ return result;
+ }
+
+ public DeferredResult<CatalogResponse> getItemById(ItemsRequest theRequest, String theItemId) {
+
+ final ItemsRequest request = (theRequest == null) ? ItemsRequest.EMPTY_REQUEST : theRequest;
+
+ Catalog catalog = catalogController.getCatalog(request.getCatalog());
+ DeferredResult<CatalogResponse> result = new DeferredResult<>(request.getTimeout());
+
+ catalog.folder(theItemId).withParts().withPartAnnotations().withItems().withItemAnnotations().withItemModels().execute().setHandler(new FolderHandler(catalog, request, result));
+ return result;
+ }
+
+ public DeferredResult getModelById(ElementRequest theRequest, String theItemId) {
+ final ElementRequest request = (theRequest == null) ? ElementRequest.EMPTY_REQUEST : theRequest;
+
+ Catalog catalog = catalogController.getCatalog(request.getCatalog());
+ DeferredResult<CatalogResponse> result = new DeferredResult<>(request.getTimeout());
+
+// try {
+ catalog.item(theItemId).withModels().execute().setHandler(new ItemHandler(catalog, request, result));
+// } catch (IllegalArgumentException e) {
+// errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error fetching catalog model with id {}. Message: {}", theItemId, e);
+// result.setErrorResult(new CatalogError(request, "Catalog API failed", e));
+// }
+ return result;
+ }
+
+ public DeferredResult<CatalogResponse> getTypeInfo(ElementRequest theRequest, String theItemId, String theTypeName) {
+ final ElementRequest request = (theRequest == null) ? ElementRequest.EMPTY_REQUEST : theRequest;
+
+ Catalog catalog = catalogController.getCatalog(request.getCatalog());
+ DeferredResult<CatalogResponse> result = new DeferredResult<>(request.getTimeout());
+
+ catalog.type(theItemId, theTypeName).withHierarchy().withCapabilities().withRequirements().execute().setHandler(catalogController.new CatalogHandler<Catalog.Type>(request, result) {
+ public CatalogResponse handleData(Catalog.Type theType) {
+ CatalogResponse response = new CatalogResponse(this.request);
+ if (theType != null) {
+ try {
+ response.data().put("type", catalogController.patchData(catalog, theType.data()));
+ } catch (JSONException e) {
+ errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Exception processing catalog {}", e);
+ }
+ }
+ return response;
+ }
+ });
+ return result;
+ }
+
+ /// Nested Catalog Data Handlers ///
+
+ private class FolderHandler extends CatalogController.CatalogHandler<Catalog.Folder> {
+
+ private Catalog catalog;
+
+ private FolderHandler(Catalog catalog, ItemsRequest request, DeferredResult result) {
+ catalogController.super(request, result);
+ this.catalog = catalog;
+ }
+
+ private void patchCatalogData(Catalog.Elements folders, Catalog catalog) {
+ if (folders != null) {
+ folders.forEach(folder -> {
+ catalogController.patchData(catalog, ((Catalog.Element) folder).data());
+ // lots of ephemere proxies created here ..
+ Catalog.Elements annotations = ((Catalog.Element) folder).elements("annotations", Catalog.Annotations.class);
+ if (annotations != null) {
+ annotations.forEach(a -> catalogController.patchData(catalog, ((Catalog.Annotation) a).data()));
+ }
+ });
+ }
+ }
+
+ public CatalogResponse handleData(Catalog.Folder theFolder) {
+ CatalogResponse response = new CatalogResponse(this.request);
+ if (theFolder == null) {
+ return response;
+ }
+ try {
+ Catalog.Elements folders = theFolder.elements("parts", Catalog.Folders.class);
+ patchCatalogData(folders, catalog);
+ Catalog.Elements items = theFolder.elements("items", Catalog.Items.class);
+ patchCatalogData(items, catalog);
+ } catch (Exception x) {
+ errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Exception processing catalog {}", x);
+ return new CatalogError(this.request, "", x);
+ }
+ try {
+ response.data().put("element", theFolder.data());
+ } catch (JSONException e) {
+ errLogger.log(LogLevel.ERROR, this.getClass().getName(), "JSONException putting element to response {}", e);
+ }
+ return response;
+ }
+ }
+
+ private class ItemHandler extends CatalogController.CatalogHandler<Catalog.Item> {
+
+ private Catalog catalog;
+
+ private ItemHandler(Catalog catalog, ElementRequest request, DeferredResult result) {
+ catalogController.super(request, result);
+ this.catalog = catalog;
+ }
+
+ public CatalogResponse handleData(Catalog.Item theItem) {
+ if (theItem == null) {
+ return new CatalogError(this.request, "No such item");
+ }
+ Catalog.Templates models;
+ try {
+ models = (Catalog.Templates) theItem.elements("models", Catalog.Templates.class);
+ } catch (Exception x) {
+ return new CatalogError(this.request, "Failed to decode templates from result", x);
+ }
+ if (models == null || models.isEmpty()) {
+ return new CatalogError(this.request, "Item has no models");
+ }
+ if (models.size() > 1) {
+ return new CatalogError(this.request, "Item has more than one model !?");
+ }
+ try {
+ catalog.template(models.get(0).id()).withInputs().withOutputs().withNodes().withNodeProperties().withNodePropertiesAssignments().withNodeRequirements().withNodeCapabilities().withNodeCapabilityProperties()
+ .withNodeCapabilityPropertyAssignments().withPolicies().withPolicyProperties().withPolicyPropertiesAssignments().execute().setHandler(new TemplateHandler(this.catalog, this.request, this.result));
+ } catch (Exception e) {
+ errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Exception caught during Catalog Item Handler: {}", e);
+ }
+ return null;
+ }
+ }
+
+ private class TemplateHandler extends CatalogController.CatalogHandler<Catalog.Template> {
+
+ private Catalog catalog;
+
+ private TemplateHandler(Catalog catalog, CatalogRequest request, DeferredResult result) {
+ catalogController.super(request, result);
+ this.catalog = catalog;
+ }
+
+ public CatalogResponse handleData(Catalog.Template theTemplate) {
+ CatalogResponse response = new CatalogResponse(this.request);
+ if (theTemplate != null) {
+ try {
+ response.data().put("model", catalogController.patchData(catalog, theTemplate.data()));
+ } catch (JSONException e) {
+ errLogger.log(LogLevel.ERROR, this.getClass().getName(), "JSONException putting model to response {}", e);
+ }
+ }
+ return response;
+ }
+ }
+}
+
+
+
+
+
+
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogic.java
index 1396cc9..9c950b6 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogic.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogic.java
@@ -34,7 +34,7 @@ public class ReferenceBusinessLogic extends BaseBusinessLogic {
.ifPresent(artifact -> sdcRestClient.deleteInstanceArtifact(userId, context, serviceUuid, normalizedVfiName, artifact.getArtifactUUID(), requestId));
}
} catch (Exception e) {
- debugLogger.log(LogLevel.DEBUG, this.getClass().getName(),"Failed to delete blueprint with serviceUuid {}, vfcmtUuid . message: {} ", serviceUuid, vfcmtUuid, e);
+ debugLogger.log(LogLevel.DEBUG, this.getClass().getName(),"Failed to delete blueprint with serviceUuid {}, vfcmtUuid {}, message: {} ", serviceUuid, vfcmtUuid, e);
return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.DELETE_BLUEPRINT_FAILED, e.getMessage());
}
return new ResponseEntity<>(HttpStatus.OK);
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogic.java
index d17a6bf..298ffac 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogic.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogic.java
@@ -29,7 +29,6 @@ import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
-import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.stream.Collectors;
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogic.java
index d04c67a..8dbe2e9 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogic.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogic.java
@@ -1,29 +1,29 @@
package org.onap.sdc.dcae.composition.impl;
- import org.onap.sdc.common.onaplog.Enums.LogLevel;
- import org.onap.sdc.dcae.composition.restmodels.AttachVFCMTServiceRequest;
- import org.onap.sdc.dcae.composition.restmodels.DcaeMinimizedService;
- import org.onap.sdc.dcae.composition.restmodels.MessageResponse;
- import org.onap.sdc.dcae.composition.restmodels.sdc.*;
- import org.onap.sdc.dcae.composition.util.DcaeBeConstants;
- import org.onap.sdc.dcae.enums.ArtifactType;
- import org.onap.sdc.dcae.enums.LifecycleOperationType;
- import org.onap.sdc.dcae.errormng.ActionStatus;
- import org.onap.sdc.dcae.errormng.DcaeException;
- import org.onap.sdc.dcae.errormng.ErrConfMgr;
- import org.onap.sdc.dcae.errormng.ResponseFormat;
- import org.onap.sdc.dcae.utils.SdcRestClientUtils;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.ResponseEntity;
- import org.springframework.stereotype.Component;
- import org.springframework.util.Base64Utils;
- import org.springframework.util.CollectionUtils;
-
- import java.util.ArrayList;
- import java.util.Comparator;
- import java.util.LinkedHashMap;
- import java.util.List;
- import java.util.stream.Collectors;
+import org.onap.sdc.common.onaplog.Enums.LogLevel;
+import org.onap.sdc.dcae.composition.restmodels.AttachVFCMTServiceRequest;
+import org.onap.sdc.dcae.composition.restmodels.DcaeMinimizedService;
+import org.onap.sdc.dcae.composition.restmodels.MessageResponse;
+import org.onap.sdc.dcae.composition.restmodels.sdc.*;
+import org.onap.sdc.dcae.composition.util.DcaeBeConstants;
+import org.onap.sdc.dcae.enums.ArtifactType;
+import org.onap.sdc.dcae.enums.LifecycleOperationType;
+import org.onap.sdc.dcae.errormng.ActionStatus;
+import org.onap.sdc.dcae.errormng.DcaeException;
+import org.onap.sdc.dcae.errormng.ErrConfMgr;
+import org.onap.sdc.dcae.errormng.ResponseFormat;
+import org.onap.sdc.dcae.utils.SdcRestClientUtils;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Component;
+import org.springframework.util.Base64Utils;
+import org.springframework.util.CollectionUtils;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.stream.Collectors;
@Component
public class ServiceBusinessLogic extends BaseBusinessLogic {
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/RuleValidator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/RuleValidator.java
index e03ca8a..33e1b33 100644
--- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/RuleValidator.java
+++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/RuleValidator.java
@@ -20,11 +20,11 @@ public class RuleValidator implements IRuleElementValidator<Rule> {
private RuleValidator(){}
-
public boolean validate(Rule rule, List<ResponseFormat> errors) {
boolean valid = true;
- if(rule.isConditionalRule())
+ if(rule.isConditionalRule()) {
valid = getConditionValidator(rule.getCondition()).validate(rule.getCondition(), errors);
+ }
if(!ValidationUtils.validateNotEmpty(rule.getDescription())) {
valid = false;
errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.MISSING_RULE_DESCRIPTION, null, null));
diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/CompositionCatalogBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/CompositionCatalogBusinessLogicTest.java
new file mode 100644
index 0000000..ac12f8d
--- /dev/null
+++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/CompositionCatalogBusinessLogicTest.java
@@ -0,0 +1,74 @@
+package org.onap.sdc.dcae.composition.impl;
+
+import org.json.JSONException;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.sdc.dcae.catalog.asdc.ASDCCatalog;
+import org.onap.sdc.dcae.catalog.engine.CatalogController;
+import org.onap.sdc.dcae.catalog.engine.CatalogError;
+import org.onap.sdc.dcae.catalog.engine.CatalogResponse;
+import org.springframework.web.context.request.async.DeferredResult;
+
+import java.net.URI;
+import java.util.UUID;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.*;
+
+public class CompositionCatalogBusinessLogicTest {
+
+ @Mock
+ private CatalogController catalogController;
+
+ private ASDCCatalog asdcCatalog = new ASDCCatalog(URI.create("https://mockUri:8888#mock"));
+
+ @InjectMocks
+ private CompositionCatalogBusinessLogic compositionCatalogBusinessLogic = new CompositionCatalogBusinessLogic();
+
+ @Before
+ public void init() throws JSONException {
+ MockitoAnnotations.initMocks(this);
+ when(catalogController.getCatalog(any())).thenReturn(asdcCatalog);
+ }
+
+ @Test
+ public void getItemsTest() {
+ compositionCatalogBusinessLogic.getItems(null).getResult();
+ verify(catalogController, times(7)).patchData(any(), any());
+ }
+
+ @Test
+ public void getItemByIdNoSuchFolderFailureTest() {
+ DeferredResult<CatalogResponse> result = compositionCatalogBusinessLogic.getItemById(null, "No Such Category");
+ verify(catalogController).getCatalog(any());
+ verify(catalogController, times(0)).patchData(any(), any());
+ CatalogError error = (CatalogError)result.getResult();
+ assertEquals("{\"exception\":\"java.lang.RuntimeException: No such folder No Such Category\",\"message\":\"Catalog API failed\"}", error.getError());
+ }
+
+ @Test
+ public void getModelByIdInvalidUuidFailureTest() {
+ try {
+ compositionCatalogBusinessLogic.getModelById(null, "Invalid-UUID");
+ } catch (IllegalArgumentException e) {
+ assertEquals("Invalid UUID string: Invalid-UUID", e.getMessage());
+ verify(catalogController).getCatalog(any());
+ verify(catalogController, times(0)).patchData(any(), any());
+ }
+ }
+
+ @Test
+ public void getTypeInfoModelNotLoadedFailureTest() {
+ // this is pretty awful. you cannot call 'getTypeInfo' unless it is preceded by a 'getModel' call of the containing model, so that the 'catalogs' item is populated by the container model id.
+ String uuid = UUID.randomUUID().toString();
+ DeferredResult<CatalogResponse> result = compositionCatalogBusinessLogic.getTypeInfo(null, uuid, "tosca.nodes.Root");
+ verify(catalogController).getCatalog(any());
+ verify(catalogController, times(0)).patchData(any(), any());
+ CatalogError error = (CatalogError)result.getResult();
+ assertEquals("{\"exception\":\"java.lang.Exception: No catalog available for resource " + uuid + ". You might want to fetch the model first.\",\"message\":\"Catalog API failed\"}", error.getError());
+ }
+} \ No newline at end of file
diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogicTest.java
index 3cac355..a6f82f6 100644
--- a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogicTest.java
+++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogicTest.java
@@ -1,173 +1,281 @@
package org.onap.sdc.dcae.composition.impl;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.when;
-
-import java.util.*;
-import java.util.stream.Collectors;
-
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
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.onap.sdc.dcae.client.ISdcClient;
+import org.onap.sdc.dcae.composition.restmodels.AttachVFCMTServiceRequest;
import org.onap.sdc.dcae.composition.restmodels.DcaeMinimizedService;
-import org.onap.sdc.dcae.composition.impl.ServiceBusinessLogic;
+import org.onap.sdc.dcae.composition.restmodels.MessageResponse;
import org.onap.sdc.dcae.composition.restmodels.ruleeditor.ActionDeserializer;
import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseAction;
import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseCondition;
import org.onap.sdc.dcae.composition.restmodels.ruleeditor.ConditionDeserializer;
-import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact;
-import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceInstance;
-import org.onap.sdc.dcae.composition.restmodels.sdc.ServiceDetailed;
+import org.onap.sdc.dcae.composition.restmodels.sdc.*;
import org.onap.sdc.dcae.composition.util.DcaeBeConstants;
-import org.onap.sdc.dcae.composition.util.DcaeBeConstants.LifecycleStateEnum;
import org.onap.sdc.dcae.errormng.ErrorConfigurationLoader;
-import org.testng.annotations.Test;
+import org.onap.sdc.dcae.errormng.ResponseFormat;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertNotEquals;
public class ServiceBusinessLogicTest {
- private String userId = "me";
- private String requestId = "1";
- private String monitoringComponentName = "monitoringComponentName";
- private String serviceUuid = "serviceUuid";
- private String vfiName = "vfiName";
+ private String uuid = "b632b1da-e6ab-419d-8853-420e259097d9";
+ private String userId = "gc786h";
+ private String requestId = "1";
+ private String monitoringComponentName = "monitoringComponentName";
+ private String serviceUuid = "serviceUuid";
+ private String vfiName = "vfiName";
+ private String vfcmtUuid = "26e8d4b5-f087-4821-a75a-0b9514b5a7ab";
+ private ResourceDetailed vfcmt = Mockito.mock(ResourceDetailed.class);
+ private String categoryName = "Template";
+ private String resourceType = "VFCMT";
+ private ISdcClient sdcClientMock = Mockito.mock(ISdcClient.class);
+
+
+ private static Gson gson = new GsonBuilder()
+ .registerTypeAdapter(BaseAction.class, new ActionDeserializer())
+ .registerTypeAdapter(BaseCondition.class, new ConditionDeserializer()).create();
+
+ @InjectMocks
+ ServiceBusinessLogic serviceBusinessLogic = new ServiceBusinessLogic();
+
+
+ @Before
+ public void setUp() {
+
+ MockitoAnnotations.initMocks(this);
+ serviceBusinessLogic.setSdcRestClient(sdcClientMock);
+
+ new ErrorConfigurationLoader(System.getProperty("user.dir") + "/src/main/webapp/WEB-INF");
+
+ setServicesMock();
+ setVfcmtMock();
+ }
+
+ private void setVfcmtMock() {
+
+ when(vfcmt.getResourceType()).thenReturn(resourceType);
+ when(vfcmt.getCategory()).thenReturn(categoryName);
+ when(vfcmt.getLifecycleState()).thenReturn("NOT_CERTIFIED_CHECKIN");
+ when(vfcmt.getUuid()).thenReturn(vfcmtUuid);
+ List<Artifact> artifactList = new ArrayList<>();
+ Artifact artifact = Mockito.mock(Artifact.class);//gson.fromJson(artifactJson, Artifact.class);
+ artifactList.add(artifact);
+ when(vfcmt.getArtifacts()).thenReturn(artifactList);
+
+ when(artifact.getArtifactName()).thenReturn(DcaeBeConstants.Composition.fileNames.SVC_REF);
+
+ when(serviceBusinessLogic.getSdcRestClient().getResource(anyString(), anyString())).thenReturn(vfcmt);
+ when(serviceBusinessLogic.getSdcRestClient().changeResourceLifecycleState(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(vfcmt);
+
+ }
+
+ private void setServicesMock() {
+
+ ServiceDetailed serviceDetailed = new ServiceDetailed();
+ ResourceInstance resourceInstance = new ResourceInstance();
+ Artifact artifact = new Artifact();
+ artifact.setArtifactName("." + monitoringComponentName + "." + DcaeBeConstants.Composition.fileNames.EVENT_PROC_BP_YAML);
+ resourceInstance.setArtifacts(Collections.singletonList(artifact));
+ resourceInstance.setResourceInstanceName(vfiName);
+ resourceInstance.setResoucreType("VF");
+ serviceDetailed.setResources(Collections.singletonList(resourceInstance));
+ when(serviceBusinessLogic.getSdcRestClient().getService(anyString(), anyString())).thenReturn(serviceDetailed);
+
+ String serviceJson = "{\n\"lastUpdaterFullName\":\"GALCOHEN\",\n\"resources\":[{\n\"resourceInstanceName\":\"LiavVf0\",\n\"resourceName\":\"LiavVf\",\n\"resourceInvariantUUID\":\"47d5c3d6-83d8-4cbc-831c-1c7e52bd2964\",\n\"resourceVersion\":\"0.1\",\n\"resoucreType\":\"VF\",\n\"resourceUUID\":\"6e3a2db2-213b-41a4-b9eb-afab3c3b1463\",\n\"artifacts\":null\n}],\n\"artifacts\":null,\n\"distributionStatus\":\"DISTRIBUTION_NOT_APPROVED\",\n\"uuid\":\"b632b1da-e6ab-419d-8853-420e259097d9\",\n\"invariantUUID\":\"4cc1f274-107c-48e7-a7c7-9768c88043f7\",\n\"name\":\"Rony7777777\",\n\"version\":\"0.2\",\n\"toscaModelURL\":\"/sdc/v1/catalog/services/b632b1da-e6ab-419d-8853-420e259097d9/toscaModel\",\n\"lastUpdaterUserId\":\"gc786h\",\n\"category\":\"NetworkL1-3\",\n\"lifecycleState\":\"NOT_CERTIFIED_CHECKOUT\"\n}\n";
+ Service service = gson.fromJson(serviceJson, Service.class);
+ List<Service> serviceList = new ArrayList<>();
+ serviceList.add(service);
+ when(serviceBusinessLogic.getSdcRestClient().getServices(requestId)).thenReturn(serviceList);
+
+ }
+
+ @Test
+ public void test_Service() {
+
+ ResponseEntity<ServiceDetailed> result = serviceBusinessLogic.service(uuid, requestId);
- private static Gson gson = new GsonBuilder()
- .registerTypeAdapter(BaseAction.class, new ActionDeserializer())
- .registerTypeAdapter(BaseCondition.class, new ConditionDeserializer()).create();
+ assertEquals(HttpStatus.OK, result.getStatusCode());
+ assertEquals("vfiName", result.getBody().getResources().get(0).getResourceInstanceName());
+ assertEquals("VF", result.getBody().getResources().get(0).getResoucreType());
+ }
- ServiceBusinessLogic target = new ServiceBusinessLogic();
+ @Test
+ public void test_Services() {
+ ResponseEntity<List<Service>> result = serviceBusinessLogic.services(userId, vfcmtUuid, requestId);
+ assertEquals(HttpStatus.OK, result.getStatusCode());
+ assertNotEquals(0, result.getBody().size());
+ assertEquals(uuid, result.getBody().get(0).getUuid());
- @Test
- public void parseAndFliterServicesByUser_nullServices_TBD() {
+ }
+
+ @Test
+ public void test_AttachService() {
+
+ AttachVFCMTServiceRequest request = new AttachVFCMTServiceRequest();
+ request.setServiceUuid(serviceUuid);
+ request.setInstanceName(vfiName);
+
+
+ ResponseEntity<MessageResponse> result = serviceBusinessLogic.attachService(vfcmtUuid, userId, request, requestId);
+ assertEquals(HttpStatus.OK, result.getStatusCode());
+ assertThat(result.getBody().getSuccessResponse()).isEqualTo("Artifact updated");
+ }
+
+ @Test
+ public void test_AttachService_verifyVfiExists_Exception() {
+
+ AttachVFCMTServiceRequest request = new AttachVFCMTServiceRequest();
+ request.setServiceUuid(serviceUuid);
+ request.setInstanceName("WrongName");
+ when(serviceBusinessLogic.checkinVfcmt(userId, uuid, requestId)).thenReturn(null);
+
+ ResponseEntity<ResponseFormat> result = serviceBusinessLogic.attachService(vfcmtUuid, userId, request, requestId);
+ assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode());
+ assertEquals("SVC6039", result.getBody().getRequestError().getServiceException().getMessageId());
+ }
+
+ @Test
+ public void test_GetAttachedService() {
+
+ when(serviceBusinessLogic.getSdcRestClient().getResourceArtifact(anyString(), anyString(), anyString())).thenReturn("artifact data");
+
+ ResponseEntity<MessageResponse> result = serviceBusinessLogic.getAttachedService(vfcmtUuid, requestId);
+ assertEquals(HttpStatus.OK, result.getStatusCode());
+ assertThat(result.getBody().getSuccessResponse()).isEqualTo("artifact data");
+ }
+
+
+ @Test
+ public void test_parseAndFliterServicesByUser_nullServices_TBD() {
// fail("TODO Auto-generated method stub");
- }
-
-
- @Test
- public void parseAndFliterServicesByUser_emptyList_emptyList() {
- // arrange
- String user_id = "test";
- String lastUpdaterUserId = "test";
- List<LinkedHashMap<String, String>> services = new ArrayList<LinkedHashMap<String, String>>();
- // act
- List<DcaeMinimizedService> result = target.parseAndFilterServicesByUser(lastUpdaterUserId, services, user_id);
- // assert
- assertThat(result).isEqualTo(new ArrayList<DcaeMinimizedService>());
- }
-
-
- @Test
- public void parseAndFliterServicesByUser_singleServicesAsMap_singleServiceParsed() {
- // arrange
- String user_id = "test";
- String lastUpdaterUserId = user_id;
- String uuid = "a";
- String invariantUUID = "1";
- String lifecycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
- String version = "0.1";
- String serviceName = "TestService";
-
- LinkedHashMap<String, String> service = createServiceAsMap(lastUpdaterUserId, uuid, invariantUUID,
- lifecycleState, version, serviceName);
- List<LinkedHashMap<String, String>> services = new ArrayList<LinkedHashMap<String, String>>(
- Arrays.asList(service));
-
- DcaeMinimizedService expected = new DcaeMinimizedService(uuid, serviceName, lastUpdaterUserId, lifecycleState,
- version, invariantUUID);
- // act
- List<DcaeMinimizedService> result = target.parseAndFilterServicesByUser(lastUpdaterUserId, services, user_id);
- // assert
- assertThat(result).usingRecursiveFieldByFieldElementComparator().contains(expected);
- }
-
-
- @Test
- public void parseAndFliterServicesByUser_unsortedServices_sortedServices() {
- // arrange
- String user_id = "test";
- String lastUpdaterUserId = user_id;
- String uuid = "a";
- String lifecycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
- String version = "0.1";
-
- List<LinkedHashMap<String, String>> unsortedServices = Arrays.asList("d", "a", "c", "b").stream()
- .map(x -> createServiceAsMap(lastUpdaterUserId, uuid, UUID.randomUUID().toString(), lifecycleState, version, x))
- .collect(Collectors.toList());
-
-
- // act
- List<DcaeMinimizedService> result = target.parseAndFilterServicesByUser(lastUpdaterUserId, unsortedServices,
- user_id);
- // assert
- assertThat(result).extracting("name").containsExactly("a","b","c","d");
- }
-
-
- @Test
- public void parseAndFliterServicesByUser_allOptionsForLastUpdaterAndIsCheckout_allOptionsButIsCheckoutAndNotLastUpdater() {
- // ------------user == last_updater
- // -----------------True----False--
- // isCheckout----------------------
- // --------True------V--------X----
- // --------False-----V--------V----
- // --------------------------------
+ }
+
+
+ @Test
+ public void test_parseAndFliterServicesByUser_emptyList_emptyList() {
+ // arrange
+ String user_id = "test";
+ String lastUpdaterUserId = "test";
+ List<LinkedHashMap<String, String>> services = new ArrayList<LinkedHashMap<String, String>>();
+ // act
+ List<DcaeMinimizedService> result = serviceBusinessLogic.parseAndFilterServicesByUser(lastUpdaterUserId, services, user_id);
+ // assert
+ assertThat(result).isEqualTo(new ArrayList<DcaeMinimizedService>());
+ }
+
+
+ @Test
+ public void test_parseAndFliterServicesByUser_singleServicesAsMap_singleServiceParsed() {
+ // arrange
+ String user_id = "test";
+ String lastUpdaterUserId = user_id;
+ String uuid = "a";
+ String invariantUUID = "1";
+ String lifecycleState = DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
+ String version = "0.1";
+ String serviceName = "TestService";
+
+ LinkedHashMap<String, String> service = createServiceAsMap(lastUpdaterUserId, uuid, invariantUUID,
+ lifecycleState, version, serviceName);
+ List<LinkedHashMap<String, String>> services = new ArrayList<LinkedHashMap<String, String>>(
+ Arrays.asList(service));
+
+ DcaeMinimizedService expected = new DcaeMinimizedService(uuid, serviceName, lastUpdaterUserId, lifecycleState,
+ version, invariantUUID);
+ // act
+ List<DcaeMinimizedService> result = serviceBusinessLogic.parseAndFilterServicesByUser(lastUpdaterUserId, services, user_id);
+ // assert
+ assertThat(result).usingRecursiveFieldByFieldElementComparator().contains(expected);
+ }
+
+
+ @Test
+ public void test_parseAndFliterServicesByUser_unsortedServices_sortedServices() {
+ // arrange
+ String user_id = "test";
+ String lastUpdaterUserId = user_id;
+ String uuid = "a";
+ String lifecycleState = DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
+ String version = "0.1";
+
+ List<LinkedHashMap<String, String>> unsortedServices = Arrays.asList("d", "a", "c", "b").stream()
+ .map(x -> createServiceAsMap(lastUpdaterUserId, uuid, UUID.randomUUID().toString(), lifecycleState, version, x))
+ .collect(Collectors.toList());
+
+
+ // act
+ List<DcaeMinimizedService> result = serviceBusinessLogic.parseAndFilterServicesByUser(lastUpdaterUserId, unsortedServices,
+ user_id);
+ // assert
+ assertThat(result).extracting("name").containsExactly("a", "b", "c", "d");
+ }
+
+
+ @Test
+ public void test_parseAndFliterServicesByUser_allOptionsForLastUpdaterAndIsCheckout_allOptionsButIsCheckoutAndNotLastUpdater() {
+ // ------------user == last_updater
+ // -----------------True----False--
+ // isCheckout----------------------
+ // --------True------V--------X----
+ // --------False-----V--------V----
+ // --------------------------------
// fail("TODO Auto-generated method stub");
- }
-
-
- @Test
- public void parseAndFliterServicesByUser_singleServiceWithMultiVersions_singleServiceWithLatestVersion() {
- // arrange
- String user_id = "test";
- String lastUpdaterUserId = user_id;
- String uuid = "a";
- String invariantUUID = "1";
- String lifecycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
- String serviceName = "TestService";
-
- List<LinkedHashMap<String, String>> singleServiceWithMultiVersions = Arrays.asList("1.0", "0.3", "11.0", "2.0", "1.8").stream()
- .map(x -> createServiceAsMap(lastUpdaterUserId, uuid, invariantUUID, lifecycleState, x, serviceName))
- .collect(Collectors.toList());
-
- // act
- List<DcaeMinimizedService> result = target.parseAndFilterServicesByUser(lastUpdaterUserId, singleServiceWithMultiVersions, user_id);
-
- // assert
- assertThat(result).extracting("version").containsExactly("11.0");
- }
-
-
- private static LinkedHashMap<String, String> createServiceAsMap(String lastUpdaterUserId, String uuid,
- String invariantUUID, String lifecycleState, String version, String serviceName) {
-
- LinkedHashMap<String, String> service = new LinkedHashMap<String, String>() {
- {
- put("invariantUUID", invariantUUID);
- put("uuid", uuid);
- put("name", serviceName);
- put("lastUpdaterUserId", lastUpdaterUserId);
- put("lifecycleState", lifecycleState);
- put("version", version);
- }
- };
-
- return service;
- }
- private void mockGetService()
- {
- ServiceDetailed serviceDetailed = new ServiceDetailed();
- ResourceInstance resourceInstance = new ResourceInstance();
- Artifact artifact = new Artifact();
- artifact.setArtifactName("." + monitoringComponentName + "." + DcaeBeConstants.Composition.fileNames.EVENT_PROC_BP_YAML);
- resourceInstance.setArtifacts(Collections.singletonList(artifact));
- resourceInstance.setResourceInstanceName(vfiName);
- serviceDetailed.setResources(Collections.singletonList(resourceInstance));
- when(target.getSdcRestClient().getService(serviceUuid, requestId)).thenReturn(serviceDetailed);
- }
-}
+ }
+
+
+ @Test
+ public void test_parseAndFliterServicesByUser_singleServiceWithMultiVersions_singleServiceWithLatestVersion() {
+ // arrange
+ String user_id = "test";
+ String lastUpdaterUserId = user_id;
+ String uuid = "a";
+ String invariantUUID = "1";
+ String lifecycleState = DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
+ String serviceName = "TestService";
+
+ List<LinkedHashMap<String, String>> singleServiceWithMultiVersions = Arrays.asList("1.0", "0.3", "11.0", "2.0", "1.8").stream()
+ .map(x -> createServiceAsMap(lastUpdaterUserId, uuid, invariantUUID, lifecycleState, x, serviceName))
+ .collect(Collectors.toList());
+
+ // act
+ List<DcaeMinimizedService> result = serviceBusinessLogic.parseAndFilterServicesByUser(lastUpdaterUserId, singleServiceWithMultiVersions, user_id);
+
+ // assert
+ assertThat(result).extracting("version").containsExactly("11.0");
+ }
+
+
+ private static LinkedHashMap<String, String> createServiceAsMap(String lastUpdaterUserId, String uuid,
+ String invariantUUID, String lifecycleState, String version, String serviceName) {
+
+ LinkedHashMap<String, String> service = new LinkedHashMap<String, String>() {
+ {
+ put("invariantUUID", invariantUUID);
+ put("uuid", uuid);
+ put("name", serviceName);
+ put("lastUpdaterUserId", lastUpdaterUserId);
+ put("lifecycleState", lifecycleState);
+ put("version", version);
+ }
+ };
+
+ return service;
+ }
+} \ No newline at end of file
diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDC.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDC.java
index 08383ea..c704689 100644
--- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDC.java
+++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDC.java
@@ -1,114 +1,52 @@
package org.onap.sdc.dcae.catalog.asdc;
-import java.net.URI;
-import java.net.URISyntaxException;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.UncheckedIOException;
-
-import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-import java.util.Collections;
-
-import java.util.function.UnaryOperator;
-
-import javax.annotation.PostConstruct;
-
+import org.apache.commons.codec.digest.DigestUtils;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.onap.sdc.common.onaplog.Enums.LogLevel;
import org.onap.sdc.common.onaplog.OnapLoggerDebug;
import org.onap.sdc.common.onaplog.OnapLoggerError;
-import org.onap.sdc.common.onaplog.Enums.LogLevel;
-import org.onap.sdc.dcae.enums.ArtifactGroupType;
-import org.onap.sdc.dcae.enums.ArtifactType;
-import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed;
-import org.springframework.http.MediaType;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpRequest;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.RequestEntity;
-import org.springframework.http.ResponseEntity;
+import org.onap.sdc.dcae.catalog.commons.Action;
+import org.onap.sdc.dcae.catalog.commons.Future;
+import org.onap.sdc.dcae.catalog.commons.Futures;
+import org.onap.sdc.dcae.catalog.commons.JSONHttpMessageConverter;
+import org.springframework.context.annotation.Scope;
+import org.springframework.http.*;
import org.springframework.http.client.AsyncClientHttpRequestExecution;
import org.springframework.http.client.AsyncClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
-import org.springframework.web.client.AsyncRestTemplate;
-import org.springframework.web.client.RestClientException;
-import org.springframework.web.client.HttpClientErrorException;
import org.springframework.http.converter.HttpMessageConverter;
-
-import org.springframework.util.Base64Utils;
-import org.apache.commons.codec.digest.DigestUtils;
-
-import org.springframework.stereotype.Component;
-import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Scheduled;
-
+import org.springframework.stereotype.Component;
+import org.springframework.util.Base64Utils;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
+import org.springframework.web.client.AsyncRestTemplate;
+import org.springframework.web.client.HttpClientErrorException;
+import org.springframework.web.client.RestClientException;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang3.StringUtils;
-
-import org.json.JSONObject;
-import org.onap.sdc.dcae.catalog.commons.Action;
-import org.onap.sdc.dcae.catalog.commons.Future;
-import org.onap.sdc.dcae.catalog.commons.Futures;
-import org.onap.sdc.dcae.catalog.commons.JSONHttpMessageConverter;
-import org.json.JSONArray;
-
-import org.apache.commons.cli.BasicParser;
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.HelpFormatter;
-import org.apache.commons.cli.OptionBuilder;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
+import javax.annotation.PostConstruct;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
@Component("asdc")
@Scope("singleton")
public class ASDC {
- private static final String TARGET = "target";
- private static final String ACTION = "action";
- private static final String ASSET_TYPE = "assetType";
- private static final String USER_ID = "USER_ID";
- public static final String ASSET_ID = "assetId";
- public static final String ARTIFACT_ID = "artifactId";
- public static final String LIST_FILTER = "listFilter";
-
public enum AssetType {
resource,
service,
product
}
- public enum LifecycleState {
- Checkin,
- Checkout,
- Certify,
- undocheckout
- }
-
-
protected static OnapLoggerError errLogger = OnapLoggerError.getInstance();
protected static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance();
- private static final String ARTIFACT_TYPE = "artifactType";
- private static final String ARTIFACT_GROUP_TYPE = "artifactGroupType";
- private static final String ARTIFACT_LABEL = "artifactLabel";
- private static final String ARTIFACT_NAME = "artifactName";
- private static final String DESCRIPTION = "description";
- private static final String PAYLOAD_DATA = "payloadData";
-
- private static final String[] artifactMandatoryEntries = new String[] {};
-
- private static final String[] updateMandatoryEntries = new String[] {ARTIFACT_NAME,
- ARTIFACT_TYPE, ARTIFACT_GROUP_TYPE, ARTIFACT_LABEL, DESCRIPTION, PAYLOAD_DATA};
-
- private static final String[] uploadMandatoryEntries = new String[] {ARTIFACT_NAME,
- ARTIFACT_TYPE, ARTIFACT_GROUP_TYPE, ARTIFACT_LABEL, DESCRIPTION, PAYLOAD_DATA};
-
private URI rootUri;
private String rootPath = "/sdc/v1/catalog/";
private String user, passwd;
@@ -187,30 +125,10 @@ public class ASDC {
return getAssets(AssetType.resource, JSONArray.class, category, subCategory, resourceType);
}
- public <T> Future<T> getServices(Class<T> theType) {
- return getAssets(AssetType.service, theType);
- }
-
- public Future<JSONArray> getServices() {
- return getAssets(AssetType.service, JSONArray.class);
- }
-
- public <T> Future<T> getServices(Class<T> theType, String theCategory, String theSubCategory) {
- return getAssets(AssetType.service, theType, theCategory, theSubCategory);
- }
-
- public Future<JSONArray> getServices(String theCategory, String theSubCategory) {
- return getAssets(AssetType.service, JSONArray.class, theCategory, theSubCategory);
- }
-
public <T> Future<T> getAssets(AssetType theAssetType, Class<T> theType) {
return fetch(refAssets(theAssetType), theType);
}
- public <T> Action<T> getAssetsAction(AssetType theAssetType, Class<T> theType) {
- return () -> fetch(refAssets(theAssetType), theType);
- }
-
public <T> Future<T> getAssets(AssetType theAssetType, Class<T> theType,
String theCategory, String theSubCategory) {
return getAssets(theAssetType, theType, theCategory, theSubCategory, null);
@@ -220,12 +138,7 @@ public class ASDC {
String theCategory, String theSubCategory, String theResourceType) {
return fetch(refAssets(theAssetType) + filter(theCategory, theSubCategory, theResourceType), theType);
}
-
- public <T> Action<T> getAssetsAction(AssetType theAssetType, Class<T> theType,
- String theCategory, String theSubCategory, String theResourceType) {
- return () -> fetch(refAssets(theAssetType) + filter(theCategory, theSubCategory, theResourceType), theType);
- }
-
+
protected String refAssets(AssetType theAssetType) {
return this.rootPath + theAssetType + "s/";
}
@@ -260,19 +173,6 @@ public class ASDC {
return getAsset(AssetType.resource, theId, JSONObject.class);
}
- public Future<ResourceDetailed> getSDCResource(UUID theId) {
- return getAsset(AssetType.resource, theId, ResourceDetailed.class);
- }
-
-
- public <T> Future<T> getService(UUID theId, Class<T> theType) {
- return getAsset(AssetType.service, theId, theType);
- }
-
- public Future<JSONObject> getService(UUID theId) {
- return getAsset(AssetType.service, theId, JSONObject.class);
- }
-
public <T> Future<T> getAsset(AssetType theAssetType, UUID theId, Class<T> theType) {
return fetch(refAsset(theAssetType, theId) + "/metadata", theType);
}
@@ -281,14 +181,6 @@ public class ASDC {
return () -> fetch(refAsset(theAssetType, theId) + "/metadata", theType);
}
- public Future<byte[]> getResourceArchive(UUID theId) {
- return getAssetArchive(AssetType.resource, theId);
- }
-
- public Future<byte[]> getServiceArchive(UUID theId) {
- return getAssetArchive(AssetType.service, theId);
- }
-
public Future<byte[]> getAssetArchive(AssetType theAssetType, UUID theId) {
return fetch(refAsset(theAssetType, theId) + "/toscaModel", byte[].class);
}
@@ -297,42 +189,6 @@ public class ASDC {
return () -> fetch(refAsset(theAssetType, theId) + "/toscaModel", byte[].class);
}
- public Future<JSONObject> checkinResource(UUID theId, String theUser, String theMessage) {
- return cycleAsset(AssetType.resource, theId, LifecycleState.Checkin, theUser, theMessage);
- }
-
- public Future<JSONObject> checkinService(UUID theId, String theUser, String theMessage) {
- return cycleAsset(AssetType.service, theId, LifecycleState.Checkin, theUser, theMessage);
- }
-
- public Future<JSONObject> checkoutResource(UUID theId, String theUser, String theMessage) {
- return cycleAsset(AssetType.resource, theId, LifecycleState.Checkout, theUser, theMessage);
- }
-
- public Future<JSONObject> checkoutService(UUID theId, String theUser, String theMessage) {
- return cycleAsset(AssetType.service, theId, LifecycleState.Checkout, theUser, theMessage);
- }
-
- public Future<JSONObject> certifyResource(UUID theId, String theUser, String theMessage) {
- return cycleAsset(AssetType.resource, theId, LifecycleState.Certify, theUser, theMessage);
- }
-
- public Future<JSONObject> certifyService(UUID theId, String theUser, String theMessage) {
- return cycleAsset(AssetType.service, theId, LifecycleState.Certify, theUser, theMessage);
- }
-
- /* Normally theMessage is mandatory (and we'd use put instead of putOpt) but .. not so for undocheckout ..
- */
- public Future<JSONObject> cycleAsset(AssetType theAssetType, UUID theId, LifecycleState theState,
- String theUser, String theMessage) {
- return post(refAsset(theAssetType, theId) + "/lifecycleState/" + theState,
- headers -> prepareHeaders(headers).header(USER_ID, theUser), new JSONObject().putOpt("userRemarks", theMessage));
- }
-
- protected String refAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theAssetInstance, UUID theArtifactId) {
- return refAsset(theAssetType, theAssetId) + "/resourceInstances/" + theAssetInstance + "/artifacts" + (theArtifactId == null ? "" : ("/" + theArtifactId));
- }
-
protected String refAssetArtifact(AssetType theAssetType, UUID theAssetId, UUID theArtifactId) {
return refAsset(theAssetType, theAssetId) + "/artifacts" + (theArtifactId == null ? "" : ("/" + theArtifactId));
}
@@ -340,414 +196,11 @@ public class ASDC {
public <T> Future<T> getResourceArtifact(UUID theAssetId, UUID theArtifactId, Class<T> theType) {
return getAssetArtifact(AssetType.resource, theAssetId, theArtifactId, theType);
}
-
- public <T> Future<T> getServiceArtifact(UUID theAssetId, UUID theArtifactId, Class<T> theType) {
- return getAssetArtifact(AssetType.service, theAssetId, theArtifactId, theType);
- }
-
- public <T> Future<T> getResourceInstanceArtifact(UUID theAssetId, UUID theArtifactId, String theInstance, Class<T> theType) {
- return getAssetInstanceArtifact(AssetType.resource, theAssetId, theInstance, theArtifactId, theType);
- }
-
- public <T> Future<T> getServiceInstanceArtifact(UUID theAssetId, UUID theArtifactId, String theInstance, Class<T> theType) {
- return getAssetInstanceArtifact(AssetType.service, theAssetId, theInstance, theArtifactId, theType);
- }
public <T> Future<T> getAssetArtifact(AssetType theAssetType, UUID theAssetId, UUID theArtifactId, Class<T> theType) {
return fetch(refAssetArtifact(theAssetType, theAssetId, theArtifactId), theType);
}
-
- public <T> Action<T> getAssetArtifactAction(AssetType theAssetType, UUID theAssetId, UUID theArtifactId, Class<T> theType) {
- return () -> fetch(refAssetArtifact(theAssetType, theAssetId, theArtifactId), theType);
- }
-
- public <T> Future<T> getAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId, Class<T> theType) {
- return fetch(refAssetInstanceArtifact(theAssetType, theAssetId, theInstance, theArtifactId), theType);
- }
-
- public <T> Action<T> getAssetInstanceArtifactAction(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId, Class<T> theType) {
- return () -> fetch(refAssetInstanceArtifact(theAssetType, theAssetId, theInstance, theArtifactId), theType);
- }
-
- public ArtifactUploadAction createResourceArtifact(UUID theAssetId) {
- return createAssetArtifact(AssetType.resource, theAssetId);
- }
-
- public ArtifactUploadAction createServiceArtifact(UUID theAssetId) {
- return createAssetArtifact(AssetType.service, theAssetId);
- }
-
- public ArtifactUploadAction createResourceInstanceArtifact(UUID theAssetId, String theInstance) {
- return createAssetInstanceArtifact(AssetType.resource, theAssetId, theInstance);
- }
-
- public ArtifactUploadAction createServiceInstanceArtifact(UUID theAssetId, String theInstance) {
- return createAssetInstanceArtifact(AssetType.service, theAssetId, theInstance);
- }
-
- public ArtifactUploadAction createAssetArtifact(AssetType theAssetType, UUID theAssetId) {
- return new ArtifactUploadAction()
- .ofAsset(theAssetType, theAssetId);
- }
-
- public ArtifactUploadAction createAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance) {
- return new ArtifactUploadAction()
- .ofAssetInstance(theAssetType, theAssetId, theInstance);
- }
-
- public ArtifactUpdateAction updateResourceArtifact(UUID theAssetId, JSONObject theArtifactInfo) {
- return updateAssetArtifact(AssetType.resource, theAssetId, theArtifactInfo);
- }
-
- public ArtifactUpdateAction updateResourceInstanceArtifact(UUID theAssetId, String theInstance, JSONObject theArtifactInfo) {
- return updateAssetInstanceArtifact(AssetType.resource, theAssetId, theInstance, theArtifactInfo);
- }
-
- public ArtifactUpdateAction updateServiceArtifact(UUID theAssetId, JSONObject theArtifactInfo) {
- return updateAssetArtifact(AssetType.service, theAssetId, theArtifactInfo);
- }
-
- public ArtifactUpdateAction updateServiceInstanceArtifact(UUID theAssetId, String theInstance, JSONObject theArtifactInfo) {
- return updateAssetInstanceArtifact(AssetType.service, theAssetId, theInstance, theArtifactInfo);
- }
-
- public ArtifactUpdateAction updateAssetArtifact(AssetType theAssetType, UUID theAssetId, JSONObject theArtifactInfo) {
- return new ArtifactUpdateAction(theArtifactInfo)
- .ofAsset(theAssetType, theAssetId);
- }
-
- public ArtifactUpdateAction updateAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance, JSONObject theArtifactInfo) {
- return new ArtifactUpdateAction(theArtifactInfo)
- .ofAssetInstance(theAssetType, theAssetId, theInstance);
- }
-
- public ArtifactDeleteAction deleteResourceArtifact(UUID theAssetId, UUID theArtifactId) {
- return deleteAssetArtifact(AssetType.resource, theAssetId, theArtifactId);
- }
-
- public ArtifactDeleteAction deleteResourceInstanceArtifact(UUID theAssetId, String theInstance, UUID theArtifactId) {
- return deleteAssetInstanceArtifact(AssetType.resource, theAssetId, theInstance, theArtifactId);
- }
-
- public ArtifactDeleteAction deleteServiceArtifact(UUID theAssetId, UUID theArtifactId) {
- return deleteAssetArtifact(AssetType.service, theAssetId, theArtifactId);
- }
-
- public ArtifactDeleteAction deleteServiceInstanceArtifact(UUID theAssetId, String theInstance, UUID theArtifactId) {
- return deleteAssetInstanceArtifact(AssetType.service, theAssetId, theInstance, theArtifactId);
- }
-
- public ArtifactDeleteAction deleteAssetArtifact(AssetType theAssetType, UUID theAssetId, UUID theArtifactId) {
- return new ArtifactDeleteAction(theArtifactId)
- .ofAsset(theAssetType, theAssetId);
- }
-
- public ArtifactDeleteAction deleteAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId) {
- return new ArtifactDeleteAction(theArtifactId)
- .ofAssetInstance(theAssetType, theAssetId, theInstance);
- }
-
-
- public abstract class ASDCAction<A extends ASDCAction<A, T>, T> implements Action<T> {
-
- protected JSONObject info; //info passed to asdc as request body
- protected String operatorId; //id of the SDC user performing the action
-
- protected ASDCAction(JSONObject theInfo) {
- this.info = theInfo;
- }
-
- protected abstract A self();
-
- protected ASDC asdc() {
- return ASDC.this;
- }
-
- protected A withInfo(JSONObject theInfo) {
- merge(this.info, theInfo);
- return self();
- }
-
- public A with(String theProperty, Object theValue) {
- info.put(theProperty, theValue);
- return self();
- }
-
- public A withOperator(String theOperator) {
- this.operatorId = theOperator;
- return self();
- }
-
- protected abstract String[] mandatoryInfoEntries();
-
- protected void checkOperatorId() {
- if (this.operatorId == null) {
- throw new IllegalStateException("No operator id was provided");
- }
- }
-
- protected void checkMandatoryInfo() {
- for (String field: mandatoryInfoEntries()) {
- if (!info.has(field)) {
- throw new IllegalStateException("No '" + field + "' was provided");
- }
- }
- }
-
- protected void checkMandatory() {
- checkOperatorId();
- checkMandatoryInfo();
- }
- }
-
-
- /**
- * We use teh same API to operate on artifacts attached to assets or to their instances
- */
- public abstract class ASDCArtifactAction<A extends ASDCArtifactAction<A>> extends ASDCAction<A, JSONObject> {
-
- protected AssetType assetType;
- protected UUID assetId;
- protected String assetInstance;
-
- protected ASDCArtifactAction(JSONObject theInfo) {
- super(theInfo);
- }
-
- protected A ofAsset(AssetType theAssetType, UUID theAssetId) {
- this.assetType = theAssetType;
- this.assetId = theAssetId;
- return self();
- }
-
- protected A ofAssetInstance(AssetType theAssetType, UUID theAssetId, String theInstance) {
- this.assetType = theAssetType;
- this.assetId = theAssetId;
- this.assetInstance = theInstance;
- return self();
- }
-
- protected String normalizeInstanceName(String theName) {
- return StringUtils.removePattern(theName, "[ \\.\\-]+").toLowerCase();
- }
-
- protected String[] mandatoryInfoEntries() {
- return ASDC.this.artifactMandatoryEntries;
- }
-
- protected String ref(UUID theArtifactId) {
- return (this.assetInstance == null) ?
- refAssetArtifact(this.assetType, this.assetId, theArtifactId) :
- refAssetInstanceArtifact(this.assetType, this.assetId, normalizeInstanceName(this.assetInstance), theArtifactId);
- }
- }
-
- public class ArtifactUploadAction extends ASDCArtifactAction<ArtifactUploadAction> {
-
- public static final String PAYLOAD_DATA = ASDC.PAYLOAD_DATA;
-
- protected ArtifactUploadAction() {
- super(new JSONObject());
- }
-
- protected ArtifactUploadAction self() {
- return this;
- }
-
- public ArtifactUploadAction withContent(byte[] theContent) {
- return with(PAYLOAD_DATA, Base64Utils.encodeToString(theContent));
- }
-
- public ArtifactUploadAction withContent(File theFile) throws IOException {
- return withContent(FileUtils.readFileToByteArray(theFile));
- }
-
- public ArtifactUploadAction withLabel(String theLabel) {
- return with(ARTIFACT_LABEL, theLabel);
- }
-
- public ArtifactUploadAction withName(String theName) {
- return with(ARTIFACT_NAME, theName);
- }
-
- public ArtifactUploadAction withDisplayName(String theName) {
- return with("artifactDisplayName", theName);
- }
-
- public ArtifactUploadAction withType(ArtifactType theType) {
- return with(ARTIFACT_TYPE, theType.toString());
- }
-
- public ArtifactUploadAction withGroupType(ArtifactGroupType theGroupType) {
- return with(ARTIFACT_GROUP_TYPE, theGroupType.toString());
- }
-
- public ArtifactUploadAction withDescription(String theDescription) {
- return with(DESCRIPTION, theDescription);
- }
-
- @Override
- protected String[] mandatoryInfoEntries() {
- return ASDC.this.uploadMandatoryEntries;
- }
-
- public Future<JSONObject> execute() {
- checkMandatory();
- return ASDC.this.post(ref(null),
- headers -> prepareHeaders(headers).header(USER_ID, this.operatorId), this.info);
- }
- }
-
-
-
- /**
- * In its current form the update relies on a previous artifact retrieval. One cannot build an update from scratch.
- * The label, tye and group type must be submitted but cannot be updated
- */
- public class ArtifactUpdateAction extends ASDCArtifactAction<ArtifactUpdateAction> {
-
-
- protected ArtifactUpdateAction(JSONObject theInfo) {
- super(theInfo);
- }
-
- protected ArtifactUpdateAction self() {
- return this;
- }
-
- public ArtifactUpdateAction withContent(byte[] theContent) {
- return with(PAYLOAD_DATA, Base64Utils.encodeToString(theContent));
- }
-
- public ArtifactUpdateAction withContent(File theFile) throws IOException {
- return withContent(FileUtils.readFileToByteArray(theFile));
- }
-
- public ArtifactUpdateAction withDescription(String theDescription) {
- return with(DESCRIPTION, theDescription);
- }
-
- public ArtifactUpdateAction withName(String theName) {
- return with(ARTIFACT_NAME, theName);
- }
-
- @Override
- protected String[] mandatoryInfoEntries() {
- return ASDC.this.updateMandatoryEntries;
- }
-
- /* The json object originates (normally) from a get so it will have entries we need to cleanup */
- protected void cleanupInfoEntries() {
- this.info.remove("artifactChecksum");
- this.info.remove("artifactUUID");
- this.info.remove("artifactVersion");
- this.info.remove("artifactURL");
- this.info.remove("artifactDescription");
- }
-
- public Future<JSONObject> execute() {
- UUID artifactUUID = UUID.fromString(this.info.getString("artifactUUID"));
- checkMandatory();
- cleanupInfoEntries();
- return ASDC.this.post(ref(artifactUUID),
- headers -> prepareHeaders(headers).header(USER_ID, this.operatorId),this.info);
- }
- }
-
- public class ArtifactDeleteAction extends ASDCArtifactAction<ArtifactDeleteAction> {
-
- private UUID artifactId;
-
- protected ArtifactDeleteAction(UUID theArtifactId) {
- super(null);
- this.artifactId = theArtifactId;
- }
-
- protected ArtifactDeleteAction self() {
- return this;
- }
-
- public Future<JSONObject> execute() {
- checkMandatory();
- return ASDC.this.delete(ref(this.artifactId),
- headers -> prepareHeaders(headers).header(USER_ID, this.operatorId));
- }
- }
-
-
-
-
- private VFCMTCreateAction createVFCMT() {
- return new VFCMTCreateAction();
- }
-
-
-
-
- public class VFCMTCreateAction extends ASDCAction<VFCMTCreateAction, JSONObject> {
-
- private static final String CONTACT_ID = "contactId";
- private final String[] vfcmtMandatoryEntries = new String[] { "name", "vendorName", "vendorRelease", CONTACT_ID};
-
- protected VFCMTCreateAction() {
-
- super(new JSONObject());
- this
- .with("resourceType", "VFCMT")
- .with("category", "Template")
- .with("subcategory", "Monitoring Template")
- .with("icon", "defaulticon");
- }
-
- protected VFCMTCreateAction self() {
- return this;
- }
- public VFCMTCreateAction withName(String theName) {
- return with("name", theName);
- }
-
- public VFCMTCreateAction withDescription(String theDescription) {
- return with(DESCRIPTION, theDescription);
- }
-
- public VFCMTCreateAction withVendorName(String theVendorName) {
- return with("vendorName", theVendorName);
- }
-
- public VFCMTCreateAction withVendorRelease(String theVendorRelease) {
- return with("vendorRelease", theVendorRelease);
- }
-
- public VFCMTCreateAction withTags(String... theTags) {
- for (String tag: theTags) {
- this.info.append("tags", tag);
- }
- return this;
- }
-
- public VFCMTCreateAction withIcon(String theIcon) {
- return with("icon", theIcon);
- }
-
- protected String[] mandatoryInfoEntries() {
- return vfcmtMandatoryEntries;
- }
-
- public VFCMTCreateAction withContact(String theContact) {
- return with(CONTACT_ID, theContact);
- }
-
- public Future<JSONObject> execute() {
-
- this.info.putOnce(CONTACT_ID, this.operatorId);
- this.info.append("tags", info.optString("name"));
- checkMandatory();
- return ASDC.this.post(refAssets(AssetType.resource),
- headers -> prepareHeaders(headers).header(USER_ID, this.operatorId), this.info);
- }
-
- }
public static JSONObject merge(JSONObject theOriginal, JSONObject thePatch) {
for (String key: (Set<String>)thePatch.keySet()) {
@@ -758,15 +211,6 @@ public class ASDC {
return theOriginal;
}
- protected URI refUri(String theRef) {
- try {
- return new URI(this.rootUri + theRef);
- }
- catch(URISyntaxException urisx) {
- throw new UncheckedIOException(new IOException(urisx));
- }
- }
-
private HttpHeaders prepareHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString((this.user + ":" + this.passwd).getBytes()));
@@ -778,38 +222,10 @@ public class ASDC {
return headers;
}
- private RequestEntity.HeadersBuilder prepareHeaders(RequestEntity.HeadersBuilder theBuilder) {
- return theBuilder
- .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString((this.user + ":" + this.passwd).getBytes()))
- .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
- .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM_VALUE)
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
- .header("X-ECOMP-InstanceID", this.instanceId);
- }
-
public <T> Future<T> fetch(String theRef, Class<T> theContentType) {
return exchange(theRef, HttpMethod.GET, new HttpEntity(prepareHeaders()), theContentType);
}
- public Future<JSONObject> post(String theRef, JSONObject thePost) {
- return exchange(theRef, HttpMethod.POST, new HttpEntity<JSONObject>(thePost, prepareHeaders()), JSONObject.class);
- }
-
- public Future<JSONObject> post(String theRef, UnaryOperator<RequestEntity.HeadersBuilder> theHeadersBuilder, JSONObject thePost) {
- RequestEntity.BodyBuilder builder = RequestEntity.post(refUri(theRef));
- theHeadersBuilder.apply(builder);
-
- return exchange(theRef, HttpMethod.POST, builder.body(thePost), JSONObject.class);
- }
-
- public Future<JSONObject> delete(String theRef, UnaryOperator<RequestEntity.HeadersBuilder> theHeadersBuilder) {
-
- RequestEntity.HeadersBuilder builder = RequestEntity.delete(refUri(theRef));
- theHeadersBuilder.apply(builder);
-
- return exchange(theRef, HttpMethod.DELETE, builder.build(), JSONObject.class);
- }
-
public <T> Future<T> exchange(String theRef, HttpMethod theMethod, HttpEntity theRequest, Class<T> theResponseType) {
AsyncRestTemplate restTemplate = new AsyncRestTemplate();
@@ -838,8 +254,6 @@ public class ASDC {
return result;
}
-
-
public class ASDCFuture<T> extends Futures.BasicFuture<T> {
ListenableFutureCallback<ResponseEntity<T>> callback = new ListenableFutureCallback<ResponseEntity<T>>() {
@@ -857,7 +271,6 @@ public class ASDC {
}
}
};
-
}
public class ContentMD5Interceptor implements AsyncClientHttpRequestInterceptor {
@@ -872,171 +285,4 @@ public class ASDC {
return theExecution.executeAsync(theRequest, theBody);
}
}
-
- public static void main(String[] theArgs) throws Exception {
-
- CommandLineParser parser = new BasicParser();
-
- String userId = "jh0003";
-
- Options options = new Options();
- options.addOption(OptionBuilder
- .withArgName(TARGET)
- .withLongOpt(TARGET)
- .withDescription("target asdc system")
- .hasArg()
- .isRequired()
- .create('t') );
-
- options.addOption(OptionBuilder
- .withArgName(ACTION)
- .withLongOpt(ACTION)
- .withDescription("one of: list, get, getartifact, checkin, checkout")
- .hasArg()
- .isRequired()
- .create('a') );
-
- options.addOption(OptionBuilder
- .withArgName(ASSET_TYPE)
- .withLongOpt(ASSET_TYPE)
- .withDescription("one of resource, service, product")
- .hasArg()
- .isRequired()
- .create('k') ); //k for 'kind' ..
-
- options.addOption(OptionBuilder
- .withArgName(ASSET_ID)
- .withLongOpt(ASSET_ID)
- .withDescription("asset uuid")
- .hasArg()
- .create('u') ); //u for 'uuid'
-
- options.addOption(OptionBuilder
- .withArgName(ARTIFACT_ID)
- .withLongOpt(ARTIFACT_ID)
- .withDescription("artifact uuid")
- .hasArg()
- .create('s') ); //s for 'stuff'
-
- options.addOption(OptionBuilder
- .withArgName(LIST_FILTER)
- .withLongOpt(LIST_FILTER)
- .withDescription("filter for list operations")
- .hasArg()
- .create('f') ); //u for 'uuid'
-
- CommandLine line = null;
- try {
- line = parser.parse(options, theArgs);
- }
- catch(ParseException exp) {
- errLogger.log(LogLevel.ERROR, ASDC.class.getName(), exp.getMessage());
- new HelpFormatter().printHelp("asdc", options);
- return;
- }
-
- ASDC asdc = new ASDC();
- asdc.setUri(new URI(line.getOptionValue(TARGET)));
-
- String action = line.getOptionValue(ACTION);
- if ("list".equals(action)) {
- JSONObject filterInfo = new JSONObject(
- line.hasOption(LIST_FILTER) ?
- line.getOptionValue(LIST_FILTER) : "{}");
- JSONArray assets =
- asdc.getAssets(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)), JSONArray.class,
- filterInfo.optString("category", null), filterInfo.optString("subCategory", null))
- .waitForResult();
- for (int i = 0; i < assets.length(); i++) {
- debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"> {}", assets.getJSONObject(i).toString(2));
- }
- }
- else if ("get".equals(action)) {
- debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),
- asdc.getAsset(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)),
- UUID.fromString(line.getOptionValue(ASSET_ID)),
- JSONObject.class)
- .waitForResult()
- .toString(2)
- );
- }
- else if ("getartifact".equals(action)) {
- debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),
- asdc.getAssetArtifact(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)),
- UUID.fromString(line.getOptionValue(ASSET_ID)),
- UUID.fromString(line.getOptionValue(ARTIFACT_ID)),
- String.class)
- .waitForResult()
- );
- }
- else if ("checkin".equals(action)) {
- debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),
- asdc.cycleAsset(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)),
- UUID.fromString(line.getOptionValue(ASSET_ID)),
- ASDC.LifecycleState.Checkin,
- userId,
- "cli op")
- .waitForResult()
- .toString()
- );
- }
- else if ("checkout".equals(action)) {
- debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),
- asdc.cycleAsset(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)),
- UUID.fromString(line.getOptionValue(ASSET_ID)),
- ASDC.LifecycleState.Checkout,
- userId,
- "cli op")
- .waitForResult()
- .toString()
- );
- }
- else if ("cleanup".equals(action)) {
- JSONArray resources = asdc.getResources()
- .waitForResult();
- debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"Got {} resources", resources.length());
-
- vfcmtCleanup(userId, asdc, resources);
- }
- else {
- try {
- debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),
- asdc.createVFCMT()
- .withName("Clonator")
- .withDescription("Clone operation target 06192017")
- .withVendorName("CloneInc")
- .withVendorRelease("1.0")
- .withTags("clone")
- .withOperator(userId)
- .execute()
- .waitForResult()
- .toString()
- );
- }
- catch(Exception x) {
- debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"Failed to create VFCMT: {}", x);
- }
- }
- }
-
- private static void vfcmtCleanup(String userId, ASDC asdc, JSONArray resources) {
- for (int i = 0; i < resources.length(); i++) {
-
- JSONObject resource = resources.getJSONObject(i);
-
- if ("VFCMT".equals(resource.getString("resourceType")) &&
- resource.getString("name").contains("test")) {
-
- debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"undocheckout for {}", resource.getString("uuid"));
-
- try {
- asdc.cycleAsset(AssetType.resource, UUID.fromString(resource.getString("uuid")), LifecycleState.undocheckout, userId, null)
- .waitForResult();
- }
- catch (Exception x) {
- debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"** {}", x);
- }
- }
- }
- }
}
diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCController.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCController.java
deleted file mode 100644
index e69de29..0000000
--- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCController.java
+++ /dev/null
diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtils.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtils.java
index d6a175f..a3ea63d 100644
--- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtils.java
+++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtils.java
@@ -4,14 +4,13 @@ import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
+import org.onap.sdc.common.onaplog.Enums.LogLevel;
import org.onap.sdc.common.onaplog.OnapLoggerDebug;
import org.onap.sdc.common.onaplog.OnapLoggerError;
-import org.onap.sdc.common.onaplog.Enums.LogLevel;
import org.onap.sdc.dcae.catalog.commons.Actions;
import org.onap.sdc.dcae.catalog.commons.Future;
import org.onap.sdc.dcae.catalog.commons.Futures;
import org.onap.sdc.dcae.catalog.commons.Recycler;
-import org.onap.sdc.dcae.checker.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Scope;
@@ -20,7 +19,9 @@ import org.springframework.util.Base64Utils;
import java.io.*;
import java.net.URI;
-import java.util.*;
+import java.util.List;
+import java.util.Spliterators;
+import java.util.UUID;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -72,58 +73,7 @@ public class ASDCUtils {
this.blueprint = theBlueprinter;
}
- public CloneAssetArtifactsAction cloneAssetArtifacts(ASDC.AssetType theAssetType, UUID theSourceId, UUID theTargetId) {
- return new CloneAssetArtifactsAction(this.asdc, theAssetType, theSourceId, theTargetId);
- }
-
- public static class CloneAssetArtifactsAction extends ASDC.ASDCAction<CloneAssetArtifactsAction, List<JSONObject>> {
-
- private ASDC.AssetType assetType;
- private UUID sourceId, targetId;
-
- CloneAssetArtifactsAction(ASDC theASDC, ASDC.AssetType theAssetType, UUID theSourceId, UUID theTargetId) {
- theASDC.super(new JSONObject());
- this.assetType = theAssetType;
- this.sourceId = theSourceId;
- this.targetId = theTargetId;
- }
-
- protected CloneAssetArtifactsAction self() {
- return this;
- }
-
- public CloneAssetArtifactsAction withLabel(String theLabel) {
- return with("artifactLabel", theLabel);
- }
-
- protected String[] mandatoryInfoEntries() {
- return new String[] {};
- }
-
- public Future<List<JSONObject>> execute() {
- checkMandatory();
-
- final Actions.Sequence<JSONObject> sequencer = new Actions.Sequence<JSONObject>();
-
- new Actions.Sequence().add(super.asdc().getAssetArchiveAction(this.assetType, this.sourceId)).add(super.asdc().getAssetAction(this.assetType, this.sourceId, JSONObject.class)).execute().setHandler(assetFuture -> {
- debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "*** {}", assetFuture.result());
- processArtifacts((List) assetFuture.result(), (JSONObject theInfo, byte[] theData) -> {
- theInfo.remove("artifactChecksum");
- theInfo.remove("artifactUUID");
- theInfo.remove("artifactVersion");
- theInfo.remove(ARTIFACT_URL);
- theInfo.put("description", theInfo.remove("artifactDescription"));
- theInfo.put("payloadData", Base64Utils.encodeToString(theData));
- return theInfo;
- }, null).forEach(artifactInfo -> sequencer.add(super.asdc().createAssetArtifact(this.assetType, this.targetId).withInfo(ASDC.merge(artifactInfo, this.info)).withOperator(this.operatorId)));
- sequencer.execute();
- });
-
- return sequencer.future();
- }
- } //the Action class
- /* */
private static JSONObject lookupArtifactInfo(JSONArray theArtifacts, String theName) {
for (int i = 0; theArtifacts != null && i < theArtifacts.length(); i++) {
@@ -151,48 +101,6 @@ public class ASDCUtils {
return baos.toByteArray();
}
- /**
- * Recycle a cdump, fetch all relevant ASDC artifacts, interact with Shu's toscalib service in order to generate
- * a blueprint. No 'Action' object here as there is nothig to set up.
- */
- public Future<Future<String>> buildBlueprint(Reader theCdump) {
-
- final Recycler recycler = new Recycler();
- Object template = null;
-
- try {
- template = recycler.recycle(theCdump);
-
- } catch (Exception x) {
- return Futures.failedFuture(x);
- }
-
- JXPathContext jxroot = JXPathContext.newContext(template);
- jxroot.setLenient(true);
-
- //based on the output of ASDCCatalog the node description will contain the UUID of the resource declaring it
- List uuids = (List) StreamSupport.stream(Spliterators.spliteratorUnknownSize(jxroot.iterate("topology_template/node_templates/*/description"), 16), false).distinct().filter(desc -> desc != null)
- //the desc contains the full URI and the resource uuid is the 5th path element
- .map(desc -> desc.toString().split("/")[5]).collect(Collectors.toList());
-
- //prepare fetching all archives/resource details
- final Futures.Accumulator accumulator = new Futures.Accumulator();
- uuids.forEach(uuid -> {
- UUID rid = UUID.fromString((String) uuid);
- accumulator.add(this.asdc.getAssetArchive(ASDC.AssetType.resource, rid));
- accumulator.add(this.asdc.getAsset(ASDC.AssetType.resource, rid, JSONObject.class));
- });
-
- final byte[] templateData = recycler.toString(template).getBytes(/*"UTF-8"*/);
- //retrieve all resource archive+details, prepare blueprint service request and send its request
- return Futures.advance(accumulator.accumulate(), (List theArchives) -> {
- Blueprinter.BlueprintAction action = blueprint.generateBlueprint();
- processArtifacts(theArchives, (JSONObject theInfo, byte[] theData) -> new JSONObject().put(theInfo.getString(ARTIFACT_NAME).split("\\.")[0], Base64Utils.encodeToString(theData)),
- (Stream<JSONObject> theAssetArtifacts) -> theAssetArtifacts.reduce(new JSONObject(), ASDC::merge)).forEach(artifactInfo -> action.withModelInfo(artifactInfo));
-
- return action.withTemplateData(templateData).execute();
- });
- }
public Future<Future<String>> buildBlueprintViaToscaLab(Reader theCdump) {
return processCdump(theCdump, (theTemplate, theArchives) -> {
@@ -205,182 +113,6 @@ public class ASDCUtils {
});
}
- private static class Tracker implements TargetLocator {
-
- private enum Position {
- SCHEMA, TEMPLATE, TRANSLATE;
- }
-
- private static final int POSITIONS = Position.values().length;
-
- private List<Target> tgts = new ArrayList<Target>(3);
-
- Tracker() {
- clear();
- }
-
- public boolean addSearchPath(URI theURI) {
- return false;
- }
-
- public boolean addSearchPath(String thePath) {
- return false;
- }
-
- public Iterable<URI> searchPaths() {
- return Collections.emptyList();
- }
-
- int position(String... theKeys) {
- for (String key : theKeys) {
- if ("schema".equals(key)) {
- return Position.SCHEMA.ordinal();
- }
- if ("template".equals(key)) {
- return Position.TEMPLATE.ordinal();
- }
- if ("translate".equals(key)) {
- return Position.TRANSLATE.ordinal();
- }
- }
- return -1;
- }
-
- public Target resolve(String theName) {
- for (Target tgt : tgts) {
- if (tgt != null && tgt.getName().equals(theName)) {
- return tgt;
- }
- }
- return null;
- }
-
- void track(JSONObject theInfo, final byte[] theData) {
- String uri = theInfo.getString(ARTIFACT_URL).split("/")[5];
- String name = theInfo.getString(ARTIFACT_NAME), desc = theInfo.getString("artifactDescription"), label = theInfo.getString("artifactLabel");
- int pos = position(desc, label);
-
- debugLogger.log(LogLevel.DEBUG, ASDCUtils.class.getName(), "Tracking {} at {}, {}", name, pos, theInfo.optString(ARTIFACT_URL));
-
- if (pos > -1) {
- tgts.set(pos, new Target(name, URI.create("asdc:" + uri + "/" + name)) {
- @Override
- public Reader open(){
- return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(theData)));
- }
- });
- }
- }
-
- boolean hasSchema() {
- return tgts.get(Position.SCHEMA.ordinal()) != null;
- }
-
- public Target schema() {
- return tgts.get(Position.SCHEMA.ordinal());
- }
-
- boolean hasTemplate() {
- return tgts.get(Position.TEMPLATE.ordinal()) != null;
- }
-
- public Target template() {
- return tgts.get(Position.TEMPLATE.ordinal());
- }
-
- boolean hasTranslation() {
- return tgts.get(Position.TRANSLATE.ordinal()) != null;
- }
-
- public Target translation() {
- return tgts.get(Position.TRANSLATE.ordinal());
- }
-
- public void clear() {
- if (tgts.isEmpty()) {
- for (int i = 0; i < POSITIONS; i++) {
- tgts.add(null);
- }
- } else {
- Collections.fill(tgts, null);
- }
- }
- }
-
- private Checker buildChecker() {
- try {
- return new Checker();
- } catch (CheckerException cx) {
- errLogger.log(LogLevel.ERROR, this.getClass().getName(), "CheckerException while creating Checker {}", cx);
- return null;
- }
- }
-
- public Future<Catalog> buildCatalog(Reader theCdump) {
-
- //
- //the purpose of the tracking is to be able to resolve import references within the 'space' of an
- //asset's artifacts
- //processing order is important too so we 'order the targets: schema, template, translation
- //
- final Tracker tracker = new Tracker();
- final Catalog catalog = Checker.buildCatalog();
-
- return processCdump(theCdump, (theTemplate, theArchives) -> {
-
- final Checker checker = buildChecker();
- if (checker == null) {
- return null;
- }
- checker.setTargetLocator(tracker);
-
- processArtifacts(theArchives, (JSONObject theInfo, byte[] theData) -> {
- tracker.track(theInfo, theData);
- return (Catalog) null;
- },
- // aggregation: this is where the actual processing takes place now that
- // we have all the targets
- (Stream<Catalog> theAssetArtifacts) -> checkAndGetCatalog(tracker, catalog, checker));
-
- Target cdump = new Target("cdump", URI.create("asdc:cdump"));
- cdump.setTarget(theTemplate);
-
- validateCatalog(catalog, checker, cdump);
-
- return catalog;
- });
- }
-
- private Catalog checkAndGetCatalog(Tracker tracker, Catalog catalog, Checker checker) {
- //the stream is full of nulls, ignore it, work with the tracker
-
- try {
- if (tracker.hasSchema()) {
- checker.check(tracker.schema(), catalog);
- }
- if (tracker.hasTemplate()) {
- checker.check(tracker.template(), catalog);
- }
- if (tracker.hasTranslation()) {
- checker.check(tracker.translation(), catalog);
- }
- } catch (CheckerException cx) {
- //got to do better than this
- errLogger.log(LogLevel.ERROR, ASDC.class.getName(),"CheckerException while checking catalog:{}", cx);
- } finally {
- tracker.clear();
- }
- return checker.catalog();
- }
-
- private void validateCatalog(Catalog catalog, Checker checker, Target cdump) {
- try {
- checker.validate(cdump, catalog);
- } catch (CheckerException cx) {
- errLogger.log(LogLevel.ERROR, ASDC.class.getName(),"CheckerException while building catalog:{}", cx);
- }
- }
-
/* The common process of recycling, retrieving all related artifacts and then doing 'something' */
private <T> Future<T> processCdump(Reader theCdump, BiFunction<Object, List, T> theProcessor) {
diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/RequestError.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/RequestError.java
index 7207916..0a44a3e 100644
--- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/RequestError.java
+++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/RequestError.java
@@ -9,6 +9,11 @@ public class RequestError {
private PolicyException policyException;
private ServiceException serviceException;
private OkResponseInfo okResponseInfo;
+ private List<ServiceException> serviceExceptions;
+
+ public PolicyException getPolicyException() {
+ return policyException;
+ }
public ServiceException getServiceException() {
return serviceException;
@@ -26,8 +31,11 @@ public class RequestError {
this.okResponseInfo = okResponseInfo;
}
+ public List<ServiceException> getServiceExceptions() {
+ return serviceExceptions;
+ }
void setServiceExceptions(List<ServiceException> serviceExceptions) {
- // no one asks for these exception ever
+ this.serviceExceptions = serviceExceptions;
}
String getFormattedMessage() {
@@ -47,11 +55,9 @@ public class RequestError {
}
AbstractSdncException getError() {
- if (null != policyException) {
- return (null != serviceException) ? serviceException : policyException;
- }
- else {
- return (null != serviceException) ? serviceException : okResponseInfo;
+ if (null != serviceException) {
+ return serviceException;
}
+ return (null != policyException) ? policyException : okResponseInfo;
}
} \ No newline at end of file
diff --git a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Action.java b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Action.java
index fb36950..2c62412 100644
--- a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Action.java
+++ b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Action.java
@@ -1,7 +1,5 @@
package org.onap.sdc.dcae.catalog.commons;
-import org.onap.sdc.dcae.catalog.commons.Future;
-
/**
*/
public interface Action<T> {
diff --git a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Future.java b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Future.java
index c50f467..61a0a11 100644
--- a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Future.java
+++ b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Future.java
@@ -1,8 +1,5 @@
package org.onap.sdc.dcae.catalog.commons;
-import org.onap.sdc.dcae.catalog.commons.Future;
-import org.onap.sdc.dcae.catalog.commons.FutureHandler;
-
/**
* Modeled after the vertx future
*/
diff --git a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/FutureHandler.java b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/FutureHandler.java
index b689412..738a6cf 100644
--- a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/FutureHandler.java
+++ b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/FutureHandler.java
@@ -1,7 +1,5 @@
package org.onap.sdc.dcae.catalog.commons;
-import org.onap.sdc.dcae.catalog.commons.Future;
-
/**
* Modeled after the vertx future
*/
diff --git a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Futures.java b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Futures.java
index a405932..1773fdd 100644
--- a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Futures.java
+++ b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Futures.java
@@ -115,10 +115,12 @@ public class Futures<T> {
BasicHandler<T> hnd = buildHandler();
setHandler(hnd);
hnd.waitForCompletion();
- if (failed())
- throw (Exception)cause();
- else
+ if (failed()) {
+ throw (Exception) cause();
+ }
+ else {
return result();
+ }
}
public Future<T> waitForCompletion() throws InterruptedException {
diff --git a/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogController.java b/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogController.java
index 90994f6..b42f8cf 100644
--- a/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogController.java
+++ b/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogController.java
@@ -21,7 +21,6 @@ package org.onap.sdc.dcae.catalog.engine;
import org.json.JSONObject;
import org.onap.sdc.common.onaplog.Enums.LogLevel;
import org.onap.sdc.common.onaplog.OnapLoggerDebug;
-import org.onap.sdc.common.onaplog.OnapLoggerError;
import org.onap.sdc.dcae.catalog.Catalog;
import org.onap.sdc.dcae.catalog.asdc.ASDCCatalog;
import org.onap.sdc.dcae.catalog.commons.Future;
@@ -93,7 +92,6 @@ import java.util.Map;
@CrossOrigin(origins="*")
public class CatalogController {
- private static OnapLoggerError errLogger = OnapLoggerError.getInstance();
private static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance();
@@ -101,7 +99,7 @@ public class CatalogController {
private SystemProperties systemProperties;
private URI defaultCatalog;
- private static Map<URI, Catalog> catalogs = new HashMap<URI, Catalog>();
+ private static Map<URI, Catalog> catalogs = new HashMap<>();
public void setDefaultCatalog(URI theUri) {
@@ -130,8 +128,9 @@ public class CatalogController {
public Catalog getCatalog(URI theCatalogUri) {
//TODO: Thread safety! Check catalog is alive!
- if (theCatalogUri == null)
+ if (theCatalogUri == null) {
theCatalogUri = this.defaultCatalog;
+ }
Catalog cat = catalogs.get(theCatalogUri);
if (cat == null && theCatalogUri != null) {
@@ -194,7 +193,7 @@ public class CatalogController {
//a null result allows the accumulatorHandler to pass the processing onto some other async processing stage
if (response != null) {
if (!this.result.setResult(response)) {
- this.result.setErrorResult(new CatalogError(this.request, "Catalog API call succesful but late"));
+ this.result.setErrorResult(new CatalogError(this.request, "Catalog API call successful but late"));
}
}
}
diff --git a/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogError.java b/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogError.java
index 0c7c418..8518b0d 100644
--- a/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogError.java
+++ b/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogError.java
@@ -1,8 +1,5 @@
package org.onap.sdc.dcae.catalog.engine;
-import org.onap.sdc.dcae.catalog.engine.CatalogRequest;
-import org.onap.sdc.dcae.catalog.engine.CatalogResponse;
-
/**
*/
public class CatalogError extends CatalogResponse {
diff --git a/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogRequest.java b/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogRequest.java
index ad6caca..3fde208 100644
--- a/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogRequest.java
+++ b/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogRequest.java
@@ -2,8 +2,6 @@ package org.onap.sdc.dcae.catalog.engine;
import java.net.URI;
-import org.onap.sdc.dcae.catalog.engine.CatalogMessage;
-
public class CatalogRequest extends CatalogMessage {
private URI catalog;