From 3982f4f67314ec37fd9b22ae54049958af777c1b Mon Sep 17 00:00:00 2001 From: jimmydot Date: Sun, 7 May 2017 14:58:24 -0400 Subject: [VID-6] Initial rebase push Change-Id: I9077be9663754d9b22f77c6a7b3109b361b39346 Signed-off-by: jimmydot --- .../openecomp/vid/controller/AaiController.java | 864 +++++++++++++++++++++ .../controller/BrowseServiceTypesController.java | 87 +++ .../vid/controller/HealthCheckController.java | 196 +++++ .../openecomp/vid/controller/MsoController.java | 761 ++++++++++++++++++ .../vid/controller/PropertyController.java | 122 +++ .../openecomp/vid/controller/VidController.java | 351 +++++++++ .../vid/controller/VidHomeController.java | 79 ++ .../vid/controller/ViewEditSubController.java | 107 +++ .../vid/controller/ViewLogController.java | 84 ++ .../vid/controller/test/TestAaiController.java | 93 +++ .../vid/controller/test/TestAsdcController.java | 112 +++ .../vid/controller/test/TestMsoController.java | 729 +++++++++++++++++ .../vid/controller/test/TestPageController.java | 57 ++ 13 files changed, 3642 insertions(+) create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/AaiController.java create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/BrowseServiceTypesController.java create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/HealthCheckController.java create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/MsoController.java create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/PropertyController.java create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/VidController.java create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/VidHomeController.java create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/ViewEditSubController.java create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/ViewLogController.java create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestAaiController.java create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestAsdcController.java create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestMsoController.java create mode 100755 vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestPageController.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 new file mode 100755 index 00000000..7cb25c26 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/AaiController.java @@ -0,0 +1,864 @@ +/*- + * ============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.io.File; +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.BadRequestException; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.QueryParam; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.openecomp.aai.util.AAIRestInterface; +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.servlet.ModelAndView; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; + +/** + * Controller to handle a&ai requests. + */ + +@RestController +public class AaiController extends RestrictedBaseController{ + + /** The view name. */ + String viewName; + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiController.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The from app id. */ + protected String fromAppId = "VidAaiController"; + + /** The model. */ + private Map model = new HashMap(); + + /** The servlet context. */ + private @Autowired ServletContext servletContext; + + /** + * 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()); + } + + /* (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(); + } + } + + 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() throws IOException, InterruptedException { + File certiPath = GetCertificatesPath(); + Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/services", false); + + return convertResponseToResponseEntity(resp); + } + + /** + * 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(@DefaultValue("n") @QueryParam("fullSet") String fullSet) throws IOException, InterruptedException { + Response resp = getSubscribers(false); + return convertResponseToResponseEntity(resp); + } + + /** + * 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. + * + * @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() throws IOException, InterruptedException { + Response resp = getSubscribers(true); + 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 GetSubscriber(@PathVariable("subscriberId") String subscriberId) { + Response resp = getSubscriberDetails(subscriberId); + return convertResponseToResponseEntity(resp); + } + + /** + * 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); + } + + /** + * 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_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; + } + + + // @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); + // } + + /** + * 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( + @PathVariable("global-customer-id") String globalCustomerId, @PathVariable("service-type") String serviceType) { + return getTenantsFromServiceType(globalCustomerId, serviceType); + } + + private ResponseEntity convertResponseToResponseEntity(Response resp) { + ResponseEntity respEnt; + 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((String)resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus())); + } + return respEnt; + } + + /** + * Gets the tenants. + * + * @param globalCustomerId the global customer id + * @return the tenants + */ + private ResponseEntity 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 + "\"" + + " }" + + " }" + + "}"; + + } + + /** + * 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 ""; + + } + + + /** + * 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 ""; + + } +} + diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/BrowseServiceTypesController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/BrowseServiceTypesController.java new file mode 100755 index 00000000..0698cfd9 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/BrowseServiceTypesController.java @@ -0,0 +1,87 @@ +/*- + * ============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 javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; + +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; + + +/** + * The Class BrowseServiceTypesController. + */ +@RestController +public class BrowseServiceTypesController extends RestrictedBaseController{ + + /** The view name. */ + String viewName; + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(BrowseServiceTypesController.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The servlet context. */ + private @Autowired ServletContext servletContext; + + /** + * Welcome. + * + * @param request the request + * @return the model and view + */ + @RequestMapping(value = {"/browseservicetypes" }, method = RequestMethod.GET) + public ModelAndView welcome(HttpServletRequest request) { + + return new ModelAndView(getViewName()); + } + + /* (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; + } + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/HealthCheckController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/HealthCheckController.java new file mode 100755 index 00000000..abef8d62 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/HealthCheckController.java @@ -0,0 +1,196 @@ +/*- + * ============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.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.springframework.http.MediaType; +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.openecomp.portalsdk.core.controller.UnRestrictedBaseController; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.vid.dao.FnAppDoaImpl; + +/** + * Controller for user profile view. The view is restricted to authenticated + * users. The view name resolves to page user_profile.jsp which uses Angular. + */ + +@RestController +@RequestMapping("/") +public class HealthCheckController extends UnRestrictedBaseController { + + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthCheckController.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + private static final String HEALTH_CHECK_PATH = "/healthCheck"; + + /** + * Model for JSON response with health-check results. + */ + public class HealthStatus { + // Either 200 or 500 + public int statusCode; + + // Additional detail in case of error, empty in case of success. + public String message; + + public String date; + + public HealthStatus(int code, String msg) { + this.statusCode = code; + this.message = msg; + } + + public HealthStatus(int code,String date, String msg) { + this.statusCode = code; + this.message = msg; + this.date=date; + } + + public int getStatusCode() { + return statusCode; + } + + public void setStatusCode(int code) { + this.statusCode = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String msg) { + this.message = msg; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + } + + @SuppressWarnings("unchecked") + public int getProfileCount(String driver, String URL, String username, String password) { + FnAppDoaImpl doa= new FnAppDoaImpl(); + int count= doa.getProfileCount(driver,URL,username,password); + return count; + } + + + + /** + * Obtain the HealthCheck Status from the System.Properties file. + * Used by IDNS for redundancy + * @return ResponseEntity The response entity + * @throws IOException Signals that an I/O exception has occurred. + * @throws InterruptedException the interrupted exception + */ + @RequestMapping(value="/healthCheck",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public HealthStatus gethealthCheckStatusforIDNS() throws IOException, InterruptedException { + + String driver = SystemProperties.getProperty("db.driver"); + String URL = SystemProperties.getProperty("db.connectionURL"); + String username = SystemProperties.getProperty("db.userName"); + String password = SystemProperties.getProperty("db.password"); + + logger.debug(EELFLoggerDelegate.debugLogger, "driver ::" + driver); + logger.debug(EELFLoggerDelegate.debugLogger, "URL::" + URL); + logger.debug(EELFLoggerDelegate.debugLogger, "username::" + username); + logger.debug(EELFLoggerDelegate.debugLogger,"password::" + password); + + + HealthStatus healthStatus = null; + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Performing health check"); + int count=getProfileCount(driver,URL,username,password); + logger.debug(EELFLoggerDelegate.debugLogger,"count:::"+count); + healthStatus = new HealthStatus(200, "health check succeeded"); + } catch (Exception ex) { + + logger.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex); + healthStatus = new HealthStatus(500, "health check failed: " + ex.toString()); + } + return healthStatus; + } + + /** + * Obtain the HealthCheck 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 + * Project : + */ + @RequestMapping(value="rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public HealthStatus getHealthCheck( + @PathVariable("User-Agent") String UserAgent, + @PathVariable("X-ECOMP-RequestID") String ECOMPRequestID) throws IOException, InterruptedException { + + String driver = SystemProperties.getProperty("db.driver"); + String URL = SystemProperties.getProperty("db.connectionURL"); + String username = SystemProperties.getProperty("db.userName"); + String password = SystemProperties.getProperty("db.password"); + + logger.debug(EELFLoggerDelegate.debugLogger, "driver ::" + driver); + logger.debug(EELFLoggerDelegate.debugLogger, "URL::" + URL); + logger.debug(EELFLoggerDelegate.debugLogger, "username::" + username); + logger.debug(EELFLoggerDelegate.debugLogger,"password::" + password); + + + HealthStatus healthStatus = null; + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Performing health check"); + logger.debug(EELFLoggerDelegate.debugLogger, "User-Agent" + UserAgent); + logger.debug(EELFLoggerDelegate.debugLogger, "X-ECOMP-RequestID" + ECOMPRequestID); + + + int count=getProfileCount(driver,URL,username,password); + + logger.debug(EELFLoggerDelegate.debugLogger,"count:::"+count); + healthStatus = new HealthStatus(200,dateFormat.format(new Date()) ,"health check succeeded"); + } catch (Exception ex) { + + logger.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex); + healthStatus = new HealthStatus(500,dateFormat.format(new Date()),"health check failed: " + ex.toString()); + } + return healthStatus; + } +} + 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 new file mode 100755 index 00000000..f051ed38 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/MsoController.java @@ -0,0 +1,761 @@ +/*- + * ============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.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.domain.mso.CloudConfiguration; +import org.openecomp.vid.domain.mso.ModelInfo; +import org.openecomp.vid.domain.mso.ModelInfo.ModelType; +import org.openecomp.vid.domain.mso.RequestInfo; +import org.openecomp.vid.domain.mso.RequestParameters; +import org.openecomp.vid.model.ExceptionResponse; +import org.openecomp.vid.mso.MsoProperties; +import org.openecomp.vid.mso.MsoResponseWrapper; +import org.openecomp.vid.mso.MsoRestInterfaceFactory; +import org.openecomp.vid.mso.MsoRestInterfaceIfc; +import org.openecomp.vid.mso.MsoUtil; +import org.openecomp.vid.mso.RestObject; +import org.openecomp.vid.mso.rest.RelatedModel; +import org.openecomp.vid.mso.rest.RequestDetails; +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. + */ +@RestController +@RequestMapping("mso") +public class MsoController extends RestrictedBaseController{ + + /** The view name. */ + String viewName; + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoController.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The Constant SVC_INSTANCE_ID. */ + public final static String SVC_INSTANCE_ID = ""; + + /** The Constant VNF_INSTANCE_ID. */ + public final static String VNF_INSTANCE_ID = ""; + + /** + * Welcome. + * + * @param request the request + * @return the model and view + + public ModelAndView welcome(HttpServletRequest request) { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== MsoController welcome start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " MSO_SERVER_URL=" + + SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) ); + return new ModelAndView(getViewName()); + } + */ + + /* (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; + } + */ + + /** + * Creates the svc instance. + * + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @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" ); + +// mso_request = retrieveRequestObject (request, mso_request); + + String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE); + + MsoResponseWrapper w = createInstance(mso_request, p); + // always return OK, the MSO status code is embedded in the body + + return ( new ResponseEntity(w.getResponse(), HttpStatus.OK) ); + + } + + /** + * Creates the vnf. + * + * @param serviceInstanceId the service instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @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 { + + 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); + + 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); + + // always return OK, the MSO status code is embedded in the body + + return ( new ResponseEntity(w.getResponse(), HttpStatus.OK) ); + + } + + /** + * Creates the nw instance. + * + * @param serviceInstanceId the service instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @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/ + + 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 + + return ( new ResponseEntity(w.getResponse(), HttpStatus.OK) ); + + } + + /** + * Creates the volume group instance. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_create_volumegroup_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) + public ResponseEntity createVolumeGroupInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, + HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + String methodName = "createVolumeGroupInstance"; + 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); + + 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); + + // always return OK, the MSO status code is embedded in the body + return ( new ResponseEntity(w.getResponse(), HttpStatus.OK) ); + } + + /** + * Creates the vf module instance. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_create_vfmodule_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) + public ResponseEntity createVfModuleInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("vnfInstanceId") String vnfInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + String methodName = "createVfModuleInstance"; + + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + //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 = createInstance(mso_request, path); + + // 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 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(); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Post, request = (" + request + ")"); + + RestObject restObjStr = new RestObject(); + String str = new String(); + restObjStr.set(str); + 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; + } + } + + /** + * Delete svc instance. + * + * @param serviceInstanceId the service instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_delete_svc_instance/{serviceInstanceId}", method = RequestMethod.POST) + public ResponseEntity deleteSvcInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + + 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 ); + + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); + // always return OK, the MSO status code is embedded in the body + + return ( new ResponseEntity(w.getResponse(), HttpStatus.OK) ); + + } + + /** + * Delete vnf. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_delete_vnf_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) + + public ResponseEntity deleteVnf(@PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, + HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + String methodName = "deleteVnf"; + + 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); + 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 ); + + // always return OK, the MSO status code is embedded in the body + return ( new ResponseEntity(w.getResponse(), HttpStatus.OK) ); + + } + + /** + * Delete vf module. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param vfModuleId the vf module id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + //mso_delete_vf_module/bc305d54-75b4-431b-adb2-eb6b9e546014/vnfs/fe9000-0009-9999/vfmodules/abeeee-abeeee-abeeee + @RequestMapping(value = "/mso_delete_vfmodule_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfModuleId}", method = RequestMethod.POST) + public ResponseEntity deleteVfModule ( + @PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, + @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"); + + //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); + + // always return OK, the MSO status code is embedded in the body + return ( new ResponseEntity(w.getResponse(), HttpStatus.OK) ); + + } + + /** + * Delete volume group instance. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param volumeGroupId the volume group id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_delete_volumegroup_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupId}", method = RequestMethod.POST) + 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"); + //RequestDetails mso_request = retrieveRequestObject (request); + + 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); + + // always return OK, the MSO status code is embedded in the body + return ( new ResponseEntity(w.getResponse(), HttpStatus.OK) ); + } + + /** + * Delete nw instance. + * + * @param serviceInstanceId the service instance id + * @param networkInstanceId the network instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @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); + + 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); + + // 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. + * + * @param requestId the request id + * @param request the request + * @return the orchestration request + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_get_orch_req/{requestId}", method = RequestMethod.GET) + public ResponseEntity getOrchestrationRequest(@PathVariable("requestId") String requestId, + HttpServletRequest request) throws Exception { + + 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); + + 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 + + } 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. + * + * @param filterString the filter string + * @param request the request + * @return the orchestration requests + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_get_orch_reqs/{filterString}", method = RequestMethod.GET) + public ResponseEntity getOrchestrationRequests(@PathVariable("filterString") String filterString, + HttpServletRequest request) throws Exception { + + 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); + + 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. + * + * @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. + * + * @param e the e + * @param response the response + * @throws IOException Signals that an I/O exception has occurred. + */ + @ExceptionHandler(Exception.class) + private void exceptionHandler(Exception e, HttpServletResponse response) throws IOException { + + /* + * 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. + */ + + String methodName = "exceptionHandler"; + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + logger.error(EELFLoggerDelegate.errorLogger, sw.toString()); + + /* + * 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. + */ + e.printStackTrace(System.err); + + response.setContentType("application/json; charset=UTF-8"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + + ExceptionResponse exceptionResponse = new ExceptionResponse(); + exceptionResponse.setException(e.getClass().toString().replaceFirst("^.*\\.", "")); + exceptionResponse.setMessage(e.getMessage()); + + response.getWriter().write(new ObjectMapper().writeValueAsString(exceptionResponse)); + + response.flushBuffer(); + + } + + /** + * Parses the orchestration requests for svc instance. + * + * @param resp the resp + * @return the list + * @throws ParseException the parse exception + * @throws Exception the exception + */ + @SuppressWarnings("unchecked") + public List parseOrchestrationRequestsForSvcInstance ( ClientResponse resp ) throws org.json.simple.parser.ParseException, Exception { + + String methodName = "parseOrchestrationRequestsForSvcInstance"; + + ArrayList json_list = new ArrayList(); + + String rlist_str = resp.readEntity (String.class); + logger.debug (EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + " Response string: " + rlist_str); + + JSONParser parser = new JSONParser(); + try { + Object obj = parser.parse(rlist_str); + + JSONObject jsonObject = (JSONObject) obj; + + JSONArray requestList = (JSONArray) jsonObject.get("requestList"); + + if ( requestList != null && ! (requestList.isEmpty()) ) + for ( Object container : requestList) { + + JSONObject containerJsonObj = (JSONObject) container; + //logger.debug(dateFormat.format(new Date()) + "<== " + "." + methodName + " reqJsonObj: " + containerJsonObj.toJSONString()); + JSONObject reqJsonObj = (JSONObject) containerJsonObj.get("request"); + + //logger.debug(dateFormat.format(new Date()) + "<== " + "." + methodName + " reqJsonObj.requestId: " + + // reqJsonObj.get("requestId") ); + JSONObject result = new JSONObject(); + + result.put("requestId", reqJsonObj.get ("requestId")); + if ( reqJsonObj.get("requestType") != null ) { + result.put("requestType", (reqJsonObj.get("requestType").toString())); + } + JSONObject req_status = (JSONObject)reqJsonObj.get("requestStatus"); + if ( req_status != null ) { + result.put("timestamp", (req_status.get("timestamp"))); + result.put("requestState", (req_status.get("requestState"))); + result.put("statusMessage", (req_status.get("statusMessage"))); + result.put("percentProgress", (req_status.get("percentProgress"))); + } + json_list.add (result); + } + } catch (org.json.simple.parser.ParseException pe) { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + " Parse exception: " + pe.toString()); + throw pe; + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + " Exception: " + e.toString()); + throw e; + } + return ( json_list ); + } + + /** + * Retrieve request object. + * + * @param request the request + * @return the request details + * @throws Exception the exception + */ + public RequestDetails retrieveRequestObject ( HttpServletRequest request, @RequestBody RequestDetails mso_request ) throws Exception { + + String methodName = "retrieveRequestObject"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start" ); + + ObjectMapper mapper = new ObjectMapper(); + //JSON from String to Object + //RequestDetails mso_request; + + try { + //mso_request = new RequestDetails(); + //mso_request = mapper.readValue(request.getInputStream(), RequestDetails.class); + } + catch ( Exception e ) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + " Unable to read json object RequestDetails e=" + e.getMessage()); + throw e; + } + if ( mso_request == null) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + " mso_request is null"); + throw new Exception ("RequestDetails is missing"); + } + try { + String json_req = mapper.writeValueAsString(mso_request); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " request=[" + json_req + "]"); + } + catch ( Exception e ) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + " Unable to convert RequestDetails to json string e=" + e.getMessage()); + throw e; + } + return (mso_request); + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/PropertyController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/PropertyController.java new file mode 100755 index 00000000..90080769 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/PropertyController.java @@ -0,0 +1,122 @@ +/*- + * ============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 javax.servlet.http.HttpServletRequest; + +import org.springframework.http.HttpStatus; +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.servlet.ModelAndView; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; + +/** + * The Class PropertyController. + */ +@RestController +public class PropertyController extends RestrictedBaseController{ + + /** The view name. */ + String viewName; + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PropertyController.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** + * Welcome. + * + * @param request the request + * @return the model and view + */ + @RequestMapping(value = {"/propertyhome" }, method = RequestMethod.GET) + public ModelAndView welcome(HttpServletRequest request) { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== PropertyController welcome start"); + return new ModelAndView(getViewName()); + } + + /* (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; + } + + /** + * Gets the property. + * + * @param name the name + * @param defaultvalue the defaultvalue + * @param request the request + * @return the property + * @throws Exception the exception + */ + @RequestMapping(value = "/get_property/{name}/{defaultvalue}", method = RequestMethod.GET) + public ResponseEntity getProperty (@PathVariable("name") String name, @PathVariable("defaultvalue") String defaultvalue, + HttpServletRequest request) throws Exception { + + String methodName = "getProperty"; + ResponseEntity resp = null; + String pvalue = null; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + + try { + // convert "_" to "." in the property name + if (name == null || name.length() == 0 ) { + return ( new ResponseEntity (defaultvalue, HttpStatus.OK)); + } + // convert "_" to "." in the property name + String propertyName = name.replace('_', '.'); + pvalue = SystemProperties.getProperty(propertyName); + if ( ( pvalue == null ) || ( pvalue.length() == 0 ) ) { + pvalue = defaultvalue; + } + resp = new ResponseEntity(pvalue, HttpStatus.OK); + } + 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 + " returning " + pvalue); + return ( resp ); + } + +} 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 new file mode 100755 index 00000000..e22448ae --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/VidController.java @@ -0,0 +1,351 @@ +/*- + * ============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.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; + +import javax.net.ssl.SSLContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Client; + +import org.json.JSONObject; +import org.json.JSONTokener; +import org.openecomp.vid.exceptions.VidServiceUnavailableException; +import org.openecomp.vid.model.ModelConstants; +import org.openecomp.vid.model.Network; +import org.openecomp.vid.model.ServiceModel; +import org.openecomp.vid.model.VNF; +import org.openecomp.vid.model.VfModule; +import org.openecomp.vid.model.VolumeGroup; +//import org.openecomp.vid.model.Service; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +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.servlet.ModelAndView; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.vid.asdc.AsdcCatalogException; +import org.openecomp.vid.asdc.AsdcClient; +import org.openecomp.vid.asdc.beans.Resource; +import org.openecomp.vid.asdc.beans.Service; +import org.openecomp.vid.asdc.beans.tosca.Group; +import org.openecomp.vid.asdc.beans.tosca.NodeTemplate; +import org.openecomp.vid.asdc.beans.tosca.ToscaCsar; +import org.openecomp.vid.asdc.beans.tosca.ToscaModel; +import org.openecomp.vid.asdc.memory.InMemoryAsdcClient; +import org.openecomp.vid.asdc.rest.RestfulAsdcClient; +import org.openecomp.vid.properties.AsdcClientConfiguration; +import org.openecomp.vid.properties.AsdcClientConfiguration.AsdcClientType; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.openecomp.vid.properties.VidProperties; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; + +/** + * The Class VidController. + */ +@RestController +public class VidController extends RestrictedBaseController { + + /** The Constant LOG. */ + private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VidController.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The app context. */ + @Autowired + private ApplicationContext appContext; + + /** + * Gets the object mapper. + * + * @return the object mapper + */ + @Bean + public ObjectMapper getObjectMapper() { + return new ObjectMapper(); + } + + /** + * Gets the asdc client. + * + * @return the asdc client + */ + @Bean + public AsdcClient getAsdcClient() { + + final AsdcClientConfiguration asdcClientConfig = appContext.getBean(AsdcClientConfiguration.class); + + switch (asdcClientConfig.getAsdcClientType()) { + case IN_MEMORY: + final InputStream asdcCatalogFile = VidController.class.getClassLoader().getResourceAsStream("catalog.json"); + final JSONTokener tokener = new JSONTokener(asdcCatalogFile); + final JSONObject catalog = new JSONObject(tokener); + + return new InMemoryAsdcClient.Builder().catalog(catalog).build(); + case REST: + + final String protocol = asdcClientConfig.getAsdcClientProtocol(); + final String host = asdcClientConfig.getAsdcClientHost(); + final int port = asdcClientConfig.getAsdcClientPort(); + final String auth = asdcClientConfig.getAsdcClientAuth(); + Client cl = null; + if ( protocol.equalsIgnoreCase("https") ) { + try { + SSLContext ctx = SSLContext.getInstance("TLSv1.2"); + ctx.init(null, null, null); + cl = ClientBuilder.newBuilder().sslContext(ctx).build(); + } + catch ( NoSuchAlgorithmException n ) { + throw new RuntimeException("SDC Client could not be instantiated due to unsupported protocol TLSv1.2", n); + } + catch ( KeyManagementException k ) { + throw new RuntimeException("SDC Client could not be instantiated due to a key management exception", k); + } + } + else { + cl = ClientBuilder.newBuilder().build(); + } + + try { + final URI uri = new URI(protocol + "://" + host + ":" + port + "/"); + return new RestfulAsdcClient.Builder(cl, uri) + .auth(auth) + .build(); + } catch (URISyntaxException e) { + throw new RuntimeException("SDC Client could not be instantiated due to a syntax error in the URI", e); + } + + default: + throw new RuntimeException(asdcClientConfig.getAsdcClientType() + " is invalid; must be one of " + Arrays.toString(AsdcClientType.values())); + } + } + + /** + * Gets the services. + * + * @param request the request + * @return the services + * @throws VidServiceUnavailableException the vid service unavailable exception + */ + @RequestMapping(value={"/rest/models/services"}, method = RequestMethod.GET) + public Collection getServices(HttpServletRequest request) throws VidServiceUnavailableException { + try { + return getAsdcClient().getServices(request.getParameterMap()); + } catch (AsdcCatalogException e) { + LOG.error("Failed to retrieve service definitions from SDC", e); + throw new VidServiceUnavailableException("Failed to retrieve service definitions from SDC", e); + } catch (Throwable t) { + LOG.debug("Unexpected error while retrieving service definitions from SDC: " + t.getMessage() + ":", t); + t.printStackTrace(); + throw new VidServiceUnavailableException("Unexpected error while retrieving service definitions from SDC: " + t.getMessage(), t); + } + } + + /** + * Gets the services. + * + * @param uuid the uuid + * @return the services + * @throws VidServiceUnavailableException the vid service unavailable exception + */ + @RequestMapping(value={"/rest/models/services/{uuid}"}, method = RequestMethod.GET) + public ServiceModel getServices(@PathVariable("uuid") String uuid) throws VidServiceUnavailableException { + String methodName = "getServices"; + LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " start"); + boolean isNewFlow = false; + + String asdcModelNamespace = VidProperties.getAsdcModelNamespace(); + + String vnfTag = asdcModelNamespace + ModelConstants.VNF; + String networkTag = asdcModelNamespace + ModelConstants.NETWORK; + String vfModuleTag = asdcModelNamespace + ModelConstants.VF_MODULE; + + try { + final ServiceModel serviceModel = new ServiceModel(); + final Map vnfs = new HashMap (); + final Map networks = new HashMap (); + + final ToscaCsar serviceCsar = getAsdcClient().getServiceToscaModel(UUID.fromString(uuid)); + final Service asdcServiceMetadata = getAsdcClient().getService(UUID.fromString(uuid)); + final ToscaModel asdcServiceToscaModel = serviceCsar.getParent(); + + serviceModel.setService(ServiceModel.extractService(asdcServiceToscaModel, asdcServiceMetadata)); + + for (Entry component: asdcServiceToscaModel.gettopology_template().getnode_templates().entrySet()) { + final String modelCustomizationName = component.getKey(); + LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " model customization name: " + modelCustomizationName); + final NodeTemplate nodeTemplate = component.getValue(); + final String type = nodeTemplate.getType(); + + if (type.startsWith(vnfTag)) { + LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " found node template type: " + type); + + final UUID vnfUuid = UUID.fromString(nodeTemplate.getMetadata().getUUID()); + final VNF vnf = new VNF(); + vnf.extractVnf(modelCustomizationName, nodeTemplate); + + if (vnf.getVersion() == null) { + // vnf version should always be populated. The call below may not return the correct metadata since + // uuid is not unique + final Resource vnfMetadata = getAsdcClient().getResource(UUID.fromString(nodeTemplate.getMetadata().getUUID())); + vnf.setVersion(vnfMetadata.getVersion()); + } + + LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " VNF commands: " + vnf.getCommands()); + vnfs.put(modelCustomizationName, vnf); + if ( (vnf.getCustomizationUuid() != null) && (vnf.getCustomizationUuid().length() > 0 ) ) { + isNewFlow = true; + } + } + // Networks + if (type.startsWith(networkTag)) { + LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " found node template type: " + type); + final UUID networkUuid = UUID.fromString(nodeTemplate.getMetadata().getUUID()); + final Network network = new Network(); + network.extractNetwork(modelCustomizationName, nodeTemplate); + + if (network.getVersion() == null) { + // network version should always be populated. The call below may not return the correct metadata since + // uuid is not unique + final Resource networkMetadata = getAsdcClient().getResource(UUID.fromString(nodeTemplate.getMetadata().getUUID())); + network.setVersion(networkMetadata.getVersion()); + } + if ( (network.getCustomizationUuid() != null) && (network.getCustomizationUuid().length() > 0 ) ) { + isNewFlow = true; + } + networks.put(modelCustomizationName, network); + + } + } + serviceModel.setVnfs(vnfs); + serviceModel.setNetworks(networks); + // If we see customization uuid under vnf or network, follow 1702 flow + if ( isNewFlow ) { + return ( getCustomizedServices(asdcServiceToscaModel, serviceModel) ); + } + VNF vnf = null; + for (ToscaModel vnfModel : serviceCsar.getChildren()) { + + // using uuid to match should only be valid for 1610 models + + final String vnfUuid = (vnfModel.getMetadata().getUUID()); + // find the VNF with that uuid, uuid is not the key anymore + for ( Entry vnfComp : vnfs.entrySet() ) { + if ( ( ( vnfComp.getValue().getUuid() ).equalsIgnoreCase(vnfUuid) ) ) { + // found the vnf + vnf = vnfComp.getValue(); + } + } + final Map vfModules = new HashMap (); + final Map volumeGroups = new HashMap (); + + if (vnf == null) { + LOG.warn("Couldn't find VNF object " + vnfUuid + ". Problem with Tosca model?"); + continue; + } + + vnf.setInputs(vnfModel.gettopology_template().getInputs()); + + for (Entry component1 : vnfModel.gettopology_template().getGroups().entrySet()) { + final Group group = component1.getValue(); + final String type = group.getType(); + final String modelCustomizationName = component1.getKey(); + + // VF Module Customization UUID: We may have the complete set of all VF Modules for all VNFs under service and VF Modules under each VNF. + // Keep using the VF Modules under VNFs but we need to get the customization uuid from the service level and put them + // under each VF module at the VNF level + + if (type.startsWith(vfModuleTag)) { + + VfModule vfMod = VfModule.extractVfModule(modelCustomizationName, group); + + // Add the vf module customization uuid from the service model + // The key of the VF Module in the service level will be the VF instance name appended to the VF Module name: + // .. + /* String normalizedVnfCustomizationName = VNF.normalizeName (vnf.getModelCustomizationName()); + org.openecomp.vid.model.Service.extractVfModuleCustomizationUUID (serviceModel.getService(), normalizedVnfCustomizationName, vfMod);*/ + + vfModules.put(modelCustomizationName, vfMod); + + if ( vfMod.isVolumeGroupAllowed() ) { + volumeGroups.put(modelCustomizationName, VolumeGroup.extractVolumeGroup(modelCustomizationName, group)); + } + + } + } + + vnf.setVfModules(vfModules); + vnf.setVolumeGroups(volumeGroups); + } + + serviceModel.setVnfs(vnfs); + serviceModel.setNetworks(networks); + + return serviceModel; + } catch (AsdcCatalogException e) { + LOG.error("Failed to retrieve service definitions from SDC", e); + throw new VidServiceUnavailableException("Failed to retrieve service definitions from SDC", e); + } + } + + public ServiceModel getCustomizedServices(ToscaModel asdcServiceToscaModel, ServiceModel serviceModel) { + String methodName = "asdcServiceToscaModel"; + LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " start"); + + // asdcServiceToscaModel should have vf modules and vol groups populated at this point but + // they are not associated with the VNFs + serviceModel.extractGroups(asdcServiceToscaModel); + // Now put the vf modules and volume groups under the VNF they belong too + serviceModel.associateGroups(); + return (serviceModel); + } + + /** + * Gets the services view. + * + * @param request the request + * @return the services view + * @throws VidServiceUnavailableException the vid service unavailable exception + */ + @RequestMapping(value={"/serviceModels"}, method=RequestMethod.GET) + public ModelAndView getServicesView(HttpServletRequest request) throws VidServiceUnavailableException { + return new ModelAndView("serviceModels"); + } +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/VidHomeController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/VidHomeController.java new file mode 100755 index 00000000..cfb915b0 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/VidHomeController.java @@ -0,0 +1,79 @@ +/*- + * ============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 javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; + + +import org.springframework.beans.factory.annotation.Autowired; + +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; + + +/** + * The Class VidHomeController. + */ +@RestController +public class VidHomeController extends RestrictedBaseController{ + + /** The view name. */ + String viewName; + + + /** The servlet context. */ + private @Autowired ServletContext servletContext; + + /** + * Welcome. + * + * @param request the request + * @return the model and view + */ + @RequestMapping(value = {"/vidhome" }, method = RequestMethod.GET) + public ModelAndView welcome(HttpServletRequest request) { + + return new ModelAndView(getViewName()); + } + + /* (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; + } + + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/ViewEditSubController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/ViewEditSubController.java new file mode 100755 index 00000000..e23b99ba --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/ViewEditSubController.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.vid.controller; + + +import java.io.File; +import java.text.DateFormat; +import java.util.HashMap; +import java.util.Map; + + + + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +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.servlet.ModelAndView; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; + + +/** + * The Class ViewEditSubController. + */ +@RestController +public class ViewEditSubController extends RestrictedBaseController{ + + /** The view name. */ + String viewName; + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ViewEditSubController.class); + + /** The model. */ + private Map model = new HashMap(); + + /** The servlet context. */ + private @Autowired ServletContext servletContext; + + /** + * Welcome. + * + * @param request the request + * @return the model and view + */ + @RequestMapping(value = {"/vieweditsub" }, method = RequestMethod.GET) + public ModelAndView welcome(HttpServletRequest request) { + return new ModelAndView("vieweditsub","model", model); + // return new ModelAndView(getViewName()); + } + + /** + * Post subscriber. + * + * @param request the request + */ + @RequestMapping(value="/vieweditsub/subedit", method = RequestMethod.POST) + public void PostSubscriber(HttpServletRequest request) { + + String subID = request.getParameter("subscriberID"); + model.put("subInfo", subID); + + } + + /* (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; + } + + + + +} + diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/ViewLogController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/ViewLogController.java new file mode 100755 index 00000000..31e64983 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/ViewLogController.java @@ -0,0 +1,84 @@ +/*- + * ============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 javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; + +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; + + +/** + * The Class ViewLogController. + */ +@RestController +public class ViewLogController extends RestrictedBaseController{ + + /** The view name. */ + String viewName; + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ViewLogController.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The servlet context. */ + private @Autowired ServletContext servletContext; + + /** + * Welcome. + * + * @param request the request + * @return the model and view + */ + @RequestMapping(value = {"/viewlog" }, method = RequestMethod.GET) + public ModelAndView welcome(HttpServletRequest request) { + + return new ModelAndView(getViewName()); + } + + /* (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; + } + + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestAaiController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestAaiController.java new file mode 100755 index 00000000..79017410 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestAaiController.java @@ -0,0 +1,93 @@ +/*- + * ============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.test; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.codehaus.jackson.map.ObjectMapper; +import org.openecomp.vid.model.ExceptionResponse; +import org.springframework.web.bind.annotation.ExceptionHandler; +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.openecomp.portalsdk.core.controller.RestrictedBaseController; + +/** + * The Class TestAaiController. + */ +@RestController +@RequestMapping("testaai") +public class TestAaiController extends RestrictedBaseController { + + /** + * Gets the subscription service type list. + * + * @param globalCustomerId the global customer id + * @param request the request + * @return the subscription service type list + * @throws Exception the exception + */ + @RequestMapping(value = "/getSubscriptionServiceTypeList/{globalCustomerId}", method = RequestMethod.GET) + public String getSubscriptionServiceTypeList(@PathVariable("globalCustomerId") String globalCustomerId, HttpServletRequest request) + throws Exception { + + System.err.println("GET SUBSCRIPTION SERVICE TYPE LIST: globalCustomerId: " + globalCustomerId); + + return "[\"vMOG\", \"sevice type 2\", \"sevice type 3\", \"sevice type 4\"]"; + } + + /** + * Exception. + * + * @param e the e + * @param response the response + * @throws IOException Signals that an I/O exception has occurred. + */ + @ExceptionHandler(Exception.class) + private void exception(Exception e, HttpServletResponse response) throws IOException { + + /* + * This logging step should preferably be replaced with an appropriate + * logging method consistent whatever logging mechanism the rest of the + * application code uses. + */ + + e.printStackTrace(System.err); + + response.setContentType("application/json; charset=UTF-8"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + + ExceptionResponse exceptionResponse = new ExceptionResponse(); + exceptionResponse.setException(e.getClass().toString().replaceFirst("^.*\\.", "")); + exceptionResponse.setMessage(e.getMessage()); + + response.getWriter().write(new ObjectMapper().writeValueAsString(exceptionResponse)); + + response.flushBuffer(); + + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestAsdcController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestAsdcController.java new file mode 100755 index 00000000..84a56b3b --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestAsdcController.java @@ -0,0 +1,112 @@ +/*- + * ============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.test; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.codehaus.jackson.map.ObjectMapper; +import org.openecomp.vid.model.ExceptionResponse; +import org.springframework.web.bind.annotation.ExceptionHandler; +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.openecomp.portalsdk.core.controller.RestrictedBaseController; + +/** + * The Class TestAsdcController. + */ +@RestController +@RequestMapping("testasdc") +public class TestAsdcController extends RestrictedBaseController { + + /** + * Gets the model. + * + * @param modelId the model id + * @param request the request + * @return the model + * @throws Exception the exception + */ + @RequestMapping(value = "/getModel/{modelId}", method = RequestMethod.GET) + public String getModel(@PathVariable("modelId") String modelId, HttpServletRequest request) throws Exception { + + System.err.println("SDC: GET MODEL: modelId: " + modelId); + + // @formatter:off + return + "{" + + "\"uuid\": \"5be686dc-fdca-4d54-8548-5d0ed23e962b\"," + + "\"invariantUUID\": \"e5962da9-fe4f-433a-bc99-b43e0d88a9a1\"," + + "\"name\": \"DE220127\"," + + "\"version\": \"0.1\"," + + "\"inputs\": {" + + "\"defaultGateway\": {" + + "\"type\": \"String\"," + + "\"default\": \"192.168.1.1\"," + + "\"description\": \"Router default gateway - use any valid IPv4 address\"" + + "}," + + "\"subnetMask\": {" + + "\"type\": \"String\"," + + "\"default\": \"255.255.255.0\"," + + "\"description\": \"Router subnet mask - example (255.255.255.0)\"" + + "}" + + "}" + + "}"; + // @formatter:on + } + + /** + * Exception. + * + * @param e the e + * @param response the response + * @throws IOException Signals that an I/O exception has occurred. + */ + @ExceptionHandler(Exception.class) + private void exception(Exception e, HttpServletResponse response) throws IOException { + + /* + * This logging step should preferably be replaced with an appropriate + * logging method consistent whatever logging mechanism the rest of the + * application code uses. + */ + + e.printStackTrace(System.err); + + response.setContentType("application/json; charset=UTF-8"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + + ExceptionResponse exceptionResponse = new ExceptionResponse(); + exceptionResponse.setException(e.getClass().toString().replaceFirst("^.*\\.", "")); + exceptionResponse.setMessage(e.getMessage()); + + response.getWriter().write(new ObjectMapper().writeValueAsString(exceptionResponse)); + + response.flushBuffer(); + + } + +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestMsoController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestMsoController.java new file mode 100755 index 00000000..02c29f67 --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestMsoController.java @@ -0,0 +1,729 @@ +/*- + * ============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.test; + +import java.io.IOException; +import java.util.stream.Collectors; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.codehaus.jackson.map.ObjectMapper; +import org.openecomp.vid.model.ExceptionResponse; +import org.springframework.http.HttpStatus; +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.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; + +/* + * The "TestMsoController" class is primarily designed to help test "msoCommitController.js" + * + * This class expects and receives JSON data in the same format as expected + * in the "real" application version of this code. However, string versions of JSON are + * maintained internally here instead of marshalled / unmarshalled JSON objects. + * The primary reasons for this were to encapsulate all the test code in this single file and + * minimize the time required to support initial test cases. + * + * The non-test equivalent of this controller could alternatively incorporate POJO objects + * instead of strings. However, the same data format sent to / received from the browser + * JavaScript code would still be expected. + * + * Two specific mechanisms used in this test class may be useful to the application version: + * + * 1) The use of "{variable}" elements in @RequestMappings along with the corresponding + * @PathVariable declarations. + * + * 2) The use of @ExceptionHandler for general purpose exception handler. + * (See @ExceptionHandler comments) + * + * This class is intended to be used in either: + * + * A) Eclipse environments + * OR + * B) Linux environments with ONLY a single user running tests. + * The "quick and dirty" error simulation approach used here makes use of static states for some + * scenarios. Thus multiple users simultaneously testing in Linux environments + * may have contention issues. + */ + +/** + * The Class TestMsoController. + */ +@RestController +@RequestMapping("testmso") +public class TestMsoController extends RestrictedBaseController { + + /* + * Artificial delay (in milliseconds) added before responding to create / + * delete requests + */ + + /** The Constant TEST_DELAY_SHORT_MSEC. */ + private final static int TEST_DELAY_SHORT_MSEC = 1000; + + /* + * Long delay to simulate non-responsive server test + */ + + /** The Constant TEST_DELAY_LONG_MSEC. */ + private final static int TEST_DELAY_LONG_MSEC = 15000; + + /* + * Default number of polls expected before transaction complete. + */ + + /** The Constant MAXIMUM_POLLS_DEFAULT. */ + private final static int MAXIMUM_POLLS_DEFAULT = 4; + + /* + * Number of polls to simulate "maximum polls exceeded" test. + */ + + /** The Constant MAXIMUM_POLLS_LARGE. */ + private final static int MAXIMUM_POLLS_LARGE = 10; + + /* + * Simulated error types. The GUI front end is expected to set these values + * in the "modelName" field of the "mso_create_svc_instance" request. + */ + + /** The Constant ERROR_POLICY_EXCEPTION. */ + private final static String ERROR_POLICY_EXCEPTION = "ERROR_POLICY_EXCEPTION"; + + /** The Constant ERROR_SERVICE_EXCEPTION. */ + private final static String ERROR_SERVICE_EXCEPTION = "ERROR_SERVICE_EXCEPTION"; + + /** The Constant ERROR_POLL_FAILURE. */ + private final static String ERROR_POLL_FAILURE = "ERROR_POLL_FAILURE"; + + /** The Constant ERROR_INVALID_FIELD_INITIAL. */ + private final static String ERROR_INVALID_FIELD_INITIAL = "ERROR_INVALID_FIELD_INITIAL"; + + /** The Constant ERROR_INVALID_FIELD_POLL. */ + private final static String ERROR_INVALID_FIELD_POLL = "ERROR_INVALID_FIELD_POLL"; + + /** The Constant ERROR_GENERAL_SERVER_EXCEPTION. */ + private final static String ERROR_GENERAL_SERVER_EXCEPTION = "ERROR_GENERAL_SERVER_EXCEPTION"; + + /** The Constant ERROR_MAX_POLLS. */ + private final static String ERROR_MAX_POLLS = "ERROR_MAX_POLLS"; + + /** The Constant ERROR_SERVER_TIMEOUT_INITIAL. */ + private final static String ERROR_SERVER_TIMEOUT_INITIAL = "ERROR_SERVER_TIMEOUT_INITIAL"; + + /** The Constant ERROR_SERVER_TIMEOUT_POLL. */ + private final static String ERROR_SERVER_TIMEOUT_POLL = "ERROR_SERVER_TIMEOUT_POLL"; + + /** The simulated error. */ + private String simulatedError = ""; + + /** The maximum polls. */ + private int maximumPolls = 0; + + /** The attempt count. */ + private int attemptCount = 0; + + /** + * Creates the svc instance. + * + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_create_svc_instance", method = RequestMethod.POST) + public ResponseEntity createSvcInstance(HttpServletRequest request) throws Exception { + readAndLogRequest("CREATE SERVICE INSTANCE", request); + Thread.sleep(TEST_DELAY_SHORT_MSEC); + maximumPolls = MAXIMUM_POLLS_DEFAULT; // Simulates MSO polling behavior + attemptCount = 0; + + /* + * This block of code simulates various errors and would NOT be expected + * in a non-test method + */ + System.err.println("simulatedError: " + simulatedError); + + if (simulatedError.equals(ERROR_POLICY_EXCEPTION)) { + return new ResponseEntity(policyExceptionResponse, HttpStatus.OK); + } + if (simulatedError.equals(ERROR_SERVICE_EXCEPTION)) { + return new ResponseEntity(serviceExceptionResponse, HttpStatus.OK); + } + if (simulatedError.equals(ERROR_INVALID_FIELD_INITIAL)) { + /* + * Force invalid response field name. Return + * "XXXXXrequestReferences" instead of "requestReferences" + */ + return new ResponseEntity(acceptResponse.replace("requestReferences", "XXXXXrequestReferences"), + HttpStatus.OK); + } + + if (simulatedError.equals(ERROR_GENERAL_SERVER_EXCEPTION)) { + throw new IOException("an example of an IO exception"); + } + + if (simulatedError.equals(ERROR_SERVER_TIMEOUT_INITIAL)) { + Thread.sleep(TEST_DELAY_LONG_MSEC); + } + + if (simulatedError.equals(ERROR_MAX_POLLS)) { + maximumPolls = MAXIMUM_POLLS_LARGE; + } + + /* + * End of block of simulated error code. + */ + + return new ResponseEntity(acceptResponse, HttpStatus.OK); + } + + /** + * Delete svc instance. + * + * @param serviceInstanceId the service instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_delete_svc_instance/{serviceInstanceId}", method = RequestMethod.POST) + public ResponseEntity deleteSvcInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + HttpServletRequest request) throws Exception { + readAndLogRequest("DELETE SERVICE INSTANCE: serviceInstanceId: " + serviceInstanceId, request); + Thread.sleep(TEST_DELAY_SHORT_MSEC); + maximumPolls = MAXIMUM_POLLS_DEFAULT; // Simulates MSO polling behavior + attemptCount = 0; + return new ResponseEntity(acceptResponse, HttpStatus.OK); + } + + /** + * Creates the vnf instance. + * + * @param serviceInstanceId the service instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_create_vnf_instance/{serviceInstanceId}", method = RequestMethod.POST) + public ResponseEntity createVnfInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + HttpServletRequest request) throws Exception { + readAndLogRequest("CREATE VNF INSTANCE: serviceInstanceId: " + serviceInstanceId, request); + Thread.sleep(TEST_DELAY_SHORT_MSEC); + maximumPolls = MAXIMUM_POLLS_DEFAULT; // Simulates MSO polling behavior + attemptCount = 0; + return new ResponseEntity(acceptResponse, HttpStatus.OK); + } + + /** + * Delete vnf instance. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_delete_vnf_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) + public ResponseEntity deleteVnfInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("vnfInstanceId") String vnfInstanceId, HttpServletRequest request) throws Exception { + readAndLogRequest( + "DELETE VNF INSTANCE: serviceInstanceId: " + serviceInstanceId + " vnfInstanceId: " + vnfInstanceId, + request); + Thread.sleep(TEST_DELAY_SHORT_MSEC); + maximumPolls = MAXIMUM_POLLS_DEFAULT; // Simulates MSO polling behavior + attemptCount = 0; + return new ResponseEntity(acceptResponse, HttpStatus.OK); + } + + /** + * Creates the vf module instance. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + // /serviceInstances/v2/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-ff1b-adb2-eb6b9e5460ff/vfModules + @RequestMapping(value = "/mso_create_vfmodule_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) + public ResponseEntity createVfModuleInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("vnfInstanceId") String vnfInstanceId, HttpServletRequest request) throws Exception { + readAndLogRequest("CREATE VF MODULE INSTANCE: serviceInstanceId: " + serviceInstanceId + " vnfInstanceId: " + + vnfInstanceId, request); + Thread.sleep(TEST_DELAY_SHORT_MSEC); + maximumPolls = MAXIMUM_POLLS_DEFAULT; // Simulates MSO polling behavior + attemptCount = 0; + return new ResponseEntity(acceptResponse, HttpStatus.OK); + } + + /** + * Delete vf module instance. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param vfModuleInstanceId the vf module instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + // /serviceInstances/v2/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-ff1b-adb2-eb6b9e5460ff/vfModules/ff305d54-75b4-ff1b-bdb2-eb6b9e5460ff + @RequestMapping(value = "/mso_delete_vfmodule_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfModuleInstanceId}", method = RequestMethod.POST) + public ResponseEntity deleteVfModuleInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("vnfInstanceId") String vnfInstanceId, + @PathVariable("vfModuleInstanceId") String vfModuleInstanceId, HttpServletRequest request) + throws Exception { + readAndLogRequest("DELETE VF MODULE INSTANCE: serviceInstanceId: " + serviceInstanceId + " vnfInstanceId: " + + vnfInstanceId + " vfModuleInstanceId: " + vfModuleInstanceId, request); + Thread.sleep(TEST_DELAY_SHORT_MSEC); + maximumPolls = MAXIMUM_POLLS_DEFAULT; // Simulates MSO polling behavior + attemptCount = 0; + return new ResponseEntity(acceptResponse, HttpStatus.OK); + } + + // POST + /** + * Creates the volume group instance. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + // /serviceInstances/v2/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups + @RequestMapping(value = "/mso_create_volumegroup_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) + public ResponseEntity createVolumeGroupInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("vnfInstanceId") String vnfInstanceId, HttpServletRequest request) throws Exception { + readAndLogRequest("CREATE VOLUME GROUP INSTANCE: seviceInstanceId: " + serviceInstanceId + " vnfInstanceId: " + + vnfInstanceId, request); + Thread.sleep(TEST_DELAY_SHORT_MSEC); + maximumPolls = MAXIMUM_POLLS_DEFAULT; // Simulates MSO polling behavior + attemptCount = 0; + return new ResponseEntity(acceptResponse, HttpStatus.OK); + } + + /** + * Delete volume group instance. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param volumeGroupInstanceId the volume group instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + // /serviceInstances/v2/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-ff1b-cdb2-eb6b9e5460ff + @RequestMapping(value = "/mso_delete_volumegroup_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}", method = RequestMethod.POST) + public ResponseEntity deleteVolumeGroupInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("vnfInstanceId") String vnfInstanceId, + @PathVariable("volumeGroupInstanceId") String volumeGroupInstanceId, HttpServletRequest request) + throws Exception { + readAndLogRequest("DELETE NW INSTANCE: serviceInstanceId: " + serviceInstanceId + " vnfInstanceId: " + + vnfInstanceId + " volumeGroupInstanceId: " + volumeGroupInstanceId, request); + Thread.sleep(TEST_DELAY_SHORT_MSEC); + maximumPolls = MAXIMUM_POLLS_DEFAULT; // Simulates MSO polling behavior + attemptCount = 0; + return new ResponseEntity(acceptResponse, HttpStatus.OK); + } + + /** + * Creates the nw instance. + * + * @param serviceInstanceId the service instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_create_nw_instance/{serviceInstanceId}", method = RequestMethod.POST) + public ResponseEntity createNwInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + HttpServletRequest request) throws Exception { + readAndLogRequest("CREATE NW INSTANCE: serviceInstanceId: " + serviceInstanceId, request); + Thread.sleep(TEST_DELAY_SHORT_MSEC); + maximumPolls = MAXIMUM_POLLS_DEFAULT; // Simulates MSO polling behavior + attemptCount = 0; + return new ResponseEntity(acceptResponse, HttpStatus.OK); + } + + /** + * Delete nw instance. + * + * @param serviceInstanceId the service instance id + * @param networkInstanceId the network instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @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) throws Exception { + readAndLogRequest("DELETE NW INSTANCE: serviceInstanceId: " + serviceInstanceId + " networkInstanceId: " + + networkInstanceId, request); + Thread.sleep(TEST_DELAY_SHORT_MSEC); + maximumPolls = MAXIMUM_POLLS_DEFAULT; // Simulates MSO polling behavior + attemptCount = 0; + return new ResponseEntity(acceptResponse, HttpStatus.OK); + } + + /** + * Gets the orchestration request. + * + * @param requestId the request id + * @param request the request + * @return the orchestration request + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_get_orch_req/{requestId}", method = RequestMethod.GET) + public ResponseEntity getOrchestrationRequest(@PathVariable("requestId") String requestId, + HttpServletRequest request) throws Exception { + + System.err.println("GET ORCHESTRATION REQUEST: requestId: " + requestId); + + /* + * This block of code simulates various errors and would NOT be expected + * in a non-test method + */ + + if (simulatedError.equals(ERROR_INVALID_FIELD_POLL)) { + /* + * Force invalid response field name. Return "XXXXXrequestStatus" + * instead of "requestStatus" + */ + return new ResponseEntity(inProgressResponse.replace("requestStatus", "XXXXXrequestStatus"), + HttpStatus.OK); + } + + if (simulatedError.equals(ERROR_POLL_FAILURE)) { + /* + * Force status field with "Failure" + */ + return new ResponseEntity(inProgressResponse.replace("InProgress", "Failure"), HttpStatus.OK); + } + + if (simulatedError.equals(ERROR_SERVER_TIMEOUT_POLL)) { + Thread.sleep(TEST_DELAY_LONG_MSEC); + } + + /* + * End of block of simulated error code. + */ + + /* + * This logic simulates how MSO might behave ... i.e. return different + * results depending on the value of 'maximumPolls'. + * + */ + int percentProgress = (++attemptCount * 100) / maximumPolls; + + System.err.println("attempts: " + attemptCount + " max: " + maximumPolls + " percent: " + percentProgress); + + String response = inProgressResponse.replace("\"50\"", "\"" + Integer.toString(percentProgress) + "\""); + + if (attemptCount < maximumPolls) { + if (attemptCount > 1) { + response = response.replace("vLan setup", "setup step " + Integer.toString(attemptCount)); + } + return new ResponseEntity(response, HttpStatus.OK); + } else { + return new ResponseEntity( + response.replace("InProgress", "Complete").replace("vLan setup complete", ""), HttpStatus.OK); + } + } + + /** + * Gets the orchestration requests. + * + * @param filterString the filter string + * @param request the request + * @return the orchestration requests + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_get_orch_reqs/{filterString}", method = RequestMethod.GET) + public ResponseEntity getOrchestrationRequests(@PathVariable("filterString") String filterString, + HttpServletRequest request) throws Exception { + + System.err.println("GET ORCHESTRATION REQUESTS: filterString: " + filterString); + + return new ResponseEntity(getOrchestrationRequestsResponse, HttpStatus.OK); + + } + + /* + * General purpose exception handler that could be used in application code. + * + * The method returns exceptions as error code 500. Both the exception type + * and message are written as a JSON object. + * + * See the following references: + * + * 1) The ExceptionResponse POJO. + * + * 2) The "getHttpErrorMessage" function in "utilityService.js" - an example + * of how the browser JavaScript code can interpret this response. + */ + + /** + * Exception. + * + * @param e the e + * @param response the response + * @throws IOException Signals that an I/O exception has occurred. + */ + @ExceptionHandler(Exception.class) + private void exception(Exception e, HttpServletResponse response) throws IOException { + + /* + * This logging step should preferably be replaced with an appropriate + * logging method consistent whatever logging mechanism the rest of the + * application code uses. + */ + + e.printStackTrace(System.err); + + response.setContentType("application/json; charset=UTF-8"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + + ExceptionResponse exceptionResponse = new ExceptionResponse(); + exceptionResponse.setException(e.getClass().toString().replaceFirst("^.*\\.", "")); + exceptionResponse.setMessage(e.getMessage()); + + response.getWriter().write(new ObjectMapper().writeValueAsString(exceptionResponse)); + + response.flushBuffer(); + + } + + /* + * 'readAndLogRequest' only intended to be used for testing. + * + * The method reads JSON from the input stream and thus prevents other + * mechanisms from reading the input. + */ + + /** + * Read and log request. + * + * @param label the label + * @param request the request + * @throws Exception the exception + */ + private void readAndLogRequest(String label, HttpServletRequest request) throws Exception { + String input = request.getReader().lines().collect(Collectors.joining(System.lineSeparator())); + + ObjectMapper mapper = new ObjectMapper(); + Object json = mapper.readValue(input, Object.class); + + System.err.println(label + "\n" + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json)); + + /* + * Only needed for error simulation ... + */ + if (input.matches("^.*modelName.*$")) { + simulatedError = input.replaceAll("^.*\"modelName\":\"", "").replaceAll("\".*$", ""); + } + } + + /* + * Various test responses: + */ + + // @formatter:off + + /** The accept response. */ + /* + * Sample responses to initial create / delete transaction + */ + private String acceptResponse = + "{" + + " \"status\": 202," + + " \"entity\": {" + + " \"requestReferences\": {" + + " \"instanceId\": \"bc305d54-75b4-431b-adb2-eb6b9e546014\"," + + " \"requestId\": \"rq1234d1-5a33-55df-13ab-12abad84e331\"" + + " }" + + " }" + + "}"; + + /** The policy exception response. */ + private String policyExceptionResponse = + "{" + + " \"status\": 400," + + " \"entity\": { " + + " \"requestError\": {" + + " \"policyException\": {" + + " \"messageId\": \"POL9003\"," + + " \"text\": \"Message content size exceeds the allowable limit\"" + + " }" + + " }" + + " }" + + "}"; + + /** The service exception response. */ + private String serviceExceptionResponse = + "{" + + " \"status\": 400," + + " \"entity\": { " + + " \"requestError\": {" + + " \"serviceException\": {" + + " \"messageId\": \"SVC2000\"," + + " \"text\": \"Missing Parameter: %1. Error code is %2\"," + + " \"variables\": [" + + " \"severity\"," + + " \"400\"" + + " ]" + + " }" + + " }" + + " }" + + "}" + + ""; + + /** The in progress response. */ + /* + * Sample response to subsequent getOrchestrationRequest + */ + private String inProgressResponse = + "{" + + " \"status\": 200," + + " \"entity\": {" + + " \"request\": {" + + " \"requestId\": \"rq1234d1-5a33-55df-13ab-12abad84e333\"," + + " \"startTime\": \"Thu, 04 Jun 2009 02:51:59 GMT\"," + + " \"instanceIds\": {" + + " \"serviceInstanceId\": \"bc305d54-75b4-431b-adb2-eb6b9e546014\"" + + " }," + + " \"requestScope\": \"service\"," + + " \"requestType\": \"createInstance\"," + + " \"requestDetails\": {" + + " \"modelInfo\": {" + + " \"modelType\": \"service\"," + + " \"modelId\": \"sn5256d1-5a33-55df-13ab-12abad84e764\"," + + " \"modelNameVersionId\": \"ab6478e4-ea33-3346-ac12-ab121484a333\"," + + " \"modelName\": \"WanBonding\"," + + " \"modelVersion\": \"1\"" + + " }," + + " \"subscriberInfo\": {" + + " \"globalSubscriberId\": \"C12345\"," + + " \"subscriberName\": \"General Electric Division 12\"" + + " }," + + " \"requestParameters\": {" + + " \"vpnId\": \"1a2b3c4d5e6f\"," + + " \"productName\": \"Trinity\"," + + " \"customerId\": \"icore9883749\"" + + " }" + + " }," + + " \"requestStatus\": {" + + " \"timestamp\": \"Thu, 04 Jun 2009 02:53:39 GMT\"," + + " \"requestState\": \"InProgress\"," + + " \"statusMessage\": \"vLan setup complete\"," + + " \"percentProgress\": \"50\"" + + " }" + + " }" + + " }" + + "}"; + + /* + * Sample response to subsequent getOrchestrationRequests + */ + + /** The get orchestration requests response. */ + private String getOrchestrationRequestsResponse = + "{" + + " \"status\": 200," + + " \"entity\": {" + + " \"requestList\": [" + + " {" + + " \"request\": {" + + " \"requestId\": \"rq1234d1-5a33-55df-13ab-12abad84e333\"," + + " \"startTime\": \"Thu, 04 Jun 2009 02:51:59 GMT\"," + + " \"finishTime\": \"Thu, 04 Jun 2009 02:55:59 GMT\"," + + " \"instanceReferences\": {" + + " \"serviceInstanceId\": \"bc305d54-75b4-431b-adb2-eb6b9e546014\"" + + " }," + + " \"requestScope\": \"service\"," + + " \"requestType\": \"createInstance\"," + + " \"requestDetails\": {" + + " \"modelInfo\": {" + + " \"modelType\": \"service\"," + + " \"modelId\": \"sn5256d1-5a33-55df-13ab-12abad84e764\"," + + " \"modelNameVersionId\": \"ab6478e4-ea33-3346-ac12-ab121484a333\"," + + " \"modelName\": \"WanBonding\"," + + " \"modelVersion\": \"1\"" + + " }," + + " \"subscriberInfo\": {" + + " \"globalSubscriberId\": \"C12345\"," + + " \"subscriberName\": \"General Electric Division 12\"" + + " }," + + " \"requestParameters\": {" + + " \"vpnId\": \"1a2b3c4d5e6f\"," + + " \"productName\": \"Trinity\"," + + " \"customerId\": \"icore9883749\"" + + " }" + + " }," + + " \"requestStatus\": {" + + " \"timestamp\": \"Thu, 04 Jun 2009 02:54:49 GMT\"," + + " \"requestState\": \"complete\"," + + " \"statusMessage\": \"Resource Created\"," + + " \"percentProgress\": \"100\"" + + " }" + + " }" + + " }," + + " {" + + " \"request\": {" + + " \"requestId\": \"rq1234d1-5a33-55df-13ab-12abad84e334\"," + + " \"startTime\": \"Thu, 04 Jun 2009 03:52:59 GMT\"," + + " \"instanceReferences\": {" + + " \"serviceInstanceId\": \"bc305d54-75b4-431b-adb2-eb6b9e546014\"" + + " }," + + " \"requestScope\": \"service\"," + + " \"requestType\": \"updateInstance\"," + + " \"requestDetails\": {" + + " \"modelInfo\": {" + + " \"modelType\": \"service\"," + + " \"modelId\": \"sn5256d1-5a33-55df-13ab-12abad84e764\"," + + " \"modelNameVersionId\": \"ab6478e4-ea33-3346-ac12-ab121484a333\"," + + " \"modelName\": \"WanBonding\"," + + " \"modelVersion\": \"1\"" + + " }," + + " \"subscriberInfo\": {" + + " \"globalSubscriberId\": \"C12345\"," + + " \"subscriberName\": \"General Electric Division 12\"" + + " }," + + " \"requestParameters\": {" + + " \"vpnId\": \"1a2b3c4d5e70\"," + + " \"productName\": \"Trinity\"," + + " \"customerId\": \"icore9883749\"" + + " }" + + " }," + + " \"requestStatus\": {" + + " \"timestamp\": \"Thu, 04 Jun 2009 03:53:39 GMT\"," + + " \"requestState\": \"InProgress\"," + + " \"statusMessage\": \"vLan setup complete\"," + + " \"percentProgress\": \"50\"" + + " }" + + " }" + + " }" + + " ]" + + " }" + + "}"; +} diff --git a/vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestPageController.java b/vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestPageController.java new file mode 100755 index 00000000..92f86f0b --- /dev/null +++ b/vid-app-common/src/main/java/org/openecomp/vid/controller/test/TestPageController.java @@ -0,0 +1,57 @@ +/*- + * ============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.test; + +import org.springframework.stereotype.Controller; +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.servlet.ModelAndView; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; + +/** + * The Class TestPageController. + */ +@Controller +public class TestPageController extends RestrictedBaseController { + + /** + * Test mso page. + * + * @return the model and view + */ + @RequestMapping(value = { "testMso.htm" }, method = RequestMethod.GET) + public ModelAndView testMsoPage() { + return new ModelAndView(getViewName()); + } + + /** + * Test view edit page. + * + * @return the model and view + */ + @RequestMapping(value = { "testViewEdit" }, method = RequestMethod.GET) + public ModelAndView testViewEditPage() { + return new ModelAndView(getViewName()); + } + +} -- cgit 1.2.3-korg