diff options
author | Stone, Avi (as206k) <as206k@att.com> | 2018-05-23 11:21:11 +0300 |
---|---|---|
committer | Stone, Avi (as206k) <as206k@att.com> | 2018-05-23 11:30:13 +0300 |
commit | 3e4c18770957b55e2f80da32c3a32caa908f1386 (patch) | |
tree | 8a94c656300e75e38febfe9826ad36fc54fe14f5 /dcaedt_catalog/asdc/src | |
parent | da9db1b89e8c9199da4791a2ccd26d1628120a08 (diff) |
Upgrade dt-be-main
Update sources for dcae-dt-be-main to latest version
Change-Id: I3d58a2dc32611c0ca90f1c97e1294a17d5748623
Issue-ID: SDC-1359
Signed-off-by: Stone, Avi (as206k) <as206k@att.com>
Diffstat (limited to 'dcaedt_catalog/asdc/src')
15 files changed, 843 insertions, 1097 deletions
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 66afab1..08383ea 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 @@ -38,13 +38,11 @@ import org.springframework.web.client.HttpClientErrorException; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.util.Base64Utils; -//import org.springframework.util.DigestUtils; 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.beans.factory.annotation.Autowired; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; @@ -57,8 +55,6 @@ 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.onap.sdc.dcae.composition.util.DcaeBeConstants; -import org.onap.sdc.dcae.composition.util.SystemProperties; import org.json.JSONArray; import org.apache.commons.cli.BasicParser; @@ -69,82 +65,68 @@ import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; - @Component("asdc") @Scope("singleton") -//@ConfigurationProperties(prefix="asdc") public class ASDC { - public static enum AssetType { + 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 static enum ArtifactType { -// DCAE_TOSCA, -// DCAE_JSON, -// DCAE_POLICY, -// DCAE_DOC, -// DCAE_EVENT, -// DCAE_INVENTORY_TOSCA, -// DCAE_INVENTORY_JSON, -// DCAE_INVENTORY_POLICY, -// DCAE_INVENTORY_DOC, -// DCAE_INVENTORY_BLUEPRINT, -// DCAE_INVENTORY_EVENT, -// HEAT, -// HEAT_VOL, -// HEAT_NET, -// HEAT_NESTED, -// HEAT_ARTIFACT, -// HEAT_ENV, -// OTHER -// } - -// public static enum ArtifactGroupType { -// DEPLOYMENT, -// INFORMATIONAL -// } - - public static enum LifecycleState { + public enum LifecycleState { Checkin, Checkout, Certify, undocheckout } - -// @Retention(RetentionPolicy.RUNTIME) -// @Target(ElementType.METHOD) -// public @interface Mandatory { -// } protected static OnapLoggerError errLogger = OnapLoggerError.getInstance(); protected static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); - - @Autowired - private SystemProperties systemProperties; - private URI rootUri; - private String rootPath = "/sdc/v1/catalog/"; - private String user, - passwd; - private String instanceId; + 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; + private String instanceId; public void setUri(URI theUri) { - //theUri = URI.create(systemProperties.getProperties().getProperty(SystemProperties.ASDC_CATALOG_URL)); String userInfo = theUri.getUserInfo(); if (userInfo != null) { String[] userInfoParts = userInfo.split(":"); setUser(userInfoParts[0]); - if (userInfoParts.length > 1) + if (userInfoParts.length > 1) { setPassword(userInfoParts[1]); + } } String fragment = theUri.getFragment(); - if (fragment == null) + if (fragment == null) { throw new IllegalArgumentException("The URI must contain a fragment specification, to be used as ASDC instance id"); + } setInstanceId(fragment); try { @@ -179,24 +161,14 @@ public class ASDC { this.instanceId = theId; } - public String getInstanceId() { - return this.instanceId; - } - - public void setRootPath(String thePath) { - this.rootPath = systemProperties.getProperties().getProperty(DcaeBeConstants.Config.ASDC_ROOTPATH); - } - - public String getRootPath() { - return systemProperties.getProperties().getProperty(DcaeBeConstants.Config.ASDC_ROOTPATH); - } - @Scheduled(fixedRateString = "${beans.context.scripts.updateCheckFrequency?:60000}") - public void checkForUpdates() { + public void checkForUpdates() { + // ffu } @PostConstruct public void initASDC() { + // ffu } public <T> Future<T> getResources(Class<T> theType) { @@ -236,7 +208,7 @@ public class ASDC { } public <T> Action<T> getAssetsAction(AssetType theAssetType, Class<T> theType) { - return (() -> fetch(refAssets(theAssetType), theType)); + return () -> fetch(refAssets(theAssetType), theType); } public <T> Future<T> getAssets(AssetType theAssetType, Class<T> theType, @@ -251,7 +223,7 @@ public class ASDC { 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)); + return () -> fetch(refAssets(theAssetType) + filter(theCategory, theSubCategory, theResourceType), theType); } protected String refAssets(AssetType theAssetType) { @@ -306,7 +278,7 @@ public class ASDC { } public <T> Action<T> getAssetAction(AssetType theAssetType, UUID theId, Class<T> theType) { - return (() -> fetch(refAsset(theAssetType, theId) + "/metadata", theType)); + return () -> fetch(refAsset(theAssetType, theId) + "/metadata", theType); } public Future<byte[]> getResourceArchive(UUID theId) { @@ -322,7 +294,7 @@ public class ASDC { } public Action<byte[]> getAssetArchiveAction(AssetType theAssetType, UUID theId) { - return (() -> fetch(refAsset(theAssetType, theId) + "/toscaModel", byte[].class)); + return () -> fetch(refAsset(theAssetType, theId) + "/toscaModel", byte[].class); } public Future<JSONObject> checkinResource(UUID theId, String theUser, String theMessage) { @@ -354,9 +326,7 @@ public class ASDC { 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)); + headers -> prepareHeaders(headers).header(USER_ID, theUser), new JSONObject().putOpt("userRemarks", theMessage)); } protected String refAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theAssetInstance, UUID theArtifactId) { @@ -388,7 +358,7 @@ public class ASDC { } public <T> Action<T> getAssetArtifactAction(AssetType theAssetType, UUID theAssetId, UUID theArtifactId, Class<T> theType) { - return (() -> fetch(refAssetArtifact(theAssetType, theAssetId, theArtifactId), theType)); + return () -> fetch(refAssetArtifact(theAssetType, theAssetId, theArtifactId), theType); } public <T> Future<T> getAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId, Class<T> theType) { @@ -396,7 +366,7 @@ public class ASDC { } public <T> Action<T> getAssetInstanceArtifactAction(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId, Class<T> theType) { - return (() -> fetch(refAssetInstanceArtifact(theAssetType, theAssetId, theInstance, theArtifactId), theType)); + return () -> fetch(refAssetInstanceArtifact(theAssetType, theAssetId, theInstance, theArtifactId), theType); } public ArtifactUploadAction createResourceArtifact(UUID theAssetId) { @@ -518,8 +488,9 @@ public class ASDC { protected void checkMandatoryInfo() { for (String field: mandatoryInfoEntries()) { - if (!info.has(field)) + if (!info.has(field)) { throw new IllegalStateException("No '" + field + "' was provided"); + } } } @@ -529,10 +500,9 @@ public class ASDC { } } - protected static final String[] artifactMandatoryEntries = new String[] {}; /** - * We use teh same API to operate on artifacts attached to assets or to their instances + * 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> { @@ -570,17 +540,12 @@ public class ASDC { refAssetArtifact(this.assetType, this.assetId, theArtifactId) : refAssetInstanceArtifact(this.assetType, this.assetId, normalizeInstanceName(this.assetInstance), theArtifactId); } - } - - protected static final String[] uploadMandatoryEntries = new String[] { "artifactName", - "artifactType", - "artifactGroupType", - "artifactLabel", - "description", - "payloadData" }; + } public class ArtifactUploadAction extends ASDCArtifactAction<ArtifactUploadAction> { - + + public static final String PAYLOAD_DATA = ASDC.PAYLOAD_DATA; + protected ArtifactUploadAction() { super(new JSONObject()); } @@ -590,7 +555,7 @@ public class ASDC { } public ArtifactUploadAction withContent(byte[] theContent) { - return with("payloadData", Base64Utils.encodeToString(theContent)); + return with(PAYLOAD_DATA, Base64Utils.encodeToString(theContent)); } public ArtifactUploadAction withContent(File theFile) throws IOException { @@ -598,11 +563,11 @@ public class ASDC { } public ArtifactUploadAction withLabel(String theLabel) { - return with("artifactLabel", theLabel); + return with(ARTIFACT_LABEL, theLabel); } public ArtifactUploadAction withName(String theName) { - return with("artifactName", theName); + return with(ARTIFACT_NAME, theName); } public ArtifactUploadAction withDisplayName(String theName) { @@ -610,17 +575,18 @@ public class ASDC { } public ArtifactUploadAction withType(ArtifactType theType) { - return with("artifactType", theType.toString()); + return with(ARTIFACT_TYPE, theType.toString()); } public ArtifactUploadAction withGroupType(ArtifactGroupType theGroupType) { - return with("artifactGroupType", theGroupType.toString()); + return with(ARTIFACT_GROUP_TYPE, theGroupType.toString()); } public ArtifactUploadAction withDescription(String theDescription) { - return with("description", theDescription); + return with(DESCRIPTION, theDescription); } - + + @Override protected String[] mandatoryInfoEntries() { return ASDC.this.uploadMandatoryEntries; } @@ -628,18 +594,11 @@ public class ASDC { public Future<JSONObject> execute() { checkMandatory(); return ASDC.this.post(ref(null), - (headers) -> prepareHeaders(headers) - .header("USER_ID", this.operatorId), - this.info); + headers -> prepareHeaders(headers).header(USER_ID, this.operatorId), this.info); } } - protected static final String[] updateMandatoryEntries = new String[] { "artifactName", - "artifactType", - "artifactGroupType", - "artifactLabel", - "description", - "payloadData" }; + /** * In its current form the update relies on a previous artifact retrieval. One cannot build an update from scratch. @@ -657,7 +616,7 @@ public class ASDC { } public ArtifactUpdateAction withContent(byte[] theContent) { - return with("payloadData", Base64Utils.encodeToString(theContent)); + return with(PAYLOAD_DATA, Base64Utils.encodeToString(theContent)); } public ArtifactUpdateAction withContent(File theFile) throws IOException { @@ -665,13 +624,14 @@ public class ASDC { } public ArtifactUpdateAction withDescription(String theDescription) { - return with("description", theDescription); + return with(DESCRIPTION, theDescription); } public ArtifactUpdateAction withName(String theName) { - return with("artifactName", theName); + return with(ARTIFACT_NAME, theName); } - + + @Override protected String[] mandatoryInfoEntries() { return ASDC.this.updateMandatoryEntries; } @@ -690,9 +650,7 @@ public class ASDC { checkMandatory(); cleanupInfoEntries(); return ASDC.this.post(ref(artifactUUID), - (headers) -> prepareHeaders(headers) - .header("USER_ID", this.operatorId), - this.info); + headers -> prepareHeaders(headers).header(USER_ID, this.operatorId),this.info); } } @@ -712,26 +670,25 @@ public class ASDC { public Future<JSONObject> execute() { checkMandatory(); return ASDC.this.delete(ref(this.artifactId), - (headers) -> prepareHeaders(headers) - .header("USER_ID", this.operatorId)); + headers -> prepareHeaders(headers).header(USER_ID, this.operatorId)); } } - public VFCMTCreateAction createVFCMT() { + private VFCMTCreateAction createVFCMT() { return new VFCMTCreateAction(); } - - protected static final String[] vfcmtMandatoryEntries = new String[] { "name", - "vendorName", - "vendorRelease", - "contactId" }; + + 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()); @@ -751,7 +708,7 @@ public class ASDC { } public VFCMTCreateAction withDescription(String theDescription) { - return with("description", theDescription); + return with(DESCRIPTION, theDescription); } public VFCMTCreateAction withVendorName(String theVendorName) { @@ -763,8 +720,9 @@ public class ASDC { } public VFCMTCreateAction withTags(String... theTags) { - for (String tag: theTags) + for (String tag: theTags) { this.info.append("tags", tag); + } return this; } @@ -773,30 +731,29 @@ public class ASDC { } protected String[] mandatoryInfoEntries() { - return ASDC.this.vfcmtMandatoryEntries; + return vfcmtMandatoryEntries; } public VFCMTCreateAction withContact(String theContact) { - return with("contactId", theContact); + return with(CONTACT_ID, theContact); } public Future<JSONObject> execute() { - this.info.putOnce("contactId", this.operatorId); + 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); + 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()) { - if (!theOriginal.has(key)) + if (!theOriginal.has(key)) { theOriginal.put(key, thePatch.get(key)); + } } return theOriginal; } @@ -883,18 +840,7 @@ public class ASDC { - public class ASDCFuture<T> - extends Futures.BasicFuture<T> { - - private boolean http404toEmpty = false; - - ASDCFuture() { - } - - public ASDCFuture setHttp404ToEmpty(boolean doEmpty) { - this.http404toEmpty = doEmpty; - return this; - } + public class ASDCFuture<T> extends Futures.BasicFuture<T> { ListenableFutureCallback<ResponseEntity<T>> callback = new ListenableFutureCallback<ResponseEntity<T>>() { @@ -904,9 +850,6 @@ public class ASDC { public void onFailure(Throwable theError) { if (theError instanceof HttpClientErrorException) { - // if (theError.getRawStatusCode() == 404 && this.http404toEmpty) - // ASDCFuture.this.result(); //th eresult is of type T ... - // else ASDCFuture.this.cause(new ASDCException((HttpClientErrorException)theError)); } else { @@ -918,70 +861,66 @@ public class ASDC { } public class ContentMD5Interceptor implements AsyncClientHttpRequestInterceptor { - - @Override - public ListenableFuture<ClientHttpResponse> intercept( - HttpRequest theRequest, byte[] theBody, AsyncClientHttpRequestExecution theExecution) - throws IOException { - if (HttpMethod.POST == theRequest.getMethod()) { - HttpHeaders headers = theRequest.getHeaders(); - headers.add("Content-MD5", Base64Utils.encodeToString( - //DigestUtils.md5Digest(theBody))); - DigestUtils.md5Hex(theBody).getBytes())); - - } - return theExecution.executeAsync(theRequest, theBody); - } + @Override + public ListenableFuture<ClientHttpResponse> intercept( + HttpRequest theRequest, byte[] theBody, AsyncClientHttpRequestExecution theExecution) + throws IOException { + if (HttpMethod.POST == theRequest.getMethod()) { + HttpHeaders headers = theRequest.getHeaders(); + headers.add("Content-MD5", Base64Utils.encodeToString(DigestUtils.md5Hex(theBody).getBytes())); + } + return theExecution.executeAsync(theRequest, theBody); + } } public static void main(String[] theArgs) throws Exception { CommandLineParser parser = new BasicParser(); - String user_id = "jh0003"; + String userId = "jh0003"; Options options = new Options(); options.addOption(OptionBuilder - .withArgName("target") - .withLongOpt("target") + .withArgName(TARGET) + .withLongOpt(TARGET) .withDescription("target asdc system") .hasArg() .isRequired() .create('t') ); options.addOption(OptionBuilder - .withArgName("action") - .withLongOpt("action") + .withArgName(ACTION) + .withLongOpt(ACTION) .withDescription("one of: list, get, getartifact, checkin, checkout") .hasArg() .isRequired() .create('a') ); options.addOption(OptionBuilder - .withArgName("assetType") - .withLongOpt("assetType") + .withArgName(ASSET_TYPE) + .withLongOpt(ASSET_TYPE) .withDescription("one of resource, service, product") .hasArg() .isRequired() .create('k') ); //k for 'kind' .. options.addOption(OptionBuilder - .withArgName("assetId") - .withLongOpt("assetId") + .withArgName(ASSET_ID) + .withLongOpt(ASSET_ID) .withDescription("asset uuid") .hasArg() .create('u') ); //u for 'uuid' options.addOption(OptionBuilder - .withArgName("artifactId") - .withLongOpt("artifactId") + .withArgName(ARTIFACT_ID) + .withLongOpt(ARTIFACT_ID) .withDescription("artifact uuid") .hasArg() .create('s') ); //s for 'stuff' options.addOption(OptionBuilder - .withArgName("listFilter") - .withLongOpt("listFilter") + .withArgName(LIST_FILTER) + .withLongOpt(LIST_FILTER) .withDescription("filter for list operations") .hasArg() .create('f') ); //u for 'uuid' @@ -997,86 +936,67 @@ public class ASDC { } ASDC asdc = new ASDC(); - asdc.setUri(new URI(line.getOptionValue("target"))); + asdc.setUri(new URI(line.getOptionValue(TARGET))); - String action = line.getOptionValue("action"); - if (action.equals("list")) { + String action = line.getOptionValue(ACTION); + if ("list".equals(action)) { JSONObject filterInfo = new JSONObject( - line.hasOption("listFilter") ? - line.getOptionValue("listFilter") : "{}"); + line.hasOption(LIST_FILTER) ? + line.getOptionValue(LIST_FILTER) : "{}"); JSONArray assets = - asdc.getAssets(ASDC.AssetType.valueOf(line.getOptionValue("assetType")), JSONArray.class, + 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 (action.equals("get")) { + else if ("get".equals(action)) { debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(), - asdc.getAsset(ASDC.AssetType.valueOf(line.getOptionValue("assetType")), - UUID.fromString(line.getOptionValue("assetId")), + asdc.getAsset(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)), + UUID.fromString(line.getOptionValue(ASSET_ID)), JSONObject.class) .waitForResult() .toString(2) ); } - else if (action.equals("getartifact")) { + else if ("getartifact".equals(action)) { debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(), - asdc.getAssetArtifact(ASDC.AssetType.valueOf(line.getOptionValue("assetType")), - UUID.fromString(line.getOptionValue("assetId")), - UUID.fromString(line.getOptionValue("artifactId")), + 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 (action.equals("checkin")) { + else if ("checkin".equals(action)) { debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(), - asdc.cycleAsset(ASDC.AssetType.valueOf(line.getOptionValue("assetType")), - UUID.fromString(line.getOptionValue("assetId")), + asdc.cycleAsset(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)), + UUID.fromString(line.getOptionValue(ASSET_ID)), ASDC.LifecycleState.Checkin, - user_id, + userId, "cli op") .waitForResult() .toString() ); } - else if (action.equals("checkout")) { + else if ("checkout".equals(action)) { debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(), - asdc.cycleAsset(ASDC.AssetType.valueOf(line.getOptionValue("assetType")), - UUID.fromString(line.getOptionValue("assetId")), + asdc.cycleAsset(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)), + UUID.fromString(line.getOptionValue(ASSET_ID)), ASDC.LifecycleState.Checkout, - user_id, + userId, "cli op") .waitForResult() .toString() ); } - else if (action.equals("cleanup")) { + else if ("cleanup".equals(action)) { JSONArray resources = asdc.getResources() .waitForResult(); debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"Got {} resources", resources.length()); - // vfcmt cleanup - for (int i = 0; i < resources.length(); i++) { - - JSONObject resource = resources.getJSONObject(i); - - if (resource.getString("resourceType").equals("VFCMT") && - 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, user_id, null) - .waitForResult(); - } - catch (Exception x) { - debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"** {}", x); - } - } - } - + vfcmtCleanup(userId, asdc, resources); } else { try { @@ -1087,7 +1007,7 @@ public class ASDC { .withVendorName("CloneInc") .withVendorRelease("1.0") .withTags("clone") - .withOperator(user_id) + .withOperator(userId) .execute() .waitForResult() .toString() @@ -1098,4 +1018,25 @@ public class ASDC { } } } + + 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/ASDCUtils.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtils.java index 1d70627..d6a175f 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 @@ -35,414 +35,422 @@ import java.util.zip.ZipInputStream; @ConfigurationProperties(prefix="asdcutils") public class ASDCUtils { - private static OnapLoggerError errLogger = OnapLoggerError.getInstance(); - private static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); - - @Autowired - private ASDC asdc; - - @Autowired - private Blueprinter blueprint; - - public ASDCUtils() { - // Making sonar happy - } - - public ASDCUtils(URI theASDCURI) { - this(theASDCURI, null); - } - - public ASDCUtils(URI theASDCURI, URI theBlueprinterURI) { - this.asdc = new ASDC(); - this.asdc.setUri(theASDCURI); - if (theBlueprinterURI != null) { - this.blueprint = new Blueprinter(); - this.blueprint.setUri(theBlueprinterURI); - } - } - - public ASDCUtils(ASDC theASDC) { - this(theASDC, null); - } - - public ASDCUtils(ASDC theASDC, Blueprinter theBlueprinter) { - this.asdc = theASDC; - 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; - - protected 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("artifactURL"); - 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++) { - JSONObject artifactInfo = theArtifacts.getJSONObject(i); - if (theName.equals(artifactInfo.getString("artifactName"))) { - debugLogger.log(LogLevel.DEBUG, ASDCUtils.class.getName(), "Found artifact info {}", artifactInfo); - return artifactInfo; - } - } - - return null; - } - - private static byte[] extractArtifactData(InputStream theEntryStream) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - byte[] buff = new byte[4096]; - int cnt = 0; - while ((cnt = theEntryStream.read(buff)) != -1) { - baos.write(buff, 0, cnt); - } - } finally { - baos.close(); - } - 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.stream().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("artifactName").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) -> { - Blueprinter.BlueprintAction action = blueprint.generateBlueprint(); - processArtifacts(theArchives, (JSONObject theInfo, byte[] theData) -> new JSONObject().put(theInfo.getString("artifactName").split("\\.")[0], Base64Utils.encodeToString(theData)), - (Stream<JSONObject> theAssetArtifacts) -> theAssetArtifacts.reduce(new JSONObject(), ASDC::merge)).forEach(artifactInfo -> action.withModelInfo(artifactInfo)); - - return action.withTemplateData(Recycler.toString(theTemplate).getBytes()).execute(); - - }); - } - - private static class Tracker implements TargetLocator { - - private static enum Position { - SCHEMA, TEMPLATE, TRANSLATE; - } - - private static final int Positions = Position.values().length; - - private List<Target> tgts = new ArrayList<Target>(3); - - public Tracker() { - clear(); - } - - public boolean addSearchPath(URI theURI) { - return false; - } - - public boolean addSearchPath(String thePath) { - return false; - } - - public Iterable<URI> searchPaths() { - return Collections.emptyList(); - } - - protected 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; - } - - public void track(JSONObject theInfo, final byte[] theData) { - String uri = theInfo.getString("artifactURL").split("/")[5]; - String name = theInfo.getString("artifactName"), 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("artifactURL")); - - 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))); - } - }); - } - } - - public boolean hasSchema() { - return tgts.get(Position.SCHEMA.ordinal()) != null; - } - - public Target schema() { - return tgts.get(Position.SCHEMA.ordinal()); - } - - public boolean hasTemplate() { - return tgts.get(Position.TEMPLATE.ordinal()) != null; - } - - public Target template() { - return tgts.get(Position.TEMPLATE.ordinal()); - } - - public 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) -> { - //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(); - }); - - Target cdump = new Target("cdump", URI.create("asdc:cdump")); - cdump.setTarget(theTemplate); - - validateCatalog(catalog, checker, cdump); - - return catalog; - }); - } - - private void validateCatalog(Catalog catalog, Checker checker, Target cdump) { - try { + private static final String ARTIFACT_URL = "artifactURL"; + private static final String ARTIFACT_NAME = "artifactName"; + private static OnapLoggerError errLogger = OnapLoggerError.getInstance(); + private static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); + + @Autowired + private ASDC asdc; + + @Autowired + private Blueprinter blueprint; + + public ASDCUtils() { + // Making sonar happy + } + + public ASDCUtils(URI theASDCURI) { + this(theASDCURI, null); + } + + public ASDCUtils(URI theASDCURI, URI theBlueprinterURI) { + this.asdc = new ASDC(); + this.asdc.setUri(theASDCURI); + if (theBlueprinterURI != null) { + this.blueprint = new Blueprinter(); + this.blueprint.setUri(theBlueprinterURI); + } + } + + public ASDCUtils(ASDC theASDC) { + this(theASDC, null); + } + + public ASDCUtils(ASDC theASDC, Blueprinter theBlueprinter) { + this.asdc = theASDC; + 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++) { + JSONObject artifactInfo = theArtifacts.getJSONObject(i); + if (theName.equals(artifactInfo.getString(ARTIFACT_NAME))) { + debugLogger.log(LogLevel.DEBUG, ASDCUtils.class.getName(), "Found artifact info {}", artifactInfo); + return artifactInfo; + } + } + + return null; + } + + private static byte[] extractArtifactData(InputStream theEntryStream) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + byte[] buff = new byte[4096]; + int cnt = 0; + while ((cnt = theEntryStream.read(buff)) != -1) { + baos.write(buff, 0, cnt); + } + } finally { + baos.close(); + } + 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) -> { + 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(Recycler.toString(theTemplate).getBytes()).execute(); + + }); + } + + 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) { - - 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 - //the desc contains the full URI and the resource uuid is the 5th path element - List uuids = (List) StreamSupport.stream(Spliterators.spliteratorUnknownSize(jxroot.iterate("topology_template/node_templates/*/description"), 16), false).distinct().filter(desc -> desc != null) - .map(desc -> desc.toString().split("/")[5]).collect(Collectors.toList()); - - //serialized fetch version - final Actions.Sequence sequencer = new Actions.Sequence(); - uuids.stream().forEach(uuid -> { - UUID rid = UUID.fromString((String) uuid); - sequencer.add(this.asdc.getAssetArchiveAction(ASDC.AssetType.resource, rid)); - sequencer.add(this.asdc.getAssetAction(ASDC.AssetType.resource, rid, JSONObject.class)); - }); - - final Object tmpl = template; - return Futures.advance(sequencer.execute(), (List theArchives) -> theProcessor.apply(tmpl, theArchives)); - } - - private static <T> Stream<T> processArtifacts(List theArtifactData, BiFunction<JSONObject, byte[], T> theProcessor, Function<Stream<T>, T> theAggregator) { - - Stream.Builder<T> assetBuilder = Stream.builder(); - - for (int i = 0; i < theArtifactData.size(); i = i + 2) { //cute old style loop - - JSONObject assetInfo = (JSONObject) theArtifactData.get(i + 1); - byte[] assetData = (byte[]) theArtifactData.get(i + 0); - - JSONArray artifacts = assetInfo.optJSONArray("artifacts"); - - Stream.Builder<T> artifactBuilder = Stream.builder(); - - try (ZipInputStream zipper = new ZipInputStream(new ByteArrayInputStream(assetData))){ - //we process the artifacts in the order they are stored in the archive .. fugly - for (ZipEntry zipped = zipper.getNextEntry(); zipped != null; zipped = zipper.getNextEntry()) { - JSONObject artifactInfo = lookupArtifactInfo(artifacts, StringUtils.substringAfterLast(zipped.getName(), "/")); - if (artifactInfo != null) { - artifactBuilder.add(theProcessor.apply(artifactInfo, extractArtifactData(zipper))); - } - zipper.closeEntry(); - } - } catch (IOException iox) { - errLogger.log(LogLevel.ERROR, ASDC.class.getName(), "IOException: {}", iox); - return null; - } - - if (theAggregator != null) { - assetBuilder.add(theAggregator.apply(artifactBuilder.build())); - } else { - artifactBuilder.build().forEach(entry -> assetBuilder.add(entry)); - } - } - - return assetBuilder.build(); - } + } + + /* 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) { + + 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 + //the desc contains the full URI and the resource uuid is the 5th path element + List uuids = (List) StreamSupport.stream(Spliterators.spliteratorUnknownSize(jxroot.iterate("topology_template/node_templates/*/description"), 16), false).distinct().filter(desc -> desc != null) + .map(desc -> desc.toString().split("/")[5]).collect(Collectors.toList()); + + //serialized fetch version + final Actions.Sequence sequencer = new Actions.Sequence(); + uuids.stream().forEach(uuid -> { + UUID rid = UUID.fromString((String) uuid); + sequencer.add(this.asdc.getAssetArchiveAction(ASDC.AssetType.resource, rid)); + sequencer.add(this.asdc.getAssetAction(ASDC.AssetType.resource, rid, JSONObject.class)); + }); + + final Object tmpl = template; + return Futures.advance(sequencer.execute(), (List theArchives) -> theProcessor.apply(tmpl, theArchives)); + } + + private static <T> Stream<T> processArtifacts(List theArtifactData, BiFunction<JSONObject, byte[], T> theProcessor, Function<Stream<T>, T> theAggregator) { + + Stream.Builder<T> assetBuilder = Stream.builder(); + + for (int i = 0; i < theArtifactData.size(); i = i + 2) { //cute old style loop + + JSONObject assetInfo = (JSONObject) theArtifactData.get(i + 1); + byte[] assetData = (byte[]) theArtifactData.get(i + 0); + + JSONArray artifacts = assetInfo.optJSONArray("artifacts"); + + Stream.Builder<T> artifactBuilder = Stream.builder(); + + try (ZipInputStream zipper = new ZipInputStream(new ByteArrayInputStream(assetData))){ + //we process the artifacts in the order they are stored in the archive .. fugly + processZipArtifacts(theProcessor, artifacts, artifactBuilder, zipper); + } catch (IOException iox) { + errLogger.log(LogLevel.ERROR, ASDC.class.getName(), "IOException: {}", iox); + return null; + } + + if (theAggregator != null) { + assetBuilder.add(theAggregator.apply(artifactBuilder.build())); + } else { + artifactBuilder.build().forEach(entry -> assetBuilder.add(entry)); + } + } + + return assetBuilder.build(); + } + + private static <T> void processZipArtifacts(BiFunction<JSONObject, byte[], T> theProcessor, JSONArray artifacts, Stream.Builder<T> artifactBuilder, ZipInputStream zipper) throws IOException { + for (ZipEntry zipped = zipper.getNextEntry(); zipped != null; zipped = zipper.getNextEntry()) { + JSONObject artifactInfo = lookupArtifactInfo(artifacts, StringUtils.substringAfterLast(zipped.getName(), "/")); + if (artifactInfo != null) { + artifactBuilder.add(theProcessor.apply(artifactInfo, extractArtifactData(zipper))); + } + zipper.closeEntry(); + } + } } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtilsController.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtilsController.java index 4432712..377e71b 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtilsController.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtilsController.java @@ -1,70 +1,30 @@ package org.onap.sdc.dcae.catalog.asdc; -import java.io.StringReader; - -import java.util.UUID; -import java.util.Map; -import java.util.List; -import java.util.concurrent.Callable; - -import java.net.URI; -import java.net.URISyntaxException; - -import javax.servlet.http.HttpServletRequest; - -import org.onap.sdc.common.onaplog.OnapLoggerDebug; import org.onap.sdc.common.onaplog.Enums.LogLevel; +import org.onap.sdc.common.onaplog.OnapLoggerDebug; import org.springframework.beans.BeansException; - -import org.springframework.web.bind.annotation.RestController; - -import org.onap.sdc.dcae.catalog.asdc.ASDC; -import org.onap.sdc.dcae.catalog.asdc.ASDCUtils; -import org.onap.sdc.dcae.catalog.asdc.ASDCUtilsController; - -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.http.HttpStatus; -import org.springframework.http.HttpHeaders; -import org.springframework.http.ResponseEntity; - +import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; - -import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.web.bind.annotation.RestController; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; -import org.json.JSONObject; - @RestController @ConfigurationProperties(prefix="asdcUtilsController") public class ASDCUtilsController implements ApplicationContextAware { - private ApplicationContext appCtx; private OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); - - //Constants// - private static String NOT_CERTIFIED_CHECKOUT = "NOT_CERTIFIED_CHECKOUT"; - private static String NOT_CERTIFIED_CHECKIN = "NOT_CERTIFIED_CHECKIN"; - private static String CERTIFICATION_IN_PROGRESS = "CERTIFICATION_IN_PROGRESS"; - private static String CERTIFIED = "CERTIFIED"; - public void setApplicationContext(ApplicationContext theCtx) throws BeansException { - this.appCtx = theCtx; + // no use for app context } @PostConstruct public void initController() { debugLogger.log(LogLevel.DEBUG, this.getClass().getName(),"initASDCUtilsController"); - - //Done debugLogger.log(LogLevel.DEBUG, this.getClass().getName(),"ASDCUtilsController started"); } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Blueprinter.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Blueprinter.java index 3e78d38..4e5349f 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Blueprinter.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Blueprinter.java @@ -10,7 +10,6 @@ import org.onap.sdc.common.onaplog.Enums.LogLevel; import org.onap.sdc.dcae.catalog.commons.Action; import org.onap.sdc.dcae.catalog.commons.Future; import org.onap.sdc.dcae.catalog.commons.Http; -import org.json.JSONArray; import org.springframework.util.Base64Utils; @@ -26,51 +25,41 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @Scope("singleton") @ConfigurationProperties(prefix="blueprinter") public class Blueprinter { + private URI serviceUri; + private OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); + public void setUri(URI theUri) { + this.serviceUri = theUri; + } - private URI serviceUri; - private OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); + public BlueprintAction generateBlueprint() { + return new BlueprintAction(); + } + public class BlueprintAction implements Action<String> { - public Blueprinter() { - } + private JSONObject body = new JSONObject(); - public void setUri(URI theUri) { - this.serviceUri = theUri; - } + protected BlueprintAction() { + } - public BlueprintAction generateBlueprint() { - return new BlueprintAction(); - } + public BlueprintAction withModelInfo(JSONObject theModelInfo) { + body.append("models", theModelInfo); + return this; + } - public class BlueprintAction implements Action<String> { + public BlueprintAction withTemplateData(byte[] theData) { + body.put("template", Base64Utils.encodeToString(theData)); + return this; + } - private JSONObject body = new JSONObject(); + public Future<String> execute() { - - protected BlueprintAction() { - } - - public BlueprintAction withModelData(byte[] theSchema, byte[] theTemplate, byte[] theTranslation) { - return this; - } - - public BlueprintAction withModelInfo(JSONObject theModelInfo) { - body.append("models", theModelInfo); - return this; - } - - public BlueprintAction withTemplateData(byte[] theData) { - body.put("template", Base64Utils.encodeToString(theData)); - return this; - } - - public Future<String> execute() { - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Blueprinter::execute() | PAYLOAD to TOSCA_LAB={}", body.toString()); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - return Http.exchange(serviceUri.toString(), HttpMethod.POST, new HttpEntity<String>(body.toString(), headers), String.class); - } - } + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Blueprinter::execute() | PAYLOAD to TOSCA_LAB={}", body.toString()); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + return Http.exchange(serviceUri.toString(), HttpMethod.POST, new HttpEntity<>(body.toString(), headers), String.class); + } + } } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Cloudify.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Cloudify.java deleted file mode 100644 index 3208bd2..0000000 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Cloudify.java +++ /dev/null @@ -1,249 +0,0 @@ -package org.onap.sdc.dcae.catalog.asdc; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.stream.Stream; - -import org.apache.commons.jxpath.JXPathContext; -import org.apache.commons.jxpath.Pointer; -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.ListBuilder; -import org.onap.sdc.dcae.catalog.commons.MapBuilder; -import org.onap.sdc.dcae.checker.Catalog; -import org.onap.sdc.dcae.checker.Construct; -import org.onap.sdc.dcae.checker.Target; - -import com.google.common.collect.Lists; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.Yaml; - - -public class Cloudify { - - private static OnapLoggerError errLogger = OnapLoggerError.getInstance(); - private static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); - - Catalog catalog; - - public Cloudify(Catalog c) - { - catalog = c; - } - public class ModelTemplate { - public Map<String, Map> template; - public JXPathContext jx; - public String node; - public ModelTemplate(Map<String, Map> t, JXPathContext j, String node_name) - { - template = t; - jx = j; - node = node_name; - } - - public Object getPropValue(JXPathContext jx_src, String name) - { - try{ - Object ret = jx_src.getValue("properties/"+name+"/get_input"); - if (ret==null) - return jx_src.getValue("properties/"+name); - return getDefaultPropValue((String)ret); - } - catch (RuntimeException e) { - - } - try{ - return jx_src.getValue("properties/"+name+""); - } - catch (RuntimeException e) { - return null; - } - } - - public Object getDefaultPropValue(String name) { - try { - return jx.getValue("//"+name+"/default"); - } - catch (RuntimeException e) { - return null; - } - - } - } - - public class ModelTranslate { - public Map<String, Map> template; - public JXPathContext jx; - public String node; - - public ModelTranslate(Map<String, Map> t, JXPathContext j, String node_name) - { - template = t; - jx = j; - node = node_name; - } - - public String getTranslateName() - { - Map<String, Object> node_temp = (Map<String, Object>)jx.getValue("//node_templates"); - Iterator it = node_temp.keySet().iterator(); - if (it.hasNext()) - return node + "_"+ it.next(); - else - return null; - } - - public Map<String, Object> translate(JXPathContext jx_src, Map<String, Map> model_lib, String node_name) - { - for (Iterator prop_iter = jx.iteratePointers("//*[@get_input]"); prop_iter.hasNext();) { - - Pointer p = (Pointer)prop_iter.next(); - JXPathContext prop_path = jx.getRelativeContext(p); - - ModelTemplate src_model =(ModelTemplate) model_lib.get(node_name).get("model"); - - Object temp_o = src_model.getPropValue(jx_src, (String) prop_path.getValue("get_input")); - //prop_path.setValue(".", temp_o); - jx.setValue(p.asPath(), temp_o); - } - -// JXPathContext jx_src = JXPathContext.newContext(src); - for (Iterator req_iter = jx_src.iteratePointers("//*/node"); req_iter.hasNext();) { - Pointer p = (Pointer)req_iter.next(); - String req_node_name = (String)jx_src.getValue(p.asPath()); - - for (Iterator it = model_lib.keySet().iterator(); it.hasNext();) { - String key = (String) it.next(); - if (key.indexOf(req_node_name) <0 ) - continue; - ModelTranslate tt = (ModelTranslate) model_lib.get(key).get("translate"); - if (tt == null) - req_node_name = null; - else - { - req_node_name = tt.getTranslateName(); - } - break; - } - - } - - String tn_name = getTranslateName(); - - if (tn_name == null) - return (Map<String, Object>)jx.getValue("//node_templates"); - else - return (new MapBuilder<String, Object>().put(tn_name, jx.getValue("//node_templates/*")).build()); - } - - } - - public ModelTranslate findTranslateTemplate(String ty, String node) { - for (Target t: catalog.targets()) { - - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "findTranslateTemplate: target {}", t.getName()); - if (t.getName().startsWith("translat") == false) { - continue; - } - - Map<String, Map>temp = (Map<String, Map>)t.getTarget(); - - JXPathContext jxroot = JXPathContext.newContext(temp); - try{ - String sub_type = (String)jxroot.getValue("topology_template/substitution_mappings/node_type"); - if (sub_type != null && sub_type.equals(ty)) { - return new ModelTranslate(temp, jxroot, node); - } - } - catch (RuntimeException e) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "translate template {} does not have substitution mapping section", t.getName()); - } - } - return null; - } - - public ModelTemplate findModelTemplate(String ty, String node) { - for (Target t: catalog.targets()) { - - if (t.getName().startsWith("templat") == false) - continue; - Map<String, Map>temp = (Map<String, Map>)t.getTarget(); - - JXPathContext jxroot = JXPathContext.newContext(temp); - for (Iterator it = jxroot.iterate("topology_template/node_templates/*/type"); it.hasNext();) { - String node_type = (String)it.next(); - if (node_type != null && node_type.equals(ty)) { - return new ModelTemplate(temp, jxroot, node); - } - } - } - return null; - } - - public Map<String, Object> createBlueprint() { - - Map<String, Map> target_temp = null; - for (Target t: catalog.targets()) { - - if (t.getName().equals("cdump")) { - target_temp = catalog.getTargetTemplates(t, Construct.Node); - } - } - - JXPathContext jxroot = JXPathContext.newContext(target_temp); - - Map<String, Object> output_temp = new HashMap<String, Object>(); - Map<String, Map> model_lib = new HashMap<String, Map>(); - - for (Iterator iter = target_temp.keySet().iterator(); iter.hasNext();) - { - String node_key = (String)iter.next(); - //jxroot.getVariables().declareVariable("name", target_temp.get(node_key)); - //String node_type = (String)jxroot.getValue("$name/type"); - String node_type = (String)jxroot.getValue(node_key+"/type"); - - ModelTranslate t_temp = findTranslateTemplate(node_type, node_key); - ModelTemplate t_model = findModelTemplate(node_type, node_key); - - model_lib.put(node_key, new MapBuilder() - .put("model", t_model) - .put("translate", t_temp) - .build()); - } - - for (Iterator iter = model_lib.keySet().iterator(); iter.hasNext();) { - String node_key = (String) iter.next(); - ModelTranslate t = (ModelTranslate) model_lib.get(node_key).get("translate"); - JXPathContext jxnode = jxroot.getRelativeContext(jxroot.getPointer(node_key)); - if (t != null) { - Map<String, Object> t_output =t.translate(jxnode, model_lib, node_key); - if (t_output != null) - output_temp.putAll(t_output); - } - - } - - return new MapBuilder<String, Object>() - .put("tosca_definitions_version", new String("cloudify_dsl_1_3")) - .put("imports", new ListBuilder() - .add(new MapBuilder() - .put("cloudify", - "http://www.getcloudify.org/spec/cloudify/3.4/types.yaml") - .build()) - .build()) - .put("node_templates", output_temp) - .build(); - - } - - public String createBlueprintDocument() { - DumperOptions options = new DumperOptions(); - options.setWidth(1000000); - Yaml yaml = new Yaml(options); - return yaml.dump(createBlueprint()); - } -} diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/ISdcClient.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/ISdcClient.java index 554991a..c389d75 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/ISdcClient.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/ISdcClient.java @@ -1,47 +1,48 @@ package org.onap.sdc.dcae.client; +import com.fasterxml.jackson.core.JsonProcessingException; import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest; -import org.onap.sdc.dcae.composition.restmodels.sdc.*; import org.onap.sdc.dcae.composition.restmodels.ReferenceUUID; -import org.onap.sdc.dcae.enums.AssetType; +import org.onap.sdc.dcae.composition.restmodels.sdc.*; import java.util.List; public interface ISdcClient { - ResourceDetailed getResource(String uuid, String requestId) throws Exception; + ResourceDetailed getResource(String uuid, String requestId); + + ServiceDetailed getService(String uuid, String requestId); - ServiceDetailed getService(String uuid, String requestId) throws Exception; + ServiceDetailed getAssetMetadata(String contextType, String uuid, String requestId); - List<Resource> getResources(String resourceType, String category, String subcategory, String requestId) throws Exception; + List<Resource> getResources(String resourceType, String category, String subcategory, String requestId); - List<Service> getServices(String requestId) throws Exception; + List<Service> getServices(String requestId); - String addExternalMonitoringReference(String userId, CreateVFCMTRequest resource, ReferenceUUID vfiUuid, String requestId); + String addExternalMonitoringReference(String userId, String contextType, String serviceUuid, String vfiName, ReferenceUUID vfcmtUuid, String requestId); - void deleteExternalMonitoringReference(String userId, String context, String uuid, String vfiName, String vfcmtUuid, String requestId); + String addExternalMonitoringReference(String userId, CreateVFCMTRequest resource, ReferenceUUID vfcmtUuid, String requestId); - ResourceDetailed createResource(String userId, CreateVFCMTRequest resource, String requestId) throws Exception; + void deleteExternalMonitoringReference(String userId, String contextType, String uuid, String vfiName, String vfcmtUuid, String requestId); - ResourceDetailed changeResourceLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, String requestId) throws Exception; + ResourceDetailed createResource(String userId, CreateVFCMTRequest resource, String requestId); - ServiceDetailed changeServiceLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, String requestId) throws Exception; + ResourceDetailed changeResourceLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, String requestId); - Asset changeAssetLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, AssetType assetType, String requestId) throws Exception; + String getResourceArtifact(String resourceUuid, String artifactUuid, String requestId); - String getResourceArtifact(String resourceUuid, String artifactUuid, String requestId) throws Exception; + Artifact createResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws JsonProcessingException; - Artifact createResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws Exception; + Artifact updateResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws JsonProcessingException; - Artifact updateResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws Exception; + void deleteResourceArtifact(String userId, String resourceUuid, String artifactId, String requestId); - void deleteResourceArtifact(String userId, String resourceUuid, String artifactId, String requestId) throws Exception; + Artifact createInstanceArtifact(String userId, String contextType, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws JsonProcessingException; - Artifact createVfInstanceArtifact(String userId, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws Exception; + Artifact updateInstanceArtifact(String userId, String contextType, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws JsonProcessingException; - Artifact updateVfInstanceArtifact(String userId, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws Exception; + ExternalReferencesMap getMonitoringReferences(String contextType, String uuid, String version, String requestId); - ExternalReferencesMap getMonitoringReferences(String context, String uuid, String version, String requestId); + void deleteInstanceArtifact(String userId, String contextType, String serviceUuid, String normalizedVfiName, String artifactUuid, String requestId); - void deleteInstanceResourceArtifact(String userId, String context, String serviceUuid, String normalizedVfiName, String artifactUuid, String requestId); } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/SdcRestClient.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/SdcRestClient.java index 058d9c7..b07126e 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/SdcRestClient.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/SdcRestClient.java @@ -1,9 +1,12 @@ package org.onap.sdc.dcae.client; +import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicHeader; +import org.onap.sdc.common.onaplog.Enums.LogLevel; +import org.onap.sdc.common.onaplog.OnapLoggerDebug; import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest; import org.onap.sdc.dcae.composition.restmodels.ReferenceUUID; import org.onap.sdc.dcae.composition.restmodels.sdc.*; @@ -14,18 +17,22 @@ import org.onap.sdc.dcae.enums.SdcConsumerInfo; import org.onap.sdc.dcae.utils.Normalizers; import org.onap.sdc.dcae.utils.SDCResponseErrorHandler; import org.onap.sdc.dcae.utils.SdcRestClientUtils; -import org.onap.sdc.common.onaplog.OnapLoggerDebug; -import org.onap.sdc.common.onaplog.Enums.LogLevel; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.*; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Component; import org.springframework.util.Base64Utils; -import org.springframework.web.client.*; +import org.springframework.web.client.RestTemplate; import javax.annotation.PostConstruct; import java.net.URI; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -39,8 +46,6 @@ public class SdcRestClient implements ISdcClient { private static final String ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID"; private static final String ECOMP_REQUEST_ID_HEADER = "X-ECOMP-RequestID"; private static final String USER_ID_HEADER = "USER_ID"; - private static final String RESOURCES_PATH = "resources"; - private static final String SERVICES_PATH = "services"; private static final String ARTIFACTS_PATH = "artifacts"; private static final String CONTENT_MD5_HEADER = "Content-MD5"; private static final String RESOURCE_INSTANCES_PATH = "resourceInstances"; @@ -76,117 +81,110 @@ public class SdcRestClient implements ISdcClient { return headers; } + public ServiceDetailed getAssetMetadata(String contextType, String uuid, String requestId) { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), uuid, METADATA_PATH); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get asset metadata from SDC. URL={}", url); + return getObject(url, requestId, ServiceDetailed.class); + } + public ResourceDetailed getResource(String uuid, String requestId) { - String url = buildRequestPath(RESOURCES_PATH, uuid, METADATA_PATH); + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), uuid, METADATA_PATH); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get resource from SDC. URL={}", url); return getObject(url, requestId, ResourceDetailed.class); } public ServiceDetailed getService(String uuid, String requestId) { - String url = buildRequestPath(SERVICES_PATH, uuid, METADATA_PATH); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get service from SDC. URL={}", url); - return getObject(url, requestId, ServiceDetailed.class); + return getAssetMetadata(AssetType.SERVICE.name(), uuid, requestId); } public List<Resource> getResources(String resourceType, String category, String subcategory, String requestId) { - String url = buildRequestPath(RESOURCES_PATH, SdcRestClientUtils.buildResourceFilterQuery(resourceType, category, subcategory)); + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), SdcRestClientUtils.buildResourceFilterQuery(resourceType, category, subcategory)); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get resources from SDC. URL={}", url); return Arrays.asList(getObject(url, requestId, Resource[].class)); } public List<Service> getServices(String requestId) { - String url = buildRequestPath(SERVICES_PATH); + String url = buildRequestPath(AssetType.SERVICE.getSdcContextPath()); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get services from SDC. URL={}", url); return Arrays.asList(getObject(url, requestId, Service[].class)); } - public String addExternalMonitoringReference(String userId, CreateVFCMTRequest resource, ReferenceUUID vfcmtUuid, String requestId) { - String url = buildRequestPath(resource.getContextType(), resource.getServiceUuid(), RESOURCE_INSTANCES_PATH, - Normalizers.normalizeComponentInstanceName(resource.getVfiName()), MONITORING_REFERENCES_PATH); - - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Connecting service id {} name {} to vfcmt {} URL={}", - resource.getServiceUuid(), resource.getVfiName(), vfcmtUuid.getReferenceUUID(), url); + public String addExternalMonitoringReference(String userId, String contextType, String serviceUuid, String vfiName, ReferenceUUID vfcmtUuid, String requestId) { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), serviceUuid, RESOURCE_INSTANCES_PATH, Normalizers.normalizeComponentInstanceName(vfiName), MONITORING_REFERENCES_PATH); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Creating external monitoring reference from service id {} vfi name {} to vfcmt {} URL={}", serviceUuid, vfiName, vfcmtUuid.getReferenceUUID(), url); + return client.postForObject(url, new HttpEntity<>(vfcmtUuid, postResourceHeaders(userId, requestId)), String.class); + } - return client.postForObject(url, new HttpEntity<>(vfcmtUuid, postResourceHeaders(userId, requestId)), - String.class); + public String addExternalMonitoringReference(String userId, CreateVFCMTRequest resource, ReferenceUUID vfcmtUuid, String requestId) { + return addExternalMonitoringReference(userId, resource.getContextType(), resource.getServiceUuid(), resource.getVfiName(), vfcmtUuid, requestId); } - public void deleteExternalMonitoringReference(String userId, String context, String uuid, String normalizeVfiName, String vfcmtUuid, String requestId) { - String url = buildRequestPath(context, uuid, RESOURCE_INSTANCES_PATH, - normalizeVfiName, MONITORING_REFERENCES_PATH, vfcmtUuid); + public void deleteExternalMonitoringReference(String userId, String contextType, String serviceUuid, String normalizeVfiName, String vfcmtUuid, String requestId) { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), serviceUuid, RESOURCE_INSTANCES_PATH, normalizeVfiName, MONITORING_REFERENCES_PATH, vfcmtUuid); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Delete external monitoring reference from SDC asset. URL={}", url); client.exchange(url, HttpMethod.DELETE, new HttpEntity(postResourceHeaders(userId, requestId)), String.class); } public ResourceDetailed createResource(String userId, CreateVFCMTRequest resource, String requestId) { - String url = buildRequestPath(RESOURCES_PATH); + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath()); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Create SDC resource with name {} URL={}", resource.getName(), url); return client.postForObject(url, new HttpEntity<>(resource, postResourceHeaders(userId, requestId)), ResourceDetailed.class); } public ResourceDetailed changeResourceLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, String requestId) { - String url = buildRequestPath(RESOURCES_PATH, uuid, LIFECYCLE_STATE_PATH); + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), uuid, LIFECYCLE_STATE_PATH); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Change SDC resource lifecycle state ({}). URL={}", lifecycleOperation, url); return client.postForObject(url, new HttpEntity<>(SdcRestClientUtils.buildUserRemarksObject(userRemarks), postResourceHeaders(userId, requestId)), ResourceDetailed.class, lifecycleOperation); } - public ServiceDetailed changeServiceLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, String requestId) { - String url = buildRequestPath(SERVICES_PATH, uuid, LIFECYCLE_STATE_PATH); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Change SDC service lifecycle state ({}). URL={}", lifecycleOperation, url); - return client.postForObject(url, new HttpEntity<>(SdcRestClientUtils.buildUserRemarksObject(userRemarks), postResourceHeaders(userId, requestId)), ServiceDetailed.class, lifecycleOperation); - } - - public Asset changeAssetLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, AssetType assetType, String requestId) { - return AssetType.RESOURCE == assetType ? changeResourceLifecycleState(userId, uuid, lifecycleOperation, userRemarks, requestId) : changeServiceLifecycleState(userId, uuid, lifecycleOperation, userRemarks, requestId); - } - public String getResourceArtifact(String resourceUuid, String artifactUuid, String requestId) { - String url = buildRequestPath(RESOURCES_PATH, resourceUuid, ARTIFACTS_PATH, artifactUuid); + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), resourceUuid, ARTIFACTS_PATH, artifactUuid); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get resource artifact from SDC. URL={}", url); return getObject(url, requestId, String.class); } - public Artifact createResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws Exception { - String url = buildRequestPath(RESOURCES_PATH, resourceUuid, ARTIFACTS_PATH); + public Artifact createResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws JsonProcessingException { + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), resourceUuid, ARTIFACTS_PATH); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Create SDC resource artifact. URL={}", url); String artifactData = SdcRestClientUtils.artifactToString(artifact); return client.postForObject(url, new HttpEntity<>(artifactData, postArtifactHeaders(userId, artifactData, requestId)), Artifact.class); } - public Artifact updateResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws Exception { - String url = buildRequestPath(RESOURCES_PATH, resourceUuid, ARTIFACTS_PATH, artifact.getArtifactUUID()); + public Artifact updateResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws JsonProcessingException { + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), resourceUuid, ARTIFACTS_PATH, artifact.getArtifactUUID()); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Update SDC resource artifact. URL={}", url); String artifactData = SdcRestClientUtils.artifactToString(artifact); return client.postForObject(url, new HttpEntity<>(artifactData, postArtifactHeaders(userId, artifactData, requestId)), Artifact.class); } public void deleteResourceArtifact(String userId, String resourceUuid, String artifactId, String requestId) { - String url = buildRequestPath(RESOURCES_PATH, resourceUuid, ARTIFACTS_PATH, artifactId); + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), resourceUuid, ARTIFACTS_PATH, artifactId); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Delete SDC resource artifact. URL={}", url); client.exchange(url, HttpMethod.DELETE, new HttpEntity(postResourceHeaders(userId, requestId)), Artifact.class); } - public Artifact createVfInstanceArtifact(String userId, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws Exception { - String url = buildRequestPath(SERVICES_PATH, serviceUuid, RESOURCE_INSTANCES_PATH, normalizedInstanceName, ARTIFACTS_PATH); + public Artifact createInstanceArtifact(String userId, String contextType, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws JsonProcessingException { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), serviceUuid, RESOURCE_INSTANCES_PATH, normalizedInstanceName, ARTIFACTS_PATH); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Create SDC resource instance artifact. URL={}", url); String artifactData = SdcRestClientUtils.artifactToString(artifact); return client.postForObject(url, new HttpEntity<>(artifactData, postArtifactHeaders(userId, artifactData, requestId)), Artifact.class); } - public Artifact updateVfInstanceArtifact(String userId, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws Exception { - String url = buildRequestPath(SERVICES_PATH, serviceUuid, RESOURCE_INSTANCES_PATH, normalizedInstanceName, ARTIFACTS_PATH, artifact.getArtifactUUID()); + public Artifact updateInstanceArtifact(String userId, String contextType, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws JsonProcessingException { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), serviceUuid, RESOURCE_INSTANCES_PATH, normalizedInstanceName, ARTIFACTS_PATH, artifact.getArtifactUUID()); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Update SDC resource instance artifact. URL={}", url); String artifactData = SdcRestClientUtils.artifactToString(artifact); return client.postForObject(url, new HttpEntity<>(artifactData, postArtifactHeaders(userId, artifactData, requestId)), Artifact.class); } - public ExternalReferencesMap getMonitoringReferences(String context, String uuid, String version, String requestId) { - String url = buildRequestPath(context, uuid, VERSION_PATH, version, MONITORING_REFERENCES_PATH); + public ExternalReferencesMap getMonitoringReferences(String contextType, String uuid, String version, String requestId) { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), uuid, VERSION_PATH, version, MONITORING_REFERENCES_PATH); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get SDC service monitoring references. URL={}", url); return getObject(url, requestId, ExternalReferencesMap.class); } - public void deleteInstanceResourceArtifact(String userId, String context, String serviceUuid, String normalizedVfiName, String artifactUuid, String requestId) { - String url = buildRequestPath(context, serviceUuid, RESOURCE_INSTANCES_PATH, normalizedVfiName, ARTIFACTS_PATH, artifactUuid); + public void deleteInstanceArtifact(String userId, String contextType, String serviceUuid, String normalizedVfiName, String artifactUuid, String requestId) { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), serviceUuid, RESOURCE_INSTANCES_PATH, normalizedVfiName, ARTIFACTS_PATH, artifactUuid); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Delete SDC instance resource artifact. URL={}", url); client.exchange(url, HttpMethod.DELETE, new HttpEntity(postResourceHeaders(userId, requestId)), Artifact.class); } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/enums/AssetType.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/enums/AssetType.java index 576643f..647349f 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/enums/AssetType.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/enums/AssetType.java @@ -1,5 +1,32 @@ package org.onap.sdc.dcae.enums; public enum AssetType { - RESOURCE, SERVICE + + RESOURCE(SdcContextPath.RESOURCES), + SERVICE(SdcContextPath.SERVICES), + VFCMT(SdcContextPath.RESOURCES), + VF(SdcContextPath.RESOURCES); + + private String sdcContextPath; + + AssetType(SdcContextPath sdcContextPath) { + this.sdcContextPath = sdcContextPath.name().toLowerCase(); + } + + public String getSdcContextPath() { + return sdcContextPath; + } + + // passing an invalid type will result in an IllegalArgumentException, which is fine as the 'type' value is an SDC enum value passed from SDC pluggable UI + public static AssetType getAssetTypeByName(String type) { + return AssetType.valueOf(type.toUpperCase()); + } + + public static String getSdcContextPath(String type) { + return getAssetTypeByName(type).getSdcContextPath(); + } + + private enum SdcContextPath { + RESOURCES, SERVICES + } } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/BaseException.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/BaseException.java index b559634..17c25b2 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/BaseException.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/BaseException.java @@ -7,55 +7,53 @@ import org.springframework.web.client.HttpClientErrorException; public class BaseException extends HttpClientErrorException { - private static Gson gson = new Gson(); - - protected RequestError requestError; - - public RequestError getRequestError() { - return requestError; - } - - public void setRequestError(RequestError requestError) { - this.requestError = requestError; - } - - public BaseException(HttpClientErrorException theError) { - super(theError.getStatusCode()); - String body = theError.getResponseBodyAsString(); - if (body != null) { - requestError = extractRequestError(body); - } - } - - public BaseException(HttpStatus status, RequestError re){ - super(status); - requestError = re; - } - - private RequestError extractRequestError(String error) { - ResponseFormat responseFormat = gson.fromJson(error, ResponseFormat.class); - return responseFormat.getRequestError(); - } - - @JsonIgnore - public String getMessageId() { - return requestError.getMessageId(); - } - - @JsonIgnore - public String[] getVariables() { - return requestError.getVariables(); - } - - @JsonIgnore - public String getText(){ - return requestError.getText(); - } - - @Override - @JsonIgnore - public String getMessage() { - return requestError.getFormattedMessage(); - } + private static final Gson gson = new Gson(); + + protected final transient RequestError requestError; + + public BaseException(HttpClientErrorException theError) { + super(theError.getStatusCode()); + String body = theError.getResponseBodyAsString(); + if (body != null) { + requestError = extractRequestError(body); + } else { + requestError = null; + } + } + + public BaseException(HttpStatus status, RequestError re){ + super(status); + requestError = re; + } + + public RequestError getRequestError() { + return requestError; + } + + private RequestError extractRequestError(String error) { + ResponseFormat responseFormat = gson.fromJson(error, ResponseFormat.class); + return responseFormat.getRequestError(); + } + + @JsonIgnore + public String getMessageId() { + return requestError.getMessageId(); + } + + @JsonIgnore + public String[] getVariables() { + return requestError.getVariables(); + } + + @JsonIgnore + public String getText(){ + return requestError.getText(); + } + + @Override + @JsonIgnore + public String getMessage() { + return requestError.getFormattedMessage(); + } }
\ No newline at end of file diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/OkResponseInfo.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/OkResponseInfo.java index 53bdf3e..f2a7f9a 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/OkResponseInfo.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/OkResponseInfo.java @@ -2,7 +2,7 @@ package org.onap.sdc.dcae.errormng; public class OkResponseInfo extends AbstractSdncException { - public OkResponseInfo(String messageId, String text, String[] variables) { + OkResponseInfo(String messageId, String text, String[] variables) { super(messageId, text, variables); } } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/PolicyException.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/PolicyException.java index 3fc2d71..8a4aec9 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/PolicyException.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/PolicyException.java @@ -5,7 +5,4 @@ public class PolicyException extends AbstractSdncException { public PolicyException(String messageId, String text, String[] variables) { super(messageId, text, variables); } - - public PolicyException() { - } } 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 00fe3f2..7207916 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,25 +9,16 @@ 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; } - public OkResponseInfo getOkResponseInfo() { - return okResponseInfo; - } - public void setPolicyException(PolicyException policyException) { this.policyException = policyException; } - void setServiceException(ServiceException serviceException) { + public void setServiceException(ServiceException serviceException) { this.serviceException = serviceException; } @@ -35,12 +26,8 @@ public class RequestError { this.okResponseInfo = okResponseInfo; } - public List<ServiceException> getServiceExceptions() { - return serviceExceptions; - } - void setServiceExceptions(List<ServiceException> serviceExceptions) { - this.serviceExceptions = serviceExceptions; + // no one asks for these exception ever } String getFormattedMessage() { @@ -60,6 +47,11 @@ public class RequestError { } AbstractSdncException getError() { - return null != serviceException ? serviceException : null != policyException ? policyException : okResponseInfo; + if (null != policyException) { + return (null != serviceException) ? serviceException : policyException; + } + else { + return (null != serviceException) ? serviceException : okResponseInfo; + } } }
\ No newline at end of file diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/ServiceException.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/ServiceException.java index 163a07f..68e646c 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/ServiceException.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/ServiceException.java @@ -1,12 +1,7 @@ package org.onap.sdc.dcae.errormng; public class ServiceException extends AbstractSdncException { - public ServiceException(String messageId, String text, String[] variables) { super(messageId, text, variables); } - - public ServiceException() { - } - }
\ No newline at end of file diff --git a/dcaedt_catalog/asdc/src/test/org/onap/sdc/dcae/utils/NormalizersTest.java b/dcaedt_catalog/asdc/src/test/java/org/onap/sdc/dcae/utils/NormalizersTest.java index bf06e22..5a9b5f5 100644 --- a/dcaedt_catalog/asdc/src/test/org/onap/sdc/dcae/utils/NormalizersTest.java +++ b/dcaedt_catalog/asdc/src/test/java/org/onap/sdc/dcae/utils/NormalizersTest.java @@ -1,11 +1,7 @@ package org.onap.sdc.dcae.utils; -import static org.assertj.core.api.Assertions.*; - import org.assertj.core.api.Assertions; import org.junit.Test; -import org.onap.sdc.dcae.utils.Normalizers; - public class NormalizersTest { diff --git a/dcaedt_catalog/asdc/src/test/java/org/onap/sdc/dcae/utils/SDCResponseErrorHandlerTest.java b/dcaedt_catalog/asdc/src/test/java/org/onap/sdc/dcae/utils/SDCResponseErrorHandlerTest.java new file mode 100644 index 0000000..f17e18f --- /dev/null +++ b/dcaedt_catalog/asdc/src/test/java/org/onap/sdc/dcae/utils/SDCResponseErrorHandlerTest.java @@ -0,0 +1,93 @@ +package org.onap.sdc.dcae.utils; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; + +import java.io.IOException; +import java.io.InputStream; + +@RunWith(MockitoJUnitRunner.class) +public class SDCResponseErrorHandlerTest { + @InjectMocks + private SDCResponseErrorHandler classUnderTest; + private ClientHttpResponse clientHttpResponse; + private HttpStatus httpStatus; + + @Before + public void setup() { + clientHttpResponse = new ClientHttpResponse() { + @Override + public HttpStatus getStatusCode() throws IOException { + return httpStatus; + } + + @Override + public int getRawStatusCode() throws IOException { + return 0; + } + + @Override + public String getStatusText() throws IOException { + return null; + } + + @Override + public void close() { + + } + + @Override + public InputStream getBody() throws IOException { + return null; + } + + @Override + public HttpHeaders getHeaders() { + return new HttpHeaders(); + } + }; + } + + @Test(expected = HttpClientErrorException.class) + public void handleError_haveError_throwsClientException() throws IOException { + httpStatus = HttpStatus.EXPECTATION_FAILED; + classUnderTest.handleError(clientHttpResponse); + } + + @Test(expected = HttpServerErrorException.class) + public void handleError_haveError_throwsServerException() throws IOException { + httpStatus = HttpStatus.BAD_GATEWAY; + classUnderTest.handleError(clientHttpResponse); + } + + @Test + public void hasError_haveClientError_returnTrue() throws IOException { + httpStatus = HttpStatus.EXPECTATION_FAILED; + boolean result = classUnderTest.hasError(clientHttpResponse); + Assert.assertTrue(result); + } + + @Test + public void hasError_haveServerError_returnTrue() throws IOException { + httpStatus = HttpStatus.BAD_GATEWAY; + boolean result = classUnderTest.hasError(clientHttpResponse); + Assert.assertTrue(result); + } + + @Test + public void hasError_200OK_returnFalse() throws IOException { + httpStatus = HttpStatus.OK; + boolean result = classUnderTest.hasError(clientHttpResponse); + Assert.assertFalse(result); + } + +}
\ No newline at end of file |