From 1ba64a4a45f26e8bdb58e866e540aa58f32e2e52 Mon Sep 17 00:00:00 2001 From: Ofir Sonsino Date: Wed, 20 Sep 2017 14:08:19 +0300 Subject: Change management and PNF support Issue-ID: VID-44, VID-48, VID-49, VID-50, VID-51, VID-52 Change-Id: I83e940aad2e4e294a0927b546c4c08ca8e539a65 Signed-off-by: Ofir Sonsino --- .../openecomp/vid/controller/AaiController.java | 1728 ++++++++++---------- .../vid/controller/ChangeManagementController.java | 71 + .../org/openecomp/vid/controller/MsoConfig.java | 29 + .../openecomp/vid/controller/MsoController.java | 528 +++--- .../openecomp/vid/controller/PolicyController.java | 90 + .../vid/controller/SchedulerController.java | 244 +++ .../openecomp/vid/controller/VidController.java | 1 + 7 files changed, 1577 insertions(+), 1114 deletions(-) create mode 100644 vid-app-common/src/main/java/org/openecomp/vid/controller/ChangeManagementController.java create mode 100644 vid-app-common/src/main/java/org/openecomp/vid/controller/MsoConfig.java create mode 100644 vid-app-common/src/main/java/org/openecomp/vid/controller/PolicyController.java create mode 100644 vid-app-common/src/main/java/org/openecomp/vid/controller/SchedulerController.java (limited to 'vid-app-common/src/main/java/org/openecomp/vid/controller') 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 c0b6a514..a8bdf39b 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 model = new HashMap(); - /** - * 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 model = new HashMap(); + /** + * 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 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 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 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(userId, HttpStatus.OK); - } - - /** - * Get services from a&ai. - * - * @return ResponseEntity 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 doGetServices(HttpServletRequest request) throws IOException, InterruptedException { - - RoleValidator roleValidator = new RoleValidator(new RoleProvider().getUserRoles(request)); - - AaiResponse subscriberList = aaiService.getServices(roleValidator); - ResponseEntity responseEntity = aaiResponseToResponseEntity( subscriberList); - - return responseEntity; - } - - - - private ResponseEntity aaiResponseToResponseEntity( AaiResponse aaiResponseData) - throws IOException, JsonGenerationException, JsonMappingException { - ResponseEntity responseEntity; - ObjectMapper objectMapper = new ObjectMapper(); - if (aaiResponseData.getHttpCode() == 200) { - responseEntity = new ResponseEntity(objectMapper.writeValueAsString(aaiResponseData.getT()), HttpStatus.OK); - } else { - responseEntity = new ResponseEntity(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 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 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 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 getTargetProvStatus() throws IOException, InterruptedException { - String p = SystemProperties.getProperty("aai.vnf.provstatus"); - return new ResponseEntity(p, HttpStatus.OK); - } - - /** - * Obtain the full subscriber list from a&ai. - *

- * 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 getFullSubscriberList(HttpServletRequest request) throws IOException, InterruptedException { - ObjectMapper objectMapper = new ObjectMapper(); - ResponseEntity responseEntity; - RoleValidator roleValidator = new RoleValidator(new RoleProvider().getUserRoles(request)); - SubscriberFilteredResults subscriberList = aaiService.getFullSubscriberList(roleValidator); - if (subscriberList.getHttpCode() == 200) { - responseEntity = new ResponseEntity(objectMapper.writeValueAsString(subscriberList.getSubscriberList()), HttpStatus.OK); - } else { - responseEntity = new ResponseEntity(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 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 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 GetSubscriberDetails(HttpServletRequest request,@PathVariable("subscriberId") String subscriberId) throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - ResponseEntity responseEntity; - List roles = new RoleProvider().getUserRoles(request); - RoleValidator roleValidator = new RoleValidator(roles); - AaiResponse subscriberData = aaiService.getSubscriberData(subscriberId,roleValidator); - String httpMessage = subscriberData.getT() != null ? - objectMapper.writeValueAsString(subscriberData.getT()) : - subscriberData.getErrorMessage(); - - responseEntity = new ResponseEntity(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 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 viewEditGetComponentList( - // @PathVariable("global-customer-id") String globalCustomerId) { - // return new ResponseEntity(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 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 viewEditGetTenantsFromServiceType(HttpServletRequest request, - @PathVariable("global-customer-id") String globalCustomerId, @PathVariable("service-type") String serviceType) { - - ResponseEntity responseEntity; - try { - ObjectMapper objectMapper = new ObjectMapper(); - List roles = new RoleProvider().getUserRoles(request); - RoleValidator roleValidator = new RoleValidator(roles); - AaiResponse response = aaiService.getTenants(globalCustomerId, serviceType, roleValidator); - if (response.getHttpCode() == 200) { - responseEntity = new ResponseEntity(objectMapper.writeValueAsString(response.getT()), HttpStatus.OK); - } else { - responseEntity = new ResponseEntity(response.getErrorMessage(), HttpStatus.valueOf(response.getHttpCode())); - } - } - catch (Exception e){ - responseEntity = new ResponseEntity("Unable to proccess getTenants reponse", HttpStatus.INTERNAL_SERVER_ERROR); - } - return responseEntity; - } - - - private ResponseEntity convertResponseToResponseEntity(Response resp) { - ResponseEntity respEnt; - ObjectMapper objectMapper = new ObjectMapper(); - if (resp == null) { - respEnt = new ResponseEntity("Failed to fetch data from A&AI, check server logs for details.", HttpStatus.INTERNAL_SERVER_ERROR); - } else { - respEnt = new ResponseEntity(resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus())); - } - return respEnt; - } - - /** - * Gets the tenants. - * - * @param globalCustomerId the global customer id - * @return the tenants - */ - private ResponseEntity getTenants(String globalCustomerId) { - File certiPath = GetCertificatesPath(); - Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + globalCustomerId, false); - - ResponseEntity respEnt; - if (resp.getStatus() >= 200 && resp.getStatus() <= 299) { - respEnt = new ResponseEntity(parseForTenants((String) resp.readEntity(String.class)), HttpStatus.OK); - } else { - respEnt = new ResponseEntity((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 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 respEnt; - if (resp.getStatus() >= 200 && resp.getStatus() <= 299) { - respEnt = new ResponseEntity(parseForTenantsByServiceSubscription((String) resp.readEntity(String.class)), HttpStatus.OK); - } else { - respEnt = new ResponseEntity((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 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 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 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 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(userId, HttpStatus.OK); + } + + /** + * Get services from a&ai. + * + * @return ResponseEntity 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 doGetServices(HttpServletRequest request) throws IOException, InterruptedException { + + RoleValidator roleValidator = new RoleValidator(new RoleProvider().getUserRoles(request)); + + AaiResponse subscriberList = aaiService.getServices(roleValidator); + ResponseEntity responseEntity = aaiResponseToResponseEntity(subscriberList); + + return responseEntity; + } + + + @RequestMapping(value = {"/aai_get_version_by_invariant_id"}, method = RequestMethod.POST) + public ResponseEntity getVersionByInvariantId(HttpServletRequest request, @RequestBody VersionByInvariantIdsRequest versions) throws IOException { + ResponseEntity responseEntity; + ObjectMapper objectMapper = new ObjectMapper(); + + Response result = aaiService.getVersionByInvariantId(versions.versions); + + return new ResponseEntity(result.readEntity(String.class), HttpStatus.OK); + } + + + private ResponseEntity aaiResponseToResponseEntity(AaiResponse aaiResponseData) + throws IOException, JsonGenerationException, JsonMappingException { + ResponseEntity responseEntity; + ObjectMapper objectMapper = new ObjectMapper(); + if (aaiResponseData.getHttpCode() == 200) { + responseEntity = new ResponseEntity(objectMapper.writeValueAsString(aaiResponseData.getT()), HttpStatus.OK); + } else { + responseEntity = new ResponseEntity(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 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 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 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 getTargetProvStatus() throws IOException, InterruptedException { + String p = SystemProperties.getProperty("aai.vnf.provstatus"); + return new ResponseEntity(p, HttpStatus.OK); + } + + /** + * Obtain the full subscriber list from a&ai. + *

+ * 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 getFullSubscriberList(HttpServletRequest request) throws IOException, InterruptedException { + ObjectMapper objectMapper = new ObjectMapper(); + ResponseEntity responseEntity; + RoleValidator roleValidator = new RoleValidator(new RoleProvider().getUserRoles(request)); + SubscriberFilteredResults subscriberList = aaiService.getFullSubscriberList(roleValidator); + if (subscriberList.getHttpCode() == 200) { + responseEntity = new ResponseEntity(objectMapper.writeValueAsString(subscriberList.getSubscriberList()), HttpStatus.OK); + } else { + responseEntity = new ResponseEntity(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 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 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 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 GetSubscriberDetails(HttpServletRequest request, @PathVariable("subscriberId") String subscriberId) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + ResponseEntity responseEntity; + List roles = new RoleProvider().getUserRoles(request); + RoleValidator roleValidator = new RoleValidator(roles); + AaiResponse subscriberData = aaiService.getSubscriberData(subscriberId, roleValidator); + String httpMessage = subscriberData.getT() != null ? + objectMapper.writeValueAsString(subscriberData.getT()) : + subscriberData.getErrorMessage(); + + responseEntity = new ResponseEntity(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 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 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 viewEditGetComponentList( + // @PathVariable("global-customer-id") String globalCustomerId) { + // return new ResponseEntity(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 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 viewEditGetTenantsFromServiceType(HttpServletRequest request, + @PathVariable("global-customer-id") String globalCustomerId, @PathVariable("service-type") String serviceType) { + + ResponseEntity responseEntity; + try { + ObjectMapper objectMapper = new ObjectMapper(); + List roles = new RoleProvider().getUserRoles(request); + RoleValidator roleValidator = new RoleValidator(roles); + AaiResponse response = aaiService.getTenants(globalCustomerId, serviceType, roleValidator); + if (response.getHttpCode() == 200) { + responseEntity = new ResponseEntity(objectMapper.writeValueAsString(response.getT()), HttpStatus.OK); + } else { + responseEntity = new ResponseEntity(response.getErrorMessage(), HttpStatus.valueOf(response.getHttpCode())); + } + } catch (Exception e) { + responseEntity = new ResponseEntity("Unable to proccess getTenants reponse", HttpStatus.INTERNAL_SERVER_ERROR); + } + return responseEntity; + } + + + private ResponseEntity convertResponseToResponseEntity(Response resp) { + ResponseEntity respEnt; + ObjectMapper objectMapper = new ObjectMapper(); + if (resp == null) { + respEnt = new ResponseEntity("Failed to fetch data from A&AI, check server logs for details.", HttpStatus.INTERNAL_SERVER_ERROR); + } else { + respEnt = new ResponseEntity(resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus())); + } + return respEnt; + } + + /** + * Gets the tenants. + * + * @param globalCustomerId the global customer id + * @return the tenants + */ + private ResponseEntity getTenants(String globalCustomerId) { + File certiPath = GetCertificatesPath(); + Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + globalCustomerId, false); + + ResponseEntity respEnt; + if (resp.getStatus() >= 200 && resp.getStatus() <= 299) { + respEnt = new ResponseEntity(parseForTenants((String) resp.readEntity(String.class)), HttpStatus.OK); + } else { + respEnt = new ResponseEntity((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 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 respEnt; + if (resp.getStatus() >= 200 && resp.getStatus() <= 299) { + respEnt = new ResponseEntity(parseForTenantsByServiceSubscription((String) resp.readEntity(String.class)), HttpStatus.OK); + } else { + respEnt = new ResponseEntity((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 00000000..1af71546 --- /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> getWorkflow(@RequestParam("vnfs") Collection vnfs) throws IOException, InterruptedException { + Collection result = this.workflowService.getWorkflowsForVNFs(vnfs); + return new ResponseEntity<>(result, HttpStatus.OK); + } + + @RequestMapping(value = {"/mso"}, method = RequestMethod.GET) + public ResponseEntity> getMSOChangeManagements() throws IOException, InterruptedException { + Collection result = this.changeManagementService.getMSOChangeManagements(); + return new ResponseEntity<>(result, HttpStatus.OK); + } + + @RequestMapping(value = "/workflow/{vnfName}", method = RequestMethod.POST) + public ResponseEntity 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 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 00000000..e0b59204 --- /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 56fbd4cb..9a064b00 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 = ""; + String viewName; + /** - * The Constant VNF_INSTANCE_ID. + * The logger. */ - public final static String 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 = ""; + public final static String REQUEST_TYPE = ""; + /** - * The logger. + * The Constant VNF_INSTANCE_ID. */ - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoController.class); + public final static String VNF_INSTANCE_ID = ""; /** * Welcome. @@ -118,37 +144,70 @@ public class MsoController extends RestrictedBaseController { */ @RequestMapping(value = "/mso_create_svc_instance", method = RequestMethod.POST) public ResponseEntity 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(w.getResponse(), HttpStatus.OK)); + + } + /** + * Creates the svc instance. + * + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + + public ResponseEntity 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(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(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(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 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(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 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 a = new AaiController(request.getServletContext()).doGetServiceInstance(instanceId,"Service Instance id"); -// return new ResponseEntity(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//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 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//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(w.getResponse(), HttpStatus.OK)); @@ -230,21 +265,11 @@ public class MsoController extends RestrictedBaseController { public ResponseEntity 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(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(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(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//vnfs//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(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 restObjStr = new RestObject(); @@ -307,14 +323,14 @@ public class MsoController extends RestrictedBaseController { restController.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(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//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(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(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//vnfs//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(w.getResponse(), HttpStatus.OK)); @@ -428,21 +426,12 @@ public class MsoController extends RestrictedBaseController { public ResponseEntity 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(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(w.getResponse(), HttpStatus.OK)); @@ -460,60 +449,18 @@ public class MsoController extends RestrictedBaseController { @RequestMapping(value = "/mso_delete_nw_instance/{serviceInstanceId}/networks/{networkInstanceId}", method = RequestMethod.POST) public ResponseEntity 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(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//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(w.getResponse(), HttpStatus.OK)); } - /** - * 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 restObjStr = new RestObject(); - String str = new String(); - restObjStr.set(str); - restController.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. * @@ -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 restObjStr = new RestObject(); - String str = new String(); - restObjStr.set(str); - restController.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(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 restObjStr = new RestObject(); - String str = new String(); - restObjStr.set(str); - restController.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(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 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 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 restObjStr = new RestObject(); - String str = new String(); - restObjStr.set(str); + MsoBusinessLogic mbl = new MsoBusinessLogic(); - restController.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 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 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(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 restObjStr = new RestObject(); +// String str = new String(); +// restObjStr.set(str); +// +// restController.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 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 00000000..83e177a6 --- /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 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(policyResWrapper.getResponse(), HttpStatus.OK).toString()); + + return ( new ResponseEntity(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 restObjStr = new RestObject(); + String str = new String(); + restObjStr.set(str); + restController.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 00000000..0fd2079e --- /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 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(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 restObjStr = new GetTimeSlotsRestObject(); + String str = new String(); + + restObjStr.set(str); + + restController.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 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(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 restObjStr = new PostCreateNewVnfRestObject(); + String str = new String(); + + restObjStr.set(str); + restController.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 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(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 restObjStr = new PostSubmitVnfChangeRestObject(); + String str = new String(); + + restObjStr.set(str); + restController.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 838793a7..aac3a0b7 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 requestParams = request.getParameterMap(); -- cgit 1.2.3-korg