diff options
Diffstat (limited to 'vid-app-common/src/main/java/org/openecomp')
95 files changed, 6910 insertions, 1427 deletions
diff --git a/vid-app-common/src/main/java/org/openecomp/aai/util/AAIRestInterface.java b/vid-app-common/src/main/java/org/openecomp/aai/util/AAIRestInterface.java index 243410050..d9bb5c1f4 100755 --- a/vid-app-common/src/main/java/org/openecomp/aai/util/AAIRestInterface.java +++ b/vid-app-common/src/main/java/org/openecomp/aai/util/AAIRestInterface.java @@ -253,6 +253,54 @@ public class AAIRestInterface { return false;
}
+
+ /**
+ * Rest put.
+ *
+ * @param fromAppId the from app id
+ * @param transId the trans id
+ * @param path the path
+ * @param payload the payload
+ * @param xml the xml
+ * @return the string
+ */
+ public Response RestPut(String fromAppId, String transId, String path, String payload, boolean xml) {
+ String methodName = "RestPost";
+ String url="";
+ transId = UUID.randomUUID().toString();
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
+
+ try {
+
+ String responseType = "application/json";
+ if (xml)
+ responseType = "application/xml";
+
+ initRestClient();
+
+ url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + path;
+
+ final Response cres = client.target(url)
+ .request()
+ .accept(responseType)
+ .header("X-TransactionId", transId)
+ .header("X-FromAppId", fromAppId)
+ .put(Entity.entity(payload, MediaType.APPLICATION_JSON));
+
+ if (cres.getStatus() == 200 && cres.getStatus() <= 299) {
+ logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!");
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!");
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName +" with status="+cres.getStatus()+", url="+url);
+ }
+ return cres;
+ } catch (Exception e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString());
+ }
+ return null;
+ }
+
+
/**
* Rest post.
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/RelatedTo.java b/vid-app-common/src/main/java/org/openecomp/vid/RelatedTo.java new file mode 100644 index 000000000..48ca49705 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/RelatedTo.java @@ -0,0 +1,36 @@ +package org.openecomp.vid; + +import com.fasterxml.jackson.annotation.*; +import org.codehaus.jackson.annotate.JsonProperty; + +import java.util.HashMap; +import java.util.Map; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "id", + "node-type", + "url" +}) +public class RelatedTo { + + @JsonProperty("id") + public String id; + @JsonProperty("node-type") + public String nodeType; + @JsonProperty("url") + public String url; + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/aai/AaiClient.java b/vid-app-common/src/main/java/org/openecomp/vid/aai/AaiClient.java index af1f4042a..0f07f2066 100644 --- a/vid-app-common/src/main/java/org/openecomp/vid/aai/AaiClient.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/aai/AaiClient.java @@ -7,9 +7,8 @@ import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.openecomp.aai.util.AAIRestInterface; -import org.apache.tiles.request.ApplicationContext; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.openecomp.vid.aai.model.ServiceRelationships; import org.openecomp.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone; import org.openecomp.vid.aai.model.AaiGetTenatns.GetTenantsResponse; import org.openecomp.vid.model.SubscriberList; @@ -25,6 +24,7 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; +import java.util.List; import java.util.UUID; @@ -33,252 +33,320 @@ import java.util.UUID; */ public class AaiClient implements AaiClientInterface { - /** - * The Constant dateFormat. - */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - protected String fromAppId = "VidAaiController"; - @Autowired - ServletContext servletContext; - /** - * The logger - */ - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class); - - - public AaiClient() { - // certiPath = getCertificatesFile().getAbsolutePath(); - // depth = "0"; - } - - public AaiClient(ServletContext context) { - servletContext = context; - } - - - - private static String checkForNull(String local) { - if (local != null) - return local; - else - return ""; - - } - + /** + * The Constant dateFormat. + */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + protected String fromAppId = "VidAaiController"; + @Autowired + ServletContext servletContext; + /** + * The logger + */ + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class); + + + public AaiClient() { + // certiPath = getCertificatesFile().getAbsolutePath(); + // depth = "0"; + } + + public AaiClient(ServletContext context) { + servletContext = context; + } + + + private static String checkForNull(String local) { + if (local != null) + return local; + else + return ""; + + } + + @Override + public AaiResponse<SubscriberList> getAllSubscribers() { + String certiPath = getCertificatesFile().getAbsolutePath(); + String depth = "0"; + Response resp = doAaiGet(certiPath, "business/customers?subscriber-type=INFRA&depth=" + depth, false); + return proccessAaiResponse(resp, SubscriberList.class, null); + } + + + @Override + public AaiResponse getAllAicZones() { + String certiPath = getCertificatesFile().getAbsolutePath(); + Response resp = doAaiGet(certiPath, "network/zones", false); + AaiResponse aaiAicZones = proccessAaiResponse(resp, AicZones.class, null); + return aaiAicZones; + } + + @Override - public AaiResponse<SubscriberList> getAllSubscribers() { + public AaiResponse<String> getAicZoneForPnf(String globalCustomerId , String serviceType , String serviceId) { String certiPath = getCertificatesFile().getAbsolutePath(); - String depth = "0"; - Response resp = doAaiGet(certiPath, "business/customers?subscriber-type=INFRA&depth=" + depth, false); - UserUtils userUtils = new UserUtils(); - return proccessAaiResponse(resp, SubscriberList.class,null); - } - - - @Override - public AaiResponse getAllAicZones() { - String certiPath = getCertificatesFile().getAbsolutePath(); - Response resp = doAaiGet(certiPath, "network/zones" , false); - AaiResponse aaiAicZones = proccessAaiResponse(resp, AicZones.class,null); - return aaiAicZones; - } - - @Override - public AaiResponse getSubscriberData(String subscriberId) { - - File certiPath = getCertificatesFile(); - String depth = "2"; - AaiResponse subscriberDataResponse; - Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId + "?depth=" + depth, false); - subscriberDataResponse = proccessAaiResponse(resp, Services.class,null); - return subscriberDataResponse; - } - - @Override - public AaiResponse getServices() { - File certiPath = getCertificatesFile(); - Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/services", false); - AaiResponse<GetServicesAAIRespone> getServicesResponse = proccessAaiResponse(resp, GetServicesAAIRespone.class,null); - - return getServicesResponse; + String aicZonePath = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId; + Response resp = doAaiGet(certiPath , aicZonePath , false); + AaiResponse<ServiceRelationships> aaiResponse = proccessAaiResponse(resp , ServiceRelationships.class , null); + ServiceRelationships serviceRelationships = (ServiceRelationships)aaiResponse.getT(); + String aicZone = serviceRelationships.getRelationshipList().getRelationship().get(0).getRelatedToPropertyList().get(0).getPropertyValue(); + AaiResponse<String> aaiAicZonaForPnfResponse = new AaiResponse(aicZone , null ,HttpStatus.SC_OK); + return aaiAicZonaForPnfResponse; } + + + @Override + public AaiResponse getVNFData() { + String certiPath = getCertificatesFile().getAbsolutePath(); + String payload = "{\"start\": [\"/business/customers/customer/e433710f-9217-458d-a79d-1c7aff376d89/service-subscriptions/service-subscription/VIRTUAL%20USP/service-instances/service-instance/3f93c7cb-2fd0-4557-9514-e189b7b04f9d\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}"; + Response resp = doAaiPut(certiPath, "query?format=simple", payload, false); + return proccessAaiResponse(resp, AaiGetVnfResponse.class, null); + + } + + @Override + public Response getVNFData(String globalSubscriberId, String serviceType) { + String certiPath = getCertificatesFile().getAbsolutePath(); + String payload = "{\"start\": [\"business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/"+ serviceType +"/service-instances\"]," + + "\"query\": \"query/vnf-topology-fromServiceInstance\"}"; + return doAaiPut(certiPath, "query?format=simple", payload, false); + + } + + @Override + public AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId) { + String certiPath = getCertificatesFile().getAbsolutePath(); + String payload = "{\"start\": [\"/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceInstanceId + "\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}"; + Response resp = doAaiPut(certiPath, "query?format=simple", payload, false); + return proccessAaiResponse(resp, AaiGetVnfResponse.class, null); + } + + @Override + public Response getVersionByInvariantId(List<String> modelInvariantId) { + File certiPath = getCertificatesFile(); + StringBuilder sb = new StringBuilder(); + for (String id : modelInvariantId){ + sb.append("&model-invariant-id="); + sb.append(id); + + } + Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/models?depth=2"+ sb.toString(), false); + return resp; + } + + @Override + public AaiResponse getSubscriberData(String subscriberId) { + File certiPath = getCertificatesFile(); + String depth = "2"; + AaiResponse subscriberDataResponse; + Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId + "?depth=" + depth, false); + subscriberDataResponse = proccessAaiResponse(resp, Services.class, null); + return subscriberDataResponse; + } + + @Override + public AaiResponse getServices() { + File certiPath = getCertificatesFile(); + Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/services", false); + AaiResponse<GetServicesAAIRespone> getServicesResponse = proccessAaiResponse(resp, GetServicesAAIRespone.class, null); + + return getServicesResponse; + } + + @Override + public AaiResponse getTenants(String globalCustomerId, String serviceType) { + File certiPath = getCertificatesFile(); + String url = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType; + + Response resp = doAaiGet(certiPath.getAbsolutePath(), url, false); + String responseAsString = parseForTenantsByServiceSubscription(resp.readEntity(String.class)); + + AaiResponse<GetTenantsResponse[]> getTenantsResponse = proccessAaiResponse(resp, GetTenantsResponse[].class, responseAsString); + return getTenantsResponse; + } + + private AaiResponse proccessAaiResponse(Response resp, Class classType, String responseBody) { + AaiResponse subscriberDataResponse; + if (resp == null) { + subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI"); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString()); + if (resp.getStatus() != HttpStatus.SC_OK) { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI"); + subscriberDataResponse = new AaiResponse<>(null, resp.readEntity(String.class), resp.getStatus()); + } else { + String finalResponse; + try { + if (responseBody != null) { + finalResponse = responseBody; + } else { + finalResponse = resp.readEntity(String.class); + } + + subscriberDataResponse = new AaiResponse<>((new ObjectMapper().readValue(finalResponse, classType)), null, HttpStatus.SC_OK); + + } catch (IOException e) { + subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + + } + } + return subscriberDataResponse; + } + + private File getCertificatesFile() { + if (servletContext != null) + return new File(servletContext.getRealPath("/WEB-INF/cert/")); + return null; + } + + @SuppressWarnings("all") + protected Response doAaiGet(String certiPath, String uri, boolean xml) { + String methodName = "doAaiGet"; + String transId = UUID.randomUUID().toString(); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + Response resp = null; + try { + + AAIRestInterface restContrller = new AAIRestInterface(certiPath); + resp = restContrller.RestGet(fromAppId, transId, uri, xml); + + } catch (WebApplicationException e) { + final String message = ((BadRequestException) e).getResponse().readEntity(String.class); + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); + } catch (Exception e) { + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + } + + return resp; + } + + private String parseForTenantsByServiceSubscription(String resp) { + String tenantList = ""; + + try { + JSONParser jsonParser = new JSONParser(); + + JSONObject jsonObject = (JSONObject) jsonParser.parse(resp); + + return parseServiceSubscriptionObjectForTenants(jsonObject); + } catch (Exception ex) { + + } + + return tenantList; + } + + protected Response doAaiPut(String certiPath, String uri, String payload, boolean xml) { + String methodName = "doAaiPut"; + String transId = UUID.randomUUID().toString(); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + Response resp = null; + try { - @Override - public AaiResponse getTenants(String globalCustomerId, String serviceType) { - File certiPath = getCertificatesFile(); - String url = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType; - - Response resp = doAaiGet(certiPath.getAbsolutePath(), url, false); - String responseAsString = parseForTenantsByServiceSubscription(resp.readEntity(String.class)); - - AaiResponse<GetTenantsResponse[]> getTenantsResponse = proccessAaiResponse(resp, GetTenantsResponse[].class,responseAsString); - return getTenantsResponse; - } - - private AaiResponse proccessAaiResponse(Response resp, Class classType,String responseBody) { - AaiResponse subscriberDataResponse; - if (resp == null) { - subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI"); - } else { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString()); - if (resp.getStatus() != HttpStatus.SC_OK) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI"); - subscriberDataResponse = new AaiResponse<>(null, resp.readEntity(String.class), resp.getStatus()); - } else { - String finalResponse; - try { - if (responseBody != null){ - finalResponse = responseBody; - } - else{ - finalResponse = resp.readEntity(String.class);; - } - - subscriberDataResponse = new AaiResponse<>((new ObjectMapper().readValue(finalResponse, classType)), null, HttpStatus.SC_OK); - - } catch (IOException e) { - subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR); - } - - } - } - return subscriberDataResponse; - } - - private File getCertificatesFile() { - if (servletContext != null) - return new File(servletContext.getRealPath("/WEB-INF/cert/")); - return null; - } - - @SuppressWarnings("all") - protected Response doAaiGet(String certiPath, String uri, boolean xml) { - String methodName = "getSubscriberList"; - String transId = UUID.randomUUID().toString(); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - Response resp = null; - try { - - AAIRestInterface restContrller = new AAIRestInterface(certiPath); - resp = restContrller.RestGet(fromAppId, transId, uri, xml); - - } catch (WebApplicationException e) { - final String message = ((BadRequestException) e).getResponse().readEntity(String.class); - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); - } catch (Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - } - - return resp; - } - - private String parseForTenantsByServiceSubscription(String resp) { - String tenantList = ""; - - try { - JSONParser jsonParser = new JSONParser(); - - JSONObject jsonObject = (JSONObject) jsonParser.parse(resp); - - return parseServiceSubscriptionObjectForTenants(jsonObject); - } catch (Exception ex) { - - } - - return tenantList; - } + AAIRestInterface restContrller = new AAIRestInterface(certiPath); + resp = restContrller.RestPut(fromAppId, transId, uri, payload, xml); + + } catch (Exception e) { + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + } + + return resp; + } + public static String parseServiceSubscriptionObjectForTenants(JSONObject jsonObject) { + + JSONArray tenantArray = new JSONArray(); + boolean bconvert = false; + + try { + JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list"); + if (relationShipListsObj != null) { + JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship"); + if (rShipArray != null) { + Iterator i1 = rShipArray.iterator(); - public static String parseServiceSubscriptionObjectForTenants(JSONObject jsonObject) { + while (i1.hasNext()) { - JSONArray tenantArray = new JSONArray(); - boolean bconvert = false; + JSONObject inner1Obj = (JSONObject) i1.next(); - try { - JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list"); - if (relationShipListsObj != null) { - JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship"); - if (rShipArray != null) { - Iterator i1 = rShipArray.iterator(); + if (inner1Obj == null) + continue; - while (i1.hasNext()) { + String relatedTo = checkForNull((String) inner1Obj.get("related-to")); + if (relatedTo.equalsIgnoreCase("tenant")) { + JSONObject tenantNewObj = new JSONObject(); - JSONObject inner1Obj = (JSONObject) i1.next(); + String relatedLink = checkForNull((String) inner1Obj.get("related-link")); + tenantNewObj.put("link", relatedLink); - if (inner1Obj == null) - continue; + JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data"); + if (rDataArray != null) { + Iterator i2 = rDataArray.iterator(); - String relatedTo = checkForNull((String) inner1Obj.get("related-to")); - if (relatedTo.equalsIgnoreCase("tenant")) { - JSONObject tenantNewObj = new JSONObject(); + while (i2.hasNext()) { + JSONObject inner2Obj = (JSONObject) i2.next(); - String relatedLink = checkForNull((String) inner1Obj.get("related-link")); - tenantNewObj.put("link", relatedLink); + if (inner2Obj == null) + continue; - JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data"); - if (rDataArray != null) { - Iterator i2 = rDataArray.iterator(); + String rShipKey = checkForNull((String) inner2Obj.get("relationship-key")); + String rShipVal = checkForNull((String) inner2Obj.get("relationship-value")); + if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) { + tenantNewObj.put("cloudOwner", rShipVal); + } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) { + tenantNewObj.put("cloudRegionID", rShipVal); + } - while (i2.hasNext()) { - JSONObject inner2Obj = (JSONObject) i2.next(); + if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) { + tenantNewObj.put("tenantID", rShipVal); + } + } + } - if (inner2Obj == null) - continue; + JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property"); + if (relatedTPropArray != null) { + Iterator i3 = relatedTPropArray.iterator(); - String rShipKey = checkForNull((String) inner2Obj.get("relationship-key")); - String rShipVal = checkForNull((String) inner2Obj.get("relationship-value")); - if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) { - tenantNewObj.put("cloudOwner", rShipVal); - } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) { - tenantNewObj.put("cloudRegionID", rShipVal); - } + while (i3.hasNext()) { + JSONObject inner3Obj = (JSONObject) i3.next(); - if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) { - tenantNewObj.put("tenantID", rShipVal); - } - } - } + if (inner3Obj == null) + continue; - JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property"); - if (relatedTPropArray != null) { - Iterator i3 = relatedTPropArray.iterator(); + String propKey = checkForNull((String) inner3Obj.get("property-key")); + String propVal = checkForNull((String) inner3Obj.get("property-value")); + if (propKey.equalsIgnoreCase("tenant.tenant-name")) { + tenantNewObj.put("tenantName", propVal); + } + } + } + bconvert = true; + tenantArray.add(tenantNewObj); + } + } - while (i3.hasNext()) { - JSONObject inner3Obj = (JSONObject) i3.next(); + } + } + } catch (NullPointerException ex) { - if (inner3Obj == null) - continue; - String propKey = checkForNull((String) inner3Obj.get("property-key")); - String propVal = checkForNull((String) inner3Obj.get("property-value")); - if (propKey.equalsIgnoreCase("tenant.tenant-name")) { - tenantNewObj.put("tenantName", propVal); - } - } - } - bconvert = true; - tenantArray.add(tenantNewObj); - } - } + } - } - } - } catch (NullPointerException ex) { + if (bconvert) + return tenantArray.toJSONString(); + else + return ""; + } - } - - if (bconvert) - return tenantArray.toJSONString(); - else - return ""; - - } }
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/openecomp/vid/aai/AaiClientInterface.java b/vid-app-common/src/main/java/org/openecomp/vid/aai/AaiClientInterface.java index fdaf602f4..f1b1ba2df 100644 --- a/vid-app-common/src/main/java/org/openecomp/vid/aai/AaiClientInterface.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/aai/AaiClientInterface.java @@ -3,6 +3,7 @@ package org.openecomp.vid.aai; import org.openecomp.vid.aai.model.AaiGetTenatns.GetTenantsResponse; import org.openecomp.vid.model.SubscriberList; +import javax.ws.rs.core.Response; import java.util.List; /** @@ -19,4 +20,14 @@ public interface AaiClientInterface { AaiResponse<GetTenantsResponse[]> getTenants(String globalCustomerId, String serviceType); AaiResponse getAllAicZones(); + + AaiResponse getAicZoneForPnf(String globalCustomerId , String serviceType , String serviceId); + + AaiResponse getVNFData(); + + Response getVNFData(String globalSubscriberId, String serviceType); + + AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId); + + Response getVersionByInvariantId(List<String> modelInvariantId); } diff --git a/vid-app-common/src/main/java/org/openecomp/vid/aai/AaiGetVnfResponse.java b/vid-app-common/src/main/java/org/openecomp/vid/aai/AaiGetVnfResponse.java new file mode 100644 index 000000000..7c9d44b12 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/aai/AaiGetVnfResponse.java @@ -0,0 +1,28 @@ +package org.openecomp.vid.aai; + +import com.fasterxml.jackson.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "results" +}) +public class AaiGetVnfResponse { + @JsonProperty("results") + public List<VnfResult> results = null; + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/aai/ServiceProperties.java b/vid-app-common/src/main/java/org/openecomp/vid/aai/ServiceProperties.java new file mode 100644 index 000000000..113f113d3 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/aai/ServiceProperties.java @@ -0,0 +1,90 @@ +package org.openecomp.vid.aai; + +import com.fasterxml.jackson.annotation.*; +import org.codehaus.jackson.annotate.JsonProperty; + +import java.util.HashMap; +import java.util.Map; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "service-instance-id", + "service-instance-name", + "model-invariant-id", + "model-version-id", + "resource-version", + "orchestration-status", + "global-customer-id", + "subscriber-name", + "subscriber-type", + "vnf-id", + "vnf-name", + "vnf-type", + "service-id", + "prov-status", + "in-maint", + "is-closed-loop-disabled", + "model-customization-id", + "nf-type", + "nf-function", + "nf-role", + "nf-naming-code" +}) +public class ServiceProperties { + + @JsonProperty("service-instance-id") + public String serviceInstanceId; + @JsonProperty("service-instance-name") + public String serviceInstanceName; + @JsonProperty("model-invariant-id") + public String modelInvariantId; + @JsonProperty("model-version-id") + public String modelVersionId; + @JsonProperty("resource-version") + public String resourceVersion; + @JsonProperty("orchestration-status") + public String orchestrationStatus; + @JsonProperty("global-customer-id") + public String globalCustomerId; + @JsonProperty("subscriber-name") + public String subscriberName; + @JsonProperty("subscriber-type") + public String subscriberType; + @JsonProperty("vnf-id") + public String vnfId; + @JsonProperty("vnf-name") + public String vnfName; + @JsonProperty("vnf-type") + public String vnfType; + @JsonProperty("service-id") + public String serviceId; + @JsonProperty("prov-status") + public String provStatus; + @JsonProperty("in-maint") + public Boolean inMaint; + @JsonProperty("is-closed-loop-disabled") + public Boolean isClosedLoopDisabled; + @JsonProperty("model-customization-id") + public String modelCustomizationId; + @JsonProperty("nf-type") + public String nfType; + @JsonProperty("nf-function") + public String nfFunction; + @JsonProperty("nf-role") + public String nfRole; + @JsonProperty("nf-naming-code") + public String nfNamingCode; + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/aai/VnfResult.java b/vid-app-common/src/main/java/org/openecomp/vid/aai/VnfResult.java new file mode 100644 index 000000000..b8294e519 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/aai/VnfResult.java @@ -0,0 +1,44 @@ +package org.openecomp.vid.aai; + +import com.fasterxml.jackson.annotation.*; +import org.codehaus.jackson.annotate.JsonProperty; +import org.openecomp.vid.RelatedTo; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "id", + "node-type", + "url", + "properties", + "related-to" +}) +public class VnfResult { + + @JsonProperty("id") + public String id; + @JsonProperty("node-type") + public String nodeType; + @JsonProperty("url") + public String url; + @JsonProperty("properties") + public ServiceProperties properties; + @JsonProperty("related-to") + public List<RelatedTo> relatedTo = null; + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/aai/model/RelatedToProperty.java b/vid-app-common/src/main/java/org/openecomp/vid/aai/model/RelatedToProperty.java new file mode 100644 index 000000000..c9f28ed69 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/aai/model/RelatedToProperty.java @@ -0,0 +1,34 @@ +package org.openecomp.vid.aai.model; + +import org.codehaus.jackson.annotate.JsonProperty; + +public class RelatedToProperty { + + public String getPropertyKey() { + return propertyKey; + } + + + public void setPropertyKey(String propertyKey) { + this.propertyKey = propertyKey; + } + + + public String getPropertyValue() { + return propertyValue; + } + + + public void setPropertyValue(String propertyValue) { + this.propertyValue = propertyValue; + } + + + @JsonProperty("property-key") + public String propertyKey; + + + @JsonProperty("property-value") + public String propertyValue; + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/aai/model/Relationship.java b/vid-app-common/src/main/java/org/openecomp/vid/aai/model/Relationship.java new file mode 100644 index 000000000..796094192 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/aai/model/Relationship.java @@ -0,0 +1,55 @@ +package org.openecomp.vid.aai.model; + +import java.util.List; + +import org.codehaus.jackson.annotate.JsonProperty; + +public class Relationship { + + @JsonProperty("related-to") + public String relatedTo; + + @JsonProperty("related-link") + public String relatedLink; + + @JsonProperty("relationship-data") + public List<RelationshipData> relationshipData; + + @JsonProperty("related-to-property") + public List<RelatedToProperty> relatedToProperty; + + + public String getRelatedTo() { + return relatedTo; + } + + public void setRelatedTo(String relatedTo) { + this.relatedTo = relatedTo; + } + + public String getRelatedLink() { + return relatedLink; + } + + public void setRelatedLink(String relatedLink) { + this.relatedLink = relatedLink; + } + + public List<RelationshipData> getRelationDataList() { + return relationshipData; + } + + public void setRelationDataList(List<RelationshipData> relationDataList) { + this.relationshipData = relationDataList; + } + + public List<RelatedToProperty> getRelatedToPropertyList() { + return relatedToProperty; + } + + public void setRelatedToPropertyList(List<RelatedToProperty> relatedToPropertyList) { + this.relatedToProperty = relatedToPropertyList; + } + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/aai/model/RelationshipData.java b/vid-app-common/src/main/java/org/openecomp/vid/aai/model/RelationshipData.java new file mode 100644 index 000000000..21af2f5d6 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/aai/model/RelationshipData.java @@ -0,0 +1,29 @@ +package org.openecomp.vid.aai.model; + +import org.codehaus.jackson.annotate.JsonProperty; + +public class RelationshipData { + + public String getRelationshipKey() { + return relationshipKey; + } + + public void setRelationshipKey(String relationshipKey) { + this.relationshipKey = relationshipKey; + } + + public String getRelationshipValue() { + return relationshipValue; + } + + public void setRelationshipValue(String relationshipValue) { + this.relationshipValue = relationshipValue; + } + + @JsonProperty("relationship-key") + public String relationshipKey; + + @JsonProperty("relationship-value") + public String relationshipValue; + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/aai/model/RelationshipList.java b/vid-app-common/src/main/java/org/openecomp/vid/aai/model/RelationshipList.java new file mode 100644 index 000000000..cdb7af46b --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/aai/model/RelationshipList.java @@ -0,0 +1,24 @@ +package org.openecomp.vid.aai.model; + +import java.util.List; + +import org.codehaus.jackson.annotate.JsonProperty; + +public class RelationshipList { + + + public List<Relationship> getRelationship() { + return relationship; + } + + public void setRelationship(List<Relationship> relationship) { + this.relationship = relationship; + } + + @JsonProperty("relationship") + public List<Relationship> relationship; + + + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/aai/model/ServiceRelationships.java b/vid-app-common/src/main/java/org/openecomp/vid/aai/model/ServiceRelationships.java new file mode 100644 index 000000000..9bedd8545 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/aai/model/ServiceRelationships.java @@ -0,0 +1,90 @@ +package org.openecomp.vid.aai.model; + +import org.codehaus.jackson.annotate.JsonProperty; + +public class ServiceRelationships { + + @JsonProperty("service-instance-id") + public String serviceInstanceId; + + @JsonProperty("service-instance-name") + public String serviceInstanceName; + + @JsonProperty("model-invariant-id") + public String modelInvariantId; + + @JsonProperty("model-version-id") + public String modelVersionId; + + @JsonProperty("resource-version") + public String resourceVersion; + + @JsonProperty("orchestration-status") + public String orchestrationStatus; + + @JsonProperty("relationship-list") + public RelationshipList relationshipList; + + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getServiceInstanceName() { + return serviceInstanceName; + } + + public void setServiceInstanceName(String serviceInstanceName) { + this.serviceInstanceName = serviceInstanceName; + } + + public String getModelInvariantId() { + return modelInvariantId; + } + + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + public String getModelVersionId() { + return modelVersionId; + } + + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public String getOrchestrationStatus() { + return orchestrationStatus; + } + + public void setOrchestrationStatus(String orchestrationStatus) { + this.orchestrationStatus = orchestrationStatus; + } + + public RelationshipList getRelationshipList() { + return relationshipList; + } + + public void setRelationshipList(RelationshipList relationshipList) { + this.relationshipList = relationshipList; + } + + + + + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/asdc/beans/tosca/ToscaMetadata.java b/vid-app-common/src/main/java/org/openecomp/vid/asdc/beans/tosca/ToscaMetadata.java index 41c7ca5ba..d42c1f150 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/asdc/beans/tosca/ToscaMetadata.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/asdc/beans/tosca/ToscaMetadata.java @@ -61,9 +61,6 @@ public class ToscaMetadata { /** The resource vendor release. */
private String resourceVendorRelease;
- /** the resourceVendorModelNumber */
- private String resourceVendorModelNumber;
-
/** The service ecomp naming. */
private String serviceEcompNaming;
@@ -91,11 +88,6 @@ public class ToscaMetadata { /** The vf module model version. */
private String vfModuleModelVersion;
-
- /** serviceType */
- private String serviceType;
- /** serviceRole */
- private String serviceRole;
/**
* Instantiates a new tosca metadata.
@@ -466,26 +458,4 @@ public class ToscaMetadata { return vfModuleModelCustomizationUUID;
}
-
- /** serviceType */
- public String getServiceType() {
- return serviceType;
- }
- public void setServiceType(String serviceType) {
- this.serviceType= serviceType;
- }
- /** serviceRole */
- public String getServiceRole() {
- return serviceRole;
- }
- public void setServiceRole(String serviceRole) {
- this.serviceRole= serviceRole;
- }
- /** resourceVendorModelNumber */
- public String getResourceVendorModelNumber() {
- return resourceVendorModelNumber;
- }
- public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
- this.resourceVendorModelNumber= resourceVendorModelNumber;
- }
}
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/asdc/parser/ToscaParserImpl2.java b/vid-app-common/src/main/java/org/openecomp/vid/asdc/parser/ToscaParserImpl2.java index 3f0dd8c31..e2b32fa8c 100644 --- a/vid-app-common/src/main/java/org/openecomp/vid/asdc/parser/ToscaParserImpl2.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/asdc/parser/ToscaParserImpl2.java @@ -191,6 +191,8 @@ public class ToscaParserImpl2 { volumeGroup.setModelCustomizationName(group.getMetadata().getValue(Constants.vfModuleModelName)); volumeGroup.setVersion(group.getMetadata().getValue(Constants.vfModuleModelVersion)); volumeGroup.setUuid(group.getMetadata().getValue(Constants.vfModuleModelUUID)); + volumeGroup.setCustomizationUuid(group.getMetadata().getValue(Constants.vfModuleModelCustomizationUUID)); + return volumeGroup; } diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/ChangeManagementRequest.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/ChangeManagementRequest.java new file mode 100644 index 000000000..adcb54683 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/ChangeManagementRequest.java @@ -0,0 +1,63 @@ +package org.openecomp.vid.changeManagement; + +import java.util.List; +import java.util.HashMap; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonPropertyOrder({ + "requestDetails", + "requestType" +}) + +public class ChangeManagementRequest { + + public ChangeManagementRequest() {} + + @JsonProperty("requestDetails") + private List<RequestDetails> requestDetails; + + @JsonProperty("requestType") + private String requestType; + + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + @JsonProperty("requestDetails") + public List<RequestDetails> getRequestDetails() { + return requestDetails; + } + + @JsonProperty("requestDetails") + public void setRequestDetails(List<RequestDetails> requestDetails) { + this.requestDetails = requestDetails; + } + + @JsonProperty("requestType") + public String getRequestType() { + return requestType; + } + + @JsonProperty("requestType") + public void setRequestType(String requestType) { + this.requestType = requestType; + } + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } + + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/ChangeManagementResponse.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/ChangeManagementResponse.java new file mode 100644 index 000000000..10ba035d6 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/ChangeManagementResponse.java @@ -0,0 +1,19 @@ +package org.openecomp.vid.changeManagement; + +import java.util.ArrayList; +import java.util.List; + +public class ChangeManagementResponse { + public List<CmResponse> cmResponses = null; + + + + public ChangeManagementResponse(String vnfName) { + List<CmResponse> cmResponses = new ArrayList<>(); + cmResponses.add(new CmResponse(vnfName)); + this.cmResponses = cmResponses; + + } + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/CloudConfiguration.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/CloudConfiguration.java new file mode 100644 index 000000000..a5debc6db --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/CloudConfiguration.java @@ -0,0 +1,55 @@ +package org.openecomp.vid.changeManagement; + +import java.util.HashMap; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"lcpCloudRegionId", +"tenantId" +}) +public class CloudConfiguration { + @JsonProperty("lcpCloudRegionId") + private String lcpCloudRegionId; + @JsonProperty("tenantId") + private String tenantId; + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + @JsonProperty("lcpCloudRegionId") + public String getLcpCloudRegionId() { + return lcpCloudRegionId; + } + + @JsonProperty("lcpCloudRegionId") + public void setLcpCloudRegionId(String lcpCloudRegionId) { + this.lcpCloudRegionId = lcpCloudRegionId; + } + + @JsonProperty("tenantId") + public String getTenantId() { + return tenantId; + } + + @JsonProperty("tenantId") + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/CmResponse.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/CmResponse.java new file mode 100644 index 000000000..70e09d83c --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/CmResponse.java @@ -0,0 +1,17 @@ +package org.openecomp.vid.changeManagement; + +public class CmResponse { + + public String orchestratorRequestId; + public String serviceInstanceId; + public String vnfInstanceId; + public String vnfName; + + public CmResponse(String vnfName){ + this.orchestratorRequestId = "Request Id"; + this.serviceInstanceId = "Service instance Id"; + this.vnfInstanceId = "Vnf instance Id"; + this.vnfName = vnfName; + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/LeanCloudConfiguration.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/LeanCloudConfiguration.java new file mode 100644 index 000000000..663ff8c49 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/LeanCloudConfiguration.java @@ -0,0 +1,20 @@ +package org.openecomp.vid.changeManagement; + +/** + * Created by Oren on 9/5/17. + */ +public class LeanCloudConfiguration { + + public LeanCloudConfiguration() { + } + + public LeanCloudConfiguration(org.openecomp.vid.domain.mso.CloudConfiguration cloudConfiguration) { + this.tenantId = cloudConfiguration.getTenantId(); + this.lcpCloudRegionId = cloudConfiguration.getLcpCloudRegionId(); + + } + public String lcpCloudRegionId; + + public String tenantId; + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/ModelInfo.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/ModelInfo.java new file mode 100644 index 000000000..517628ca0 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/ModelInfo.java @@ -0,0 +1,138 @@ +package org.openecomp.vid.changeManagement; +import java.util.HashMap; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"modelType", +"modelInvariantId", +"modelVersionId", +"modelName", +"modelVersion", +"modelCustomizationName", +"modelCustomizationId" +}) +public class ModelInfo { + + public ModelInfo(){ + + } + + public ModelInfo(org.openecomp.vid.domain.mso.ModelInfo modelInfo){ + this.setModelType(modelInfo.getModelType().toString()); + this.setModelInvariantId(modelInfo.getModelInvariantId()); + this.setModelVersionId(modelInfo.getModelNameVersionId()); + this.setModelName(modelInfo.getModelName()); + this.setModelVersion(modelInfo.getModelVersion()); + this.setModelCustomizationId(modelInfo.getModelCustomizationId()); + this.setModelVersionId(modelInfo.getModelVersionId()); + } + + + @JsonProperty("modelType") + private String modelType; + @JsonProperty("modelInvariantId") + private String modelInvariantId; + @JsonProperty("modelVersionId") + private String modelVersionId; + @JsonProperty("modelName") + private String modelName; + @JsonProperty("modelVersion") + private String modelVersion; + @JsonProperty("modelCustomizationName") + private String modelCustomizationName; + @JsonProperty("modelCustomizationId") + private String modelCustomizationId; + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + @JsonProperty("modelType") + public String getModelType() { + return modelType; + } + + @JsonProperty("modelType") + public void setModelType(String modelType) { + this.modelType = modelType; + } + + @JsonProperty("modelInvariantId") + public String getModelInvariantId() { + return modelInvariantId; + } + + @JsonProperty("modelInvariantId") + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + @JsonProperty("modelVersionId") + public String getModelVersionId() { + return modelVersionId; + } + + @JsonProperty("modelVersionId") + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + @JsonProperty("modelName") + public String getModelName() { + return modelName; + } + + @JsonProperty("modelName") + public void setModelName(String modelName) { + this.modelName = modelName; + } + + @JsonProperty("modelVersion") + public String getModelVersion() { + return modelVersion; + } + + @JsonProperty("modelVersion") + public void setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + } + + @JsonProperty("modelCustomizationName") + public String getModelCustomizationName() { + return modelCustomizationName; + } + + @JsonProperty("modelCustomizationName") + public void setModelCustomizationName(String modelCustomizationName) { + this.modelCustomizationName = modelCustomizationName; + } + + @JsonProperty("modelCustomizationId") + public String getModelCustomizationId() { + return modelCustomizationId; + } + + @JsonProperty("modelCustomizationId") + public void setModelCustomizationId(String modelCustomizationId) { + this.modelCustomizationId = modelCustomizationId; + } + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/ModelInfoOfRelatedInstance.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/ModelInfoOfRelatedInstance.java new file mode 100644 index 000000000..c60ed2f77 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/ModelInfoOfRelatedInstance.java @@ -0,0 +1,122 @@ +package org.openecomp.vid.changeManagement; + +import java.util.HashMap; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"modelType", +"modelInvariantId", +"modelVersionId", +"modelName", +"modelVersion", +"modelCustomizationName", +"modelCustomizationId" +}) + +public class ModelInfoOfRelatedInstance { + + @JsonProperty("modelType") + private String modelType; + @JsonProperty("modelInvariantId") + private String modelInvariantId; + @JsonProperty("modelVersionId") + private String modelVersionId; + @JsonProperty("modelName") + private String modelName; + @JsonProperty("modelVersion") + private String modelVersion; + @JsonProperty("modelCustomizationName") + private String modelCustomizationName; + @JsonProperty("modelCustomizationId") + private String modelCustomizationId; + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + @JsonProperty("modelType") + public String getModelType() { + return modelType; + } + + @JsonProperty("modelType") + public void setModelType(String modelType) { + this.modelType = modelType; + } + + @JsonProperty("modelInvariantId") + public String getModelInvariantId() { + return modelInvariantId; + } + + @JsonProperty("modelInvariantId") + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + @JsonProperty("modelVersionId") + public String getModelVersionId() { + return modelVersionId; + } + + @JsonProperty("modelVersionId") + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + @JsonProperty("modelName") + public String getModelName() { + return modelName; + } + + @JsonProperty("modelName") + public void setModelName(String modelName) { + this.modelName = modelName; + } + + @JsonProperty("modelVersion") + public String getModelVersion() { + return modelVersion; + } + + @JsonProperty("modelVersion") + public void setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + } + + @JsonProperty("modelCustomizationName") + public String getModelCustomizationName() { + return modelCustomizationName; + } + + @JsonProperty("modelCustomizationName") + public void setModelCustomizationName(String modelCustomizationName) { + this.modelCustomizationName = modelCustomizationName; + } + + @JsonProperty("modelCustomizationId") + public String getModelCustomizationId() { + return modelCustomizationId; + } + + @JsonProperty("modelCustomizationId") + public void setModelCustomizationId(String modelCustomizationId) { + this.modelCustomizationId = modelCustomizationId; + } + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/MsoRequestDetails.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/MsoRequestDetails.java new file mode 100644 index 000000000..9e442f28b --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/MsoRequestDetails.java @@ -0,0 +1,31 @@ +package org.openecomp.vid.changeManagement; + + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Oren on 9/5/17. + */ +public class MsoRequestDetails { + + public ModelInfo modelInfo; + + public LeanCloudConfiguration cloudConfiguration; + + public UpdateRequestInfo requestInfo; + + public List<RelatedInstanceList> relatedInstanceList; + + public RequestParameters requestParameters; + + public MsoRequestDetails(RequestDetails r) { + this.modelInfo = new ModelInfo(r.getModelInfo()); + this.cloudConfiguration = new LeanCloudConfiguration(r.getCloudConfiguration()); + this.requestInfo = new UpdateRequestInfo(r.getRequestInfo()); + this.relatedInstanceList = new ArrayList<>(); + relatedInstanceList = r.getRelatedInstList(); + + + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RelatedInstance.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RelatedInstance.java new file mode 100644 index 000000000..49368c20e --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RelatedInstance.java @@ -0,0 +1,29 @@ +package org.openecomp.vid.changeManagement; + +import com.fasterxml.jackson.annotation.*; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "instanceId", + "modelInfo" +}) +public class RelatedInstance { + + @JsonProperty("instanceId") + public String instanceId; + + + @JsonProperty("modelInfo") + public ModelInfo modelInfo; + + @JsonGetter + public String getInstanceId() { + return instanceId; + } + + @JsonSetter + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RelatedInstanceList.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RelatedInstanceList.java new file mode 100644 index 000000000..21a41c3f7 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RelatedInstanceList.java @@ -0,0 +1,23 @@ +package org.openecomp.vid.changeManagement; + +import com.fasterxml.jackson.annotation.*; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "relatedInstance" +}) +public class RelatedInstanceList { + + @JsonProperty("relatedInstance") + public RelatedInstance relatedInstance; + + @JsonSetter + public RelatedInstance getRelatedInstance() { + return relatedInstance; + } + + @JsonSetter + public void setRelatedInstance(RelatedInstance relatedInstance) { + this.relatedInstance = relatedInstance; + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RequestDetails.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RequestDetails.java new file mode 100644 index 000000000..94e4c4468 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RequestDetails.java @@ -0,0 +1,56 @@ +package org.openecomp.vid.changeManagement; + +import com.fasterxml.jackson.annotation.*; + +import java.util.List; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"modelInfo", +"cloudConfiguration", +"requestInfo", +"requestParameters", +"vnfName", +"vnfInstanceId" +}) +public class RequestDetails extends org.openecomp.vid.mso.rest.RequestDetails{ + + @JsonProperty("vnfName") + private String vnfName; + @JsonProperty("vnfInstanceId") + private String vnfInstanceId; + + /** The related model list. */ + @JsonProperty("relatedInstanceList") + public List<RelatedInstanceList> relatedInstList; + + @JsonProperty("vnfName") + public String getVnfName() { + return vnfName; + } + + @JsonProperty("vnfName") + public void setVnfName(String vnfName) { + this.vnfName = vnfName; + } + @JsonProperty("vnfInstanceId") + public String getVnfInstanceId() { + return vnfInstanceId; + } + + @JsonProperty("vnfInstanceId") + public void setVnfInstanceId(String vnfInstanceId) { + this.vnfInstanceId = vnfInstanceId; + } + + @JsonGetter + public List<RelatedInstanceList> getRelatedInstList() { + return relatedInstList; + } + + @JsonSetter + public void setRelatedInstList(List<RelatedInstanceList> relatedInstList) { + this.relatedInstList = relatedInstList; + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RequestDetailsWrapper.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RequestDetailsWrapper.java new file mode 100644 index 000000000..2f49aff0a --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RequestDetailsWrapper.java @@ -0,0 +1,9 @@ +package org.openecomp.vid.changeManagement; + +/** + * Created by Oren on 9/5/17. + */ +public class RequestDetailsWrapper { + + public MsoRequestDetails requestDetails; +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RequestInfo.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RequestInfo.java new file mode 100644 index 000000000..a7236c4b1 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RequestInfo.java @@ -0,0 +1,69 @@ +package org.openecomp.vid.changeManagement; + +import java.util.HashMap; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"source", +"suppressRollback", +"requestorId" +}) +public class RequestInfo { + @JsonProperty("source") + private String source; + @JsonProperty("suppressRollback") + private Boolean suppressRollback; + @JsonProperty("requestorId") + private String requestorId; + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + @JsonProperty("source") + public String getSource() { + return source; + } + + @JsonProperty("source") + public void setSource(String source) { + this.source = source; + } + + @JsonProperty("suppressRollback") + public Boolean getSuppressRollback() { + return suppressRollback; + } + + @JsonProperty("suppressRollback") + public void setSuppressRollback(Boolean suppressRollback) { + this.suppressRollback = suppressRollback; + } + + @JsonProperty("requestorId") + public String getRequestorId() { + return requestorId; + } + + @JsonProperty("requestorId") + public void setRequestorId(String requestorId) { + this.requestorId = requestorId; + } + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RequestParameters.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RequestParameters.java new file mode 100644 index 000000000..37cad4735 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/RequestParameters.java @@ -0,0 +1,44 @@ +package org.openecomp.vid.changeManagement; + +import java.util.HashMap; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"usePreload" +}) + +public class RequestParameters { + + + @JsonProperty("usePreload") + private Boolean usePreload; + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + @JsonProperty("usePreload") + public Boolean getUsePreload() { + return usePreload; + } + + @JsonProperty("usePreload") + public void setUsePreload(Boolean usePreload) { + this.usePreload = usePreload; + } + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/UpdateRequestInfo.java b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/UpdateRequestInfo.java new file mode 100644 index 000000000..ab8189484 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/changeManagement/UpdateRequestInfo.java @@ -0,0 +1,26 @@ +package org.openecomp.vid.changeManagement; + +import org.openecomp.vid.domain.mso.*; + +/** + * Created by Oren on 9/5/17. + */ +public class UpdateRequestInfo { + + public UpdateRequestInfo() { + } + + + public UpdateRequestInfo(org.openecomp.vid.domain.mso.RequestInfo requestInfo) { + this.requestorId = requestInfo.getRequestorId(); + this.suppressRollback = requestInfo.getSuppressRollback(); + this.source = requestInfo.getSource(); + } + public String source; + + public Boolean suppressRollback; + + public String requestorId; + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/AaiController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/AaiController.java index c0b6a5140..a8bdf39bb 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/controller/AaiController.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/AaiController.java @@ -35,6 +35,7 @@ import org.openecomp.vid.aai.AaiResponse; import org.openecomp.vid.aai.SubscriberData;
import org.openecomp.vid.aai.SubscriberFilteredResults;
import org.openecomp.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
+import org.openecomp.vid.model.VersionByInvariantIdsRequest;
import org.openecomp.vid.roles.Role;
import org.openecomp.vid.roles.RoleProvider;
import org.openecomp.vid.roles.RoleValidator;
@@ -43,13 +44,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
-
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@@ -70,859 +67,886 @@ import java.util.*; @RestController
public class AaiController extends RestrictedBaseController {
-
- public AaiController() {
-
- }
-public AaiController(ServletContext servletContext) {
- this.servletContext = servletContext;
-
- }
-
-
-
-
- /**
- * The Constant dateFormat.
- */
- final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
- /**
- * The from app id.
- */
- protected String fromAppId = "VidAaiController";
- /**
- * The view name.
- */
- String viewName;
- /**
- * The logger.
- */
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiController.class);
-
-
- /**
- * The model.
- */
- private Map<String, Object> model = new HashMap<String, Object>();
- /**
- * The servlet context.
- */
- @Autowired
- private ServletContext servletContext;
-
- /**
- * aai service
- */
- @Autowired
- private AaiService aaiService;
-
-
-
- /**
- * Return tenant details.
- *
- * @param jsonObject the json object
- * @return String The parsing results
- */
- public static String parseCustomerObjectForTenants(JSONObject jsonObject) {
-
- JSONArray tenantArray = new JSONArray();
- boolean bconvert = false;
-
- try {
-
- JSONObject serviceSubsObj = (JSONObject) jsonObject.get("service-subscriptions");
-
- if (serviceSubsObj != null) {
- JSONArray srvcSubArray = (JSONArray) serviceSubsObj.get("service-subscription");
-
- if (srvcSubArray != null) {
- Iterator i = srvcSubArray.iterator();
-
- while (i.hasNext()) {
-
- JSONObject innerObj = (JSONObject) i.next();
-
- if (innerObj == null)
- continue;
-
- JSONObject relationShipListsObj = (JSONObject) innerObj.get("relationship-list");
- if (relationShipListsObj != null) {
- JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");
- if (rShipArray != null) {
- Iterator i1 = rShipArray.iterator();
-
- while (i1.hasNext()) {
-
- JSONObject inner1Obj = (JSONObject) i1.next();
-
- if (inner1Obj == null)
- continue;
-
- String relatedTo = checkForNull((String) inner1Obj.get("related-to"));
- if (relatedTo.equalsIgnoreCase("tenant")) {
- JSONObject tenantNewObj = new JSONObject();
-
- String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
- tenantNewObj.put("link", relatedLink);
-
- JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
- if (rDataArray != null) {
- Iterator i2 = rDataArray.iterator();
-
- while (i2.hasNext()) {
- JSONObject inner2Obj = (JSONObject) i2.next();
-
- if (inner2Obj == null)
- continue;
-
- String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));
- String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));
- if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) {
- tenantNewObj.put("cloudOwner", rShipVal);
- } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) {
- tenantNewObj.put("cloudRegionID", rShipVal);
- }
-
- if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) {
- tenantNewObj.put("tenantID", rShipVal);
- }
- }
- }
-
- JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
- if (relatedTPropArray != null) {
- Iterator i3 = relatedTPropArray.iterator();
-
- while (i3.hasNext()) {
- JSONObject inner3Obj = (JSONObject) i3.next();
-
- if (inner3Obj == null)
- continue;
-
- String propKey = checkForNull((String) inner3Obj.get("property-key"));
- String propVal = checkForNull((String) inner3Obj.get("property-value"));
- if (propKey.equalsIgnoreCase("tenant.tenant-name")) {
- tenantNewObj.put("tenantName", propVal);
- }
- }
- }
- bconvert = true;
- tenantArray.add(tenantNewObj);
- }
- }
- }
- }
- }
- }
- }
- } catch (NullPointerException ex) {
+ /**
+ * The Constant dateFormat.
+ */
+ final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
+ /**
+ * The from app id.
+ */
+ protected String fromAppId = "VidAaiController";
+ /**
+ * The view name.
+ */
+ String viewName;
+ /**
+ * The logger.
+ */
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiController.class);
+ /**
+ * The model.
+ */
+ private Map<String, Object> model = new HashMap<String, Object>();
+ /**
+ * The servlet context.
+ */
+ @Autowired
+ private ServletContext servletContext;
+ /**
+ * aai service
+ */
+ @Autowired
+ private AaiService aaiService;
+ public AaiController() {
+
+ }
+
+ public AaiController(ServletContext servletContext) {
+ this.servletContext = servletContext;
+
+ }
+
+ /**
+ * Return tenant details.
+ *
+ * @param jsonObject the json object
+ * @return String The parsing results
+ */
+ public static String parseCustomerObjectForTenants(JSONObject jsonObject) {
+
+ JSONArray tenantArray = new JSONArray();
+ boolean bconvert = false;
+
+ try {
+
+ JSONObject serviceSubsObj = (JSONObject) jsonObject.get("service-subscriptions");
+
+ if (serviceSubsObj != null) {
+ JSONArray srvcSubArray = (JSONArray) serviceSubsObj.get("service-subscription");
+
+ if (srvcSubArray != null) {
+ Iterator i = srvcSubArray.iterator();
+
+ while (i.hasNext()) {
+
+ JSONObject innerObj = (JSONObject) i.next();
+
+ if (innerObj == null)
+ continue;
+
+ JSONObject relationShipListsObj = (JSONObject) innerObj.get("relationship-list");
+ if (relationShipListsObj != null) {
+ JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");
+ if (rShipArray != null) {
+ Iterator i1 = rShipArray.iterator();
+
+ while (i1.hasNext()) {
+
+ JSONObject inner1Obj = (JSONObject) i1.next();
+
+ if (inner1Obj == null)
+ continue;
+
+ String relatedTo = checkForNull((String) inner1Obj.get("related-to"));
+ if (relatedTo.equalsIgnoreCase("tenant")) {
+ JSONObject tenantNewObj = new JSONObject();
+
+ String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
+ tenantNewObj.put("link", relatedLink);
+
+ JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
+ if (rDataArray != null) {
+ Iterator i2 = rDataArray.iterator();
+
+ while (i2.hasNext()) {
+ JSONObject inner2Obj = (JSONObject) i2.next();
+
+ if (inner2Obj == null)
+ continue;
+
+ String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));
+ String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));
+ if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) {
+ tenantNewObj.put("cloudOwner", rShipVal);
+ } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) {
+ tenantNewObj.put("cloudRegionID", rShipVal);
+ }
+
+ if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) {
+ tenantNewObj.put("tenantID", rShipVal);
+ }
+ }
+ }
+
+ JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
+ if (relatedTPropArray != null) {
+ Iterator i3 = relatedTPropArray.iterator();
+
+ while (i3.hasNext()) {
+ JSONObject inner3Obj = (JSONObject) i3.next();
+
+ if (inner3Obj == null)
+ continue;
+
+ String propKey = checkForNull((String) inner3Obj.get("property-key"));
+ String propVal = checkForNull((String) inner3Obj.get("property-value"));
+ if (propKey.equalsIgnoreCase("tenant.tenant-name")) {
+ tenantNewObj.put("tenantName", propVal);
+ }
+ }
+ }
+ bconvert = true;
+ tenantArray.add(tenantNewObj);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ } catch (NullPointerException ex) {
- }
- if (bconvert)
- return tenantArray.toJSONString();
- else
- return "";
+ }
- }
+ if (bconvert)
+ return tenantArray.toJSONString();
+ else
+ return "";
+ }
- /**
- * Retrieve the service subscription from the jsonObject.
- *
- * @param jsonObject the json object
- * @return String
- */
- public static String parseServiceSubscriptionObjectForTenants(JSONObject jsonObject) {
-
- JSONArray tenantArray = new JSONArray();
- boolean bconvert = false;
-
- try {
- JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list");
- if (relationShipListsObj != null) {
- JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");
- if (rShipArray != null) {
- Iterator i1 = rShipArray.iterator();
-
- while (i1.hasNext()) {
-
- JSONObject inner1Obj = (JSONObject) i1.next();
-
- if (inner1Obj == null)
- continue;
-
- String relatedTo = checkForNull((String) inner1Obj.get("related-to"));
- if (relatedTo.equalsIgnoreCase("tenant")) {
- JSONObject tenantNewObj = new JSONObject();
-
- String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
- tenantNewObj.put("link", relatedLink);
-
- JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
- if (rDataArray != null) {
- Iterator i2 = rDataArray.iterator();
-
- while (i2.hasNext()) {
- JSONObject inner2Obj = (JSONObject) i2.next();
-
- if (inner2Obj == null)
- continue;
-
- String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));
- String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));
- if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) {
- tenantNewObj.put("cloudOwner", rShipVal);
- } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) {
- tenantNewObj.put("cloudRegionID", rShipVal);
- }
-
- if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) {
- tenantNewObj.put("tenantID", rShipVal);
- }
- }
- }
-
- JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
- if (relatedTPropArray != null) {
- Iterator i3 = relatedTPropArray.iterator();
-
- while (i3.hasNext()) {
- JSONObject inner3Obj = (JSONObject) i3.next();
-
- if (inner3Obj == null)
- continue;
-
- String propKey = checkForNull((String) inner3Obj.get("property-key"));
- String propVal = checkForNull((String) inner3Obj.get("property-value"));
- if (propKey.equalsIgnoreCase("tenant.tenant-name")) {
- tenantNewObj.put("tenantName", propVal);
- }
- }
- }
- bconvert = true;
- tenantArray.add(tenantNewObj);
- }
- }
-
- }
- }
- } catch (NullPointerException ex) {
-
-
- }
-
- if (bconvert)
- return tenantArray.toJSONString();
- else
- return "";
-
- }
-
- /**
- * Check for null.
- *
- * @param local the local
- * @return the string
- */
- private static String checkForNull(String local) {
- if (local != null)
- return local;
- else
- return "";
-
- }
-
- /**
- * Welcome method.
- *
- * @param request the request
- * @return ModelAndView The view
- */
- @RequestMapping(value = {"/subscriberSearch"}, method = RequestMethod.GET)
- public ModelAndView welcome(HttpServletRequest request) {
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== AaiController welcome start");
- return new ModelAndView(getViewName());
- }
-
- @RequestMapping(value = {"/aai_get_aic_zones"}, method = RequestMethod.GET)
- public ResponseEntity<String> getAicZones(HttpServletRequest request) throws JsonGenerationException, JsonMappingException, IOException {
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== getAicZones controller start");
- AaiResponse response = aaiService.getAaiZones();
- return aaiResponseToResponseEntity(response);
-
- }
-
- /* (non-Javadoc)
- * @see org.openecomp.portalsdk.core.controller.RestrictedBaseController#getViewName()
- */
- public String getViewName() {
- return viewName;
- }
-
- /* (non-Javadoc)
- * @see org.openecomp.portalsdk.core.controller.RestrictedBaseController#setViewName(java.lang.String)
- */
- public void setViewName(String viewName) {
- this.viewName = viewName;
- }
-
- /**
- * Get services from a&ai.
- *
- * @return ResponseEntity<String> The response entity with the logged in user uuid.
- * @throws IOException Signals that an I/O exception has occurred.
- * @throws InterruptedException the interrupted exception
- */
- @RequestMapping(value = {"/getuserID"}, method = RequestMethod.GET)
- public ResponseEntity<String> getUserID(HttpServletRequest request) throws IOException, InterruptedException {
-
- String userId = "";
- HttpSession session = request.getSession();
- if (session != null) {
- User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
- if (user != null) {
- //userId = user.getHrid();
- userId = user.getLoginId();
- if (userId == null)
- userId = user.getOrgUserId();
- }
- }
-
- return new ResponseEntity<String>(userId, HttpStatus.OK);
- }
-
- /**
- * Get services from a&ai.
- *
- * @return ResponseEntity<String> The response entity
- * @throws IOException Signals that an I/O exception has occurred.
- * @throws InterruptedException the interrupted exception
- */
- @RequestMapping(value = "/aai_get_services", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public ResponseEntity<String> doGetServices(HttpServletRequest request) throws IOException, InterruptedException {
-
- RoleValidator roleValidator = new RoleValidator(new RoleProvider().getUserRoles(request));
-
- AaiResponse subscriberList = aaiService.getServices(roleValidator);
- ResponseEntity<String> responseEntity = aaiResponseToResponseEntity( subscriberList);
-
- return responseEntity;
- }
-
-
-
- private ResponseEntity<String> aaiResponseToResponseEntity( AaiResponse aaiResponseData)
- throws IOException, JsonGenerationException, JsonMappingException {
- ResponseEntity<String> responseEntity;
- ObjectMapper objectMapper = new ObjectMapper();
- if (aaiResponseData.getHttpCode() == 200) {
- responseEntity = new ResponseEntity<String>(objectMapper.writeValueAsString(aaiResponseData.getT()), HttpStatus.OK);
- } else {
- responseEntity = new ResponseEntity<String>(aaiResponseData.getErrorMessage(), HttpStatus.valueOf(aaiResponseData.getHttpCode()));
- }
- return responseEntity;
- }
-
- /**
- * Lookup single service instance in a&ai. Get the service-subscription and customer, too, i guess?
- *
- * @param serviceInstanceId the service instance Id
- * @return ResponseEntity The response entity
- * @throws IOException Signals that an I/O exception has occurred.
- * @throws InterruptedException the interrupted exception
- */
- @RequestMapping(value = "/aai_get_service_instance/{service-instance-id}/{service-instance-type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public ResponseEntity<String> doGetServiceInstance(@PathVariable("service-instance-id") String serviceInstanceId, @PathVariable("service-instance-type") String serviceInstanceType) throws IOException, InterruptedException {
- File certiPath = GetCertificatesPath();
- Response resp = null;
-
- if (serviceInstanceType.equalsIgnoreCase("Service Instance Id")) {
- resp = doAaiGet(certiPath.getAbsolutePath(),
- "search/nodes-query?search-node-type=service-instance&filter=service-instance-id:EQUALS:"
- + serviceInstanceId, false);
- } else {
- resp = doAaiGet(certiPath.getAbsolutePath(),
- "search/nodes-query?search-node-type=service-instance&filter=service-instance-name:EQUALS:"
- + serviceInstanceId, false);
- }
- return convertResponseToResponseEntity(resp);
- }
-
- /**
- * Get services from a&ai.
- *
- * @param globalCustomerId the global customer id
- * @param serviceSubscriptionId the service subscription id
- * @return ResponseEntity The response entity
- * @throws IOException Signals that an I/O exception has occurred.
- * @throws InterruptedException the interrupted exception
- */
- @RequestMapping(value = "/aai_get_service_subscription/{global-customer-id}/{service-subscription-id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public ResponseEntity<String> doGetServices(@PathVariable("global-customer-id") String globalCustomerId,
- @PathVariable("service-subscription-id") String serviceSubscriptionId) throws IOException, InterruptedException {
- File certiPath = GetCertificatesPath();
- Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + globalCustomerId
- + "/service-subscriptions/service-subscription/" + serviceSubscriptionId + "?depth=0", false);
- return convertResponseToResponseEntity(resp);
- }
-
- /**
- * Obtain the subscriber list from a&ai.
- *
- * @param fullSet the full set
- * @return ResponseEntity The response entity
- * @throws IOException Signals that an I/O exception has occurred.
- * @throws InterruptedException the interrupted exception
- */
- @RequestMapping(value = "/aai_get_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public ResponseEntity<String> doGetSubscriberList(HttpServletRequest request,@DefaultValue("n") @QueryParam("fullSet") String fullSet) throws IOException, InterruptedException {
- return getFullSubscriberList(request);
- }
-
- /**
- * Obtain the Target Prov Status from the System.Properties file.
- *
- * @return ResponseEntity The response entity
- * @throws IOException Signals that an I/O exception has occurred.
- * @throws InterruptedException the interrupted exception
- */
- @RequestMapping(value = "/get_system_prop_vnf_prov_status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public ResponseEntity<String> getTargetProvStatus() throws IOException, InterruptedException {
- String p = SystemProperties.getProperty("aai.vnf.provstatus");
- return new ResponseEntity<String>(p, HttpStatus.OK);
- }
-
- /**
- * Obtain the full subscriber list from a&ai.
- * <p>
- * g @return ResponseEntity The response entity
- *
- * @throws IOException Signals that an I/O exception has occurred.
- * @throws InterruptedException the interrupted exception
- */
- @RequestMapping(value = "/aai_get_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public ResponseEntity<String> getFullSubscriberList(HttpServletRequest request) throws IOException, InterruptedException {
- ObjectMapper objectMapper = new ObjectMapper();
- ResponseEntity<String> responseEntity;
- RoleValidator roleValidator = new RoleValidator(new RoleProvider().getUserRoles(request));
- SubscriberFilteredResults subscriberList = aaiService.getFullSubscriberList(roleValidator);
- if (subscriberList.getHttpCode() == 200) {
- responseEntity = new ResponseEntity<String>(objectMapper.writeValueAsString(subscriberList.getSubscriberList()), HttpStatus.OK);
- } else {
- responseEntity = new ResponseEntity<String>(subscriberList.getErrorMessage(), HttpStatus.valueOf(subscriberList.getHttpCode()));
- }
-
-
- return responseEntity;
- }
-
- /**
- * Refresh the subscriber list from a&ai.
- *
- * @return ResponseEntity The response entity
- * @throws IOException Signals that an I/O exception has occurred.
- */
- @RequestMapping(value = "/aai_refresh_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public ResponseEntity<String> doRefreshSubscriberList() throws IOException {
- Response resp = getSubscribers(false);
- return convertResponseToResponseEntity(resp);
- }
-
- /**
- * Refresh the full subscriber list from a&ai.
- *
- * @return ResponseEntity The response entity
- * @throws IOException Signals that an I/O exception has occurred.
- */
- @RequestMapping(value = "/aai_refresh_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public ResponseEntity<String> doRefreshFullSubscriberList() throws IOException {
- Response resp = getSubscribers(false);
- return convertResponseToResponseEntity(resp);
- }
-
- /**
- * Get subscriber details from a&ai.
- *
- * @param subscriberId the subscriber id
- * @return ResponseEntity The response entity
- */
- @RequestMapping(value = "/aai_sub_details/{subscriberId}", method = RequestMethod.GET)
- public ResponseEntity<String> GetSubscriberDetails(HttpServletRequest request,@PathVariable("subscriberId") String subscriberId) throws IOException {
- ObjectMapper objectMapper = new ObjectMapper();
- ResponseEntity responseEntity;
- List<Role> roles = new RoleProvider().getUserRoles(request);
- RoleValidator roleValidator = new RoleValidator(roles);
- AaiResponse<SubscriberData> subscriberData = aaiService.getSubscriberData(subscriberId,roleValidator);
- String httpMessage = subscriberData.getT() != null ?
- objectMapper.writeValueAsString(subscriberData.getT()) :
- subscriberData.getErrorMessage();
-
- responseEntity = new ResponseEntity<String>(httpMessage, HttpStatus.valueOf(subscriberData.getHttpCode()));
- return responseEntity;
- }
-
- /**
- * Issue a named query to a&ai.
- *
- * @param namedQueryId the named query id
- * @param globalCustomerId the global customer id
- * @param serviceType the service type
- * @param serviceInstance the service instance
- * @return ResponseEntity The response entity
- */
- @RequestMapping(value = "/aai_sub_viewedit/{namedQueryId}/{globalCustomerId}/{serviceType}/{serviceInstance}", method = RequestMethod.GET)
- public ResponseEntity<String> viewEditGetComponentList(
- @PathVariable("namedQueryId") String namedQueryId,
- @PathVariable("globalCustomerId") String globalCustomerId,
- @PathVariable("serviceType") String serviceType,
- @PathVariable("serviceInstance") String serviceInstance) {
-
- String componentListPayload = getComponentListPutPayload(namedQueryId, globalCustomerId, serviceType, serviceInstance);
- File certiPath = GetCertificatesPath();
-
- Response resp = doAaiPost(certiPath.getAbsolutePath(), "search/named-query", componentListPayload, false);
- return convertResponseToResponseEntity(resp);
- }
-
-
- // @RequestMapping(value="/aai_get_tenants/{global-customer-id}", method = RequestMethod.GET)
- // public ResponseEntity<String> viewEditGetComponentList(
- // @PathVariable("global-customer-id") String globalCustomerId) {
- // return new ResponseEntity<String>(getTenants(globalCustomerId), HttpStatus.OK);
- // }
-
- /**
- * Issue a named query to a&ai.
- *
- * @param namedQueryId the named query id
- * @param globalCustomerId the global customer id
- * @param serviceType the service type
- * @return ResponseEntity The response entity
- */
- @RequestMapping(value = "/aai_get_models_by_service_type/{namedQueryId}/{globalCustomerId}/{serviceType}", method = RequestMethod.GET)
- public ResponseEntity<String> viewEditGetComponentList(
- @PathVariable("namedQueryId") String namedQueryId,
- @PathVariable("globalCustomerId") String globalCustomerId,
- @PathVariable("serviceType") String serviceType) {
-
- String componentListPayload = getModelsByServiceTypePayload(namedQueryId, globalCustomerId, serviceType);
- File certiPath = GetCertificatesPath();
-
- Response resp = doAaiPost(certiPath.getAbsolutePath(), "search/named-query", componentListPayload, false);
- return convertResponseToResponseEntity(resp);
- }
-
- /**
- * Parses the for tenants.
- *
- * @param resp the resp
- * @return the string
- */
- private String parseForTenants(String resp) {
- String tenantList = "";
-
- try {
- JSONParser jsonParser = new JSONParser();
-
- JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
-
- return parseCustomerObjectForTenants(jsonObject);
- } catch (Exception ex) {
-
- }
-
- return tenantList;
- }
-
- /**
- * Parses the for tenants by service subscription.
- *
- * @param resp the resp
- * @return the string
- */
- private String parseForTenantsByServiceSubscription(String resp) {
- String tenantList = "";
-
- try {
- JSONParser jsonParser = new JSONParser();
-
- JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
-
- return parseServiceSubscriptionObjectForTenants(jsonObject);
- } catch (Exception ex) {
-
- }
-
- return tenantList;
- }
-
- /**
- * Obtain tenants for a given service type.
- *
- * @param globalCustomerId the global customer id
- * @param serviceType the service type
- * @return ResponseEntity The response entity
- */
- @RequestMapping(value = "/aai_get_tenants/{global-customer-id}/{service-type}", method = RequestMethod.GET)
- public ResponseEntity<String> viewEditGetTenantsFromServiceType(HttpServletRequest request,
- @PathVariable("global-customer-id") String globalCustomerId, @PathVariable("service-type") String serviceType) {
-
- ResponseEntity responseEntity;
- try {
- ObjectMapper objectMapper = new ObjectMapper();
- List<Role> roles = new RoleProvider().getUserRoles(request);
- RoleValidator roleValidator = new RoleValidator(roles);
- AaiResponse<GetTenantsResponse[]> response = aaiService.getTenants(globalCustomerId, serviceType, roleValidator);
- if (response.getHttpCode() == 200) {
- responseEntity = new ResponseEntity<String>(objectMapper.writeValueAsString(response.getT()), HttpStatus.OK);
- } else {
- responseEntity = new ResponseEntity<String>(response.getErrorMessage(), HttpStatus.valueOf(response.getHttpCode()));
- }
- }
- catch (Exception e){
- responseEntity = new ResponseEntity<String>("Unable to proccess getTenants reponse", HttpStatus.INTERNAL_SERVER_ERROR);
- }
- return responseEntity;
- }
-
-
- private ResponseEntity<String> convertResponseToResponseEntity(Response resp) {
- ResponseEntity<String> respEnt;
- ObjectMapper objectMapper = new ObjectMapper();
- if (resp == null) {
- respEnt = new ResponseEntity<String>("Failed to fetch data from A&AI, check server logs for details.", HttpStatus.INTERNAL_SERVER_ERROR);
- } else {
- respEnt = new ResponseEntity<String>(resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus()));
- }
- return respEnt;
- }
-
- /**
- * Gets the tenants.
- *
- * @param globalCustomerId the global customer id
- * @return the tenants
- */
- private ResponseEntity<String> getTenants(String globalCustomerId) {
- File certiPath = GetCertificatesPath();
- Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + globalCustomerId, false);
-
- ResponseEntity<String> respEnt;
- if (resp.getStatus() >= 200 && resp.getStatus() <= 299) {
- respEnt = new ResponseEntity<String>(parseForTenants((String) resp.readEntity(String.class)), HttpStatus.OK);
- } else {
- respEnt = new ResponseEntity<String>((String) resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus()));
- }
- return respEnt;
-
- }
-
- /**
- * Gets the tenants from service type.
- *
- * @param globalCustomerId the global customer id
- * @param serviceType the service type
- * @return the tenants from service type
- */
- private ResponseEntity<String> getTenantsFromServiceType(String globalCustomerId, String serviceType) {
-
-
-
-
-
- File certiPath = GetCertificatesPath();
- String url = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType;
-
- Response resp = doAaiGet(certiPath.getAbsolutePath(), url, false);
-
- ResponseEntity<String> respEnt;
- if (resp.getStatus() >= 200 && resp.getStatus() <= 299) {
- respEnt = new ResponseEntity<String>(parseForTenantsByServiceSubscription((String) resp.readEntity(String.class)), HttpStatus.OK);
- } else {
- respEnt = new ResponseEntity<String>((String) resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus()));
- }
- return respEnt;
-
- }
-
- /**
- * Gets the services.
- *
- * @return the services
- */
- private Response getServices() {
- File certiPath = GetCertificatesPath();
- Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/services", false);
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getServices() resp=" + resp.getStatusInfo());
-
- //model.put("aai_get_services", resp);
- return resp;
- }
-
- /**
- * Gets the subscribers.
- *
- * @param isFullSet the is full set
- * @return the subscribers
- */
- private Response getSubscribers(boolean isFullSet) {
-
- File certiPath = GetCertificatesPath();
- String depth = "0";
-
- Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers?subscriber-type=INFRA&depth=" + depth, false);
- if (resp != null) {
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString());
- }
- return resp;
- }
-
- /**
- * Gets the subscriber details.
- *
- * @param subscriberId the subscriber id
- * @return the subscriber details
- */
- private Response getSubscriberDetails(String subscriberId) {
- File certiPath = GetCertificatesPath();
- Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId + "?depth=2", false);
- //String resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId, false);
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscriberDetails() resp=" + resp.getStatusInfo().toString());
- return resp;
- }
-
- /**
- * Gets the certificates path.
- *
- * @return the file
- */
- private File GetCertificatesPath() {
- if (servletContext != null)
- return new File(servletContext.getRealPath("/WEB-INF/cert/"));
- return null;
- }
-
- /**
- * Send a GET request to a&ai.
- *
- * @param certiPath the certi path
- * @param uri the uri
- * @param xml the xml
- * @return String The response
- */
- protected Response doAaiGet(String certiPath, String uri, boolean xml) {
- String methodName = "getSubscriberList";
- String transId = UUID.randomUUID().toString();
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
-
- Response resp = null;
- try {
-
- AAIRestInterface restContrller = new AAIRestInterface(certiPath);
- resp = restContrller.RestGet(fromAppId, transId, uri, xml);
-
- } catch (WebApplicationException e) {
- final String message = ((BadRequestException) e).getResponse().readEntity(String.class);
- logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);
- } catch (Exception e) {
- logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- }
-
- return resp;
- }
-
- /**
- * Send a POST request to a&ai.
- *
- * @param certiPath the certi path
- * @param uri the uri
- * @param payload the payload
- * @param xml the xml
- * @return String The response
- */
- protected Response doAaiPost(String certiPath, String uri, String payload, boolean xml) {
- String methodName = "getSubscriberList";
- String transId = UUID.randomUUID().toString();
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
-
- Response resp = null;
- try {
-
- AAIRestInterface restContrller = new AAIRestInterface(certiPath);
- resp = restContrller.RestPost(fromAppId, transId, uri, payload, xml);
-
- } catch (Exception e) {
- logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- }
-
- return resp;
- }
-
- /**
- * Gets the component list put payload.
- *
- * @param namedQueryId the named query id
- * @param globalCustomerId the global customer id
- * @param serviceType the service type
- * @param serviceInstance the service instance
- * @return the component list put payload
- */
- private String getComponentListPutPayload(String namedQueryId, String globalCustomerId, String serviceType, String serviceInstance) {
- return
- " {" +
- " \"instance-filters\": {" +
- " \"instance-filter\": [" +
- " {" +
- " \"customer\": {" +
- " \"global-customer-id\": \"" + globalCustomerId + "\"" +
- " }," +
- " \"service-instance\": {" +
- " \"service-instance-id\": \"" + serviceInstance + "\"" +
- " }," +
- " \"service-subscription\": {" +
- " \"service-type\": \"" + serviceType + "\"" +
- " }" +
- " }" +
- " ]" +
- " }," +
- " \"query-parameters\": {" +
- " \"named-query\": {" +
- " \"named-query-uuid\": \"" + namedQueryId + "\"" +
- " }" +
- " }" +
- "}";
-
- }
-
- private String getModelsByServiceTypePayload(String namedQueryId, String globalCustomerId, String serviceType) {
- // TODO Auto-generated method stub
- return " {" +
- " \"instance-filters\": {" +
- " \"instance-filter\": [" +
- " {" +
- " \"customer\": {" +
- " \"global-customer-id\": \"" + globalCustomerId + "\"" +
- " }," +
- " \"service-subscription\": {" +
- " \"service-type\": \"" + serviceType + "\"" +
- " }" +
- " }" +
- " ]" +
- " }," +
- " \"query-parameters\": {" +
- " \"named-query\": {" +
- " \"named-query-uuid\": \"" + namedQueryId + "\"" +
- " }" +
- " }" +
- "}";
-
- }
+ /**
+ * Retrieve the service subscription from the jsonObject.
+ *
+ * @param jsonObject the json object
+ * @return String
+ */
+ public static String parseServiceSubscriptionObjectForTenants(JSONObject jsonObject) {
+
+ JSONArray tenantArray = new JSONArray();
+ boolean bconvert = false;
+
+ try {
+ JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list");
+ if (relationShipListsObj != null) {
+ JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");
+ if (rShipArray != null) {
+ Iterator i1 = rShipArray.iterator();
+
+ while (i1.hasNext()) {
+
+ JSONObject inner1Obj = (JSONObject) i1.next();
+
+ if (inner1Obj == null)
+ continue;
+
+ String relatedTo = checkForNull((String) inner1Obj.get("related-to"));
+ if (relatedTo.equalsIgnoreCase("tenant")) {
+ JSONObject tenantNewObj = new JSONObject();
+
+ String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
+ tenantNewObj.put("link", relatedLink);
+
+ JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
+ if (rDataArray != null) {
+ Iterator i2 = rDataArray.iterator();
+
+ while (i2.hasNext()) {
+ JSONObject inner2Obj = (JSONObject) i2.next();
+
+ if (inner2Obj == null)
+ continue;
+
+ String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));
+ String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));
+ if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) {
+ tenantNewObj.put("cloudOwner", rShipVal);
+ } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) {
+ tenantNewObj.put("cloudRegionID", rShipVal);
+ }
+
+ if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) {
+ tenantNewObj.put("tenantID", rShipVal);
+ }
+ }
+ }
+
+ JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
+ if (relatedTPropArray != null) {
+ Iterator i3 = relatedTPropArray.iterator();
+
+ while (i3.hasNext()) {
+ JSONObject inner3Obj = (JSONObject) i3.next();
+
+ if (inner3Obj == null)
+ continue;
+
+ String propKey = checkForNull((String) inner3Obj.get("property-key"));
+ String propVal = checkForNull((String) inner3Obj.get("property-value"));
+ if (propKey.equalsIgnoreCase("tenant.tenant-name")) {
+ tenantNewObj.put("tenantName", propVal);
+ }
+ }
+ }
+ bconvert = true;
+ tenantArray.add(tenantNewObj);
+ }
+ }
+
+ }
+ }
+ } catch (NullPointerException ex) {
+
+
+ }
+
+ if (bconvert)
+ return tenantArray.toJSONString();
+ else
+ return "";
+
+ }
+
+ /**
+ * Check for null.
+ *
+ * @param local the local
+ * @return the string
+ */
+ private static String checkForNull(String local) {
+ if (local != null)
+ return local;
+ else
+ return "";
+
+ }
+
+ /**
+ * Welcome method.
+ *
+ * @param request the request
+ * @return ModelAndView The view
+ */
+ @RequestMapping(value = {"/subscriberSearch"}, method = RequestMethod.GET)
+ public ModelAndView welcome(HttpServletRequest request) {
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== AaiController welcome start");
+ return new ModelAndView(getViewName());
+ }
+
+ @RequestMapping(value = {"/aai_get_aic_zones"}, method = RequestMethod.GET)
+ public ResponseEntity<String> getAicZones(HttpServletRequest request) throws JsonGenerationException, JsonMappingException, IOException {
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== getAicZones controller start");
+ AaiResponse response = aaiService.getAaiZones();
+ return aaiResponseToResponseEntity(response);
+ }
+
+ @RequestMapping(value = {"/aai_get_aic_zone_for_pnf/{globalCustomerId}/{serviceType}/{serviceId}"}, method = RequestMethod.GET)
+ public ResponseEntity<String> getAicZoneForPnf(@PathVariable("globalCustomerId") String globalCustomerId ,@PathVariable("serviceType") String serviceType , @PathVariable("serviceId") String serviceId ,HttpServletRequest request) throws JsonGenerationException, JsonMappingException, IOException {
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== getAicZoneForPnf controller start");
+ AaiResponse response = aaiService.getAicZoneForPnf(globalCustomerId , serviceType , serviceId);
+ return aaiResponseToResponseEntity(response);
+ }
+
+ /* (non-Javadoc)
+ * @see org.openecomp.portalsdk.core.controller.RestrictedBaseController#getViewName()
+ */
+ public String getViewName() {
+ return viewName;
+ }
+
+ /* (non-Javadoc)
+ * @see org.openecomp.portalsdk.core.controller.RestrictedBaseController#setViewName(java.lang.String)
+ */
+ public void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+ /**
+ * Get services from a&ai.
+ *
+ * @return ResponseEntity<String> The response entity with the logged in user uuid.
+ * @throws IOException Signals that an I/O exception has occurred.
+ * @throws InterruptedException the interrupted exception
+ */
+ @RequestMapping(value = {"/getuserID"}, method = RequestMethod.GET)
+ public ResponseEntity<String> getUserID(HttpServletRequest request) throws IOException, InterruptedException {
+
+ String userId = "";
+ HttpSession session = request.getSession();
+ if (session != null) {
+ User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
+ if (user != null) {
+ //userId = user.getHrid();
+ userId = user.getLoginId();
+ if (userId == null)
+ userId = user.getOrgUserId();
+ }
+ }
+
+ return new ResponseEntity<String>(userId, HttpStatus.OK);
+ }
+
+ /**
+ * Get services from a&ai.
+ *
+ * @return ResponseEntity<String> The response entity
+ * @throws IOException Signals that an I/O exception has occurred.
+ * @throws InterruptedException the interrupted exception
+ */
+ @RequestMapping(value = "/aai_get_services", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity<String> doGetServices(HttpServletRequest request) throws IOException, InterruptedException {
+
+ RoleValidator roleValidator = new RoleValidator(new RoleProvider().getUserRoles(request));
+
+ AaiResponse subscriberList = aaiService.getServices(roleValidator);
+ ResponseEntity<String> responseEntity = aaiResponseToResponseEntity(subscriberList);
+
+ return responseEntity;
+ }
+
+
+ @RequestMapping(value = {"/aai_get_version_by_invariant_id"}, method = RequestMethod.POST)
+ public ResponseEntity<String> getVersionByInvariantId(HttpServletRequest request, @RequestBody VersionByInvariantIdsRequest versions) throws IOException {
+ ResponseEntity<String> responseEntity;
+ ObjectMapper objectMapper = new ObjectMapper();
+
+ Response result = aaiService.getVersionByInvariantId(versions.versions);
+
+ return new ResponseEntity<String>(result.readEntity(String.class), HttpStatus.OK);
+ }
+
+
+ private ResponseEntity<String> aaiResponseToResponseEntity(AaiResponse aaiResponseData)
+ throws IOException, JsonGenerationException, JsonMappingException {
+ ResponseEntity<String> responseEntity;
+ ObjectMapper objectMapper = new ObjectMapper();
+ if (aaiResponseData.getHttpCode() == 200) {
+ responseEntity = new ResponseEntity<String>(objectMapper.writeValueAsString(aaiResponseData.getT()), HttpStatus.OK);
+ } else {
+ responseEntity = new ResponseEntity<String>(aaiResponseData.getErrorMessage(), HttpStatus.valueOf(aaiResponseData.getHttpCode()));
+ }
+ return responseEntity;
+ }
+
+ /**
+ * Lookup single service instance in a&ai. Get the service-subscription and customer, too, i guess?
+ *
+ * @param serviceInstanceId the service instance Id
+ * @return ResponseEntity The response entity
+ * @throws IOException Signals that an I/O exception has occurred.
+ * @throws InterruptedException the interrupted exception
+ */
+ @RequestMapping(value = "/aai_get_service_instance/{service-instance-id}/{service-instance-type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity<String> doGetServiceInstance(@PathVariable("service-instance-id") String serviceInstanceId, @PathVariable("service-instance-type") String serviceInstanceType) throws IOException, InterruptedException {
+ File certiPath = GetCertificatesPath();
+ Response resp = null;
+
+ if (serviceInstanceType.equalsIgnoreCase("Service Instance Id")) {
+ resp = doAaiGet(certiPath.getAbsolutePath(),
+ "search/nodes-query?search-node-type=service-instance&filter=service-instance-id:EQUALS:"
+ + serviceInstanceId, false);
+ } else {
+ resp = doAaiGet(certiPath.getAbsolutePath(),
+ "search/nodes-query?search-node-type=service-instance&filter=service-instance-name:EQUALS:"
+ + serviceInstanceId, false);
+ }
+ return convertResponseToResponseEntity(resp);
+ }
+
+ /**
+ * Get services from a&ai.
+ *
+ * @param globalCustomerId the global customer id
+ * @param serviceSubscriptionId the service subscription id
+ * @return ResponseEntity The response entity
+ * @throws IOException Signals that an I/O exception has occurred.
+ * @throws InterruptedException the interrupted exception
+ */
+ @RequestMapping(value = "/aai_get_service_subscription/{global-customer-id}/{service-subscription-id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity<String> doGetServices(@PathVariable("global-customer-id") String globalCustomerId,
+ @PathVariable("service-subscription-id") String serviceSubscriptionId) throws IOException, InterruptedException {
+ File certiPath = GetCertificatesPath();
+ Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + globalCustomerId
+ + "/service-subscriptions/service-subscription/" + serviceSubscriptionId + "?depth=0", false);
+ return convertResponseToResponseEntity(resp);
+ }
+
+ /**
+ * Obtain the subscriber list from a&ai.
+ *
+ * @param fullSet the full set
+ * @return ResponseEntity The response entity
+ * @throws IOException Signals that an I/O exception has occurred.
+ * @throws InterruptedException the interrupted exception
+ */
+ @RequestMapping(value = "/aai_get_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity<String> doGetSubscriberList(HttpServletRequest request, @DefaultValue("n") @QueryParam("fullSet") String fullSet) throws IOException, InterruptedException {
+ return getFullSubscriberList(request);
+ }
+
+ /**
+ * Obtain the Target Prov Status from the System.Properties file.
+ *
+ * @return ResponseEntity The response entity
+ * @throws IOException Signals that an I/O exception has occurred.
+ * @throws InterruptedException the interrupted exception
+ */
+ @RequestMapping(value = "/get_system_prop_vnf_prov_status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity<String> getTargetProvStatus() throws IOException, InterruptedException {
+ String p = SystemProperties.getProperty("aai.vnf.provstatus");
+ return new ResponseEntity<String>(p, HttpStatus.OK);
+ }
+
+ /**
+ * Obtain the full subscriber list from a&ai.
+ * <p>
+ * g @return ResponseEntity The response entity
+ *
+ * @throws IOException Signals that an I/O exception has occurred.
+ * @throws InterruptedException the interrupted exception
+ */
+ @RequestMapping(value = "/aai_get_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity<String> getFullSubscriberList(HttpServletRequest request) throws IOException, InterruptedException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ ResponseEntity<String> responseEntity;
+ RoleValidator roleValidator = new RoleValidator(new RoleProvider().getUserRoles(request));
+ SubscriberFilteredResults subscriberList = aaiService.getFullSubscriberList(roleValidator);
+ if (subscriberList.getHttpCode() == 200) {
+ responseEntity = new ResponseEntity<String>(objectMapper.writeValueAsString(subscriberList.getSubscriberList()), HttpStatus.OK);
+ } else {
+ responseEntity = new ResponseEntity<String>(subscriberList.getErrorMessage(), HttpStatus.valueOf(subscriberList.getHttpCode()));
+ }
+
+
+ return responseEntity;
+ }
+
+
+ @RequestMapping(value = "/get_vnf_data_by_globalid_and_service_type/{globalCustomerId}/{serviceType}",
+ method = RequestMethod.GET,
+ produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity<String> getVnfDataByGlobalIdAndServiceType(HttpServletRequest request,
+ @PathVariable("globalCustomerId") String globalCustomerId,
+ @PathVariable("serviceType") String serviceType) throws IOException {
+
+ Response resp = aaiService.getVNFData(globalCustomerId, serviceType);
+ return convertResponseToResponseEntity(resp);
+ }
+
+
+ /**
+ * Refresh the subscriber list from a&ai.
+ *
+ * @return ResponseEntity The response entity
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ @RequestMapping(value = "/aai_refresh_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity<String> doRefreshSubscriberList() throws IOException {
+ Response resp = getSubscribers(false);
+ return convertResponseToResponseEntity(resp);
+ }
+
+ /**
+ * Refresh the full subscriber list from a&ai.
+ *
+ * @return ResponseEntity The response entity
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ @RequestMapping(value = "/aai_refresh_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity<String> doRefreshFullSubscriberList() throws IOException {
+ Response resp = getSubscribers(false);
+ return convertResponseToResponseEntity(resp);
+ }
+
+ /**
+ * Get subscriber details from a&ai.
+ *
+ * @param subscriberId the subscriber id
+ * @return ResponseEntity The response entity
+ */
+ @RequestMapping(value = "/aai_sub_details/{subscriberId}", method = RequestMethod.GET)
+ public ResponseEntity<String> GetSubscriberDetails(HttpServletRequest request, @PathVariable("subscriberId") String subscriberId) throws IOException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ ResponseEntity responseEntity;
+ List<Role> roles = new RoleProvider().getUserRoles(request);
+ RoleValidator roleValidator = new RoleValidator(roles);
+ AaiResponse<SubscriberData> subscriberData = aaiService.getSubscriberData(subscriberId, roleValidator);
+ String httpMessage = subscriberData.getT() != null ?
+ objectMapper.writeValueAsString(subscriberData.getT()) :
+ subscriberData.getErrorMessage();
+
+ responseEntity = new ResponseEntity<String>(httpMessage, HttpStatus.valueOf(subscriberData.getHttpCode()));
+ return responseEntity;
+ }
+
+ /**
+ * Issue a named query to a&ai.
+ *
+ * @param namedQueryId the named query id
+ * @param globalCustomerId the global customer id
+ * @param serviceType the service type
+ * @param serviceInstance the service instance
+ * @return ResponseEntity The response entity
+ */
+ @RequestMapping(value = "/aai_sub_viewedit/{namedQueryId}/{globalCustomerId}/{serviceType}/{serviceInstance}", method = RequestMethod.GET)
+ public ResponseEntity<String> viewEditGetComponentList(
+ @PathVariable("namedQueryId") String namedQueryId,
+ @PathVariable("globalCustomerId") String globalCustomerId,
+ @PathVariable("serviceType") String serviceType,
+ @PathVariable("serviceInstance") String serviceInstance) {
+
+ String componentListPayload = getComponentListPutPayload(namedQueryId, globalCustomerId, serviceType, serviceInstance);
+ File certiPath = GetCertificatesPath();
+
+ Response resp = doAaiPost(certiPath.getAbsolutePath(), "search/named-query", componentListPayload, false);
+ return convertResponseToResponseEntity(resp);
+ }
+
+
+ @RequestMapping(value = "/aai_get_vnf_data/{globalCustomerId}/{serviceType}/{serviceInstanceId}", method = RequestMethod.GET)
+ public AaiResponse<String> getVnfData(
+ @PathVariable("globalCustomerId") String globalCustomerId,
+ @PathVariable("serviceType") String serviceType,
+ @PathVariable("serviceInstanceId") String serviceInstanceId) {
+
+ return aaiService.getVNFData(globalCustomerId, serviceType, serviceInstanceId);
+
+ }
+
+
+ // @RequestMapping(value="/aai_get_tenants/{global-customer-id}", method = RequestMethod.GET)
+ // public ResponseEntity<String> viewEditGetComponentList(
+ // @PathVariable("global-customer-id") String globalCustomerId) {
+ // return new ResponseEntity<String>(getTenants(globalCustomerId), HttpStatus.OK);
+ // }
+
+ /**
+ * Issue a named query to a&ai.
+ *
+ * @param namedQueryId the named query id
+ * @param globalCustomerId the global customer id
+ * @param serviceType the service type
+ * @return ResponseEntity The response entity
+ */
+ @RequestMapping(value = "/aai_get_models_by_service_type/{namedQueryId}/{globalCustomerId}/{serviceType}", method = RequestMethod.GET)
+ public ResponseEntity<String> viewEditGetComponentList(
+ @PathVariable("namedQueryId") String namedQueryId,
+ @PathVariable("globalCustomerId") String globalCustomerId,
+ @PathVariable("serviceType") String serviceType) {
+
+ String componentListPayload = getModelsByServiceTypePayload(namedQueryId, globalCustomerId, serviceType);
+ File certiPath = GetCertificatesPath();
+
+ Response resp = doAaiPost(certiPath.getAbsolutePath(), "search/named-query", componentListPayload, false);
+ return convertResponseToResponseEntity(resp);
+ }
+
+ /**
+ * Parses the for tenants.
+ *
+ * @param resp the resp
+ * @return the string
+ */
+ private String parseForTenants(String resp) {
+ String tenantList = "";
+
+ try {
+ JSONParser jsonParser = new JSONParser();
+
+ JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
+
+ return parseCustomerObjectForTenants(jsonObject);
+ } catch (Exception ex) {
+
+ }
+
+ return tenantList;
+ }
+
+ /**
+ * Parses the for tenants by service subscription.
+ *
+ * @param resp the resp
+ * @return the string
+ */
+ private String parseForTenantsByServiceSubscription(String resp) {
+ String tenantList = "";
+
+ try {
+ JSONParser jsonParser = new JSONParser();
+
+ JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
+
+ return parseServiceSubscriptionObjectForTenants(jsonObject);
+ } catch (Exception ex) {
+
+ }
+
+ return tenantList;
+ }
+
+ /**
+ * Obtain tenants for a given service type.
+ *
+ * @param globalCustomerId the global customer id
+ * @param serviceType the service type
+ * @return ResponseEntity The response entity
+ */
+ @RequestMapping(value = "/aai_get_tenants/{global-customer-id}/{service-type}", method = RequestMethod.GET)
+ public ResponseEntity<String> viewEditGetTenantsFromServiceType(HttpServletRequest request,
+ @PathVariable("global-customer-id") String globalCustomerId, @PathVariable("service-type") String serviceType) {
+
+ ResponseEntity responseEntity;
+ try {
+ ObjectMapper objectMapper = new ObjectMapper();
+ List<Role> roles = new RoleProvider().getUserRoles(request);
+ RoleValidator roleValidator = new RoleValidator(roles);
+ AaiResponse<GetTenantsResponse[]> response = aaiService.getTenants(globalCustomerId, serviceType, roleValidator);
+ if (response.getHttpCode() == 200) {
+ responseEntity = new ResponseEntity<String>(objectMapper.writeValueAsString(response.getT()), HttpStatus.OK);
+ } else {
+ responseEntity = new ResponseEntity<String>(response.getErrorMessage(), HttpStatus.valueOf(response.getHttpCode()));
+ }
+ } catch (Exception e) {
+ responseEntity = new ResponseEntity<String>("Unable to proccess getTenants reponse", HttpStatus.INTERNAL_SERVER_ERROR);
+ }
+ return responseEntity;
+ }
+
+
+ private ResponseEntity<String> convertResponseToResponseEntity(Response resp) {
+ ResponseEntity<String> respEnt;
+ ObjectMapper objectMapper = new ObjectMapper();
+ if (resp == null) {
+ respEnt = new ResponseEntity<String>("Failed to fetch data from A&AI, check server logs for details.", HttpStatus.INTERNAL_SERVER_ERROR);
+ } else {
+ respEnt = new ResponseEntity<String>(resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus()));
+ }
+ return respEnt;
+ }
+
+ /**
+ * Gets the tenants.
+ *
+ * @param globalCustomerId the global customer id
+ * @return the tenants
+ */
+ private ResponseEntity<String> getTenants(String globalCustomerId) {
+ File certiPath = GetCertificatesPath();
+ Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + globalCustomerId, false);
+
+ ResponseEntity<String> respEnt;
+ if (resp.getStatus() >= 200 && resp.getStatus() <= 299) {
+ respEnt = new ResponseEntity<String>(parseForTenants((String) resp.readEntity(String.class)), HttpStatus.OK);
+ } else {
+ respEnt = new ResponseEntity<String>((String) resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus()));
+ }
+ return respEnt;
+
+ }
+
+ /**
+ * Gets the tenants from service type.
+ *
+ * @param globalCustomerId the global customer id
+ * @param serviceType the service type
+ * @return the tenants from service type
+ */
+ private ResponseEntity<String> getTenantsFromServiceType(String globalCustomerId, String serviceType) {
+
+
+ File certiPath = GetCertificatesPath();
+ String url = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType;
+
+ Response resp = doAaiGet(certiPath.getAbsolutePath(), url, false);
+
+ ResponseEntity<String> respEnt;
+ if (resp.getStatus() >= 200 && resp.getStatus() <= 299) {
+ respEnt = new ResponseEntity<String>(parseForTenantsByServiceSubscription((String) resp.readEntity(String.class)), HttpStatus.OK);
+ } else {
+ respEnt = new ResponseEntity<String>((String) resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus()));
+ }
+ return respEnt;
+
+ }
+
+ /**
+ * Gets the services.
+ *
+ * @return the services
+ */
+ private Response getServices() {
+ File certiPath = GetCertificatesPath();
+ Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/services", false);
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getServices() resp=" + resp.getStatusInfo());
+
+ //model.put("aai_get_services", resp);
+ return resp;
+ }
+
+ /**
+ * Gets the subscribers.
+ *
+ * @param isFullSet the is full set
+ * @return the subscribers
+ */
+ private Response getSubscribers(boolean isFullSet) {
+
+ File certiPath = GetCertificatesPath();
+ String depth = "0";
+
+ Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers?subscriber-type=INFRA&depth=" + depth, false);
+ if (resp != null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString());
+ }
+ return resp;
+ }
+
+ /**
+ * Gets the subscriber details.
+ *
+ * @param subscriberId the subscriber id
+ * @return the subscriber details
+ */
+ private Response getSubscriberDetails(String subscriberId) {
+ File certiPath = GetCertificatesPath();
+ Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId + "?depth=2", false);
+ //String resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId, false);
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscriberDetails() resp=" + resp.getStatusInfo().toString());
+ return resp;
+ }
+
+ /**
+ * Gets the certificates path.
+ *
+ * @return the file
+ */
+ private File GetCertificatesPath() {
+ if (servletContext != null)
+ return new File(servletContext.getRealPath("/WEB-INF/cert/"));
+ return null;
+ }
+
+ /**
+ * Send a GET request to a&ai.
+ *
+ * @param certiPath the certi path
+ * @param uri the uri
+ * @param xml the xml
+ * @return String The response
+ */
+ protected Response doAaiGet(String certiPath, String uri, boolean xml) {
+ String methodName = "getSubscriberList";
+ String transId = UUID.randomUUID().toString();
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
+
+ Response resp = null;
+ try {
+
+ AAIRestInterface restContrller = new AAIRestInterface(certiPath);
+ resp = restContrller.RestGet(fromAppId, transId, uri, xml);
+
+ } catch (WebApplicationException e) {
+ final String message = ((BadRequestException) e).getResponse().readEntity(String.class);
+ logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);
+ } catch (Exception e) {
+ logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
+ }
+
+ return resp;
+ }
+
+ /**
+ * Send a POST request to a&ai.
+ *
+ * @param certiPath the certi path
+ * @param uri the uri
+ * @param payload the payload
+ * @param xml the xml
+ * @return String The response
+ */
+ protected Response doAaiPost(String certiPath, String uri, String payload, boolean xml) {
+ String methodName = "getSubscriberList";
+ String transId = UUID.randomUUID().toString();
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
+
+ Response resp = null;
+ try {
+
+ AAIRestInterface restContrller = new AAIRestInterface(certiPath);
+ resp = restContrller.RestPost(fromAppId, transId, uri, payload, xml);
+
+ } catch (Exception e) {
+ logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
+ }
+
+ return resp;
+ }
+
+ /**
+ * Gets the component list put payload.
+ *
+ * @param namedQueryId the named query id
+ * @param globalCustomerId the global customer id
+ * @param serviceType the service type
+ * @param serviceInstance the service instance
+ * @return the component list put payload
+ */
+ private String getComponentListPutPayload(String namedQueryId, String globalCustomerId, String serviceType, String serviceInstance) {
+ return
+ " {" +
+ " \"instance-filters\": {" +
+ " \"instance-filter\": [" +
+ " {" +
+ " \"customer\": {" +
+ " \"global-customer-id\": \"" + globalCustomerId + "\"" +
+ " }," +
+ " \"service-instance\": {" +
+ " \"service-instance-id\": \"" + serviceInstance + "\"" +
+ " }," +
+ " \"service-subscription\": {" +
+ " \"service-type\": \"" + serviceType + "\"" +
+ " }" +
+ " }" +
+ " ]" +
+ " }," +
+ " \"query-parameters\": {" +
+ " \"named-query\": {" +
+ " \"named-query-uuid\": \"" + namedQueryId + "\"" +
+ " }" +
+ " }" +
+ "}";
+
+ }
+
+ private String getModelsByServiceTypePayload(String namedQueryId, String globalCustomerId, String serviceType) {
+ // TODO Auto-generated method stub
+ return " {" +
+ " \"instance-filters\": {" +
+ " \"instance-filter\": [" +
+ " {" +
+ " \"customer\": {" +
+ " \"global-customer-id\": \"" + globalCustomerId + "\"" +
+ " }," +
+ " \"service-subscription\": {" +
+ " \"service-type\": \"" + serviceType + "\"" +
+ " }" +
+ " }" +
+ " ]" +
+ " }," +
+ " \"query-parameters\": {" +
+ " \"named-query\": {" +
+ " \"named-query-uuid\": \"" + namedQueryId + "\"" +
+ " }" +
+ " }" +
+ "}";
+
+ }
}
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/ChangeManagementController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/ChangeManagementController.java new file mode 100644 index 000000000..1af715464 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/ChangeManagementController.java @@ -0,0 +1,71 @@ +package org.openecomp.vid.controller; + +import org.json.simple.JSONArray; +import org.openecomp.portalsdk.core.controller.UnRestrictedBaseController; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.vid.services.ChangeManagementService; +import org.openecomp.vid.services.WorkflowService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import org.openecomp.vid.changeManagement.ChangeManagementRequest; +import org.openecomp.vid.mso.rest.Request; + +import java.io.IOException; +import java.util.Collection; + +import javax.servlet.http.HttpServletRequest; + +/** + * Controller to handle ChangeManagement feature requests. + */ +@RestController +@RequestMapping("change-management") +public class ChangeManagementController extends UnRestrictedBaseController { + private EELFLoggerDelegate logger; + private String fromAppId; + private final WorkflowService workflowService; + private final ChangeManagementService changeManagementService; + + @Autowired + public ChangeManagementController(WorkflowService workflowService, ChangeManagementService changeManagementService) { + this.logger = EELFLoggerDelegate.getLogger(ChangeManagementController.class); + this.fromAppId = "VidChangeManagementController"; + this.workflowService = workflowService; + this.changeManagementService = changeManagementService; + } + + @RequestMapping(value = {"/workflow"}, method = RequestMethod.GET) + public ResponseEntity<Collection<String>> getWorkflow(@RequestParam("vnfs") Collection<String> vnfs) throws IOException, InterruptedException { + Collection<String> result = this.workflowService.getWorkflowsForVNFs(vnfs); + return new ResponseEntity<>(result, HttpStatus.OK); + } + + @RequestMapping(value = {"/mso"}, method = RequestMethod.GET) + public ResponseEntity<Collection<Request>> getMSOChangeManagements() throws IOException, InterruptedException { + Collection<Request> result = this.changeManagementService.getMSOChangeManagements(); + return new ResponseEntity<>(result, HttpStatus.OK); + } + + @RequestMapping(value = "/workflow/{vnfName}", method = RequestMethod.POST) + public ResponseEntity<String> changeManagement(@PathVariable("vnfName") String vnfName, + HttpServletRequest request, + @RequestBody ChangeManagementRequest changeManagmentRequest) + throws Exception { + return this.changeManagementService.doChangeManagement(changeManagmentRequest, vnfName); + } + + + @RequestMapping(value = {"/scheduler"}, method = RequestMethod.GET) + public ResponseEntity<JSONArray> getSchedulerChangeManagements() throws IOException, InterruptedException { + JSONArray result = this.changeManagementService.getSchedulerChangeManagements(); + return new ResponseEntity<>(result, HttpStatus.OK); + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/MsoConfig.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/MsoConfig.java new file mode 100644 index 000000000..e0b59204a --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/MsoConfig.java @@ -0,0 +1,29 @@ +package org.openecomp.vid.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.openecomp.vid.factories.MsoRequestFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + + +@Configuration +public class MsoConfig { + + /** + * Gets the object mapper. + * + * @return the object mapper + */ + @Bean + public ObjectMapper getObjectMapper() { + return new ObjectMapper(); + } + + @Bean + public MsoRequestFactory createRequestDetailsFactory(){ + return new MsoRequestFactory(); + } + + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/MsoController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/MsoController.java index 56fbd4cbd..9a064b000 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/controller/MsoController.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/MsoController.java @@ -21,35 +21,56 @@ package org.openecomp.vid.controller;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.glassfish.jersey.client.ClientResponse;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.vid.model.ExceptionResponse;
-import org.openecomp.vid.mso.*;
-import org.openecomp.vid.mso.rest.RequestDetails;
-import org.openecomp.vid.roles.RoleProvider;
-import org.openecomp.vid.roles.RoleValidator;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.*;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
+import java.io.BufferedReader;
import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
+//import java.util.UUID;
import java.util.Date;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Scanner;
+import java.util.stream.Collectors;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.codehaus.jackson.JsonEncoding;
+import org.codehaus.jackson.JsonFactory;
+import org.codehaus.jackson.JsonGenerator;
+import org.codehaus.jackson.JsonParser;
+import org.codehaus.jackson.JsonToken;
+import org.glassfish.jersey.client.ClientResponse;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.openecomp.vid.model.ExceptionResponse;
+import org.openecomp.vid.mso.*;
+import org.openecomp.vid.mso.rest.*;
+import org.springframework.http.HttpStatus;
+//import org.springframework.http.ResponseEntity;
+//import org.springframework.http.RequestEntity;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.servlet.ModelAndView;
+
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectReader;
+import com.fasterxml.jackson.databind.DeserializationFeature;
/**
* The Class MsoController.
@@ -59,25 +80,30 @@ import java.util.Map; public class MsoController extends RestrictedBaseController {
/**
- * The Constant SVC_INSTANCE_ID.
+ * The view name.
*/
- public final static String SVC_INSTANCE_ID = "<service_instance_id>";
+ String viewName;
+
/**
- * The Constant VNF_INSTANCE_ID.
+ * The logger.
*/
- public final static String VNF_INSTANCE_ID = "<vnf_instance_id>";
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoController.class);
+
/**
* The Constant dateFormat.
*/
final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
+
/**
- * The view name.
+ * The Constant SVC_INSTANCE_ID.
*/
- String viewName;
+ public final static String SVC_INSTANCE_ID = "<service_instance_id>";
+ public final static String REQUEST_TYPE = "<request_type>";
+
/**
- * The logger.
+ * The Constant VNF_INSTANCE_ID.
*/
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoController.class);
+ public final static String VNF_INSTANCE_ID = "<vnf_instance_id>";
/**
* Welcome.
@@ -118,37 +144,70 @@ public class MsoController extends RestrictedBaseController { */
@RequestMapping(value = "/mso_create_svc_instance", method = RequestMethod.POST)
public ResponseEntity<String> createSvcInstance(HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception {
+ String methodName = "createSvcInstance";
+
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
+
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
+ // always return OK, the MSO status code is embedded in the body
+
+ MsoResponseWrapper w = mbl.createSvcInstance(mso_request);
+
+ return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
+
+ }
+ /**
+ * Creates the svc instance.
+ *
+ * @param request the request
+ * @return the response entity
+ * @throws Exception the exception
+ */
+
+ public ResponseEntity<String> createSvcInstanceNewRest(HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception {
String methodName = "createSvcInstance";
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
- if (!userIsPermmited(request, mso_request)) {
- return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
- }
-// mso_request = retrieveRequestObject (request, mso_request);
+ MsoBusinessLogicNew mbln = new MsoBusinessLogicNew();
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE);
- String userId = "";
- HttpSession session = request.getSession();
- System.out.println((new ObjectMapper().writeValueAsString(session.getAttribute("roles"))));
- MsoResponseWrapper w = createInstance(mso_request, p);
- return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
// always return OK, the MSO status code is embedded in the body
+ MsoResponseWrapper w = mbln.createSvcInstanceRest(mso_request);
+
+ if (w == null) {
+ return null;
+ }
+ return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
}
- private boolean userIsPermmited(HttpServletRequest request, RequestDetails mso_request) {
+ /**
+ * Creates the svc instance.
+ *
+ * @param request the request
+ * @return the response entity
+ * @throws Exception the exception
+ */
+
+ public ResponseEntity<String> createSvcInstanceNew(HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception {
+ String methodName = "createSvcInstance";
+
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
+
+ MsoBusinessLogicNew mbln = new MsoBusinessLogicNew();
+ // always return OK, the MSO status code is embedded in the body
+
+ MsoResponseWrapper w = mbln.createSvcInstance(mso_request);
- RoleValidator roleValidator = new RoleValidator(new RoleProvider().getUserRoles(request));
- boolean isPermitted = roleValidator.isMsoRequestValid(mso_request);
- if (!isPermitted) {
- return false;
- } else {
- return true;
+ if (w == null) {
+ return null;
}
+
+ return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
+
}
/**
@@ -161,23 +220,10 @@ public class MsoController extends RestrictedBaseController { */
@RequestMapping(value = "/mso_create_vnf_instance/{serviceInstanceId}", method = RequestMethod.POST)
public ResponseEntity<String> createVnf(@PathVariable("serviceInstanceId") String serviceInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception {
-// if (!userIsPermmited(request, mso_request)) {
- String instanceId = (String) ((Map)((Map)((ArrayList)((Map) mso_request.getAdditionalProperties().get("requestDetails")).get("relatedInstanceList")).get(0)).get("relatedInstance")).get("instanceId");
- ResponseEntity<String> a = new AaiController(request.getServletContext()).doGetServiceInstance(instanceId,"Service Instance id");
-// return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
-// }
- String methodName = "createVnf";
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
- //RequestDetails mso_request = retrieveRequestObject (request);
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_VNF_INSTANCE);
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
- if (p == null || p.isEmpty()) {
- throw new Exception("Vnf instance path is not defined");
- }
- // /serviceInstances/v2/<service_instance_id>/vnfs
- String vnf_path = p.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
- MsoResponseWrapper w = createInstance(mso_request, vnf_path);
+ MsoResponseWrapper w = mbl.createVnf(mso_request, serviceInstanceId);
// always return OK, the MSO status code is embedded in the body
@@ -195,23 +241,12 @@ public class MsoController extends RestrictedBaseController { */
@RequestMapping(value = "/mso_create_nw_instance/{serviceInstanceId}", method = RequestMethod.POST)
public ResponseEntity<String> createNwInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception {
-
String methodName = "createNwInstance";
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start, serviceInstanceId = " + serviceInstanceId);
- //RequestDetails mso_request = retrieveRequestObject (request);
-
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_NETWORK_INSTANCE);
-
- if (p == null || p.isEmpty()) {
- throw new Exception("Network instance path is not defined");
- }
- // /serviceInstances/v2/<serviceInstanceId>/networks/
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
- String nw_path = p.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
- MsoResponseWrapper w = createInstance(mso_request, nw_path);
-
- // always return OK, the MSO status code is embedded in the body
+ MsoResponseWrapper w = mbl.createNwInstance(mso_request, serviceInstanceId);
return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
@@ -230,21 +265,11 @@ public class MsoController extends RestrictedBaseController { public ResponseEntity<String> createVolumeGroupInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId,
HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception {
String methodName = "createVolumeGroupInstance";
- if (!userIsPermmited(request, mso_request)) {
- return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
- }
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
- //RequestDetails mso_request = retrieveRequestObject (request);
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE);
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
- if (p == null || p.isEmpty()) {
- throw new Exception("Volume group instance path is not defined");
- }
- String path = p.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
- path = path.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId);
-
- MsoResponseWrapper w = createInstance(mso_request, path);
+ MsoResponseWrapper w = mbl.createVolumeGroupInstance(mso_request, serviceInstanceId, vnfInstanceId);
// always return OK, the MSO status code is embedded in the body
return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
@@ -265,40 +290,31 @@ public class MsoController extends RestrictedBaseController { String methodName = "createVfModuleInstance";
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
- if (!userIsPermmited(request, mso_request)) {
- return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
- }
- //RequestDetails mso_request = retrieveRequestObject (request);
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE);
- if (p == null || p.isEmpty()) {
- throw new Exception("VF module instance path is not defined");
- }
- // /serviceInstances/v2/<serviceInstanceId>/vnfs/<vnfInstanceId>/vfmodules
- String path = p.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
- path = path.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId);
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
- MsoResponseWrapper w = createInstance(mso_request, path);
+ MsoResponseWrapper w = mbl.createVfModuleInstance(mso_request, serviceInstanceId, vnfInstanceId);
// always return OK, the MSO status code is embedded in the body
return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
}
- /**
- * Creates the instance.
- *
- * @param request the request
- * @param path the path
- * @return the mso response wrapper
- * @throws Exception the exception
- */
- protected MsoResponseWrapper createInstance(RequestDetails request, String path) throws Exception {
- String methodName = "createInstance";
- logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start");
+ /**
+ * Creates the instance.
+ *
+ * @param request the request
+ * @param path the path
+ * @return the mso response wrapper
+ * @throws ClientHandlerException the client handler exception
+ * @throws Exception the exception
+ */
+ protected MsoResponseWrapper createInstance(RequestDetails request, String path) throws Exception {
+ String methodName = "createInstance";
+ logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start");
try {
- MsoRestInterfaceIfc restController = MsoRestInterfaceFactory.getInstance();
+ MsoRestInterfaceIfc restController = new MsoRestInterface();
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Post, request = (" + request + ")");
RestObject<String> restObjStr = new RestObject<String>();
@@ -307,14 +323,14 @@ public class MsoController extends RestrictedBaseController { restController.<String>Post(str, request, "", path, restObjStr);
MsoResponseWrapper w = MsoUtil.wrapResponse(restObjStr);
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse());
- return w;
- } catch (Exception e) {
- logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- throw e;
- }
- }
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse());
+ return w;
+ } catch (Exception e) {
+ logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
+ throw e;
+ }
+ }
/**
* Delete svc instance.
@@ -331,10 +347,9 @@ public class MsoController extends RestrictedBaseController { String methodName = "deleteSvcInstance";
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
- //RequestDetails mso_request = retrieveRequestObject (request);
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE);
- String path = p + "/" + serviceInstanceId;
- MsoResponseWrapper w = deleteInstance(mso_request, path);
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
+
+ MsoResponseWrapper w = mbl.deleteSvcInstance(mso_request, serviceInstanceId);
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse());
// always return OK, the MSO status code is embedded in the body
@@ -359,17 +374,10 @@ public class MsoController extends RestrictedBaseController { String methodName = "deleteVnf";
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
- if (!userIsPermmited(request, mso_request)) {
- return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
- }
- //RequestDetails mso_request = retrieveRequestObject (request);
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_VNF_INSTANCE);
- if (p == null || p.isEmpty()) {
- throw new Exception("Vnf instance path is not defined");
- }
- // /serviceInstances/v2/<service_instance_id>/vnfs/
- String vnf_path = p.replaceFirst(SVC_INSTANCE_ID, vnfInstanceId);
- MsoResponseWrapper w = deleteInstance(mso_request, vnf_path + "/" + vnfInstanceId);
+
+ MsoBusinessLogic mlb = new MsoBusinessLogic();
+
+ MsoResponseWrapper w = mlb.deleteVnf(mso_request, serviceInstanceId, vnfInstanceId);
// always return OK, the MSO status code is embedded in the body
return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
@@ -393,21 +401,11 @@ public class MsoController extends RestrictedBaseController { @PathVariable("vfModuleId") String vfModuleId, HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception {
String methodName = "deleteVfModule";
-
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
- if (!userIsPermmited(request, mso_request)) {
- return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
- }
- //RequestDetails mso_request = new RequestDetails();
- //mso_request = retrieveRequestObject (request);
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE);
- if (p == null || p.isEmpty()) {
- throw new Exception("VF Module instance path is not defined");
- }
- // /serviceInstances/v2/<serviceInstanceId>/vnfs/<vnfInstanceId>/vfmodules
- String path = p.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
- path = path.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId);
- MsoResponseWrapper w = deleteInstance(mso_request, path + "/" + vfModuleId);
+
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
+
+ MsoResponseWrapper w = mbl.deleteVfModule(mso_request, serviceInstanceId, vnfInstanceId);
// always return OK, the MSO status code is embedded in the body
return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
@@ -428,21 +426,12 @@ public class MsoController extends RestrictedBaseController { public ResponseEntity<String> deleteVolumeGroupInstance(
@PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, @PathVariable("volumeGroupId") String volumeGroupId,
HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception {
-
String methodName = "deleteVolumeGroupInstance";
-
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
- if (!userIsPermmited(request, mso_request)) {
- return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
- }
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE);
- if (p == null || p.isEmpty()) {
- throw new Exception("Volume group instance path is not defined");
- }
- // /serviceInstances/v2/{serviceInstanceId}/volumeGroups
- String path = p.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
- path = path.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId);
- MsoResponseWrapper w = deleteInstance(mso_request, path + "/" + volumeGroupId);
+
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
+
+ MsoResponseWrapper w = mbl.deleteVolumeGroupInstance(mso_request, serviceInstanceId, vnfInstanceId, volumeGroupId);
// always return OK, the MSO status code is embedded in the body
return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
@@ -460,21 +449,12 @@ public class MsoController extends RestrictedBaseController { @RequestMapping(value = "/mso_delete_nw_instance/{serviceInstanceId}/networks/{networkInstanceId}", method = RequestMethod.POST)
public ResponseEntity<String> deleteNwInstance(@PathVariable("serviceInstanceId") String serviceInstanceId,
@PathVariable("networkInstanceId") String networkInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception {
-
String methodName = "deleteNwInstance";
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
- //RequestDetails mso_request = retrieveRequestObject (request);
- if (!userIsPermmited(request, mso_request)) {
- return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
- }
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_NETWORK_INSTANCE);
- if (p == null || p.isEmpty()) {
- throw new Exception("Network instance path is not defined");
- }
- // /serviceInstances/v2/<service_instance_id>/networks
- String path = p.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
- MsoResponseWrapper w = deleteInstance(mso_request, path + "/" + networkInstanceId);
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
+
+ MsoResponseWrapper w = mbl.deleteNwInstance(mso_request, serviceInstanceId, networkInstanceId);
// always return OK, the MSO status code is embedded in the body
return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
@@ -482,39 +462,6 @@ public class MsoController extends RestrictedBaseController { }
/**
- * Delete instance.
- *
- * @param request the request
- * @param path the path
- * @return the mso response wrapper
- * @throws Exception the exception
- */
- protected MsoResponseWrapper deleteInstance(RequestDetails request, String path) throws Exception {
- String methodName = "deleteInstance";
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
-
- try {
- MsoRestInterfaceIfc restController = MsoRestInterfaceFactory.getInstance();
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Delete, path =[" + path + "]");
-
- RestObject<String> restObjStr = new RestObject<String>();
- String str = new String();
- restObjStr.set(str);
- restController.<String>Delete(str, request, "", path, restObjStr);
- MsoResponseWrapper w = MsoUtil.wrapResponse(restObjStr);
-
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse());
- return w;
-
- } catch (Exception e) {
- logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- throw e;
- }
-
- }
-
- /**
* Gets the orchestration request.
*
* @param requestId the request id
@@ -528,27 +475,12 @@ public class MsoController extends RestrictedBaseController { String methodName = "getOrchestrationRequest";
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
- MsoResponseWrapper w = null;
- try {
- MsoRestInterfaceIfc restController = MsoRestInterfaceFactory.getInstance();
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQ);
- String path = p + "/" + requestId;
- RestObject<String> restObjStr = new RestObject<String>();
- String str = new String();
- restObjStr.set(str);
- restController.<String>Get(str, "", path, restObjStr);
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
- w = MsoUtil.wrapResponse(restObjStr);
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse());
- // always return OK, the MSO status code is embedded in the body
+ MsoResponseWrapper w = mbl.getOrchestrationRequest(requestId);
- } catch (Exception e) {
- logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- throw e;
- }
// always return OK, the MSO status code is embedded in the body
return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
}
@@ -568,63 +500,134 @@ public class MsoController extends RestrictedBaseController { String methodName = "getOrchestrationRequests";
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
- MsoResponseWrapper w = null;
- try {
- MsoRestInterfaceIfc restController = MsoRestInterfaceFactory.getInstance();
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQS);
- String path = p + filterString;
- RestObject<String> restObjStr = new RestObject<String>();
- String str = new String();
- restObjStr.set(str);
- restController.<String>Get(str, "", path, restObjStr);
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
+
+ MsoResponseWrapper w = mbl.getOrchestrationRequests(filterString);
- w = MsoUtil.wrapResponse(restObjStr);
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse());
- } catch (Exception e) {
- logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- throw e;
- }
// always return OK, the MSO status code is embedded in the body
return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK));
}
+
/**
- * Gets the orchestration requests for svc instance.
+ * activate to a pnf instance.
*
- * @param svc_instance_id the svc instance id
- * @return the orchestration requests for svc instance
+ * @param serviceInstanceId the id of the service.
+ * @param requestDetails the body of the request.
+ * @return the response entity
* @throws Exception the exception
*/
- public MsoResponseWrapper getOrchestrationRequestsForSvcInstance(String svc_instance_id) throws Exception {
+ @RequestMapping(value = "/mso_activate_service_instance/{serviceInstanceId}", method = RequestMethod.POST)
+ public ResponseEntity<String> activateServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @RequestBody RequestDetails requestDetails) throws Exception {
+ String methodName = "activateServiceInstance";
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
+
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
+
+ MsoResponseWrapper w = mbl.activateServiceInstance(requestDetails, serviceInstanceId);
+ return new ResponseEntity<>(w.getResponse(), HttpStatus.OK);
+ }
+
- String methodName = "getOrchestrationRequestsForSvcInstance";
+ /**
+ * Gets the orchestration requests for the dashboard.
+ * currently its all the orchestration requests with RequestType updateInstance or replaceInstance.
+ * @return the orchestration requests
+ * @throws Exception the exception
+ */
+ @RequestMapping(value = "/mso_get_orch_reqs/dashboard", method = RequestMethod.GET)
+ public List<Request> getOrchestrationRequestsForDashboard() throws Exception {
+
+ String methodName = "getOrchestrationRequestsForDashboard";
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
- MsoResponseWrapper w = null;
- try {
- MsoRestInterfaceIfc restController = MsoRestInterfaceFactory.getInstance();
- String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQS);
- String path = p + svc_instance_id;
- RestObject<String> restObjStr = new RestObject<String>();
- String str = new String();
- restObjStr.set(str);
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
- restController.<String>Get(str, "", path, restObjStr);
- w = MsoUtil.wrapResponse(restObjStr);
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse());
+ return mbl.getOrchestrationRequestsForDashboard();
+ }
- } catch (Exception e) {
- logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
- throw e;
- }
- return w;
+ /**
+ * Gets the Manual Tasks for the given request id.
+ *
+ * @param originalRequestId the id of the original request.
+ * @return the tasks
+ * @throws Exception the exception
+ */
+ @RequestMapping(value = "/mso_get_man_task/{originalRequestId}", method = RequestMethod.GET)
+ public List<Task> getManualTasksByRequestId(@PathVariable("originalRequestId") String originalRequestId) throws Exception {
+
+ String methodName = "getManualTasksByRequestId";
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
+
+
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
+
+ return mbl.getManualTasksByRequestId(originalRequestId);
+ }
+
+
+
+ /**
+ * Complete the manual task.
+ *
+ * @param taskId the id of the task to complete.
+ * @param requestDetails the body of the request.
+ * @return the response entity
+ * @throws Exception the exception
+ */
+ @RequestMapping(value = "/mso_post_man_task/{taskId}", method = RequestMethod.POST)
+ public ResponseEntity<String> manualTaskComplete(@PathVariable("taskId") String taskId , @RequestBody RequestDetails requestDetails) throws Exception {
+
+ String methodName = "manualTaskComplete";
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
+
+ MsoBusinessLogic mbl = new MsoBusinessLogic();
+
+ MsoResponseWrapper w = mbl.completeManualTask(requestDetails, taskId);
+ return new ResponseEntity<String>(w.getResponse(), HttpStatus.OK);
}
+
+
+
+
+ /**
+ * Gets the orchestration requests for svc instance.
+ *
+ * @param svc_instance_id the svc instance id
+ * @return the orchestration requests for svc instance
+ * @throws Exception the exception
+ */
+// public MsoResponseWrapper getOrchestrationRequestsForSvcInstance(String svc_instance_id) throws Exception {
+
+// String methodName = "getOrchestrationRequestsForSvcInstance";
+// logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
+// MsoResponseWrapper w = null;
+//
+// try {
+// MsoRestInterfaceIfc restController = MsoRestInterfaceFactory.getInstance();
+// String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQS);
+// String path = p + svc_instance_id;
+//
+// RestObject<String> restObjStr = new RestObject<String>();
+// String str = new String();
+// restObjStr.set(str);
+//
+// restController.<String>Get(str, "", path, restObjStr);
+// w = MsoUtil.wrapResponse(restObjStr);
+// logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse());
+//
+// } catch (Exception e) {
+// logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
+// logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
+// throw e;
+// }
+// return w;
+// }
+
/**
* Exception handler.
*
@@ -636,7 +639,7 @@ public class MsoController extends RestrictedBaseController { private void exceptionHandler(Exception e, HttpServletResponse response) throws IOException {
/*
- * The following "logger.error" lines "should" be sufficient for logging the exception.
+ * The following "logger.error" lines "should" be sufficient for logging the exception.
* However, the console output in my Eclipse environment is NOT showing ANY of the
* logger statements in this class. Thus the temporary "e.printStackTrace" statement
* is also included.
@@ -649,7 +652,7 @@ public class MsoController extends RestrictedBaseController { logger.error(EELFLoggerDelegate.errorLogger, sw.toString());
/*
- * Temporary - IF the above mentioned "logger.error" glitch is resolved ...
+ * Temporary - IF the above mentioned "logger.error" glitch is resolved ...
* this statement could be removed since it would then likely result in duplicate
* trace output.
*/
@@ -673,7 +676,8 @@ public class MsoController extends RestrictedBaseController { *
* @param resp the resp
* @return the list
- * @throws Exception the exception
+ * @throws ParseException the parse exception
+ * @throws Exception the exception
*/
@SuppressWarnings("unchecked")
public List<JSONObject> parseOrchestrationRequestsForSvcInstance(ClientResponse resp) throws org.json.simple.parser.ParseException, Exception {
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/PolicyController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/PolicyController.java new file mode 100644 index 000000000..83e177a61 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/PolicyController.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.controller; + +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; + +import org.json.simple.JSONObject; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.vid.policy.PolicyProperties; +import org.openecomp.vid.policy.PolicyResponseWrapper; +import org.openecomp.vid.policy.PolicyRestInterfaceFactory; +import org.openecomp.vid.policy.PolicyRestInterfaceIfc; +import org.openecomp.vid.policy.PolicyUtil; +import org.openecomp.vid.policy.RestObject; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +/** + * Controller to handle Policy requests. + */ + +@RestController +public class PolicyController extends RestrictedBaseController{ + + /** The logger. */ + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyController.class); + + @RequestMapping(value="/get_policy",method = RequestMethod.POST) + public ResponseEntity<String> getPolicyInfo( HttpServletRequest request, @RequestBody JSONObject policy_request) throws Exception { + + logger.debug("#####################POLICY API CALL STARTED ###############"+ PolicyProperties.POLICY_GET_CONFIG_VAL); + logger.debug("#####################Policy Request ###############"+policy_request.toString()); + + String path = PolicyProperties.getProperty(PolicyProperties.POLICY_GET_CONFIG_VAL); + PolicyResponseWrapper policyResWrapper = getPolicyConfig(policy_request,path); + + logger.debug("$$$$$$$$$$$$$$$$$$$$$$ " + new ResponseEntity<String>(policyResWrapper.getResponse(), HttpStatus.OK).toString()); + + return ( new ResponseEntity<String>(policyResWrapper.getResponse(), HttpStatus.valueOf(policyResWrapper.getStatus())) ); + } + + protected static PolicyResponseWrapper getPolicyConfig(JSONObject request, String path) throws Exception { + String methodName = "getPolicyConfig"; + String uuid = UUID.randomUUID().toString(); + logger.debug( "starting getPolicyConfig "); + + try { + //STARTING REST API CALL AS AN FACTORY INSTACE + PolicyRestInterfaceIfc restController = PolicyRestInterfaceFactory.getInstance(); + + RestObject<String> restObjStr = new RestObject<String>(); + String str = new String(); + restObjStr.set(str); + restController.<String>Post(str, request, uuid, path, restObjStr ); + PolicyResponseWrapper policyRespWrapper = PolicyUtil.wrapResponse (restObjStr); + + logger.debug( "<== " + methodName + " w=" + policyRespWrapper.getResponse()); + return policyRespWrapper; + } catch (Exception e) { + logger.debug( "EXCEPTION in getPolicyConfig <== " + "." + methodName + e.toString()); + throw e; + } + } +} + diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/SchedulerController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/SchedulerController.java new file mode 100644 index 000000000..0fd2079e9 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/SchedulerController.java @@ -0,0 +1,244 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.controller; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; + +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.vid.scheduler.RestObjects.GetTimeSlotsRestObject; +import org.openecomp.vid.scheduler.RestObjects.PostCreateNewVnfRestObject; +import org.openecomp.vid.scheduler.RestObjects.PostSubmitVnfChangeRestObject; +import org.openecomp.vid.scheduler.SchedulerProperties; +import org.openecomp.vid.scheduler.SchedulerRestInterface; +import org.openecomp.vid.scheduler.SchedulerResponseWrappers.GetTimeSlotsWrapper; +import org.openecomp.vid.scheduler.SchedulerResponseWrappers.PostCreateNewVnfWrapper; +import org.openecomp.vid.scheduler.SchedulerResponseWrappers.PostSubmitVnfChangeTimeSlotsWrapper; +import org.openecomp.vid.scheduler.SchedulerUtil; + +/** + * Controller to handle Scheduler requests. + */ + +@RestController +public class SchedulerController extends RestrictedBaseController { + + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerController.class); + + /** The request date format. */ + public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); + + @Autowired + private SchedulerRestInterface restController; + + /* + * + * GET SCHEDULER CONTROLLERS + * + */ + + @RequestMapping(value = "/get_time_slots/{scheduler_request}", method = RequestMethod.GET) + public ResponseEntity<String> getTimeSlots(HttpServletRequest request, @PathVariable("scheduler_request") String scheduler_request) throws Exception { + + Date startingTime = new Date(); + String startTimeRequest = requestDateFormat.format(startingTime); + + System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); + System.out.println(startTimeRequest + " | Controller Scheduler GET : /get_time_slots/{scheduler_request} \n"); + System.out.println("Original Request : \n " + scheduler_request + '\n'); + + String path = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_GET_TIME_SLOTS) + scheduler_request; + + GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(scheduler_request, path, scheduler_request); + + Date endTime = new Date(); + String endTimeRequest = requestDateFormat.format(endTime); + System.out.println(endTimeRequest + " | Controller Scheduler - GET\n"); + + return (new ResponseEntity<String>(schedulerResWrapper.getResponse(), HttpStatus.OK)); + + } + + protected GetTimeSlotsWrapper getTimeSlots(String request, String path, String uuid) throws Exception { + + try { + //STARTING REST API CALL AS AN FACTORY INSTACE + System.out.println("<== Get Time Slots Request START \n"); + + GetTimeSlotsRestObject<String> restObjStr = new GetTimeSlotsRestObject<String>(); + String str = new String(); + + restObjStr.set(str); + + restController.<String>Get(str, uuid, path, restObjStr); + GetTimeSlotsWrapper schedulerRespWrapper = SchedulerUtil.getTimeSlotsWrapResponse(restObjStr); + + System.out.println("<== Get Time Slots Request END : Response = " + schedulerRespWrapper.getResponse() + '\n'); + + return schedulerRespWrapper; + + } catch (Exception e) { + System.out.println("<== Get Time Slots Request ERROR : " + e.toString() + '\n'); + throw e; + } + } + + /* + * + * POST SCHEDULER CONTROLLERS + * + */ + + @SuppressWarnings("unchecked") + @RequestMapping(value = "/post_create_new_vnf_change", method = RequestMethod.POST) + public ResponseEntity<String> postCreateNewVNFChange(HttpServletRequest request, @RequestBody JSONObject scheduler_request) throws Exception { + + Date startingTime = new Date(); + String startTimeRequest = requestDateFormat.format(startingTime); + + System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); + System.out.println(startTimeRequest + " | Controller Scheduler POST : post_create_new_vnf_change \n"); + + //Generating uuid + String uuid = UUID.randomUUID().toString(); + + scheduler_request.put("scheduleId", uuid); + System.out.println("<== UUID : " + uuid + '\n'); + + //adding uuid to the request payload + scheduler_request.put("scheduleId", uuid); + + System.out.println("<== UUID : " + uuid + '\n'); + System.out.println("Original Request : \n " + scheduler_request.toString() + '\n'); + + String path = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL) + uuid; + + PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(scheduler_request, path, uuid); + + Date endTime = new Date(); + String endTimeRequest = requestDateFormat.format(endTime); + System.out.println(endTimeRequest + " | Controller Scheduler - POST\n"); + + return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.OK)); + } + + protected PostCreateNewVnfWrapper postSchedulingRequest(JSONObject request, String path, String uuid) throws Exception { + + try { + //STARTING REST API CALL AS AN FACTORY INSTACE + System.out.println("<== Post Create New Vnf Scheduling Request START \n"); + + PostCreateNewVnfRestObject<String> restObjStr = new PostCreateNewVnfRestObject<String>(); + String str = new String(); + + restObjStr.set(str); + restController.<String>Post(str, request, path, restObjStr); + + int status = restObjStr.getStatusCode(); + if (status >= 200 && status <= 299) { + restObjStr.setUUID(uuid); + } + + PostCreateNewVnfWrapper responseWrapper = SchedulerUtil.postCreateNewVnfWrapResponse(restObjStr); + + System.out.println("<== Post Create New Vnf Scheduling Request END : Response = " + responseWrapper.getResponse() + '\n'); + + return responseWrapper; + + } catch (Exception e) { + System.out.println("<== Post Create New Vnf Scheduling Request ERROR : " + e.toString() + '\n'); + throw e; + } + } + + @RequestMapping(value = "/submit_vnf_change_timeslots", method = RequestMethod.POST) + public ResponseEntity<String> postSubmitVnfChangeTimeslots(HttpServletRequest request, @RequestBody JSONObject scheduler_request) throws Exception { + + Date startingTime = new Date(); + String startTimeRequest = requestDateFormat.format(startingTime); + + System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); + System.out.println(startTimeRequest + " | Controller Scheduler POST : submit_vnf_change_timeslots \n"); + + //Generating uuid + String uuid = (String) scheduler_request.get("scheduleId"); + scheduler_request.remove("scheduleId"); + + System.out.println("<== UUID : " + uuid + '\n'); + System.out.println("Original Request : \n " + scheduler_request.toString() + '\n'); + + String path = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE).replace("{scheduleId}", uuid); + + PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = postSubmitSchedulingRequest(scheduler_request, path, uuid); + + Date endTime = new Date(); + String endTimeRequest = requestDateFormat.format(endTime); + System.out.println(endTimeRequest + " | Controller Scheduler - POST Submit\n"); + + return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.OK)); + } + + protected PostSubmitVnfChangeTimeSlotsWrapper postSubmitSchedulingRequest(JSONObject request, String path, String uuid) throws Exception { + + try { + //STARTING REST API CALL AS AN FACTORY INSTACE + System.out.println("<== Post Submit Scheduling Request START \n"); + + PostSubmitVnfChangeRestObject<String> restObjStr = new PostSubmitVnfChangeRestObject<String>(); + String str = new String(); + + restObjStr.set(str); + restController.<String>Post(str, request, path, restObjStr); + + int status = restObjStr.getStatusCode(); + if (status >= 200 && status <= 299) { + restObjStr.setUUID(uuid); + } + + PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = SchedulerUtil.postSubmitNewVnfWrapResponse(restObjStr); + + System.out.println("<== Post Submit Scheduling Request END : Response = " + responseWrapper.getResponse() + '\n'); + + return responseWrapper; + + } catch (Exception e) { + System.out.println("<== Post Submit Scheduling Request ERROR : " + e.toString() + '\n'); + throw e; + } + } +} + diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/VidController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/VidController.java index 838793a76..aac3a0b7e 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/controller/VidController.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/VidController.java @@ -67,6 +67,7 @@ public class VidController extends RestrictedBaseController { @RequestMapping(value={"/rest/models/services"}, method = RequestMethod.GET)
public SecureServices getServices(HttpServletRequest request) throws VidServiceUnavailableException {
try {
+ LOG.info("Start API for browse ASDC was called");
SecureServices secureServices = new SecureServices();
RoleProvider roleProvider = new RoleProvider();
Map<String, String[]> requestParams = request.getParameterMap();
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/factories/MsoRequestFactory.java b/vid-app-common/src/main/java/org/openecomp/vid/factories/MsoRequestFactory.java new file mode 100644 index 000000000..9cc9c5f66 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/factories/MsoRequestFactory.java @@ -0,0 +1,15 @@ +package org.openecomp.vid.factories; + +import org.openecomp.vid.mso.rest.RequestDetails; + +/** + * Created by pickjonathan on 19/06/2017. + */ +public class MsoRequestFactory { + + public RequestDetails createMsoRequest(String path) + { + return null; + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/model/CommandProperty.java b/vid-app-common/src/main/java/org/openecomp/vid/model/CommandProperty.java index fe114c380..740f9d781 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/model/CommandProperty.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/model/CommandProperty.java @@ -1,9 +1,9 @@ /*-
- * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ + * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -14,7 +14,7 @@ * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
- * limitations under the License. + * limitations under the License.
* ============LICENSE_END=========================================================
*/
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/model/VersionByInvariantIdsRequest.java b/vid-app-common/src/main/java/org/openecomp/vid/model/VersionByInvariantIdsRequest.java new file mode 100644 index 000000000..7c86165b4 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/model/VersionByInvariantIdsRequest.java @@ -0,0 +1,11 @@ +package org.openecomp.vid.model; + +import java.util.List; + +/** + * Created by Oren on 9/5/17. + */ +public class VersionByInvariantIdsRequest { + + public List<String> versions; +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/model/VolumeGroup.java b/vid-app-common/src/main/java/org/openecomp/vid/model/VolumeGroup.java index d09ef9a33..baa535171 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/model/VolumeGroup.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/model/VolumeGroup.java @@ -161,7 +161,7 @@ public class VolumeGroup { *
* @param u the new customization uuid
*/
- private void setCustomizationUuid(String u) {
+ public void setCustomizationUuid(String u) {
this.customizationUuid = u;
}
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/model/Workflow.java b/vid-app-common/src/main/java/org/openecomp/vid/model/Workflow.java new file mode 100644 index 000000000..6032ec5aa --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/model/Workflow.java @@ -0,0 +1,47 @@ +package org.openecomp.vid.model; + + +import java.util.Collection; + +public class Workflow { + //Private members: + private int id; + private String workflowName; + private Collection<String> vnfNames; + + + //Constructors: + public Workflow() {} + + public Workflow(int id, String workflowName, Collection<String> vnfNames) { + this.id = id; + this.workflowName = workflowName; + this.vnfNames = vnfNames; + } + + + //Setters and getters: + public int getId() { + return id; + } + + public String getWorkflowName() { + return workflowName; + } + + public Collection<String> getVnfNames() { + return this.vnfNames; + } + + public void setId(int id) { + this.id = id; + } + + public void setWorkflowName(String workflowName) { + this.workflowName = workflowName; + } + + public void setVnfName(Collection<String> vnfNames) { + this.vnfNames = vnfNames; + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoBusinessLogic.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoBusinessLogic.java new file mode 100644 index 000000000..cd6003ad4 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoBusinessLogic.java @@ -0,0 +1,415 @@ +package org.openecomp.vid.mso; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.vid.controller.MsoController; +import org.openecomp.vid.mso.rest.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import static org.openecomp.vid.controller.MsoController.SVC_INSTANCE_ID; +import static org.openecomp.vid.controller.MsoController.REQUEST_TYPE; +import static org.openecomp.vid.controller.MsoController.VNF_INSTANCE_ID; + +/** + * Created by pickjonathan on 19/06/2017. + */ +public class MsoBusinessLogic { + + /** + * The Mso REST client + * This should be replaced with mso client factory. + */ + private MsoInterface msoClientInterface; + + /** + * The logger. + */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoController.class); + + /** + * The Constant dateFormat. + */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + public MsoBusinessLogic() { + msoClientInterface = MsoRestInterfaceFactory.getInstance(); + } + + // this function should get params from tosca and send them to instance at mso, then return success response. + public MsoResponseWrapper createSvcInstance(RequestDetails msoRequest) throws Exception { + String methodName = "createSvcInstance "; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + String endpoint; + try { + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_SVC_INSTANCE); + } catch (Exception exception) { + throw exception; + } + + return msoClientInterface.createSvcInstance(msoRequest, endpoint); + } + + public MsoResponseWrapper createVnf(RequestDetails requestDetails, String serviceInstanceId) throws Exception { + String methodName = "createVnf"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + String endpoint; + try { + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); + } catch (Exception exception) { + throw exception; + } + + String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + return msoClientInterface.createVnf(requestDetails, vnf_endpoint); + } + + public MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception { + String methodName = "createNwInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + String endpoint; + try { + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); + } catch (Exception exception) { + throw exception; + } + + String nw_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + return msoClientInterface.createNwInstance(requestDetails, nw_endpoint); + } + + public MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception { + String methodName = "createVolumeGroupInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + String endpoint; + try { + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); + } catch (Exception exception) { + throw exception; + } + + String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + vnf_endpoint = vnf_endpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); + + return msoClientInterface.createVolumeGroupInstance(requestDetails, vnf_endpoint); + } + + public MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception{ + String methodName = "createVfModuleInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + String endpoint; + try { + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); + } catch (Exception exception) { + throw exception; + } + + String partial_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + String vf_module_endpoint = partial_endpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); + + return msoClientInterface.createVfModuleInstance(requestDetails, vf_module_endpoint); + } + + public MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception{ + String methodName = "deleteSvcInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + String endpoint; + try { + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_SVC_INSTANCE); + } catch (Exception exception) { + throw exception; + } + + String svc_endpoint = endpoint + "/" + serviceInstanceId; + + return msoClientInterface.deleteSvcInstance(requestDetails, svc_endpoint); + } + + public MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception{ + String methodName = "deleteVnf"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + String endpoint; + try { + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); + } catch (Exception exception) { + throw exception; + } + String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + vnf_endpoint = vnf_endpoint + '/' + vnfInstanceId; + + return msoClientInterface.deleteVnf(requestDetails, vnf_endpoint); + } + + public MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception{ + String methodName = "deleteVfModule"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + String endpoint; + try { + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); + } catch (Exception exception) { + throw exception; + } + + String svc_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + String delete_vf_endpoint = svc_endpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); + + return msoClientInterface.deleteVfModule(requestDetails, delete_vf_endpoint); + } + + public MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId, String volumeGroupId)throws Exception{ + String methodName = "deleteVolumeGroupInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + String endpoint; + try { + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); + } catch (Exception exception) { + throw exception; + } + + String svc_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + String vnf_endpoint = svc_endpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); + String delete_volume_group_endpoint = vnf_endpoint + "/" + volumeGroupId; + + return msoClientInterface.deleteVolumeGroupInstance(requestDetails, delete_volume_group_endpoint); + } + + public MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String serviceInstanceId, String networkInstanceId) throws Exception{ + String methodName = "deleteNwInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + String endpoint; + try { + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); + } catch (Exception exception) { + throw exception; + } + + String svc_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + String delete_nw_endpoint = svc_endpoint + "/" + networkInstanceId; + + return msoClientInterface.deleteNwInstance(requestDetails, delete_nw_endpoint); + } + + public MsoResponseWrapper getOrchestrationRequest(String requestId)throws Exception{ + String methodName = "getOrchestrationRequest"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + MsoResponseWrapper w = null; + try { + String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQ); + String path = p + "/" + requestId; + + RestObject<String> restObjStr = new RestObject<String>(); + String str = new String(); + restObjStr.set(str); + + msoClientInterface.getOrchestrationRequest(str, "", path, restObjStr); + + return MsoUtil.wrapResponse(restObjStr); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + public MsoResponseWrapper getOrchestrationRequests(String filterString)throws Exception{ + String methodName = "getOrchestrationRequest"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + MsoResponseWrapper w = null; + try { + String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQS); + String path = p + filterString; + + RestObject<String> restObjStr = new RestObject<String>(); + String str = new String(); + restObjStr.set(str); + + msoClientInterface.getOrchestrationRequest(str, "", path, restObjStr); + + return MsoUtil.wrapResponse(restObjStr); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + public List<Request> getOrchestrationRequestsForDashboard()throws Exception{ + String methodName = "getOrchestrationRequestsForDashboard"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + String path = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQS); + path += "filter=modelType:EQUALS:vnf"; + RestObject<String> restObjStr = new RestObject<String>(); + String str = new String(); + restObjStr.set(str); + + MsoResponseWrapper msoResponseWrapper = msoClientInterface.getOrchestrationRequestsForDashboard(str, "", path, restObjStr); + List<RequestWrapper> allOrchestrationRequests = deserializeOrchestrationRequestsJson(msoResponseWrapper.getEntity()); + + List<Request> filteredOrchestrationRequests = new ArrayList<>(); + for (RequestWrapper currentRequest:allOrchestrationRequests){ + if ((currentRequest.getRequest() != null) && (currentRequest.getRequest().getRequestScope() == Request.RequestScope.VNF) && ((currentRequest.getRequest().getRequestType() == + Request.RequestType.REPLACE_INSTANCE)||(currentRequest.getRequest().getRequestType() == + Request.RequestType.UPDATE_INSTANCE) )) { + filteredOrchestrationRequests.add(currentRequest.getRequest()); + } + } + return filteredOrchestrationRequests; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + + } + + private List<RequestWrapper> deserializeOrchestrationRequestsJson(String orchestrationRequestsJson) throws Exception { + String methodName = "deserializeOrchestrationRequestsJson"; + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true); + RequestList requestList = mapper.readValue(orchestrationRequestsJson , RequestList.class); + return requestList.getRequestList(); + } + + + public List<Task> getManualTasksByRequestId(String originalRequestId)throws Exception{ + String methodName = "getManualTasksByRequestId"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_MAN_TASKS); + String path = p + "?originalRequestId=" + originalRequestId; + + RestObject<String> restObjStr = new RestObject<String>(); + String str = new String(); + restObjStr.set(str); + + MsoResponseWrapper msoResponseWrapper = msoClientInterface.getManualTasksByRequestId(str, "", path, restObjStr); + return deserializeManualTasksJson(msoResponseWrapper.getEntity()); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + private List<Task> deserializeManualTasksJson(String manualTasksJson) throws Exception{ + String methodName = "deserializeManualTasksJson"; + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + + ObjectMapper mapper = new ObjectMapper(); + TaskList taskList = mapper.readValue(manualTasksJson , TaskList.class); + return taskList.getTaskList(); + } + + + public MsoResponseWrapper completeManualTask(RequestDetails requestDetails , String taskId)throws Exception{ + String methodName = "completeManualTask"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + MsoResponseWrapper w = null; + try { + String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_MAN_TASKS); + String path = p + "/" + taskId + "/complete"; + + RestObject<String> restObjStr = new RestObject<String>(); + String str = new String(); + restObjStr.set(str); + + msoClientInterface.completeManualTask(requestDetails , str, "", path, restObjStr); + + return MsoUtil.wrapResponse(restObjStr); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + public MsoResponseWrapper activateServiceInstance(RequestDetails requestDetails , String serviceInstanceId)throws Exception{ + String methodName = "activateServiceInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + try { + String path ="/" + serviceInstanceId + "/activate"; + + RestObject<String> restObjStr = new RestObject<>(); + String str = ""; + restObjStr.set(str); + + msoClientInterface.activateServiceInstance(requestDetails , str, "", path, restObjStr); + + return MsoUtil.wrapResponse(restObjStr); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + + + + private String validateEndpointPath(String endpointEnvVariable) throws Exception { + String endpoint = SystemProperties.getProperty(endpointEnvVariable); + if (endpoint == null || endpoint.isEmpty()) { + throw new Exception(endpointEnvVariable + " env variable is not defined"); + } + return endpoint; + } + + public MsoResponseWrapper updateVnf(org.openecomp.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception { + String methodName = "updateVnf"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + String endpoint; + try { + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); + } catch (Exception exception) { + throw exception; + } + String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + vnf_endpoint = vnf_endpoint + '/' + vnfInstanceId; + return msoClientInterface.updateVnf(requestDetails, vnf_endpoint); + } + + public MsoResponseWrapper replaceVnf(org.openecomp.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception { + String methodName = "replaceVnf"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + String endpoint; + try { + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_CHANGE_MANAGEMENT_INSTANCE); + } catch (Exception exception) { + throw exception; + } + String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + vnf_endpoint = vnf_endpoint.replace(VNF_INSTANCE_ID, vnfInstanceId); + vnf_endpoint = vnf_endpoint.replace(REQUEST_TYPE, "replace"); //No Constants file, TODO: once you create - add it. + return msoClientInterface.replaceVnf(requestDetails, vnf_endpoint); + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoClientFactory.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoClientFactory.java new file mode 100644 index 000000000..fb0ead440 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoClientFactory.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.mso; + +import org.openecomp.vid.mso.rest.MsoRestClientNew; + +/** + * A factory for creating MsoRestInterface objects. + */ +public class MsoClientFactory { + + /** + * MSO client factory that creates the right client according to env. + * @return + */ + public static MsoInterface getInstance() { + return new MsoRestClientNew(); + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoInterface.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoInterface.java new file mode 100644 index 000000000..cdeb1bbd2 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoInterface.java @@ -0,0 +1,75 @@ +package org.openecomp.vid.mso; + +import org.openecomp.vid.mso.rest.Request; +import org.openecomp.vid.mso.rest.RequestDetails; +import org.openecomp.vid.mso.rest.Task; + +import java.util.List; + +/** + * Created by pickjonathan on 21/06/2017. + */ +public interface MsoInterface { + + /** + * This function will post MSO service with information about how to instantiate the requested service + * @param requestDetails The details about the service as they come from the web. + * @return MsoResponseWrapper containing information about the service instantiation + * --> success : see JSON at resources folder mso_create_instance_response. + * --> failure : would return 200 with failure data. + * @throws Exception + */ + MsoResponseWrapper createSvcInstance(RequestDetails requestDetails, String endpoint) throws Exception; + + /** + * will create a virtual network function using MSO service. + * @param requestDetails - information about the vnf to create + * @return - the response body recived from MSO + * @throws Exception + */ + MsoResponseWrapper createVnf(RequestDetails requestDetails, String endpoint) throws Exception; + + MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String endpoint) throws Exception; + /** + * + * @param requestDetails + * @param path + * @return + * @throws Exception + */ + MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String path) throws Exception; + + /** + * + * @param requestDetails + * @return + * @throws Exception + */ + MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String endpoint) throws Exception; + + MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String endpoint) throws Exception; + + MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String endpoint) throws Exception; + + MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String endpoint) throws Exception; + + MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String endpoint) throws Exception; + + MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String endpoint) throws Exception; + + void getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject) throws Exception; + + MsoResponseWrapper getOrchestrationRequestsForDashboard(String t , String sourceId , String endpoint , RestObject restObject) throws Exception; + + MsoResponseWrapper getManualTasksByRequestId(String t , String sourceId , String endpoint , RestObject restObject) throws Exception; + + MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject restObject) throws Exception; + + MsoResponseWrapper updateVnf(org.openecomp.vid.changeManagement.RequestDetails requestDetails, String vnf_endpoint) throws Exception; + + MsoResponseWrapper replaceVnf(org.openecomp.vid.changeManagement.RequestDetails requestDetails, String vnf_endpoint) throws Exception; + + + void activateServiceInstance(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject<String> restObject) throws Exception; + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoLocalClient.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoLocalClient.java new file mode 100644 index 000000000..0179400dc --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoLocalClient.java @@ -0,0 +1,85 @@ +package org.openecomp.vid.mso; + +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.vid.changeManagement.ChangeManagementRequest; +import org.openecomp.vid.controller.VidController; +import org.openecomp.vid.mso.rest.RequestDetails; + +import javax.ws.rs.client.Client; +import javax.ws.rs.core.MultivaluedHashMap; +import java.io.InputStream; +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +/** + * Created by pickjonathan on 20/06/2017. + */ +public class MsoLocalClient implements MsoRestInterfaceIfc { + + /** + * The logger. + */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoLocalClient.class); + + /** + * The Constant dateFormat. + */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** + * The client. + */ + private static Client client = null; + + /** + * The common headers. + */ + private MultivaluedHashMap<String, Object> commonHeaders; + + /** + * Instantiates a new mso rest interface. + */ + public MsoLocalClient() { + super(); + } + + public void initMsoClient() { + final String methodname = "initRestClient()"; + } + + @Override + public <T> void Get(T t, String sourceId, String path, RestObject<T> restObject) throws Exception { + + } + + @Override + public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) throws Exception { + + } + + @Override + public <T> void Post(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) throws Exception { + initMsoClient(); + + final InputStream asdcServicesFile = MsoLocalClient.class.getClassLoader().getResourceAsStream("mso_create_instance_response.json"); + + t = (T) IOUtils.toString(asdcServicesFile); + restObject.setStatusCode(200); + restObject.set(t); + } + + @Override + public void logRequest(RequestDetails r) { + + } + + @Override + public <T> void Put(T t, ChangeManagementRequest r, String sourceID, String path, RestObject<T> restObject) + throws Exception { + + + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoLocalClientNew.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoLocalClientNew.java new file mode 100644 index 000000000..1b15df721 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoLocalClientNew.java @@ -0,0 +1,216 @@ +package org.openecomp.vid.mso; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.NotImplementedException; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.vid.mso.rest.*; + +import java.io.InputStream; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * Created by pickjonathan on 21/06/2017. + */ +public class MsoLocalClientNew implements MsoInterface { + + + /** + * The logger. + */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoLocalClient.class); + + /** + * The Constant dateFormat. + */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + + @Override + public MsoResponseWrapper createSvcInstance(RequestDetails requestDetails, String endpoint) throws Exception { + + String methodName = "createSvcInstance "; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + MsoResponseWrapper w = createInstance(requestDetails, ""); + + return w; + } + + public MsoResponseWrapper createInstance(RequestDetails request, String path) throws Exception { + String methodName = "createInstance"; + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + RestObject<String> restObjStr = new RestObject<String>(); + + String str = new String(); + + restObjStr.set(str); + + final InputStream asdcServicesFile = MsoLocalClient.class.getClassLoader().getResourceAsStream("mso_create_instance_response.json"); + + restObjStr.setStatusCode(200); + restObjStr.set(IOUtils.toString(asdcServicesFile)); + + MsoResponseWrapper w = MsoUtil.wrapResponse(restObjStr); + + return w; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + @Override + public MsoResponseWrapper createVnf(RequestDetails requestDetails, String endpoint) throws Exception { + return null; + } + + @Override + public MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String endpoint) throws Exception { + return null; + } + + @Override + public MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String path) throws Exception { + return null; + } + + @Override + public MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String endpoint) throws Exception { + return null; + } + + @Override + public MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String endpoint) throws Exception { + return null; + } + + @Override + public MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String endpoint) throws Exception { + return null; + } + + @Override + public MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String endpoint) throws Exception { + return null; + } + + @Override + public MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String endpoint) throws Exception { + return null; + } + + @Override + public MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String endpoint) throws Exception { + return null; + } + + @Override + public void getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject) throws Exception { } + + @Override + public MsoResponseWrapper getOrchestrationRequestsForDashboard(String t, String sourceId, String endpoint, RestObject restObject) throws Exception { + String methodName = "getOrchestrationRequestsForDashboard"; + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + + final InputStream asdcServicesFile = MsoLocalClient.class.getClassLoader().getResourceAsStream("mso_get_orchestration_requests.json"); + + restObject.setStatusCode(200); + restObject.set(IOUtils.toString(asdcServicesFile)); + + MsoResponseWrapper w = MsoUtil.wrapResponse(restObject); + + return w; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + public void activateServiceInstance(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject<String> restObject) throws Exception{ + String methodName = "activateServiceInstance"; + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + + final InputStream asdcServicesFile = MsoLocalClient.class.getClassLoader().getResourceAsStream("mso_activate_service_instance.json"); + + restObject.setStatusCode(200); + restObject.set(IOUtils.toString(asdcServicesFile)); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + + @Override + public MsoResponseWrapper getManualTasksByRequestId(String t, String sourceId, String endpoint, RestObject restObject) throws Exception { + String methodName = "getManualTasksByRequestId"; + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + + final InputStream asdcServicesFile = MsoLocalClient.class.getClassLoader().getResourceAsStream("mso_get_manual_task_by_request_id.json"); + + restObject.setStatusCode(200); + restObject.set(IOUtils.toString(asdcServicesFile)); + + MsoResponseWrapper w = MsoUtil.wrapResponse(restObject); + + return w; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + @Override + public MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject restObject) throws Exception { + String methodName = "getManualTasksByRequestId"; + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + + final InputStream asdcServicesFile = MsoLocalClient.class.getClassLoader().getResourceAsStream("mso_complete_manual_task.json"); + + restObject.setStatusCode(200); + restObject.set(IOUtils.toString(asdcServicesFile)); + + MsoResponseWrapper w = MsoUtil.wrapResponse(restObject); + + return w; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + @Override + public MsoResponseWrapper replaceVnf(org.openecomp.vid.changeManagement.RequestDetails requestDetails, String vnf_endpoint) throws Exception { + throw new NotImplementedException("Function was not implemented at this point."); + } + + + + @Override + public MsoResponseWrapper updateVnf(org.openecomp.vid.changeManagement.RequestDetails requestDetails, + String vnf_endpoint) { + // TODO Auto-generated method stub + return null; + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoProperties.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoProperties.java index 272a2a2b8..0eed0e1d1 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoProperties.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoProperties.java @@ -24,7 +24,6 @@ import org.openecomp.portalsdk.core.util.SystemProperties; import java.text.DateFormat;
import java.text.SimpleDateFormat;
-import java.util.Date;
import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
/**
@@ -35,10 +34,10 @@ public class MsoProperties extends SystemProperties { /** The Constant MSO_SERVER_URL. */
//VID Properties related to MSO
public static final String MSO_SERVER_URL = "mso.server.url";
-
+
/** The Constant MSO_DME2_SERVER_URL. */
public static final String MSO_DME2_SERVER_URL = "mso.dme2.server.url";
-
+
/** The Constant MSO_DME2_CLIENT_TIMEOUT. */
public static final String MSO_DME2_CLIENT_TIMEOUT = "mso.dme2.client.timeout";
@@ -51,7 +50,7 @@ public class MsoProperties extends SystemProperties { /** The Constant MSO_POLLING_INTERVAL_MSECS. */
// number of msecs to wait between polling requests
public static final String MSO_POLLING_INTERVAL_MSECS = "mso.polling.interval.msecs";
-
+
/** The Constant MSO_POLLING_INTERVAL_MSECS_DEFAULT. */
public static final String MSO_POLLING_INTERVAL_MSECS_DEFAULT = "60000";
@@ -68,14 +67,17 @@ public class MsoProperties extends SystemProperties { public static final String MSO_USER_NAME = "mso.user.name"; //m03346
/** The Constant MSO_PASSWORD. */
- public static final String MSO_PASSWORD = "mso.password.x";
+ public static final String MSO_PASSWORD = "mso.password.x";
/** The Constant MSO_REST_API_SVC_INSTANCE. */
- public static final String MSO_REST_API_SVC_INSTANCE = "mso.restapi.svc.instance"; // /serviceInstances/v2
+ public static final String MSO_REST_API_SVC_INSTANCE = "mso.restapi.svc.instance"; // /serviceInstances/v2
/** The Constant MSO_REST_API_VNF_INSTANCE. */
public static final String MSO_REST_API_VNF_INSTANCE = "mso.restapi.vnf.instance"; // /serviceInstances/v2/{service_instance_id}/vnfs
+ /** The Constant MSO_REST_API_VNF_CHANGE_MANAGEMENT_INSTANCE. */
+ public static final String MSO_REST_API_VNF_CHANGE_MANAGEMENT_INSTANCE = "mso.restapi.vnf.changemanagement.instance"; // /serviceInstances/v2/{service_instance_id}/vnfs/{request_type}
+
/** The Constant MSO_REST_API_NETWORK_INSTANCE. */
public static final String MSO_REST_API_NETWORK_INSTANCE = "mso.restapi.network.instance"; // /serviceInstances/v2/{serviceInstanceId}/networks
@@ -84,10 +86,13 @@ public class MsoProperties extends SystemProperties { /** The Constant MSO_REST_API_GET_ORC_REQS. */
public static final String MSO_REST_API_GET_ORC_REQS = "mso.restapi.get.orc.reqs";
-
+
+ /** The Constant MSO_REST_API_GET_MAN_TASK. */
+ public static final String MSO_REST_API_GET_MAN_TASKS = "mso.restapi.get.man.tasks";
+
/** The Constant MSO_REST_API_VF_MODULE_INSTANCE. */
public static final String MSO_REST_API_VF_MODULE_INSTANCE = "mso.restapi.vf.module.instance";
-
+
/** The Constant MSO_REST_API_VOLUME_GROUP_INSTANCE. */
public static final String MSO_REST_API_VOLUME_GROUP_INSTANCE = "mso.restapi.volume.group.instance"; //serviceInstances/v2/{serviceInstanceId}/volumeGroups
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoRestInterface.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoRestInterface.java index f964b8353..5b331e908 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoRestInterface.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoRestInterface.java @@ -37,6 +37,7 @@ import org.openecomp.portalsdk.core.util.SystemProperties; import org.apache.commons.codec.binary.Base64;
import org.eclipse.jetty.util.security.Password;
+import org.openecomp.vid.changeManagement.ChangeManagementRequest;
import org.openecomp.vid.client.HttpBasicClient;
import org.openecomp.vid.client.HttpsBasicClient;
import org.openecomp.vid.mso.rest.RequestDetails;
@@ -57,7 +58,7 @@ public class MsoRestInterface extends MsoRestInt implements MsoRestInterfaceIfc /** The common headers. */
private MultivaluedHashMap<String, Object> commonHeaders;
-
+
/**
* Instantiates a new mso rest interface.
*/
@@ -68,7 +69,7 @@ public class MsoRestInterface extends MsoRestInt implements MsoRestInterfaceIfc /* (non-Javadoc)
* @see org.openecomp.vid.mso.MsoRestInterfaceIfc#initRestClient()
*/
- public void initRestClient()
+ public void initMsoClient()
{
final String methodname = "initRestClient()";
@@ -131,7 +132,7 @@ public class MsoRestInterface extends MsoRestInt implements MsoRestInterfaceIfc url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " sending request to url= " + url);
- initRestClient();
+ initMsoClient();
final Response cres = client.target(url)
.request()
@@ -170,7 +171,7 @@ public class MsoRestInterface extends MsoRestInt implements MsoRestInterfaceIfc logRequest (r);
try {
- initRestClient();
+ initMsoClient();
url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + " methodName sending request to: " + url);
@@ -232,8 +233,64 @@ public class MsoRestInterface extends MsoRestInt implements MsoRestInterfaceIfc logRequest (r);
try {
+
+ initMsoClient();
+
+ url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
+ logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " sending request to url= " + url);
+ // Change the content length
+ final Response cres = client.target(url)
+ .request()
+ .accept("application/json")
+ .headers(commonHeaders)
+ //.header("content-length", 201)
+ //.header("X-FromAppId", sourceID)
+ .post(Entity.entity(r, MediaType.APPLICATION_JSON));
- initRestClient();
+ try {
+ t = (T) cres.readEntity(t.getClass());
+ restObject.set(t);
+ }
+ catch ( Exception e ) {
+ logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e="
+ + e.getMessage());
+ }
+
+ int status = cres.getStatus();
+ restObject.setStatusCode (status);
+
+ if ( status >= 200 && status <= 299 ) {
+ logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!");
+ logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!");
+
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with status="+status+", url="+url);
+ }
+
+ } catch (Exception e)
+ {
+ logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString());
+ throw e;
+
+ }
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.openecomp.vid.mso.MsoRestInterfaceIfc#Put(java.lang.Object, org.openecomp.vid.mso.rest.RequestDetails, java.lang.String, java.lang.String, org.openecomp.vid.mso.RestObject)
+ */
+ @SuppressWarnings("unchecked")
+ public <T> void Put(T t, ChangeManagementRequest r, String sourceID, String path, RestObject<T> restObject) throws Exception {
+
+ String methodName = "Put";
+ String url="";
+
+ logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " start");
+
+// logRequest (r);
+ try {
+
+ initMsoClient();
url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " sending request to url= " + url);
@@ -244,7 +301,7 @@ public class MsoRestInterface extends MsoRestInt implements MsoRestInterfaceIfc .headers(commonHeaders)
//.header("content-length", 201)
//.header("X-FromAppId", sourceID)
- .post(Entity.entity(r, MediaType.APPLICATION_JSON));
+ .put(Entity.entity(r, MediaType.APPLICATION_JSON));
try {
t = (T) cres.readEntity(t.getClass());
@@ -287,7 +344,9 @@ public class MsoRestInterface extends MsoRestInt implements MsoRestInterfaceIfc public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException
{
return clazz.newInstance();
- }
+ }
+
+
}
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoRestInterfaceFactory.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoRestInterfaceFactory.java index 8bb3093c1..ab12c7b14 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoRestInterfaceFactory.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoRestInterfaceFactory.java @@ -21,28 +21,24 @@ package org.openecomp.vid.mso;
import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.openecomp.vid.mso.rest.MsoRestClientNew;
/**
* A factory for creating MsoRestInterface objects.
*/
public class MsoRestInterfaceFactory {
-
- /**
- * Gets the single instance of MsoRestInterfaceFactory.
- *
- * @return single instance of MsoRestInterfaceFactory
- */
- public static MsoRestInterfaceIfc getInstance () {
- MsoRestInterfaceIfc obj = null;
-
-// String mso_dme2_enabled = SystemProperties.getProperty(MsoProperties.MSO_DME2_ENABLED);
-// if ( (mso_dme2_enabled != null) && (mso_dme2_enabled.equalsIgnoreCase("true") ) ) {
-// obj = new MsoDme2RestInterface();
-// }
-// else {
- obj = new MsoRestInterface();
-// }
- return ( obj );
- }
+ /**
+ * Gets the single instance of MsoRestInterfaceFactory.
+ *
+ * @return single instance of MsoRestInterfaceFactory
+ */
+ public static MsoInterface getInstance() {
+ String msoPropertyName = "mso.client.type";
+ if (SystemProperties.containsProperty(msoPropertyName) &&
+ SystemProperties.getProperty(msoPropertyName).equals("LOCAL")) {
+ return new MsoLocalClientNew();
+ } else
+ return new MsoRestClientNew();
+ }
}
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoRestInterfaceIfc.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoRestInterfaceIfc.java index 1a6dbcccb..4ff13eddd 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoRestInterfaceIfc.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/MsoRestInterfaceIfc.java @@ -20,6 +20,7 @@ package org.openecomp.vid.mso;
+import org.openecomp.vid.changeManagement.ChangeManagementRequest;
import org.openecomp.vid.mso.rest.RequestDetails;
/**
@@ -30,7 +31,7 @@ public interface MsoRestInterfaceIfc { /**
* Inits the rest client.
*/
- public void initRestClient();
+ public void initMsoClient();
/**
* Gets the.
@@ -70,6 +71,18 @@ public interface MsoRestInterfaceIfc { */
public <T> void Post(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) throws Exception;
+ /**
+ * Put.
+ *
+ * @param <T> the generic type
+ * @param t the t
+ * @param r the r
+ * @param sourceID the source ID
+ * @param path the path
+ * @param restObject the rest object
+ * @throws Exception the exception
+ */
+ public <T> void Put(T t, ChangeManagementRequest r, String sourceID, String path, RestObject<T> restObject) throws Exception ;
/***
* Log request.
*
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/RestMsoImplementation.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/RestMsoImplementation.java new file mode 100644 index 000000000..ba0fdfaa8 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/RestMsoImplementation.java @@ -0,0 +1,326 @@ +package org.openecomp.vid.mso; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.codec.binary.Base64; +import org.eclipse.jetty.util.security.Password; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.vid.changeManagement.MsoRequestDetails; +import org.openecomp.vid.client.HttpBasicClient; +import org.openecomp.vid.client.HttpsBasicClient; +import org.openecomp.vid.mso.rest.RequestDetails; +import org.openecomp.vid.mso.rest.RestInterface; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.Response; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; + +/** + * Created by pickjonathan on 26/06/2017. + */ +public class RestMsoImplementation implements RestInterface { + + /** + * The logger. + */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMsoImplementation.class); + + /** + * The Constant dateFormat. + */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The client. */ + private static Client client = null; + + /** The common headers. */ + private MultivaluedHashMap<String, Object> commonHeaders; + /** + * Instantiates a new mso rest interface. + */ + + @Override + public void initMsoClient() + { + final String methodname = "initRestClient()"; + + final String username = SystemProperties.getProperty(MsoProperties.MSO_USER_NAME); + final String password = SystemProperties.getProperty(MsoProperties.MSO_PASSWORD); + final String mso_url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL); + final String decrypted_password = Password.deobfuscate(password); + + String authString = username + ":" + decrypted_password; + + byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); + String authStringEnc = new String(authEncBytes); + + commonHeaders = new MultivaluedHashMap<String, Object>(); + commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authStringEnc))); + + boolean use_ssl = true; + if ( (mso_url != null) && ( !(mso_url.isEmpty()) ) ) { + if ( mso_url.startsWith("https")) { + use_ssl = true; + } + else { + use_ssl = false; + } + } + if (client == null) { + + try { + if ( use_ssl ) { + //logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + methodname + " getting HttpsBasicClient with username=" + username + // + " password=" + password); + client = HttpsBasicClient.getClient(); + } + else { + //logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + methodname + " getting HttpsBasicClient with username=" + username + // + " password=" + password); + client = HttpBasicClient.getClient(); + } + } catch (Exception e) { + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + methodname + " Unable to get the SSL client"); + } + } + } + + public <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ) throws Exception { + String methodName = "Get"; + + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start"); + + String url=""; + restObject.set(t); + + url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " sending request to url= " + url); + + initMsoClient(); + + final Response cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + .get(); + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if (status == 200 || status == 202) { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " REST api was successfull!"); + + } else { + throw new Exception(methodName + " with status="+ status + ", url= " + url ); + } + + logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status ); + + return; + } + + @Override + public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) { + + String methodName = "Delete"; + String url=""; + Response cres = null; + + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " start"); + logRequest (r); + + try { + initMsoClient(); + + url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + " methodName sending request to: " + url); + + cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + //.entity(r) + .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke(); + // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)); + //.delete(Entity.entity(r, MediaType.APPLICATION_JSON)); + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if (status == 404) { // resource not found + String msg = "Resource does not exist...: " + cres.getStatus(); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); + } else if (status == 200 || status == 204){ + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + "Resource " + url + " deleted"); + } else if (status == 202) { + String msg = "Delete in progress: " + status; + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); + } + else { + String msg = "Deleting Resource failed: " + status; + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); + } + + try { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + } + catch ( Exception e ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e=" + + e.getMessage()); + } + + } + catch (Exception e) + { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString()); + throw e; + + } + } + + @Override + public <T> void Post(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) throws Exception { + String methodName = "Post"; + String url=""; + + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " start"); + + logRequest (r); + try { + + initMsoClient(); + + url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " sending request to url= " + url); + // Change the content length + final Response cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + //.header("content-length", 201) + //.header("X-FromAppId", sourceID) + .post(Entity.entity(r, MediaType.APPLICATION_JSON)); + + try { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + } + catch ( Exception e ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e=" + + e.getMessage()); + } + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if ( status >= 200 && status <= 299 ) { + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!"); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!"); + + } else { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with status="+status+", url="+url); + } + + } catch (Exception e) + { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString()); + throw e; + + } + } + + @Override + public void logRequest(RequestDetails r) { + String methodName = "logRequest"; + ObjectMapper mapper = new ObjectMapper(); + String r_json_str = ""; + if ( r != null ) { + r_json_str = r.toString(); + try { + r_json_str = mapper.writeValueAsString(r); + } + catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse request as json"); + } + } + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Request=(" + r_json_str + ")"); + } + + @Override + public void logRequest(org.openecomp.vid.changeManagement.RequestDetails r) { + String methodName = "logRequest"; + ObjectMapper mapper = new ObjectMapper(); + String r_json_str = ""; + if ( r != null ) { + r_json_str = r.toString(); + try { + r_json_str = mapper.writeValueAsString(r); + } + catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse request as json"); + } + } + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Request=(" + r_json_str + ")"); + } + + @Override + public <T> void Put(T t, org.openecomp.vid.changeManagement.RequestDetailsWrapper r, String sourceID, String path, RestObject<T> restObject) throws Exception { + + String methodName = "Put"; + String url=""; + + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " start"); + +// logRequest (r); + try { + + initMsoClient(); + + url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " sending request to url= " + url); + // Change the content length + final Response cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + //.header("content-length", 201) + //.header("X-FromAppId", sourceID) + .put(Entity.entity(r, MediaType.APPLICATION_JSON)); + + try { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + } + catch ( Exception e ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e=" + + e.getMessage()); + } + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if ( status >= 200 && status <= 299 ) { + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!"); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!"); + + } else { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with status="+status+", url="+url); + } + + } catch (Exception e) + { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString()); + throw e; + + } + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/MsoBusinessLogicNew.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/MsoBusinessLogicNew.java new file mode 100644 index 000000000..1afb2df21 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/MsoBusinessLogicNew.java @@ -0,0 +1,67 @@ +package org.openecomp.vid.mso.rest; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.vid.mso.MsoClientFactory; +import org.openecomp.vid.mso.MsoInterface; +import org.openecomp.vid.mso.MsoResponseWrapper; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * Created by pickjonathan on 21/06/2017. + * This class was created only for testing the new logic. + * It is not used by any of the controllers binded to the ui. + * This can be deleted in the future in order to keep a cleaner project. + * If deleting please dont forget to delete the controllers, factory and all involved in the assert test. + */ +public class MsoBusinessLogicNew { + + /** + * \ + * The MSO Client + */ + private MsoInterface msoClient; + + private MsoInterface msoRestTempClient; + + /** + * The logger. + */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoBusinessLogicNew.class); + + /** + * The Constant dateFormat. + */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + public MsoBusinessLogicNew() { + msoClient = MsoClientFactory.getInstance(); + msoRestTempClient = new MsoRestClientNew(); + } + + public MsoResponseWrapper createSvcInstance(RequestDetails msoRequest) throws Exception { + String methodName = "createSvcInstance "; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + +// String endpoint = SystemProperties.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE); +// +// MsoResponseWrapper w = createInstance(msoRequest, p); + + MsoResponseWrapper w = msoClient.createSvcInstance(msoRequest, ""); + + return w; + } + + + public MsoResponseWrapper createSvcInstanceRest(RequestDetails msoRequest) throws Exception { + String methodName = "createSvcInstance "; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + + MsoResponseWrapper w = msoRestTempClient.createSvcInstance(msoRequest, ""); + + return w; + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/MsoRestClientNew.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/MsoRestClientNew.java new file mode 100644 index 000000000..1beeafb13 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/MsoRestClientNew.java @@ -0,0 +1,333 @@ +package org.openecomp.vid.mso.rest; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.vid.changeManagement.MsoRequestDetails; +import org.openecomp.vid.changeManagement.RequestDetailsWrapper; +import org.openecomp.vid.mso.*; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + + +/** + * Created by pickjonathan on 21/06/2017. + */ +public class MsoRestClientNew extends RestMsoImplementation implements MsoInterface { + + /** + * The logger. + */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoRestClientNew.class); + + /** + * The Constant dateFormat. + */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + private final String ORIGINAL_REQUEST_ID = "originalRequestId"; + + + @Override + public MsoResponseWrapper createSvcInstance(RequestDetails requestDetails, String endpoint) throws Exception { + String methodName = "createSvcInstance "; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + return createInstance(requestDetails, endpoint); + } + + @Override + public MsoResponseWrapper createVnf(RequestDetails requestDetails, String endpoint) throws Exception { + + String methodName = "createVnf"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + return createInstance(requestDetails, endpoint); + } + + @Override + public MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String endpoint) throws Exception { + + String methodName = "createNwInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + return createInstance(requestDetails, endpoint); + } + + @Override + public MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String endpoint) throws Exception { + String methodName = "createVolumeGroupInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + return createInstance(requestDetails, endpoint); + } + + @Override + public MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String endpoint) throws Exception { + String methodName = "createVfModuleInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + return createInstance(requestDetails, endpoint); + } + + @Override + public MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String endpoint) throws Exception { + String methodName = "deleteSvcInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + return deleteInstance(requestDetails, endpoint); + } + + @Override + public MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String endpoint) throws Exception { + String methodName = "deleteVnf"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + return deleteInstance(requestDetails, endpoint); + } + + @Override + public MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String endpoint) throws Exception { + String methodName = "deleteVfModule"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + return deleteInstance(requestDetails, endpoint); + } + + @Override + public MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String endpoint) throws Exception { + String methodName = "deleteVolumeGroupInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + return deleteInstance(requestDetails, endpoint); + } + + @Override + public MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String endpoint) throws Exception { + String methodName = "deleteNwInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + return deleteInstance(requestDetails, endpoint); + } + + @Override + public void getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject) throws Exception { + Get(t, sourceId, endpoint, restObject); + } + + public void getManualTasks(String t, String sourceId, String endpoint, RestObject restObject) throws Exception { + Get(t, sourceId, endpoint, restObject); + } + + + public MsoResponseWrapper createInstance(RequestDetails request, String path) throws Exception { + String methodName = "createInstance"; + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + RestObject<String> restObjStr = new RestObject<String>(); + + String str = new String(); + + restObjStr.set(str); + + Post(str, request, "", path, restObjStr); + MsoResponseWrapper w = MsoUtil.wrapResponse(restObjStr); + + return w; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + + /** + * Delete instance. + * + * @param request the request + * @param path the path + * @return the mso response wrapper + * @throws Exception the exception + */ + public MsoResponseWrapper deleteInstance(RequestDetails request, String path) throws Exception { + String methodName = "deleteInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Delete, path =[" + path + "]"); + + RestObject<String> restObjStr = new RestObject<String>(); + String str = new String(); + restObjStr.set(str); + Delete(str, request, "", path, restObjStr); + MsoResponseWrapper w = MsoUtil.wrapResponse(restObjStr); + + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); + return w; + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + + } + + public MsoResponseWrapper getOrchestrationRequestsForDashboard(String t, String sourceId, String endpoint, RestObject restObject) throws Exception{ + String methodName = "getOrchestrationRequestsForDashboard"; + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + getOrchestrationRequest(t, sourceId, endpoint, restObject); + MsoResponseWrapper w = MsoUtil.wrapResponse(restObject); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); + + return w; + + } catch (Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + public MsoResponseWrapper getManualTasksByRequestId(String t , String sourceId , String endpoint , RestObject restObject) throws Exception{ + String methodName = "getManualTasksByRequestId"; + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + getManualTasks(t , sourceId , endpoint , restObject); + MsoResponseWrapper w = MsoUtil.wrapResponse(restObject); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); + + return MsoUtil.wrapResponse(restObject); + + } catch (Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + + + @Override + public MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject restObject) throws Exception { + String methodName = "completeManualTask"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Complete "); + try { + + Post(t, requestDetails , sourceId, endpoint, restObject); + MsoResponseWrapper w = MsoUtil.wrapResponse(restObject); + + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); + return w; + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + @Override + public MsoResponseWrapper replaceVnf(org.openecomp.vid.changeManagement.RequestDetails requestDetails, String endpoint) throws Exception { + String methodName = "replaceVnf"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + return replaceInstance(requestDetails, endpoint); + } + + public MsoResponseWrapper replaceInstance(org.openecomp.vid.changeManagement.RequestDetails request, String path) throws Exception { + String methodName = "replaceInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Replace VNF, path =[" + path + "]"); + + RestObject<String> restObjStr = new RestObject<String>(); + String str = new String(); + restObjStr.set(str); + RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper(); + requestDetailsWrapper.requestDetails = new MsoRequestDetails(request); + + Post(str, request, "", path, restObjStr); + MsoResponseWrapper msoResponseWrapperObject = MsoUtil.wrapResponse(restObjStr); + int status = msoResponseWrapperObject.getStatus(); + if (status == 202){ + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + + ",post succeeded, msoResponseWrapperObject response:" + msoResponseWrapperObject.getResponse()); + } + else { + logger.error(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + + ": post failed, msoResponseWrapperObject status" + status + ", response:" + msoResponseWrapperObject.getResponse()); + + // TODO + } + return msoResponseWrapperObject; + + } catch (Exception e) { + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + + } + + @Override + public MsoResponseWrapper updateVnf(org.openecomp.vid.changeManagement.RequestDetails requestDetails, String endpoint) throws Exception { + String methodName = "updateVnf"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + RequestDetailsWrapper wrapper = new RequestDetailsWrapper(); + wrapper.requestDetails = new MsoRequestDetails(requestDetails);; + return updateInstance(requestDetails, endpoint); + } + + public MsoResponseWrapper updateInstance(org.openecomp.vid.changeManagement.RequestDetails request, String path) throws Exception { + String methodName = "updateInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Delete, path =[" + path + "]"); + + RestObject<String> restObjStr = new RestObject<String>(); + String str = new String(); + restObjStr.set(str); + RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper(); + requestDetailsWrapper.requestDetails = new MsoRequestDetails(request); + + + + Put(str, requestDetailsWrapper, "", path, restObjStr); + MsoResponseWrapper w = MsoUtil.wrapResponse(restObjStr); + + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); + return w; + + } catch (Exception e) { + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + + } + + public void activateServiceInstance(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject<String> restObject) throws Exception{ + String methodName = "activateServiceInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start "); + try { + + Post(t, requestDetails , sourceId, endpoint, restObject); + MsoResponseWrapper w = MsoUtil.wrapResponse(restObject); + + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w =" + w.getResponse()); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RelatedModel.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RelatedModel.java index dc67a9456..427d71dd1 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RelatedModel.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RelatedModel.java @@ -46,6 +46,10 @@ public class RelatedModel extends org.openecomp.vid.domain.mso.RelatedModel { /** (Required). */
@JsonProperty("modelInfo")
private org.openecomp.vid.domain.mso.ModelInfo modelInfo;
+
+// /** The related model object instance list. */
+// @JsonProperty("instanceId")
+// private org.openecomp.vid.domain.mso.InstanceIds instanceId;
/** The additional properties. */
@JsonIgnore
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RequestDetails.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RequestDetails.java index 6e7c5af32..0cf697e0b 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RequestDetails.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RequestDetails.java @@ -65,7 +65,7 @@ public class RequestDetails extends org.openecomp.vid.domain.mso.RequestDetails /** The related model list. */
@JsonProperty("relatedModelList")
- private List<RelatedModel> relatedModelList;
+ private List<RelatedModel> relatedInstanceList;
/** The request info. */
@JsonProperty("requestInfo")
@@ -122,25 +122,24 @@ public class RequestDetails extends org.openecomp.vid.domain.mso.RequestDetails public void setModelInfo(ModelInfo modelInfo) {
this.modelInfo = modelInfo;
}
-
/**
- * Gets the related model list.
+ * Gets the related instance list.
*
- * @return The relatedModelList
+ * @return The relatedInstanceList
*/
- @JsonProperty("relatedModelList")
- public List<RelatedModel> getRelatedModelList() {
- return relatedModelList;
+ @JsonProperty("relatedInstanceList")
+ public List<RelatedModel> getRelatedInstanceList() {
+ return relatedInstanceList;
}
/**
* Sets the related model list.
*
- * @param relatedModelList The relatedModelList
+ * @param relatedInstanceList The relatedInstanceList
*/
- @JsonProperty("relatedModelList")
- public void setRelatedModelList( List<RelatedModel> relatedModelList) {
- this.relatedModelList = relatedModelList;
+ @JsonProperty("relatedInstanceList")
+ public void setRelatedInstanceList( List<RelatedModel> relatedInstanceList) {
+ this.relatedInstanceList = relatedInstanceList;
}
/**
@@ -212,7 +211,7 @@ public class RequestDetails extends org.openecomp.vid.domain.mso.RequestDetails */
@Override
public int hashCode() {
- return new HashCodeBuilder().append(cloudConfiguration).append(modelInfo).append(relatedModelList).append(requestInfo).append(getRequestParameters()).append(subscriberInfo).append(additionalProperties).toHashCode();
+ return new HashCodeBuilder().append(cloudConfiguration).append(modelInfo).append(relatedInstanceList).append(requestInfo).append(getRequestParameters()).append(subscriberInfo).append(additionalProperties).toHashCode();
}
/* (non-Javadoc)
@@ -227,7 +226,7 @@ public class RequestDetails extends org.openecomp.vid.domain.mso.RequestDetails return false;
}
RequestDetails rhs = ((RequestDetails) other);
- return new EqualsBuilder().append(cloudConfiguration, rhs.cloudConfiguration).append(modelInfo, rhs.modelInfo).append(relatedModelList, rhs.relatedModelList).append(requestInfo, rhs.requestInfo).append(getRequestParameters(), rhs.getRequestParameters()).append(subscriberInfo, rhs.subscriberInfo).append(additionalProperties, rhs.additionalProperties).isEquals();
+ return new EqualsBuilder().append(cloudConfiguration, rhs.cloudConfiguration).append(modelInfo, rhs.modelInfo).append(relatedInstanceList, rhs.relatedInstanceList).append(requestInfo, rhs.requestInfo).append(getRequestParameters(), rhs.getRequestParameters()).append(subscriberInfo, rhs.subscriberInfo).append(additionalProperties, rhs.additionalProperties).isEquals();
}
}
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RequestList.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RequestList.java index 7c366ac82..8a57c74b7 100755 --- a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RequestList.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RequestList.java @@ -58,7 +58,7 @@ import java.util.List; public class RequestList {
/** The request list. */
- private List<Request> requestList;
+ private List<RequestWrapper> requestList;
/** The additional properties. */
@JsonIgnore
@@ -69,7 +69,7 @@ public class RequestList { *
* @return The RelatedModel List
*/
- public List<Request> getRequestList() {
+ public List<RequestWrapper> getRequestList() {
return requestList;
}
@@ -78,7 +78,7 @@ public class RequestList { *
* @param l the new request list
*/
- public void setRequestList(List<Request> l) {
+ public void setRequestList(List<RequestWrapper> l) {
this.requestList = l;
}
diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RequestWrapper.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RequestWrapper.java new file mode 100644 index 000000000..b0e9fa125 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RequestWrapper.java @@ -0,0 +1,35 @@ +package org.openecomp.vid.mso.rest; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * request wrapper structure. + */ +public class RequestWrapper { + + + /** The request. */ + private Request request; + + + /** + * Gets the request. + * + * @return The requestDetails + */ + @JsonProperty("request") + public Request getRequest() { + return request; + } + + /** + * Sets the request. + * + * @param request The request + */ + @JsonProperty + public void setRequest(Request request) { + this.request = request; + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/Response.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/Response.java new file mode 100644 index 000000000..ee3a8bfef --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/Response.java @@ -0,0 +1,54 @@ +package org.openecomp.vid.mso.rest; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Response { + + /** The status. */ + private int status; + + /** The entity. */ + private RequestList entity; + + /** + * Gets the status. + * + * @return The status + */ + @JsonProperty("status") + public int getStatus() { + return status; + } + + /** + * Sets the status. + * + * @param status The status + */ + @JsonProperty("status") + public void setStatus(int status) { + this.status = status; + } + + /** + * Gets the entity. + * + * @return The entity + */ + @JsonProperty("entity") + public RequestList getEntity() { + return entity; + } + + /** + * Sets the entity. + * + * @param entity The entity + */ + @JsonProperty("entity") + public void setEntity(RequestList entity) { + this.entity = entity; + } + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RestInterface.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RestInterface.java new file mode 100644 index 000000000..1e2733587 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/RestInterface.java @@ -0,0 +1,81 @@ +package org.openecomp.vid.mso.rest; + +import org.openecomp.vid.mso.RestObject; + +/** + * Created by pickjonathan on 26/06/2017. + */ +public interface RestInterface { + + /** + * Inits the rest client. + */ + public void initMsoClient(); + + /** + * Gets the. + * + * @param <T> the generic type + * @param t the t + * @param sourceId the source id + * @param path the path + * @param restObject the rest object + * @throws Exception the exception + */ + public <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ) throws Exception; + + /** + * Delete. + * + * @param <T> the generic type + * @param t the t + * @param r the r + * @param sourceID the source ID + * @param path the path + * @param restObject the rest object + * @throws Exception the exception + */ + public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) throws Exception; + + /** + * Post. + * + * @param <T> the generic type + * @param t the t + * @param r the r + * @param sourceID the source ID + * @param path the path + * @param restObject the rest object + * @throws Exception the exception + */ + public <T> void Post(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) throws Exception; + + /** + * Put. + * + * @param <T> the generic type + * @param t the t + * @param r the r + * @param sourceID the source ID + * @param path the path + * @param restObject the rest object + * @throws Exception the exception + */ + public <T> void Put(T t, org.openecomp.vid.changeManagement.RequestDetailsWrapper r, String sourceID, String path, RestObject<T> restObject) throws Exception; + + + /*** + * Log request. + * + * @param r the r + */ + public void logRequest ( RequestDetails r ); + /*** + * Log request. + * + * @param r the r + */ + public void logRequest(org.openecomp.vid.changeManagement.RequestDetails r); + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/Task.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/Task.java new file mode 100644 index 000000000..8d72890ff --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/Task.java @@ -0,0 +1,119 @@ +package org.openecomp.vid.mso.rest; + +import java.util.List; + +public class Task { + + private String taskId; + private String type; + private String nfRole; + private String subscriptionServiceType; + private String originalRequestId; + private String originalRequestorId; + private String errorSource; + private String errorCode; + private String errorMessage; + private String buildingBlockName; + private String buildingBlockStep; + private List<String> validResponses; + + + public String getTaskId() { + return taskId; + } + + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getNfRole() { + return nfRole; + } + + public void setNfRole(String nfRole) { + this.nfRole = nfRole; + } + + public String getSubscriptionServiceType() { + return subscriptionServiceType; + } + + public void setSubscriptionServiceType(String subscriptionServiceType) { + this.subscriptionServiceType = subscriptionServiceType; + } + + public String getOriginalRequestId() { + return originalRequestId; + } + + public void setOriginalRequestId(String originalRequestId) { + this.originalRequestId = originalRequestId; + } + + public String getOriginalRequestorId() { + return originalRequestorId; + } + + public void setOriginalRequestorId(String originalRequestorId) { + this.originalRequestorId = originalRequestorId; + } + + public String getErrorSource() { + return errorSource; + } + + public void setErrorSource(String errorSource) { + this.errorSource = errorSource; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public String getBuildingBlockName() { + return buildingBlockName; + } + + public void setBuildingBlockName(String buildingBlockName) { + this.buildingBlockName = buildingBlockName; + } + + public String getBuildingBlockStep() { + return buildingBlockStep; + } + + public void setBuildingBlockStep(String buildingBlockStep) { + this.buildingBlockStep = buildingBlockStep; + } + + public List<String> getValidResponses() { + return validResponses; + } + + public void setValidResponses(List<String> validResponses) { + this.validResponses = validResponses; + } + + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/TaskList.java b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/TaskList.java new file mode 100644 index 000000000..7232364a3 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/mso/rest/TaskList.java @@ -0,0 +1,16 @@ +package org.openecomp.vid.mso.rest; + +import java.util.List; + +public class TaskList { + + public List<Task> getTaskList() { + return taskList; + } + + public void setTaskList(List<Task> taskList) { + this.taskList = taskList; + } + + private List<Task> taskList; +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyProperties.java b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyProperties.java new file mode 100644 index 000000000..d273aa6a7 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyProperties.java @@ -0,0 +1,26 @@ +package org.openecomp.vid.policy; + +import org.openecomp.portalsdk.core.util.SystemProperties; + + +public class PolicyProperties extends SystemProperties { + + public static final String POLICY_CLIENTAUTH_VAL = "policy.ClientAuth"; + + public static final String POLICY_CLIENT_MECHID_VAL = "policy.client.mechId"; + + public static final String POLICY_CLIENT_PASSWORD_VAL = "policy.client.password"; + + public static final String POLICY_USERNAME_VAL = "policy.username"; + + public static final String POLICY_PASSWORD_VAL = "policy.password"; + + public static final String POLICY_AUTHORIZATION_VAL = "policy.Authorization"; + + public static final String POLICY_SERVER_URL_VAL = "policy.server.url"; + + public static final String POLICY_ENVIRONMENT_VAL = "policy.environment"; + + public static final String POLICY_GET_CONFIG_VAL = "policy.get.config"; + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyResponseWrapper.java b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyResponseWrapper.java new file mode 100644 index 000000000..02ca0f0ec --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyResponseWrapper.java @@ -0,0 +1,56 @@ +package org.openecomp.vid.policy; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +/** + * This wrapper encapsulates the Policy response + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "status", + "entity" +}) + +public class PolicyResponseWrapper { + + @JsonProperty("status") + private int status; + + @JsonProperty("entity") + private String entity; + + @JsonProperty("entity") + public String getEntity() { + return entity; + } + + @JsonProperty("status") + public int getStatus() { + return status; + } + + @JsonProperty("status") + public void setStatus(int v) { + this.status = v; + } + + @JsonProperty("entity") + public void setEntity(String v) { + this.entity = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse () { + + StringBuilder b = new StringBuilder ("{ \"status\": "); + b.append(getStatus()).append(", \"entity\": " ).append(this.getEntity()).append("}"); + return (b.toString()); + } +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyRestInt.java b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyRestInt.java new file mode 100644 index 000000000..7c075a535 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyRestInt.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.policy; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.vid.policy.rest.RequestDetails; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PolicyRestInt { + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyRestInterface.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The request date format. */ + public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); + + public PolicyRestInt() { + requestDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT")); + } + + /** + * Log request. + * + * @param r the r + */ + public void logRequest ( RequestDetails r ) { + String methodName = "logRequest"; + ObjectMapper mapper = new ObjectMapper(); + String r_json_str = ""; + if ( r != null ) { + r_json_str = r.toString(); + try { + r_json_str = mapper.writeValueAsString(r); + } + catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse request as json"); + } + } + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Request=(" + r_json_str + ")"); + } +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyRestInterface.java b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyRestInterface.java new file mode 100644 index 000000000..d6a59da20 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyRestInterface.java @@ -0,0 +1,234 @@ +package org.openecomp.vid.policy; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.Response; + +import org.apache.commons.codec.binary.Base64; +import org.eclipse.jetty.util.security.Password; +import org.json.simple.JSONObject; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.vid.client.HttpBasicClient; +import org.openecomp.vid.policy.rest.RequestDetails; + +public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInterfaceIfc { + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyRestInterface.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The client. */ + private static Client client = null; + + /** The common headers. */ + private MultivaluedHashMap<String, Object> commonHeaders; + + public PolicyRestInterface() { + super(); + } + + public void initRestClient() + { + final String methodname = "initRestClient()"; + + //final String clientAuth = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENTAUTH_VAL); + //final String authorization = SystemProperties.getProperty(PolicyProperties.POLICY_AUTHORIZATION_VAL); + final String mechId = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENT_MECHID_VAL); + final String clientPassword = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENT_PASSWORD_VAL); + final String username = SystemProperties.getProperty(PolicyProperties.POLICY_USERNAME_VAL); + final String password = SystemProperties.getProperty(PolicyProperties.POLICY_PASSWORD_VAL); + final String environment = SystemProperties.getProperty(PolicyProperties.POLICY_ENVIRONMENT_VAL); + + final String decrypted_client_password = Password.deobfuscate(clientPassword); + String mechAuthString = mechId + ":" + decrypted_client_password; + byte[] mechAuthEncBytes = Base64.encodeBase64(mechAuthString.getBytes()); + String clientAuth = new String(mechAuthEncBytes); + + final String decrypted_password = Password.deobfuscate(password); + String authString = username + ":" + decrypted_password; + byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); + String authorization = new String(authEncBytes); + + commonHeaders = new MultivaluedHashMap<String, Object> (); + commonHeaders.put("ClientAuth", Collections.singletonList((Object) ("Basic " + clientAuth))); + commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authorization))); + commonHeaders.put("Environment", Collections.singletonList((Object) (environment))); + + if (client == null) { + + try { + client = HttpBasicClient.getClient(); + } catch (Exception e) { + System.out.println( methodname + " Unable to get the SSL client"); + } + } + } + + @SuppressWarnings("unchecked") + public <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ) throws Exception { + String methodName = "Get"; + + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start"); + + String url=""; + restObject.set(t); + + url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " sending request to url= " + url); + + initRestClient(); + + final Response cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + .get(); + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if (status == 200) { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " REST api was successfull!"); + + } else { + throw new Exception(methodName + " with status="+ status + ", url= " + url ); + } + + logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status ); + + return; + } + + @SuppressWarnings("unchecked") + public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) { + + String methodName = "Delete"; + String url=""; + Response cres = null; + + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " start"); + logRequest (r); + + try { + initRestClient(); + + url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path; + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + " methodName sending request to: " + url); + + cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + //.entity(r) + .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke(); + // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)); + //.delete(Entity.entity(r, MediaType.APPLICATION_JSON)); + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if (status == 404) { // resource not found + String msg = "Resource does not exist...: " + cres.getStatus(); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); + } else if (status == 200 || status == 204){ + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + "Resource " + url + " deleted"); + } else if (status == 202) { + String msg = "Delete in progress: " + status; + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); + } + else { + String msg = "Deleting Resource failed: " + status; + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); + } + + try { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + } + catch ( Exception e ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e=" + + e.getMessage()); + } + + } + catch (Exception e) + { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString()); + throw e; + + } + } + + @SuppressWarnings("unchecked") + public <T> void Post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject) throws Exception { + + String methodName = "Post"; + String url=""; + + System.out.println( "POST policy rest interface"); + + // logRequest (requestDetails); + try { + + initRestClient(); + + url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path; + System.out.println( "<== " + methodName + " sending request to url= " + url); + // Change the content length + final Response cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + //.header("content-length", 201) + //.header("X-FromAppId", sourceID) + .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); + + try { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + } + catch ( Exception e ) { + + System.out.println("<== " + methodName + " No response entity, this is probably ok, e=" + e.getMessage()); + } + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if ( status >= 200 && status <= 299 ) { + System.out.println( "<== " + methodName + " REST api POST was successful!"); + + } else { + System.out.println( "<== " + methodName + " with status="+status+", url="+url); + } + + } catch (Exception e) + { + System.out.println( "<== " + methodName + " with url="+url+ ", Exception: " + e.toString()); + throw e; + + } + } + + public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException + { + return clazz.newInstance(); + } + + @Override + public void logRequest(RequestDetails r) { + // TODO Auto-generated method stub + } +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyRestInterfaceFactory.java b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyRestInterfaceFactory.java new file mode 100644 index 000000000..1570875c0 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyRestInterfaceFactory.java @@ -0,0 +1,14 @@ + +package org.openecomp.vid.policy; + +public class PolicyRestInterfaceFactory { + + + public static PolicyRestInterfaceIfc getInstance () { + PolicyRestInterfaceIfc obj = null; + + obj = new PolicyRestInterface(); + + return ( obj ); + } +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyRestInterfaceIfc.java b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyRestInterfaceIfc.java new file mode 100644 index 000000000..f56924b36 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyRestInterfaceIfc.java @@ -0,0 +1,58 @@ + +package org.openecomp.vid.policy; + +import org.json.simple.JSONObject; +import org.openecomp.vid.policy.rest.RequestDetails; + +public interface PolicyRestInterfaceIfc { + /** + * Inits the rest client. + */ + public void initRestClient(); + + /** + * Gets the. + * + * @param <T> the generic type + * @param t the t + * @param sourceId the source id + * @param path the path + * @param restObject the rest object + * @throws Exception the exception + */ + public <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ) throws Exception; + + /** + * Delete. + * + * @param <T> the generic type + * @param t the t + * @param r the r + * @param sourceID the source ID + * @param path the path + * @param restObject the rest object + * @throws Exception the exception + */ + public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) throws Exception; + + /** + * Post. + * + * @param <T> the generic type + * @param t the t + * @param r the r + * @param sourceID the source ID + * @param path the path + * @param restObject the rest object + * @throws Exception the exception + */ + public <T> void Post(T t, JSONObject r, String sourceID, String path, RestObject<T> restObject) throws Exception; + + /*** + * Log request. + * + * @param r the r + */ + public void logRequest ( RequestDetails r ); + +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyUtil.java b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyUtil.java new file mode 100644 index 000000000..ceda7c427 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/policy/PolicyUtil.java @@ -0,0 +1,71 @@ +package org.openecomp.vid.policy; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.glassfish.jersey.client.ClientResponse; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.vid.policy.PolicyResponseWrapper; +import org.openecomp.vid.policy.PolicyUtil; +import org.openecomp.vid.policy.RestObject; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PolicyUtil { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyUtil.class); + + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + public static PolicyResponseWrapper wrapResponse ( String body, int statusCode ) { + + PolicyResponseWrapper w = new PolicyResponseWrapper(); + w.setStatus (statusCode); + w.setEntity(body); + + return w; + } + + public static PolicyResponseWrapper wrapResponse (ClientResponse cres) { + String resp_str = ""; + if ( cres != null ) { + resp_str = cres.readEntity(String.class); + } + int statuscode = cres.getStatus(); + PolicyResponseWrapper w = PolicyUtil.wrapResponse ( resp_str, statuscode ); + return (w); + } + + public static PolicyResponseWrapper wrapResponse (RestObject<String> rs) { + String resp_str = ""; + int status = 0; + if ( rs != null ) { + resp_str = rs.get(); + status = rs.getStatusCode(); + } + PolicyResponseWrapper w = PolicyUtil.wrapResponse ( resp_str, status ); + return (w); + } + + public static <T> String convertPojoToString ( T t ) throws com.fasterxml.jackson.core.JsonProcessingException { + + String methodName = "convertPojoToString"; + ObjectMapper mapper = new ObjectMapper(); + String r_json_str = ""; + if ( t != null ) { + try { + r_json_str = mapper.writeValueAsString(t); + } + catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse object as json"); + } + } + return (r_json_str); + } + + + public static void main(String[] args) { + // TODO Auto-generated method stub + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/policy/RestObject.java b/vid-app-common/src/main/java/org/openecomp/vid/policy/RestObject.java new file mode 100644 index 000000000..de085f24b --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/policy/RestObject.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.policy; + +/** + * The Class RestObject. + * + * @param <T> the generic type + */ +public class RestObject<T> { + + /** + * Generic version of the RestObject class. + * + */ + // T stands for "Type" + private T t; + + /** The status code. */ + private int statusCode= 0; + + /** + * Sets the. + * + * @param t the t + */ + public void set(T t) { this.t = t; } + + /** + * Gets the. + * + * @return the t + */ + public T get() { return t; } + + /** + * Sets the status code. + * + * @param v the new status code + */ + public void setStatusCode(int v) { this.statusCode = v; } + + /** + * Gets the status code. + * + * @return the status code + */ + public int getStatusCode() { return this.statusCode; } + +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/openecomp/vid/policy/rest/RequestDetails.java b/vid-app-common/src/main/java/org/openecomp/vid/policy/rest/RequestDetails.java new file mode 100644 index 000000000..93e80d6b3 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/policy/rest/RequestDetails.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.policy.rest; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +/* + [ + { + "policyConfigMessage": "Config Retrieved! ", + "policyConfigStatus": "CONFIG_RETRIEVED", + "type": "JSON", + "config": "{\"service\":\"TimeLimitAndVerticalTopology\",\"policyName\":\"SNIRO_CM_1707.Demo_TimeLimitAndVerticalTopology_zone_localTime\",\"description\":\"dev instance\",\"templateVersion\":\"1702.03\",\"version\":\"1707\",\"priority\":\"4\",\"riskType\":\"test\",\"riskLevel\":\"3\",\"guard\":\"False\",\"content\":{\"serviceType\":\"networkOnDemand\",\"identity\":\"vnf_upgrade_policy\",\"policyScope\":{\"serviceType\":[\"networkOnDemand\"],\"aicZone\":[\" \"],\"entityType\":[\"vnf\"]},\"timeSchedule\":{\"allowedPeriodicTime\":[{\"day\":\"weekday\",\"timeRange\":[{\"start_time\":\"04:00:00\",\"end_time\":\"13:00:00\"}]}]},\"nodeType\":[\"vnf\"],\"type\":\"timeLimitAndVerticalTopology\",\"conflictScope\":\"vnf_zone\"}}", + "policyName": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_zone_localTime.1.xml", + "policyVersion": "1", + "matchingConditions": { + "ECOMPName": "SNIRO-Placement", + "ConfigName": "", + "service": "TimeLimitAndVerticalTopology", + "uuid": "", + "Location": "" + }, + "responseAttributes": {}, + "property": null + }, + { + "policyConfigMessage": "Config Retrieved! ", + "policyConfigStatus": "CONFIG_RETRIEVED", + "type": "JSON", + "config": "{\"service\":\"TimeLimitAndVerticalTopology\",\"policyName\":\"SNIRO_CM_1707.Demo_TimeLimitAndVerticalTopology_pserver_localTime\",\"description\":\"dev instance\",\"templateVersion\":\"1702.03\",\"version\":\"1707\",\"priority\":\"4\",\"riskType\":\"test\",\"riskLevel\":\"3\",\"guard\":\"False\",\"content\":{\"serviceType\":\"networkOnDemand\",\"identity\":\"vnf_upgrade_policy\",\"policyScope\":{\"serviceType\":[\"networkOnDemand\"],\"aicZone\":[\" \"],\"entityType\":[\"vnf\"]},\"timeSchedule\":{\"allowedPeriodicTime\":[{\"day\":\"weekday\",\"timeRange\":[{\"start_time\":\"04:00:00\",\"end_time\":\"13:00:00\"}]}]},\"nodeType\":[\"vnf\"],\"type\":\"timeLimitAndVerticalTopology\",\"conflictScope\":\"vnf_pserver\"}}", + "policyName": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_pserver_localTime.1.xml", + "policyVersion": "1", + "matchingConditions": { + "ECOMPName": "SNIRO-Placement", + "ConfigName": "", + "service": "TimeLimitAndVerticalTopology", + "uuid": "", + "Location": "" + }, + "responseAttributes": {}, + "property": null + }, + { + "policyConfigMessage": "Config Retrieved! ", + "policyConfigStatus": "CONFIG_RETRIEVED", + "type": "JSON", + "config": "{\"service\":\"TimeLimitAndVerticalTopology\",\"policyName\":\"SNIRO_CM_1707.Demo_TimeLimitAndVerticalTopology_vnf_localTime\",\"description\":\"dev instance\",\"templateVersion\":\"1702.03\",\"version\":\"1707\",\"priority\":\"4\",\"riskType\":\"test\",\"riskLevel\":\"3\",\"guard\":\"False\",\"content\":{\"serviceType\":\"networkOnDemand\",\"identity\":\"vnf_upgrade_policy\",\"policyScope\":{\"serviceType\":[\"networkOnDemand\"],\"aicZone\":[\" \"],\"entityType\":[\"vnf\"]},\"timeSchedule\":{\"allowedPeriodicTime\":[{\"day\":\"weekday\",\"timeRange\":[{\"start_time\":\"04:00:00\",\"end_time\":\"13:00:00\"}]}]},\"nodeType\":[\"vnf\"],\"type\":\"timeLimitAndVerticalTopology\",\"conflictScope\":\"vnf\"}}", + "policyName": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_vnf_localTime.1.xml", + "policyVersion": "1", + "matchingConditions": { + "ECOMPName": "SNIRO-Placement", + "ConfigName": "", + "service": "TimeLimitAndVerticalTopology", + "uuid": "", + "Location": "" + }, + "responseAttributes": {}, + "property": null + } + ] +*/ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "policyConfigMessage", + "policyConfigStatus", + "type", + "config", + "policyName", + "policyVersion", + "matchingConditions" +}) +public class RequestDetails { + + @JsonProperty("policyName") + private String policyName; + + @JsonProperty("policyName") + public String getPolicyName() { + return policyName; + } + + @JsonProperty("policyName") + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/openecomp/vid/properties/MsoClientConfiguration.java b/vid-app-common/src/main/java/org/openecomp/vid/properties/MsoClientConfiguration.java new file mode 100644 index 000000000..f7a331a7e --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/properties/MsoClientConfiguration.java @@ -0,0 +1,9 @@ +package org.openecomp.vid.properties; + +/** + * Created by pickjonathan on 20/06/2017. + */ +public class MsoClientConfiguration { + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/roles/Role.java b/vid-app-common/src/main/java/org/openecomp/vid/roles/Role.java index d4ded5303..f818e48fa 100644 --- a/vid-app-common/src/main/java/org/openecomp/vid/roles/Role.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/roles/Role.java @@ -1,9 +1,9 @@ package org.openecomp.vid.roles; - /** * Created by Oren on 7/1/17. */ + public class Role { private EcompRole ecompRole; diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObject.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObject.java new file mode 100644 index 000000000..57b36830e --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObject.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.scheduler; + + +public class RestObject<T> { + + private T t; + + private int statusCode= 0; + + public String uuid; + + public void set(T t) { this.t = t; } + + public T get() { return t; } + + public void setStatusCode(int v) { this.statusCode = v; } + + public int getStatusCode() { return this.statusCode; } + + public void setUUID(String uuid) { this.uuid = uuid; } + + public String getUUID() { return this.uuid; } +} + diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObjects/GetTimeSlotsRestObject.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObjects/GetTimeSlotsRestObject.java new file mode 100644 index 000000000..614b557a0 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObjects/GetTimeSlotsRestObject.java @@ -0,0 +1,11 @@ +package org.openecomp.vid.scheduler.RestObjects; + +public class GetTimeSlotsRestObject<T> extends org.openecomp.vid.scheduler.RestObject<T> { + + public String uuid; + + public void setUUID(String uuid) { this.uuid = uuid; } + + public String getUUID() { return this.uuid; } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObjects/PostCreateNewVnfRestObject.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObjects/PostCreateNewVnfRestObject.java new file mode 100644 index 000000000..86cbab8a6 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObjects/PostCreateNewVnfRestObject.java @@ -0,0 +1,10 @@ +package org.openecomp.vid.scheduler.RestObjects; + +public class PostCreateNewVnfRestObject<T> extends RestObject<T> { + + public String uuid; + + public void setUUID(String uuid) { this.uuid = uuid; } + + public String getUUID() { return this.uuid; } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObjects/PostSubmitVnfChangeRestObject.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObjects/PostSubmitVnfChangeRestObject.java new file mode 100644 index 000000000..6fb56f67d --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObjects/PostSubmitVnfChangeRestObject.java @@ -0,0 +1,10 @@ +package org.openecomp.vid.scheduler.RestObjects; + +public class PostSubmitVnfChangeRestObject<T> extends RestObject<T> { + + public String uuid; + + public void setUUID(String uuid) { this.uuid = uuid; } + + public String getUUID() { return this.uuid; } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObjects/RestObject.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObjects/RestObject.java new file mode 100644 index 000000000..2d0eec74d --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/RestObjects/RestObject.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.scheduler.RestObjects; + + +public class RestObject<T> { + + private T t; + + private int statusCode= 0; + + public void set(T t) { this.t = t; } + + public T get() { return t; } + + public void setStatusCode(int v) { this.statusCode = v; } + + public int getStatusCode() { return this.statusCode; } + +} + diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerProperties.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerProperties.java new file mode 100644 index 000000000..15855b7be --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerProperties.java @@ -0,0 +1,24 @@ +package org.openecomp.vid.scheduler; + +import org.openecomp.portalsdk.core.util.SystemProperties; + + +public class SchedulerProperties extends SystemProperties { + + public static final String SCHEDULER_USER_NAME_VAL = "scheduler.user.name"; + + public static final String SCHEDULER_PASSWORD_VAL = "scheduler.password"; + + public static final String SCHEDULER_SERVER_URL_VAL = "scheduler.server.url"; + + public static final String SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL = "scheduler.create.new.vnf.change.instance"; + + public static final String SCHEDULER_GET_TIME_SLOTS = "scheduler.get.time.slots"; + + public static final String SCHEDULER_SUBMIT_NEW_VNF_CHANGE = "scheduler.submit.new.vnf.change"; + + public static final String SCHEDULER_GET_SCHEDULES = "scheduler.get.schedules"; + + public static final String GET_VERSION_BY_INVARIANT_ID = "aai_get_version_by_invariant_id"; + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrapper.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrapper.java new file mode 100644 index 000000000..5f148c06b --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrapper.java @@ -0,0 +1,71 @@ +package org.openecomp.vid.scheduler; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +/** + * This wrapper encapsulates the Scheduler response + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "status", + "entity", + "uuid" +}) + +public class SchedulerResponseWrapper { + + @JsonProperty("status") + private int status; + + @JsonProperty("entity") + private String entity; + + @JsonProperty("uuid") + private String uuid; + + @JsonProperty("entity") + public String getEntity() { + return entity; + } + + @JsonProperty("status") + public int getStatus() { + return status; + } + + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + + @JsonProperty("status") + public void setStatus(int v) { + this.status = v; + } + + @JsonProperty("entity") + public void setEntity(String v) { + this.entity = v; + } + + @JsonProperty("uuid") + public void setUuid(String v) { + this.uuid = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse () { + + StringBuilder b = new StringBuilder ("{ \"status\": "); + b.append(getStatus()).append(", \"entity\": \" " ).append(this.getEntity()).append("\" ,\"uuid\": \"" ).append(this.getUuid()).append("\"}"); + return (b.toString()); + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrappers/GetTimeSlotsWrapper.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrappers/GetTimeSlotsWrapper.java new file mode 100644 index 000000000..e5001d41f --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrappers/GetTimeSlotsWrapper.java @@ -0,0 +1,5 @@ +package org.openecomp.vid.scheduler.SchedulerResponseWrappers; + +public class GetTimeSlotsWrapper extends SchedulerResponseWrapper { + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrappers/PostCreateNewVnfWrapper.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrappers/PostCreateNewVnfWrapper.java new file mode 100644 index 000000000..f1baeaf6e --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrappers/PostCreateNewVnfWrapper.java @@ -0,0 +1,39 @@ +package org.openecomp.vid.scheduler.SchedulerResponseWrappers; + +import org.apache.commons.lang.builder.ToStringBuilder; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "uuid" +}) +public class PostCreateNewVnfWrapper extends SchedulerResponseWrapper { + + @JsonProperty("uuid") + private String uuid; + + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + + @JsonProperty("uuid") + public void setUuid(String v) { + this.uuid = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse () { + + StringBuilder b = new StringBuilder ("{ \"status\": "); + b.append(getStatus()).append(", \"entity\": \" " ).append(this.getEntity()).append("\" ,\"uuid\": \"" ).append(this.getUuid()).append("\"}"); + return (b.toString()); + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrappers/PostSubmitVnfChangeTimeSlotsWrapper.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrappers/PostSubmitVnfChangeTimeSlotsWrapper.java new file mode 100644 index 000000000..86e4c0a74 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrappers/PostSubmitVnfChangeTimeSlotsWrapper.java @@ -0,0 +1,38 @@ +package org.openecomp.vid.scheduler.SchedulerResponseWrappers; + +import org.apache.commons.lang.builder.ToStringBuilder; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "uuid" +}) +public class PostSubmitVnfChangeTimeSlotsWrapper extends SchedulerResponseWrapper { + @JsonProperty("uuid") + private String uuid; + + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + + @JsonProperty("uuid") + public void setUuid(String v) { + this.uuid = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse () { + + StringBuilder b = new StringBuilder ("{ \"status\": "); + b.append(getStatus()).append(", \"entity\": \" " ).append(this.getEntity()).append("\" ,\"uuid\": \"" ).append(this.getUuid()).append("\"}"); + return (b.toString()); + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrappers/SchedulerResponseWrapper.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrappers/SchedulerResponseWrapper.java new file mode 100644 index 000000000..081ed3dc4 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerResponseWrappers/SchedulerResponseWrapper.java @@ -0,0 +1,57 @@ +package org.openecomp.vid.scheduler.SchedulerResponseWrappers; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +/** + * This wrapper encapsulates the Scheduler response + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "status", + "entity" +}) + +public class SchedulerResponseWrapper { + + @JsonProperty("status") + private int status; + + @JsonProperty("entity") + private String entity; + + @JsonProperty("entity") + public String getEntity() { + return entity; + } + + @JsonProperty("status") + public int getStatus() { + return status; + } + + @JsonProperty("status") + public void setStatus(int v) { + this.status = v; + } + + @JsonProperty("entity") + public void setEntity(String v) { + this.entity = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse () { + + StringBuilder b = new StringBuilder ("{ \"status\": "); + + b.append(getStatus()).append(", \"entity\": " ).append(this.getEntity()).append("}"); + return (b.toString()); + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerRestInt.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerRestInt.java new file mode 100644 index 000000000..32b3a9c8c --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerRestInt.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.scheduler; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class SchedulerRestInt { + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The request date format. */ + public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); + + public SchedulerRestInt() { + requestDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT")); + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerRestInterface.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerRestInterface.java new file mode 100644 index 000000000..5f529f390 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerRestInterface.java @@ -0,0 +1,208 @@ +package org.openecomp.vid.scheduler; + +import java.util.Collections; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.Response; + +import org.apache.commons.codec.binary.Base64; +import org.eclipse.jetty.util.security.Password; +import org.json.simple.JSONObject; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.vid.client.HttpBasicClient; +import org.openecomp.vid.client.HttpsBasicClient; +import org.openecomp.vid.scheduler.SchedulerProperties; +import org.openecomp.vid.scheduler.RestObjects.RestObject; +import org.springframework.stereotype.Service; + +@Service +public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { + + private static Client client = null; + + private MultivaluedHashMap<String, Object> commonHeaders; + + /** The logger. */ + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); + + public SchedulerRestInterface() { + super(); + } + + public void initRestClient() + { + System.out.println( "\t <== Starting to initialize rest client "); + + final String username; + final String password; + + /*Setting user name based on properties*/ + String retrievedUsername = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL); + if(retrievedUsername.isEmpty()) { + username = ""; + } else { + username = retrievedUsername; + } + + /*Setting password based on properties*/ + String retrievedPassword = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL); + if(retrievedPassword.isEmpty()) { + password = ""; + } else { + if (retrievedPassword.contains("OBF:")) { + password = Password.deobfuscate(retrievedPassword); + } else { + password = retrievedPassword; + } + } + + String authString = username + ":" + password; + + byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); + String authStringEnc = new String(authEncBytes); + + commonHeaders = new MultivaluedHashMap<String, Object> (); + commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authStringEnc))); + + try { + if ( !username.isEmpty() ) { + + client = HttpsBasicClient.getClient(); + } + else { + + client = HttpBasicClient.getClient(); + } + } catch (Exception e) { + System.out.println( " <== Unable to initialize rest client "); + } + + System.out.println( "\t<== Client Initialized \n"); + } + + @SuppressWarnings("unchecked") + public <T> void Get (T t, String sourceId, String path, org.openecomp.vid.scheduler.RestObject<T> restObject ) throws Exception { + + String methodName = "Get"; + String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; + + + System.out.println( "<== URL FOR GET : " + url + "\n"); + + initRestClient(); + + final Response cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + .get(); + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if (status == 200) { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + + } else { + throw new Exception(methodName + " with status="+ status + ", url= " + url ); + } + + return; + } + + @SuppressWarnings("unchecked") + public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) throws Exception { + + String methodName = "Post"; + String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; + + System.out.println( "<== URL FOR POST : " + url + "\n"); + + try { + + initRestClient(); + + // Change the content length + final Response cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); + + try { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + } + catch ( Exception e ) { + + System.out.println("<== " + methodName + " : No response entity, this is probably ok, e=" + e.getMessage()); + } + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if ( status >= 200 && status <= 299 ) { + + System.out.println( "<== " + methodName + " : REST api POST was successful!" + "\n"); + + } else { + System.out.println( "<== " + methodName + " : FAILED with http status : "+status+", url = " + url + "\n"); + } + + } catch (Exception e) + { + System.out.println( "<== " + methodName + " : with url="+url+ ", Exception: " + e.toString() + "\n"); + throw e; + } + } + + @Override + public void logRequest(JSONObject requestDetails) {} + + @SuppressWarnings("unchecked") + public <T> void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject<T> restObject) { + + String url=""; + Response cres = null; + + try { + initRestClient(); + + url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; + + cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + //.entity(r) + .build("DELETE", Entity.entity(requestDetails, MediaType.APPLICATION_JSON)).invoke(); + // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)); + //.delete(Entity.entity(r, MediaType.APPLICATION_JSON)); + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + try { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + } + catch ( Exception e ) { + } + + } + catch (Exception e) + { + throw e; + } + } + + public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException + { + return clazz.newInstance(); + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerRestInterfaceFactory.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerRestInterfaceFactory.java new file mode 100644 index 000000000..bf7bd8891 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerRestInterfaceFactory.java @@ -0,0 +1,15 @@ + +package org.openecomp.vid.scheduler; + +public class SchedulerRestInterfaceFactory { + + + public static SchedulerRestInterfaceIfc getInstance () { + SchedulerRestInterfaceIfc obj = null; + + obj = new SchedulerRestInterface(); + + return ( obj ); + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerRestInterfaceIfc.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerRestInterfaceIfc.java new file mode 100644 index 000000000..839ab348d --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerRestInterfaceIfc.java @@ -0,0 +1,21 @@ + +package org.openecomp.vid.scheduler; + +import org.json.simple.JSONObject; +import org.openecomp.vid.scheduler.RestObjects.RestObject; +import org.springframework.stereotype.Service; + +@Service +public interface SchedulerRestInterfaceIfc { + + public void initRestClient(); + + public <T> void Get (T t, String sourceId, String path, org.openecomp.vid.scheduler.RestObject<T> restObject ) throws Exception; + + public <T> void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject<T> restObject) + throws Exception; + + public <T> void Post(T t, JSONObject r, String path, RestObject<T> restObject) throws Exception; + + public void logRequest(JSONObject requestDetails); +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerUtil.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerUtil.java new file mode 100644 index 000000000..f82f474f6 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/SchedulerUtil.java @@ -0,0 +1,100 @@ +package org.openecomp.vid.scheduler; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.vid.scheduler.SchedulerResponseWrappers.GetTimeSlotsWrapper; +import org.openecomp.vid.scheduler.SchedulerResponseWrappers.PostCreateNewVnfWrapper; +import org.openecomp.vid.scheduler.SchedulerResponseWrappers.PostSubmitVnfChangeTimeSlotsWrapper; +import org.openecomp.vid.scheduler.SchedulerUtil; +import org.openecomp.vid.scheduler.RestObjects.GetTimeSlotsRestObject; +import org.openecomp.vid.scheduler.RestObjects.PostCreateNewVnfRestObject; +import org.openecomp.vid.scheduler.RestObjects.PostSubmitVnfChangeRestObject; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class SchedulerUtil { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerUtil.class); + + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + public static GetTimeSlotsWrapper getTimeSlotsWrapResponse (GetTimeSlotsRestObject<String> rs) { + + String resp_str = ""; + int status = 0; + + if ( rs != null ) { + resp_str = rs.get(); + status = rs.getStatusCode(); + } + + GetTimeSlotsWrapper w = new GetTimeSlotsWrapper(); + + w.setEntity(resp_str); + w.setStatus (status); + + return (w); + } + + public static PostSubmitVnfChangeTimeSlotsWrapper postSubmitNewVnfWrapResponse (PostSubmitVnfChangeRestObject<String> rs) { + + String resp_str = ""; + int status = 0; + String uuid = ""; + + if ( rs != null ) { + resp_str = rs.get(); + status = rs.getStatusCode(); + uuid = rs.getUUID(); + } + + PostSubmitVnfChangeTimeSlotsWrapper w = new PostSubmitVnfChangeTimeSlotsWrapper(); + + w.setEntity(resp_str); + w.setStatus (status); + w.setUuid(uuid); + + return (w); + } + + public static PostCreateNewVnfWrapper postCreateNewVnfWrapResponse (PostCreateNewVnfRestObject<String> rs) { + + String resp_str = ""; + int status = 0; + String uuid = ""; + + if ( rs != null ) { + resp_str = rs.get(); + status = rs.getStatusCode(); + uuid = rs.getUUID(); + } + + PostCreateNewVnfWrapper w = new PostCreateNewVnfWrapper(); + + w.setEntity(resp_str); + w.setStatus (status); + w.setUuid(uuid); + + return (w); + } + + public static <T> String convertPojoToString ( T t ) throws com.fasterxml.jackson.core.JsonProcessingException { + + String methodName = "convertPojoToString"; + ObjectMapper mapper = new ObjectMapper(); + String r_json_str = ""; + if ( t != null ) { + try { + r_json_str = mapper.writeValueAsString(t); + } + catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse object as json"); + } + } + return (r_json_str); + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/scheduler/rest/RequestDetails.java b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/rest/RequestDetails.java new file mode 100644 index 000000000..746fd9b24 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/scheduler/rest/RequestDetails.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.scheduler.rest; + +import java.util.HashMap; +import java.util.Map; +import java.util.List; +//import javax.annotation.Generated; + +import org.openecomp.vid.domain.mso.CloudConfiguration; +import org.openecomp.vid.domain.mso.ModelInfo; +import org.openecomp.vid.domain.mso.RequestInfo; +import org.openecomp.vid.domain.mso.RequestParameters; +import org.openecomp.vid.domain.mso.SubscriberInfo; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; + +/* + * "domain" : "ChangeManagement", + "scheduleId" : "3569b875-d40e-4adb-a288-a74f4b59ec1c", + "scheduleName" : "VnfUpgrade/DWF", + "userId" : "jf9860@att.com", + "domainData" : { + "WorkflowName" : "HEAT Stack Software Update for vNFs" + }, + "status" : "PendingOptimization", + "schedulingInfo" : { + "scheduleId" : "ChangeManagement.3569b875-d40e-4adb-a288-a74f4b59ec1c", + "normalDurationInSecs" : 60, + "AdditionalDurationInSecs" : 0, + "concurrencyLimit" : 10, + "policyId" : ["SNIRO.TimeLimitAndVerticalTopology"], + "groups" : [{ + "groupId" : " group1", + "node" : ["satmo415vbc", "satmo455vbc"], + "changeWindows" : [{ + "startTime" : "2017-02-15T01:00:00Z", + "finishTime" : "2017-02-15T02:00:00Z" + } + ] + }, { + "groupId" : " group2", + "node" : ["satmo555vbc"], + "changeWindows" : [{ + "startTime" : "2017-02-15T01:00:00Z", + "finishTime" : "2017-02-15T02:00:00Z" + }, { + "startTime" : "2017-02-15T05:00:00Z", + "finishTime" : "2017-02-15T05:30:00Z" + } + ] + } + ] +*/ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "domain", + "scheduleId", + "scheduleName", + "userId", + "domainData", + "status", + "schcedulingInfo" +}) +public class RequestDetails { + + @JsonProperty("domain") + private String domain; + + + + @JsonProperty("domain") + public String getDomain() { + return domain; + } + + @JsonProperty("domain") + public void setDomain(String domain) { + this.domain = domain; + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/services/AaiService.java b/vid-app-common/src/main/java/org/openecomp/vid/services/AaiService.java index 274419fb8..d3bacadec 100644 --- a/vid-app-common/src/main/java/org/openecomp/vid/services/AaiService.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/services/AaiService.java @@ -5,6 +5,7 @@ import org.openecomp.vid.aai.SubscriberFilteredResults; import org.openecomp.vid.aai.model.AaiGetTenatns.GetTenantsResponse; import org.openecomp.vid.roles.RoleValidator; +import javax.ws.rs.core.Response; import java.util.List; /** @@ -21,5 +22,13 @@ public interface AaiService { AaiResponse getAaiZones(); + AaiResponse getAicZoneForPnf(String globalCustomerId , String serviceType , String serviceId); + + Response getVNFData(String globalSubscriberId, String serviceType); + AaiResponse<GetTenantsResponse[]> getTenants(String globalCustomerId, String serviceType, RoleValidator roleValidator); + + AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId); + + Response getVersionByInvariantId(List<String> modelInvariantId); } diff --git a/vid-app-common/src/main/java/org/openecomp/vid/services/AaiServiceImpl.java b/vid-app-common/src/main/java/org/openecomp/vid/services/AaiServiceImpl.java index 38b670fe5..cb0962869 100644 --- a/vid-app-common/src/main/java/org/openecomp/vid/services/AaiServiceImpl.java +++ b/vid-app-common/src/main/java/org/openecomp/vid/services/AaiServiceImpl.java @@ -1,12 +1,17 @@ package org.openecomp.vid.services; import org.ecomp.aai.model.AaiAICZones.AicZones; +import org.openecomp.portalsdk.core.util.SystemProperties; import org.openecomp.vid.aai.*; import org.openecomp.vid.aai.model.AaiGetServicesRequestModel.*; import org.openecomp.vid.aai.model.AaiGetTenatns.GetTenantsResponse; import org.openecomp.vid.model.*; import org.openecomp.vid.roles.RoleValidator; +import org.openecomp.vid.scheduler.SchedulerProperties; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; + +import javax.ws.rs.core.Response; import java.util.List; @@ -37,13 +42,23 @@ public class AaiServiceImpl implements AaiService { String subscriberGlobalId = subscriberResponse.getT().globalCustomerId; for (ServiceSubscription serviceSubscription : subscriberResponse.getT().serviceSubscriptions.serviceSubscription) { String serviceType = serviceSubscription.serviceType; - serviceSubscription.isPermitted = roleProvider.isServicePermitted(subscriberGlobalId,serviceType);; + serviceSubscription.isPermitted = roleProvider.isServicePermitted(subscriberGlobalId,serviceType); } return subscriberResponse; } @Override + public Response getVersionByInvariantId(List<String> modelInvariantId) { + try { + return aaiClient.getVersionByInvariantId(modelInvariantId); + }catch (Exception e){ + e.printStackTrace(); + } + return null; + } + + @Override public AaiResponse getServices(RoleValidator roleValidator) { AaiResponse<GetServicesAAIRespone> subscriberResponse = aaiClient.getServices(); for (org.openecomp.vid.aai.model.AaiGetServicesRequestModel.Service service :subscriberResponse.getT().service){ @@ -62,9 +77,25 @@ public class AaiServiceImpl implements AaiService { return aaiGetTenantsResponse; } - @Override + @Override + public AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId) { + return aaiClient.getVNFData(globalSubscriberId,serviceType,serviceInstanceId); + } + + @Override + public Response getVNFData(String globalSubscriberId, String serviceType) { + return aaiClient.getVNFData(globalSubscriberId,serviceType); + } + + @Override public AaiResponse getAaiZones() { AaiResponse<AicZones> response = aaiClient.getAllAicZones(); return response; } + + @Override + public AaiResponse getAicZoneForPnf(String globalCustomerId , String serviceType , String serviceId) { + AaiResponse<AicZones> response = aaiClient.getAicZoneForPnf(globalCustomerId , serviceType , serviceId); + return response; + } } diff --git a/vid-app-common/src/main/java/org/openecomp/vid/services/ChangeManagementService.java b/vid-app-common/src/main/java/org/openecomp/vid/services/ChangeManagementService.java new file mode 100644 index 000000000..3ac528282 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/services/ChangeManagementService.java @@ -0,0 +1,14 @@ +package org.openecomp.vid.services; + +import org.openecomp.vid.changeManagement.ChangeManagementRequest; +import org.json.simple.JSONArray; +import org.openecomp.vid.mso.rest.Request; +import org.springframework.http.ResponseEntity; + +import java.util.Collection; + +public interface ChangeManagementService { + Collection<Request> getMSOChangeManagements(); + ResponseEntity<String> doChangeManagement(ChangeManagementRequest request, String vnfName); + JSONArray getSchedulerChangeManagements(); +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/services/ChangeManagementServiceImpl.java b/vid-app-common/src/main/java/org/openecomp/vid/services/ChangeManagementServiceImpl.java new file mode 100644 index 000000000..7e69d8fec --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/services/ChangeManagementServiceImpl.java @@ -0,0 +1,109 @@ +package org.openecomp.vid.services; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.vid.changeManagement.ChangeManagementRequest; +import org.openecomp.vid.changeManagement.RequestDetails; +import org.openecomp.vid.mso.MsoBusinessLogic; +import org.openecomp.vid.mso.MsoResponseWrapper; +import org.openecomp.vid.controller.MsoController; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.vid.scheduler.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.openecomp.vid.mso.rest.Request; +import org.springframework.stereotype.Service; +import org.json.simple.JSONArray; +import org.json.simple.parser.JSONParser; + +import java.util.Date; +import java.util.List; +import java.util.Collection; + + +@Service +public class ChangeManagementServiceImpl implements ChangeManagementService { + @Override + public Collection<Request> getMSOChangeManagements() { + Collection<Request> result = null; + MsoBusinessLogic msoBusinessLogic = new MsoBusinessLogic(); + try { + result = msoBusinessLogic.getOrchestrationRequestsForDashboard(); + } catch (Exception e) { + e.printStackTrace(); + } + + return result; + } + + private RequestDetails findRequestByVnfName(List<RequestDetails> requests, String vnfName){ + + if (requests == null) + return null; + + for(RequestDetails requestDetails: requests){ + if(requestDetails.getVnfName().equals(vnfName)){ + return requestDetails; + } + } + + return null; + } + + @Override + public ResponseEntity<String> doChangeManagement(ChangeManagementRequest request, String vnfName) { + if (request == null) + return null; + ResponseEntity<String> response = null; + RequestDetails currentRequestDetails = findRequestByVnfName(request.getRequestDetails(), vnfName); + MsoResponseWrapper msoResponseWrapperObject = null; + if(currentRequestDetails != null){ + MsoBusinessLogic msoBusinessLogicObject = new MsoBusinessLogic(); + String serviceInstanceId = currentRequestDetails.getRelatedInstList().get(0).getRelatedInstance().getInstanceId(); + String vnfInstanceId = currentRequestDetails.getVnfInstanceId(); + try { + if (request.getRequestType().equalsIgnoreCase("update")) { + + msoResponseWrapperObject = msoBusinessLogicObject.updateVnf(currentRequestDetails, serviceInstanceId, vnfInstanceId); + } + else if (request.getRequestType().equalsIgnoreCase("replace")) + { + msoResponseWrapperObject = msoBusinessLogicObject.replaceVnf(currentRequestDetails, serviceInstanceId, vnfInstanceId); +// throw new NotImplementedException(); + } + response = new ResponseEntity<String>(msoResponseWrapperObject.getResponse(), HttpStatus.OK); + return response; + } catch (Exception e) { + e.printStackTrace(); + } + + } + + // AH:TODO: return ChangeManagementResponse + return null; + } + + @Override + public JSONArray getSchedulerChangeManagements() { + JSONArray result = null; + try { + String path = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_GET_SCHEDULES); + org.openecomp.vid.scheduler.RestObject<String> restObject = new org.openecomp.vid.scheduler.RestObject<>(); + SchedulerRestInterfaceIfc restClient = SchedulerRestInterfaceFactory.getInstance(); + + String str = new String(); + restObject.set(str); + restClient.Get(str, "", path, restObject); + String restCallResult = restObject.get(); + JSONParser parser = new JSONParser(); + Object parserResult = parser.parse(restCallResult); + result = (JSONArray) parserResult; + } catch (Exception e) { + e.printStackTrace(); + } + + return result; + } + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/services/WorkflowService.java b/vid-app-common/src/main/java/org/openecomp/vid/services/WorkflowService.java new file mode 100644 index 000000000..7f43433de --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/services/WorkflowService.java @@ -0,0 +1,9 @@ +package org.openecomp.vid.services; + +import org.openecomp.vid.model.Workflow; +import java.util.Collection; + +public interface WorkflowService { + Collection<String> getWorkflowsForVNFs(Collection<String> vnfNames); + Collection<String> getAllWorkflows(); +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/services/WorkflowServiceImpl.java b/vid-app-common/src/main/java/org/openecomp/vid/services/WorkflowServiceImpl.java new file mode 100644 index 000000000..deb506069 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/services/WorkflowServiceImpl.java @@ -0,0 +1,40 @@ +package org.openecomp.vid.services; + +import org.openecomp.vid.model.Workflow; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.stream.Collectors; + +@Service +public class WorkflowServiceImpl implements WorkflowService { + //TODO: Add the list of workflows hard coded or from DB. + private ArrayList<Workflow> workflows = new ArrayList<>(Arrays.asList( + new Workflow(0, "Upgrade", new ArrayList<>(Arrays.asList("VNF1", "VNF2", "VNF3", "VNF4"))), + new Workflow(1, "Clean", new ArrayList<>(Arrays.asList("VNF1", "VNF2", "VNF3"))), + new Workflow(2, "Reinstall", new ArrayList<>(Arrays.asList("VNF1", "VNF2", "VNF4"))), + new Workflow(3, "Dump", new ArrayList<>(Arrays.asList("VNF1", "VNF3", "VNF4"))), + new Workflow(4, "Flush", new ArrayList<>(Arrays.asList("VNF2", "VNF3", "VNF4"))) + )); + + @Override + public Collection<String> getWorkflowsForVNFs(Collection<String> vnfNames) { + Collection<String> result = workflows.stream() + .filter(workflow -> workflow.getVnfNames().containsAll(vnfNames)) + .map(workflow -> workflow.getWorkflowName()) + .distinct() + .collect(Collectors.toList()); + + return result; + } + + @Override + public Collection<String> getAllWorkflows() { + return workflows.stream() + .map(workflow -> workflow.getWorkflowName()) + .distinct() + .collect(Collectors.toList()); + } +} |