diff options
Diffstat (limited to 'ccsdk-app-common')
33 files changed, 5161 insertions, 2999 deletions
diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/Authorizer.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/Authorizer.java deleted file mode 100644 index 27b887a..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/Authorizer.java +++ /dev/null @@ -1,149 +0,0 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2019 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.controller; - -import java.io.IOException; -import java.util.Collections; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.web.support.AppUtils; - -public class Authorizer { - - private static Authorizer authorizer = new Authorizer(); - private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(Authorizer.class); - private static final String AUTH_PROP_FILE_NAME = "authorizer.properties"; - private static final String DCAE_ROLES_KEY = "dcae_roles"; - - public static Authorizer getAuthorizer() { - return authorizer; - } - - public boolean isAuthorized(HttpServletRequest request) { - final String method = request.getMethod(); - final String resource = request.getRequestURI(); - - final Set<Authorizer.Role> authorizedRoles = getAuthorizedRoles(method, resource); - - // Anybody can access this page, no need to check - if (authorizedRoles.contains(Role.ANY)) { - return true; - } - - final Set<Authorizer.Role> roles = getRoles(request); - final Set<Authorizer.Role> intersection = new HashSet<>(roles); - - intersection.retainAll(authorizedRoles); // Removes all roles in roles that aren't contained in authorizedRoles. - - return !intersection.isEmpty(); // If the intersection is not empty, then this user is authorized - } - - // Helper method to set roles - public void putRoles(HttpServletRequest request, Set<Role> roles) { - request.getSession().setAttribute(DCAE_ROLES_KEY, roles); - } - - // Returns roles for the current user making the request - @SuppressWarnings("unchecked") - private Set<Authorizer.Role> getRoles(HttpServletRequest request) { - - // If roles is empty, then write the user's roles to the session - if (request.getSession().getAttribute(DCAE_ROLES_KEY) == null) { - - // HashSet to be used to for putRoles - HashSet<Role> roles = new HashSet<>(); - roles.add(Role.READER); - - // Get roles and turn into list of role objects - HttpSession session = AppUtils.getSession(request); - String roleType = (String) session.getAttribute("auth_role"); - if (roleType != null) { - switch (roleType) { - case "ADMIN": - roles.add(Role.ADMIN); - break; - case "WRITE": - roles.add(Role.WRITER); - break; - case "READ": - roles.add(Role.READER); - break; - default: - roles.add(Role.READER); - break; - } - } - // Write user roles - putRoles(request, roles); - } - - // Check if attribute DCAE_ROLES_KEY is valid - final Object rawRoles = request.getSession().getAttribute(DCAE_ROLES_KEY); - - if (!(rawRoles instanceof Set<?>)) { - throw new RuntimeException("Unrecognized object found in session for key=" + DCAE_ROLES_KEY); - } - - return (Set<Authorizer.Role>) request.getSession().getAttribute(DCAE_ROLES_KEY); - } - - // Returns roles authorized to perform the requested method (i.e. - // getAuthorizedRoles("POST", "/ecd-app-att/deployments")) - private Set<Authorizer.Role> getAuthorizedRoles(String method, String resource) { - final Properties resourceRoles = new Properties(); - - try { - resourceRoles.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(AUTH_PROP_FILE_NAME)); - - final String[] splitMethodResourceKey = (method + resource.replace("/", ".")).split("\\.", 0); - final String methodResourceKey = splitMethodResourceKey[0] + "." + splitMethodResourceKey[2]; - - if (!resourceRoles.containsKey(methodResourceKey)) { - LOGGER.warn(AUTH_PROP_FILE_NAME + " does not contain roles for " + methodResourceKey + "; defaulting " - + Authorizer.Role.ANY); - return new HashSet<>(Collections.singleton(Role.ANY)); - } - - final String[] rawAuthorizedRoles = ((String) resourceRoles.get(methodResourceKey)).split(","); - final Set<Authorizer.Role> authorizedRoles = new HashSet<>(); - - for (String rawAuthorizedRole : rawAuthorizedRoles) { - authorizedRoles.add(Authorizer.Role.valueOf(rawAuthorizedRole)); - } - - return authorizedRoles; - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public enum Role { - ADMIN, READER, WRITER, ANY, NONE; - } - -}
\ No newline at end of file diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CloudifyController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CloudifyController.java index 06ca980..16949cd 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CloudifyController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CloudifyController.java @@ -33,14 +33,11 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprint; import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintUpload; import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; import org.onap.ccsdk.dashboard.model.CloudifyDeployment; import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentRequest; import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; import org.onap.ccsdk.dashboard.model.CloudifyEvent; import org.onap.ccsdk.dashboard.model.CloudifyEventList; @@ -53,12 +50,12 @@ import org.onap.ccsdk.dashboard.model.ECTransportModel; import org.onap.ccsdk.dashboard.model.RestResponseError; import org.onap.ccsdk.dashboard.model.RestResponsePage; import org.onap.ccsdk.dashboard.rest.CloudifyClient; -import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.web.support.UserUtils; import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -81,8 +78,11 @@ import com.fasterxml.jackson.core.JsonProcessingException; @RequestMapping("/") public class CloudifyController extends DashboardRestrictedBaseController { - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CloudifyController.class); - private CloudifyClient restClient; + private static EELFLoggerDelegate logger = + EELFLoggerDelegate.getLogger(CloudifyController.class); + + @Autowired + CloudifyClient cloudifyClient; /** * Enum for selecting an item type. @@ -94,37 +94,15 @@ public class CloudifyController extends DashboardRestrictedBaseController { private static Date begin; private static Date end; private static final String BLUEPRINTS_PATH = "blueprints"; - private static final String VIEW_BLUEPRINTS_PATH = "viewblueprints"; private static final String DEPLOYMENTS_PATH = "deployments"; private static final String EXECUTIONS_PATH = "executions"; private static final String TENANTS_PATH = "tenants"; private static final String NODE_INSTANCES_PATH = "node-instances"; private static final String UPDATE_DEPLOYMENT_PATH = "update-deployment"; - private static final String SECRETS_PATH = "secrets"; private static final String EVENTS_PATH = "events"; private static final String DEP_TENANT_STATUS = "deployment-status"; /** - * Supports sorting blueprints by ID - */ - private static Comparator<CloudifyBlueprint> blueprintComparator = new Comparator<CloudifyBlueprint>() { - @Override - public int compare(CloudifyBlueprint o1, CloudifyBlueprint o2) { - return o1.id.compareTo(o2.id); - } - }; - - /** - * Supports sorting deployments by ID - */ - private static Comparator<CloudifyDeployment> deploymentComparator = new Comparator<CloudifyDeployment>() { - @Override - public int compare(CloudifyDeployment o1, CloudifyDeployment o2) { - return o1.id.compareTo(o2.id); - } - }; - - /** * Supports sorting events by timestamp */ private static Comparator<CloudifyEvent> eventComparator = new Comparator<CloudifyEvent>() { @@ -148,49 +126,41 @@ public class CloudifyController extends DashboardRestrictedBaseController { * Gets one page of objects and supporting information via the REST client. On * success, returns a PaginatedRestResponse object as String. * - * @param option Specifies which item list type to get - * @param pageNum Page number of results + * @param option Specifies which item list type to get + * @param pageNum Page number of results * @param pageSize Number of items per browser page * @return JSON block as String, see above. * @throws Exception On any error; e.g., Network failure. */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - private String getItemListForPage(long userId, CloudifyDataItem option, int pageNum, int pageSize) - throws Exception { - if (this.restClient == null) { - this.restClient = getCloudifyRestClient(userId); - } - List itemList = null; - switch (option) { + @SuppressWarnings({"rawtypes"}) + private String getItemListForPage(long userId, CloudifyDataItem option, int pageNum, + int pageSize) throws Exception { /* - * case BLUEPRINT: itemList = restClient.getBlueprints().items; - * Collections.sort(itemList, blueprintComparator); break; case DEPLOYMENT: - * itemList = restClient.getDeployments().items; Collections.sort(itemList, - * deploymentComparator); break; + * if (this.restClient == null) { this.restClient = + * getCloudifyRestClient(userId); } */ - case TENANT: - itemList = restClient.getTenants().items; - break; - default: - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting page of items failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPage caught exception"); - throw new Exception("getItemListForPage failed: unimplemented case: " + option.name()); + List itemList = null; + switch (option) { + /* + * case BLUEPRINT: itemList = restClient.getBlueprints().items; + * Collections.sort(itemList, blueprintComparator); break; case DEPLOYMENT: + * itemList = restClient.getDeployments().items; Collections.sort(itemList, + * deploymentComparator); break; + */ + case TENANT: + itemList = cloudifyClient.getTenants().items; + break; + default: + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting page of items failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPage caught exception"); + throw new Exception( + "getItemListForPage failed: unimplemented case: " + option.name()); } - /* - * String cloudPrimTenant = - * getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); - * String aicPrimTenant = - * getAppProperties().getProperty(DashboardProperties.AIC_TENANT_PRIM); - * - * for (CloudifyTenant ct: (List<CloudifyTenant>)itemList) { if ( - * ct.name.equals(cloudPrimTenant) ) { ct.dName = aicPrimTenant; } else { - * ct.dName = ct.name; } } - */ // Shrink if needed final int totalItems = itemList.size(); final int pageCount = (int) Math.ceil((double) totalItems / pageSize); @@ -247,30 +217,29 @@ public class CloudifyController extends DashboardRestrictedBaseController { * @param request HttpServletRequest * @return List of CloudifyBlueprint objects */ - @RequestMapping(value = { BLUEPRINTS_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getBlueprintsByPage(HttpServletRequest request) { - preLogAudit(request); - String json = getItemListForPageWrapper(request, CloudifyDataItem.BLUEPRINT); - postLogAudit(request); - return json; - } - + /* + * @RequestMapping(value = { BLUEPRINTS_PATH }, method = RequestMethod.GET, + * produces = "application/json") + * + * @ResponseBody public String getBlueprintsByPage(HttpServletRequest request) { + * preLogAudit(request); String json = getItemListForPageWrapper(request, + * CloudifyDataItem.BLUEPRINT); postLogAudit(request); return json; } + */ /** * Serves one page of deployments * * @param request HttpServletRequest * @return List of CloudifyDeployment objects */ - @RequestMapping(value = { DEPLOYMENTS_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getDeploymentsByPage(HttpServletRequest request) { - preLogAudit(request); - String json = getItemListForPageWrapper(request, CloudifyDataItem.DEPLOYMENT); - postLogAudit(request); - return json; - } + /* + * @RequestMapping(value = { DEPLOYMENTS_PATH }, method = RequestMethod.GET, + * produces = "application/json") + * + * @ResponseBody public String getDeploymentsByPage(HttpServletRequest request) + * { preLogAudit(request); String json = getItemListForPageWrapper(request, + * CloudifyDataItem.DEPLOYMENT); postLogAudit(request); return json; } + */ /** * gets the tenants list * @@ -303,8 +272,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { preLogAudit(request); ECTransportModel result = null; try { - restClient = getCloudifyRestClient(request); - result = restClient.getBlueprint(id, tenant); + result = cloudifyClient.getBlueprint(id, tenant); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -314,7 +282,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Getting blueprint " + id + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getBlueprintById caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); @@ -338,39 +306,30 @@ public class CloudifyController extends DashboardRestrictedBaseController { * @throws Exception on serialization error * */ - @RequestMapping(value = { - VIEW_BLUEPRINTS_PATH + "/{id}" }, method = RequestMethod.GET, produces = "application/yaml") - @ResponseBody - public String viewBlueprintContentById(@PathVariable("id") String id, HttpServletRequest request) throws Exception { - preLogAudit(request); - ECTransportModel result = null; - try { - restClient = getCloudifyRestClient(request); - result = restClient.viewBlueprint(id); - } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Viewing blueprint " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "viewBlueprintContentById caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Viewing blueprint " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "viewBlueprintContentById caught exception"); - result = new RestResponseError("getBlueprintContentById failed", t); - } finally { - postLogAudit(request); - } - return objectMapper.writeValueAsString(result); - } - + /* + * @RequestMapping(value = { VIEW_BLUEPRINTS_PATH + "/{id}" }, method = + * RequestMethod.GET, produces = "application/yaml") + * + * @ResponseBody public String viewBlueprintContentById(@PathVariable("id") + * String id, HttpServletRequest request) throws Exception { + * preLogAudit(request); ECTransportModel result = null; try { result = + * cloudifyClient.viewBlueprint(id); } catch (HttpStatusCodeException e) { + * MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", + * "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); + * MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); + * MDC.put("ErrorDescription", "Viewing blueprint " + id + " failed!"); + * logger.error(EELFLoggerDelegate.errorLogger, + * "viewBlueprintContentById caught exception"); result = new + * RestResponseError(e.getResponseBodyAsString()); } catch (Throwable t) { + * MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", + * "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); + * MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); + * MDC.put("ErrorDescription", "Viewing blueprint " + id + " failed!"); + * logger.error(EELFLoggerDelegate.errorLogger, + * "viewBlueprintContentById caught exception"); result = new + * RestResponseError("getBlueprintContentById failed", t); } finally { + * postLogAudit(request); } return objectMapper.writeValueAsString(result); } + */ /** * Processes request to upload a blueprint from a remote server. * @@ -379,39 +338,30 @@ public class CloudifyController extends DashboardRestrictedBaseController { * @return Blueprint as uploaded; or error. * @throws Exception on serialization error */ - @RequestMapping(value = { BLUEPRINTS_PATH }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String uploadBlueprint(HttpServletRequest request, @RequestBody CloudifyBlueprintUpload blueprint) - throws Exception { - preLogAudit(request); - ECTransportModel result = null; - try { - CloudifyClient restClient = getCloudifyRestClient(request); - result = restClient.uploadBlueprint(blueprint); - } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Uploading blueprint failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "uploadBlueprint caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Uploading blueprint failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "uploadBlueprint caught exception"); - result = new RestResponseError("uploadBlueprint failed", t); - } finally { - postLogAudit(request); - } - return objectMapper.writeValueAsString(result); - } - + /* + * @RequestMapping(value = { BLUEPRINTS_PATH }, method = RequestMethod.POST, + * produces = "application/json") + * + * @ResponseBody public String uploadBlueprint(HttpServletRequest + * request, @RequestBody CloudifyBlueprintUpload blueprint) throws Exception { + * preLogAudit(request); ECTransportModel result = null; try { result = + * cloudifyClient.uploadBlueprint(blueprint); } catch (HttpStatusCodeException + * e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", + * "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); + * MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); + * MDC.put("ErrorDescription", "Uploading blueprint failed!"); + * logger.error(EELFLoggerDelegate.errorLogger, + * "uploadBlueprint caught exception"); result = new + * RestResponseError(e.getResponseBodyAsString()); } catch (Throwable t) { + * MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", + * "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); + * MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); + * MDC.put("ErrorDescription", "Uploading blueprint failed!"); + * logger.error(EELFLoggerDelegate.errorLogger, + * "uploadBlueprint caught exception"); result = new + * RestResponseError("uploadBlueprint failed", t); } finally { + * postLogAudit(request); } return objectMapper.writeValueAsString(result); } + */ /** * Deletes the specified blueprint. * @@ -421,43 +371,32 @@ public class CloudifyController extends DashboardRestrictedBaseController { * @return No content on success; error on failure. * @throws Exception On serialization failure */ - @RequestMapping(value = { BLUEPRINTS_PATH + "/{id}" }, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String deleteBlueprint(@PathVariable("id") String id, HttpServletRequest request, - HttpServletResponse response) throws Exception { - preLogAudit(request); - ECTransportModel result = null; - try { - CloudifyClient restClient = getCloudifyRestClient(request); - int code = restClient.deleteBlueprint(id); - response.setStatus(code); - } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting blueprint " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting blueprint " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); - result = new RestResponseError("deleteBlueprint failed on ID " + id, t); - } finally { - postLogAudit(request); - } - if (result == null) - return null; - else - return objectMapper.writeValueAsString(result); - } + /* + * @RequestMapping(value = { BLUEPRINTS_PATH + "/{id}" }, method = + * RequestMethod.DELETE, produces = "application/json") + * + * @ResponseBody public String deleteBlueprint(@PathVariable("id") String id, + * HttpServletRequest request, HttpServletResponse response) throws Exception { + * preLogAudit(request); ECTransportModel result = null; try { int code = + * cloudifyClient.deleteBlueprint(id); response.setStatus(code); } catch + * (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + * MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", + * "Cloudify Manager"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", + * "ERROR"); MDC.put("ErrorDescription", "Deleting blueprint " + id + + * " failed!"); logger.error(EELFLoggerDelegate.errorLogger, + * "deleteBlueprint caught exception"); result = new + * RestResponseError(e.getResponseBodyAsString()); } catch (Throwable t) { + * MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", + * "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); + * MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); + * MDC.put("ErrorDescription", "Deleting blueprint " + id + " failed!"); + * logger.error(EELFLoggerDelegate.errorLogger, + * "deleteBlueprint caught exception"); result = new + * RestResponseError("deleteBlueprint failed on ID " + id, t); } finally { + * postLogAudit(request); } if (result == null) return null; else return + * objectMapper.writeValueAsString(result); } + */ /** * Gets the specified deployment. * @@ -475,11 +414,10 @@ public class CloudifyController extends DashboardRestrictedBaseController { preLogAudit(request); ECTransportModel result = null; try { - CloudifyClient restClient = getCloudifyRestClient(request); if (tenant != null && tenant.length() > 0) { - result = restClient.getDeployment(id, tenant); + result = cloudifyClient.getDeployment(id, tenant); } else { - result = restClient.getDeployment(id); + result = cloudifyClient.getDeployment(id); } } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -490,7 +428,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Getting deployment " + id + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); @@ -515,9 +453,6 @@ public class CloudifyController extends DashboardRestrictedBaseController { public String getTenantStatusForService(HttpServletRequest request, @RequestBody String[] serviceList) throws Exception { preLogAudit(request); - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getId() == null) - throw new Exception("getControllerRestClient: Failed to get application user"); /* * 1) Get all the tenant names 2) Get the deployment IDs per tenant for all the * tenants, aggregate the deployments list 3) Get the input deployments list @@ -525,18 +460,17 @@ public class CloudifyController extends DashboardRestrictedBaseController { * the list from step#3, get the execution status info and generate the final * response */ - ECTransportModel result = null; - HashMap<String, Object> resultMap = new HashMap<String, Object>(); + String outboundJson = ""; + CloudifyDeployedTenantList cfyTenantDeployMapList = null; + new HashMap<String, Object>(); List<CloudifyDeployedTenant> tenantList = new ArrayList<CloudifyDeployedTenant>(); List<CloudifyExecution> cfyExecList = new ArrayList<CloudifyExecution>(); try { - CloudifyClient restClient = getCloudifyRestClient(request); - List<CloudifyTenant> cldfyTen = restClient.getTenants().items; + List<CloudifyTenant> cldfyTen = cloudifyClient.getTenants().items; for (CloudifyTenant ct : (List<CloudifyTenant>) cldfyTen) { - result = restClient.getTenantInfoFromDeploy(ct.name); - tenantList.addAll(((CloudifyDeployedTenantList) result).items); + cfyTenantDeployMapList = cloudifyClient.getTenantInfoFromDeploy(ct.name); + tenantList.addAll(((CloudifyDeployedTenantList) cfyTenantDeployMapList).items); } - result = null; List<CloudifyDeployedTenant> currSrvcTenants = new ArrayList<CloudifyDeployedTenant>(); for (String serviceId : serviceList) { @@ -551,27 +485,23 @@ public class CloudifyController extends DashboardRestrictedBaseController { boolean isHelmType = false; boolean helmStatus = false; for (CloudifyDeployedTenant deplItem : currSrvcTenants) { - CloudifyExecutionList execResults = restClient.getExecutionsSummary(deplItem.id, deplItem.tenant_name); + CloudifyExecutionList execResults = + cloudifyClient.getExecutionsSummary(deplItem.id, deplItem.tenant_name); isHelmType = false; helmStatus = false; - CloudifyBlueprintList bpList = restClient.getBlueprint(deplItem.id, deplItem.tenant_name); + CloudifyBlueprintList bpList = + cloudifyClient.getBlueprint(deplItem.id, deplItem.tenant_name); Map<String, Object> bpPlan = bpList.items.get(0).plan; Map<String, String> workflows = (Map<String, String>) bpPlan.get("workflows"); - Map<String, String> pluginInfo = ((List<Map<String, String>>) bpPlan - .get("deployment_plugins_to_install")).get(0); + Map<String, String> pluginInfo = + ((List<Map<String, String>>) bpPlan.get("deployment_plugins_to_install")) + .get(0); if (pluginInfo.get("name").equals("helm-plugin")) { isHelmType = true; } if (workflows.containsKey("status")) { helmStatus = true; } - /* - * for (CloudifyExecution cfyExec: execResults.items) { if - * (cfyExec.workflow_id.equalsIgnoreCase("create_deployment_environment")) { - * Map<String, String> pluginInfo = ((List<Map<String, - * String>>)cfyExec.parameters.get("deployment_plugins_to_install")).get(0); if - * (pluginInfo.get("name").equals("helm-plugin") ) { isHelmType = true; } } } - */ for (CloudifyExecution cfyExec : execResults.items) { if (cfyExec.workflow_id.equalsIgnoreCase("install")) { cfyExec.is_helm = isHelmType; @@ -580,6 +510,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { } } } + outboundJson = objectMapper.writeValueAsString(cfyExecList); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -587,8 +518,17 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Getting deployments failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getTenantStatusForService caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); + logger.error(EELFLoggerDelegate.errorLogger, + "getTenantStatusForService caught exception"); + RestResponseError result = null; + result = new RestResponseError( + "getTenantStatusForService failed" + e.getResponseBodyAsString()); + try { + outboundJson = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } } catch (Throwable t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -596,13 +536,21 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Getting deployments failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getTenantStatusForService caught exception"); - result = new RestResponseError("getTenantStatusForService failed", t); + logger.error(EELFLoggerDelegate.errorLogger, + "getTenantStatusForService caught exception"); + RestResponseError result = null; + result = new RestResponseError("getTenantStatusForService failed"); + try { + outboundJson = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } } finally { postLogAudit(request); } - return objectMapper.writeValueAsString(cfyExecList); + return outboundJson; } /** @@ -613,39 +561,30 @@ public class CloudifyController extends DashboardRestrictedBaseController { * @return Body of deployment; error on failure * @throws Exception On serialization failure */ - @RequestMapping(value = { DEPLOYMENTS_PATH }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String createDeployment(HttpServletRequest request, @RequestBody CloudifyDeploymentRequest deployment) - throws Exception { - preLogAudit(request); - ECTransportModel result = null; - try { - CloudifyClient restClient = getCloudifyRestClient(request); - result = restClient.createDeployment(deployment); - } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Creating deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "createDeployment caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Creating deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "createDeployment caught exception"); - result = new RestResponseError("createDeployment failed", t); - } finally { - postLogAudit(request); - } - return objectMapper.writeValueAsString(result); - } - + /* + * @RequestMapping(value = { DEPLOYMENTS_PATH }, method = RequestMethod.POST, + * produces = "application/json") + * + * @ResponseBody public String createDeployment(HttpServletRequest + * request, @RequestBody CloudifyDeploymentRequest deployment) throws Exception + * { preLogAudit(request); ECTransportModel result = null; try { result = + * cloudifyClient.createDeployment(deployment); } catch (HttpStatusCodeException + * e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", + * "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); + * MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); + * MDC.put("ErrorDescription", "Creating deployment failed!"); + * logger.error(EELFLoggerDelegate.errorLogger, + * "createDeployment caught exception"); result = new + * RestResponseError(e.getResponseBodyAsString()); } catch (Throwable t) { + * MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", + * "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); + * MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); + * MDC.put("ErrorDescription", "Creating deployment failed!"); + * logger.error(EELFLoggerDelegate.errorLogger, + * "createDeployment caught exception"); result = new + * RestResponseError("createDeployment failed", t); } finally { + * postLogAudit(request); } return objectMapper.writeValueAsString(result); } + */ /** * Deletes the specified deployment. * @@ -657,44 +596,35 @@ public class CloudifyController extends DashboardRestrictedBaseController { * @return Passes thru HTTP status code from remote endpoint; no body on success * @throws Exception on serialization failure */ - @RequestMapping(value = { - DEPLOYMENTS_PATH + "/{id}" }, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String deleteDeployment(@PathVariable("id") String id, - @RequestParam(value = "ignore_live_nodes", required = false) Boolean ignoreLiveNodes, - HttpServletRequest request, HttpServletResponse response) throws Exception { - preLogAudit(request); - ECTransportModel result = null; - try { - CloudifyClient restClient = getCloudifyRestClient(request); - int code = restClient.deleteDeployment(id, ignoreLiveNodes == null ? false : ignoreLiveNodes); - response.setStatus(code); - } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting deployment " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting deployment " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); - result = new RestResponseError("deleteDeployment failed on ID " + id, t); - } finally { - postLogAudit(request); - } - if (result == null) - return null; - else - return objectMapper.writeValueAsString(result); - } + /* + * @RequestMapping(value = { DEPLOYMENTS_PATH + "/{id}" }, method = + * RequestMethod.DELETE, produces = "application/json") + * + * @ResponseBody public String deleteDeployment(@PathVariable("id") String id, + * + * @RequestParam(value = "ignore_live_nodes", required = false) Boolean + * ignoreLiveNodes, HttpServletRequest request, HttpServletResponse response) + * throws Exception { preLogAudit(request); ECTransportModel result = null; try + * { int code = cloudifyClient.deleteDeployment(id, ignoreLiveNodes == null ? + * false : ignoreLiveNodes); response.setStatus(code); } catch + * (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + * MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", + * "Cloudify Manager"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", + * "ERROR"); MDC.put("ErrorDescription", "Deleting deployment " + id + + * " failed!"); logger.error(EELFLoggerDelegate.errorLogger, + * "deleteDeployment caught exception"); result = new + * RestResponseError(e.getResponseBodyAsString()); } catch (Throwable t) { + * MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", + * "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); + * MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", + * "Deleting deployment " + id + " failed!"); + * logger.error(EELFLoggerDelegate.errorLogger, + * "deleteDeployment caught exception"); result = new + * RestResponseError("deleteDeployment failed on ID " + id, t); } finally { + * postLogAudit(request); } if (result == null) return null; else return + * objectMapper.writeValueAsString(result); } + */ /** * Gets and serves one page of executions: * <OL> @@ -719,28 +649,26 @@ public class CloudifyController extends DashboardRestrictedBaseController { @RequestMapping(value = { EXECUTIONS_PATH }, method = RequestMethod.GET, produces = "application/json") @ResponseBody public String getExecutionsByPage(HttpServletRequest request, - @RequestParam(value = "deployment_id", required = false) String deployment_id, - @RequestParam(value = "status", required = false) String status, - @RequestParam(value = "tenant", required = false) String tenant) throws Exception { + @RequestParam(value = "deployment_id", required = false) String deployment_id, + @RequestParam(value = "status", required = false) String status, + @RequestParam(value = "tenant", required = true) String tenant) throws Exception { preLogAudit(request); ECTransportModel result = null; try { + if (tenant == null) { + throw new Exception("required tenant input missing"); + } List<CloudifyExecution> itemList = new ArrayList<CloudifyExecution>(); - CloudifyClient restClient = getCloudifyRestClient(request); List<String> depIds = new ArrayList<>(); if (deployment_id == null) { - CloudifyDeploymentList depList = restClient.getDeployments(); + CloudifyDeploymentList depList = cloudifyClient.getDeployments(); for (CloudifyDeployment cd : depList.items) depIds.add(cd.id); } else { depIds.add(deployment_id); } - String cloudPrimTenant = getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); - if (tenant == null) { - tenant = cloudPrimTenant; - } for (String depId : depIds) { - CloudifyExecutionList exeList = restClient.getExecutions(depId, tenant); + CloudifyExecutionList exeList = cloudifyClient.getExecutions(depId, tenant); itemList.addAll(exeList.items); } // Filter down to specified status as needed @@ -763,7 +691,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { if (totalItems > pageSize) itemList = getPageOfList(pageNum, pageSize, itemList); result = new RestResponsePage<>(totalItems, pageCount, itemList); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); @@ -798,12 +726,10 @@ public class CloudifyController extends DashboardRestrictedBaseController { preLogAudit(request); ECTransportModel result = null; try { - String cloudPrimTenant = getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); if (tenant == null) { - tenant = cloudPrimTenant; + throw new Exception("required tenant input missing"); } - CloudifyClient restClient = getCloudifyRestClient(request); - result = restClient.getExecutions(deployment_id, tenant); + result = cloudifyClient.getExecutions(deployment_id, tenant); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -814,7 +740,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { "Getting executions " + execution_id + " for deployment " + deployment_id + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); @@ -843,20 +769,19 @@ public class CloudifyController extends DashboardRestrictedBaseController { @SuppressWarnings("unchecked") @RequestMapping(value = { EVENTS_PATH }, method = RequestMethod.GET, produces = "application/json") @ResponseBody - public String getExecutionEventsById(@RequestParam(value = "execution_id", required = false) String execution_id, - @RequestParam(value = "logType", required = false) String isLogEvent, - @RequestParam(value = "tenant", required = false) String tenant, HttpServletRequest request) - throws Exception { + public String getExecutionEventsById( + @RequestParam(value = "execution_id", required = false) String execution_id, + @RequestParam(value = "logType", required = false) String isLogEvent, + @RequestParam(value = "tenant", required = true) String tenant, HttpServletRequest request) + throws Exception { preLogAudit(request); CloudifyEventList eventsList = null; ECTransportModel result = null; try { - String cloudPrimTenant = getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); if (tenant == null) { - tenant = cloudPrimTenant; + throw new Exception("required tenant input missing"); } - CloudifyClient restClient = getCloudifyRestClient(request); - eventsList = restClient.getEventlogs(execution_id, tenant); + eventsList = cloudifyClient.getEventlogs(execution_id, tenant); // Filter down to specified event type as needed List<CloudifyEvent> itemList = eventsList.items; if (!isLogEvent.isEmpty() && isLogEvent.equals("false")) { @@ -887,7 +812,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Getting executions " + execution_id + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getExecutionEventsById caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); @@ -903,124 +828,6 @@ public class CloudifyController extends DashboardRestrictedBaseController { } /** - * Gets the cloudify secret data for the specified secret name. - * - * - * @param secret_name Secret name (path variable) - * @param request HttpServletRequest - * @return CloudifySecret - * @throws Exception on serialization failure - */ - /* - * @RequestMapping(value = { SECRETS_PATH }, method = RequestMethod.GET, - * produces = "application/json") - * - * @ResponseBody public String getSecrets( - * - * @RequestParam(value = "tenant") String tenant, HttpServletRequest request) - * throws Exception { preLogAudit(request); ECTransportModel result = null; try - * { String cloudPrimTenant = - * getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); if - * (tenant == null) { tenant = cloudPrimTenant; } IControllerRestClient - * restClient = getControllerRestClient(); result = - * restClient.getSecrets(tenant); } catch (HttpStatusCodeException e) { - * MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", - * "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); - * MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - * MDC.put("ErrorDescription", "Getting secrets failed!"); - * logger.error(EELFLoggerDelegate.errorLogger, "getSecret caught exception"); - * result = new RestResponseError(e.getResponseBodyAsString()); } catch - * (Throwable t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - * MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", - * "Cloudify Manager"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", - * "ERROR"); MDC.put("ErrorDescription", "Getting secrets failed!"); - * logger.error(EELFLoggerDelegate.errorLogger, "getSecret caught exception"); - * result = new RestResponseError("getSecret failed", t); } finally { - * postLogAudit(request); } return objectMapper.writeValueAsString(result); } - * - * /** Gets the cloudify secret data for the specified secret name. - * - * - * @param secret_name Secret name (path variable) - * - * @param request HttpServletRequest - * - * @return CloudifySecret - * - * @throws Exception on serialization failure - */ - @RequestMapping(value = { - SECRETS_PATH + "/{secret_name}" }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getSecret(@PathVariable("secret_name") String secret_name, - @RequestParam(value = "tenant") String tenant, HttpServletRequest request) throws Exception { - preLogAudit(request); - ECTransportModel result = null; - try { - String cloudPrimTenant = getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); - if (tenant == null) { - tenant = cloudPrimTenant; - } - CloudifyClient restClient = getCloudifyRestClient(request); - result = restClient.getSecret(secret_name, tenant); - } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting secret for name " + secret_name + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getSecret caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting secret for name " + secret_name + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getSecret caught exception"); - result = new RestResponseError("getSecret failed", t); - } finally { - postLogAudit(request); - } - return objectMapper.writeValueAsString(result); - } - - /** - * Processes request to create secrets in cloudify manager. - * - * @param request HttpServletRequest - * @param execution Execution model - * @return Information about the execution - * @throws Exception on serialization failure - */ - /* - * @RequestMapping(value = { SECRETS_PATH }, method = RequestMethod.POST, - * produces = "application/json") - * - * @ResponseBody public String createSecret(HttpServletRequest - * request, @RequestBody CloudifySecretUpload secret) throws Exception { - * preLogAudit(request); ECTransportModel result = null; try { - * IControllerRestClient restClient = getControllerRestClient(request); result = - * restClient.createSecret(secret); } catch (HttpStatusCodeException e) { - * MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", - * "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); - * MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - * MDC.put("ErrorDescription", "Starting execution failed!"); - * logger.error(EELFLoggerDelegate.errorLogger, - * "startExecution caught exception"); result = new - * RestResponseError(e.getResponseBodyAsString()); } catch (Throwable t) { - * MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", - * "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); - * MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - * MDC.put("ErrorDescription", "Starting execution failed!"); - * logger.error(EELFLoggerDelegate.errorLogger, - * "startExecution caught exception"); result = new - * RestResponseError("startExecution failed", t); } finally { - * postLogAudit(request); } return objectMapper.writeValueAsString(result); } - */ - /** * Processes request to create an execution based on a deployment. * * @param request HttpServletRequest @@ -1035,12 +842,12 @@ public class CloudifyController extends DashboardRestrictedBaseController { preLogAudit(request); ECTransportModel result = null; try { - CloudifyClient restClient = getCloudifyRestClient(request); - if (!execution.workflow_id.equals("status") && !execution.getParameters().containsKey("node_instance_id")) { + if (!execution.workflow_id.equals("status") + && !execution.getParameters().containsKey("node_instance_id")) { // get the node instance ID for the deployment String nodeInstId = ""; - CloudifyNodeInstanceIdList nodeInstList = restClient.getNodeInstanceId(execution.getDeployment_id(), - execution.getTenant()); + CloudifyNodeInstanceIdList nodeInstList = cloudifyClient + .getNodeInstanceId(execution.getDeployment_id(), execution.getTenant()); if (nodeInstList != null) { nodeInstId = nodeInstList.items.get(0).id; } @@ -1048,7 +855,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { inParms.put("node_instance_id", nodeInstId); execution.setParameters(inParms); } - result = restClient.startExecution(execution); + result = cloudifyClient.startExecution(execution); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -1058,7 +865,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Starting execution failed!"); logger.error(EELFLoggerDelegate.errorLogger, "startExecution caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); @@ -1088,8 +895,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { preLogAudit(request); ECTransportModel result = null; try { - CloudifyClient restClient = getCloudifyRestClient(request); - result = restClient.updateDeployment(execution); + result = cloudifyClient.updateDeployment(execution); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -1099,7 +905,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Updating deployment failed!"); logger.error(EELFLoggerDelegate.errorLogger, "updateDeployment caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); @@ -1135,8 +941,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { List<String> tenant = null; try { tenant = headers.get("tenant"); - CloudifyClient restClient = getCloudifyRestClient(request); - result = restClient.cancelExecution(id, parameters, tenant.get(0)); + result = cloudifyClient.cancelExecution(id, parameters, tenant.get(0)); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -1146,7 +951,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Cancelling execution " + id + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); @@ -1183,8 +988,10 @@ public class CloudifyController extends DashboardRestrictedBaseController { preLogAudit(request); ECTransportModel result = null; try { - CloudifyClient restClient = getCloudifyRestClient(request); - result = restClient.getNodeInstanceId(deploymentId, nodeId, tenant); + if (tenant == null) { + throw new Exception("required tenant input missing"); + } + result = cloudifyClient.getNodeInstanceId(deploymentId, nodeId, tenant); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -1195,7 +1002,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { + nodeId + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getNodeInstanceId caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); @@ -1219,12 +1026,10 @@ public class CloudifyController extends DashboardRestrictedBaseController { preLogAudit(request); ECTransportModel result = null; try { - String cloudPrimTenant = getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); if (tenant == null) { - tenant = cloudPrimTenant; + throw new Exception("required tenant input missing"); } - CloudifyClient restClient = getCloudifyRestClient(request); - result = restClient.getNodeInstanceVersion(deploymentId, tenant); + result = cloudifyClient.getNodeInstanceVersion(deploymentId, tenant); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -1234,7 +1039,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CommonApiController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CommonApiController.java index efe2ab7..c50fcec 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CommonApiController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CommonApiController.java @@ -26,11 +26,9 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Date; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Scanner; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; @@ -77,7 +75,6 @@ import org.onap.ccsdk.dashboard.rest.CloudifyClient; import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; import org.onap.ccsdk.dashboard.rest.InventoryClient; import org.onap.ccsdk.dashboard.service.ControllerEndpointService; -import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; @@ -97,27 +94,31 @@ import org.springframework.web.client.HttpStatusCodeException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; @RestController @RequestMapping("/ecomp-api") public class CommonApiController extends DashboardRestrictedBaseController { - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DeploymentHandlerController.class); + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CommonApiController.class); private static final String COMPONENTS_PATH = "components"; private static final String DEPLOYMENTS_PATH = "deployments"; private static final String SERVICE_TYPES_PATH = "blueprints"; private static final String EXECUTIONS_PATH = "executions"; - private static final String API_HELP = "docs"; - private static final String DOCS_FILE_NAME = "ecompApiHelp.txt"; - private static final String DEP_IDS_FOR_TYPE = "deployments/typeIds"; private static final String DEP_TENANT_STATUS = "deployment-status"; private static final String TENANTS_PATH = "tenants"; @Autowired private ControllerEndpointService controllerEndpointService; + @Autowired + InventoryClient inventoryClient; + + @Autowired + DeploymentHandlerClient deploymentHandlerClient; + + @Autowired + CloudifyClient cloudifyClient; + /** * Enum for selecting an item type. */ @@ -160,8 +161,7 @@ public class CommonApiController extends DashboardRestrictedBaseController { @ResponseBody public String getTenants(HttpServletRequest request) throws Exception { preLogAudit(request); - CloudifyClient restClient = getCloudifyRestClient(); - List itemList = restClient.getTenants().items; + List itemList = cloudifyClient.getTenants().items; final int totalItems = itemList.size(); final int pageSize = 20; final int pageNum = 1; @@ -189,15 +189,14 @@ public class CommonApiController extends DashboardRestrictedBaseController { * the list from step#3, get the execution status info and generate the final * response */ + String outboundJson = ""; ECTransportModel result = null; - HashMap<String, Object> resultMap = new HashMap<String, Object>(); List<CloudifyDeployedTenant> tenantList = new ArrayList<CloudifyDeployedTenant>(); List<CloudifyExecution> cfyExecList = new ArrayList<CloudifyExecution>(); try { - CloudifyClient restClient = getCloudifyRestClient(); - List<CloudifyTenant> cldfyTen = restClient.getTenants().items; + List<CloudifyTenant> cldfyTen = cloudifyClient.getTenants().items; for (CloudifyTenant ct : (List<CloudifyTenant>) cldfyTen) { - result = restClient.getTenantInfoFromDeploy(ct.name); + result = cloudifyClient.getTenantInfoFromDeploy(ct.name); tenantList.addAll(((CloudifyDeployedTenantList) result).items); } result = null; @@ -213,13 +212,15 @@ public class CommonApiController extends DashboardRestrictedBaseController { } // Get concise execution status for each of the tenant deployment items for (CloudifyDeployedTenant deplItem : currSrvcTenants) { - CloudifyExecutionList execResults = restClient.getExecutionsSummary(deplItem.id, deplItem.tenant_name); + CloudifyExecutionList execResults = + cloudifyClient.getExecutionsSummary(deplItem.id, deplItem.tenant_name); for (CloudifyExecution cfyExec : execResults.items) { if (cfyExec.workflow_id.equalsIgnoreCase("install")) { cfyExecList.add(cfyExec); } } } + outboundJson = objectMapper.writeValueAsString(cfyExecList); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -229,7 +230,13 @@ public class CommonApiController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Getting deployments failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getTenantStatusForService caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { + try { + outboundJson = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); @@ -238,11 +245,17 @@ public class CommonApiController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Getting deployments failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getTenantStatusForService caught exception"); result = new RestResponseError("getTenantStatusForService failed", t); + try { + outboundJson = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } } finally { postLogAudit(request); } - return objectMapper.writeValueAsString(cfyExecList); + return outboundJson; } @RequestMapping(value = { SERVICE_TYPES_PATH }, method = RequestMethod.POST, produces = "application/json") @@ -251,7 +264,7 @@ public class CommonApiController extends DashboardRestrictedBaseController { String json = null; try { Blueprint.parse(serviceTypeUplReq.getBlueprintTemplate()); - InventoryClient inventoryClient = getInventoryClient(); + // InventoryClient inventoryClient = getInventoryClient(); Collection<String> serviceIds = new ArrayList<String>(); Collection<String> vnfTypes = new ArrayList<String>(); Collection<String> serviceLocations = new ArrayList<String>(); @@ -397,47 +410,46 @@ public class CommonApiController extends DashboardRestrictedBaseController { @SuppressWarnings({ "rawtypes", "unchecked" }) private String getItemListForPage(InventoryDataItem option, int pageNum, int pageSize, String searchBy, String filters) throws Exception { - - InventoryClient inventoryClient = getInventoryClient(); String outboundJson = ""; List itemList = null; switch (option) { - case SERVICES: - itemList = inventoryClient.getServices().collect(Collectors.toList()); - if (searchBy != null) { - itemList = (List) itemList.stream().filter(s -> ((Service) s).contains(searchBy)) - .collect(Collectors.toList()); - } - // Get the tenant names for all the deployments from Cloudify/API handler - ECTransportModel result = null; - List<CloudifyDeployedTenant> tenantList = new ArrayList<CloudifyDeployedTenant>(); - try { - CloudifyClient restClient = getCloudifyRestClient(); - List<CloudifyTenant> cldfyTen = restClient.getTenants().items; - for (CloudifyTenant ct : (List<CloudifyTenant>) cldfyTen) { - result = restClient.getTenantInfoFromDeploy(ct.name); - tenantList.addAll(((CloudifyDeployedTenantList) result).items); + case SERVICES: + itemList = inventoryClient.getServices().collect(Collectors.toList()); + if (searchBy != null) { + itemList = (List) itemList.stream() + .filter(s -> ((Service) s).contains(searchBy)).collect(Collectors.toList()); } - } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting deployments failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getTenantInfoFromDeploy caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting deployments failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); - result = new RestResponseError("getTenantInfoFromDeploy failed", t); - } finally { + // Get the tenant names for all the deployments from Cloudify/API handler + ECTransportModel result = null; + List<CloudifyDeployedTenant> tenantList = new ArrayList<CloudifyDeployedTenant>(); + try { + List<CloudifyTenant> cldfyTen = cloudifyClient.getTenants().items; + for (CloudifyTenant ct : (List<CloudifyTenant>) cldfyTen) { + result = cloudifyClient.getTenantInfoFromDeploy(ct.name); + tenantList.addAll(((CloudifyDeployedTenantList) result).items); + } + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting deployments failed!"); + logger.error(EELFLoggerDelegate.errorLogger, + "getTenantInfoFromDeploy caught exception"); + //result = new RestResponseError(e.getResponseBodyAsString()); + } catch (Throwable t) { + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Cloudify Manager"); + MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting deployments failed!"); + logger.error(EELFLoggerDelegate.errorLogger, + "getDeploymentById caught exception"); + //result = new RestResponseError("getTenantInfoFromDeploy failed", t); + } finally { } @@ -471,7 +483,9 @@ public class CommonApiController extends DashboardRestrictedBaseController { bpOut.setTypeName(bp.getTypeName()); break; case "typeId": + if (bp.getTypeId().isPresent()) { bpOut.setTypeId(bp.getTypeId().get()); + } break; case "typeVersion": bpOut.setTypeVersion(bp.getTypeVersion()); @@ -512,7 +526,7 @@ public class CommonApiController extends DashboardRestrictedBaseController { @SuppressWarnings({ "rawtypes", "unchecked" }) private String getBlueprintTypeId(String searchBy, Optional<Integer> version, String typeId) throws Exception { - InventoryClient inventoryClient = getInventoryClient(); + // InventoryClient inventoryClient = getInventoryClient(); ServiceTypeQueryParams serviceQueryParams = null; if (version.isPresent()) { @@ -551,12 +565,10 @@ public class CommonApiController extends DashboardRestrictedBaseController { preLogAudit(request); ECTransportModel result = null; try { - String cloudPrimTenant = getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); if (tenant == null) { - tenant = cloudPrimTenant; + throw new Exception("tenant name is missing"); } - CloudifyClient restClient = getCloudifyRestClient(); - result = restClient.getNodeInstanceVersion(deploymentId, tenant); + result = cloudifyClient.getNodeInstanceVersion(deploymentId, tenant); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -593,16 +605,15 @@ public class CommonApiController extends DashboardRestrictedBaseController { @RequestMapping(value = { DEPLOYMENTS_PATH + "/{deploymentId}/inputs" }, method = RequestMethod.GET, produces = "application/json") public String getDeploymentInputs(@PathVariable("deploymentId") String deploymentId, - @RequestParam(value = "tenant") String tenant, HttpServletRequest request) throws Exception { + @RequestParam(value = "tenant", required = true) String tenant, HttpServletRequest request) + throws Exception { preLogAudit(request); ECTransportModel result = null; try { - String cloudPrimTenant = getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); if (tenant == null) { - tenant = cloudPrimTenant; + throw new Exception("tenant name is missing"); } - CloudifyClient restClient = getCloudifyRestClient(); - result = restClient.getDeploymentInputs(deploymentId, tenant); + result = cloudifyClient.getDeploymentInputs(deploymentId, tenant); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -642,7 +653,6 @@ public class CommonApiController extends DashboardRestrictedBaseController { preLogAudit(request); ECTransportModel result = null; try { - CloudifyClient restClient = getCloudifyRestClient(); String nodeInstId = ""; Map<String, Object> parameters = objectMapper.readValue(upgParams, new TypeReference<Map<String, Object>>() { @@ -652,14 +662,15 @@ public class CommonApiController extends DashboardRestrictedBaseController { parameters.remove("tenant"); parameters.remove("workflow"); // get the node instance ID for the deployment - CloudifyNodeInstanceIdList nodeInstList = restClient.getNodeInstanceId(deploymentId, tenant); + CloudifyNodeInstanceIdList nodeInstList = + cloudifyClient.getNodeInstanceId(deploymentId, tenant); if (nodeInstList != null) { nodeInstId = nodeInstList.items.get(0).id; } parameters.put("node_instance_id", nodeInstId); - CloudifyExecutionRequest execution = new CloudifyExecutionRequest(deploymentId, workflow, false, false, - tenant, parameters); - result = restClient.startExecution(execution); + CloudifyExecutionRequest execution = new CloudifyExecutionRequest(deploymentId, + workflow, false, false, tenant, parameters); + result = cloudifyClient.startExecution(execution); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -690,7 +701,7 @@ public class CommonApiController extends DashboardRestrictedBaseController { throws Exception { preLogAudit(request); List<ServiceTypeServiceMap> result = new ArrayList<ServiceTypeServiceMap>(); - InventoryClient inventoryClient = getInventoryClient(); + // InventoryClient inventoryClient = getInventoryClient(); ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); ServiceTypeServiceMap srvcMap = new ServiceTypeServiceMap(typeId, srvcRefs); @@ -747,11 +758,9 @@ public class CommonApiController extends DashboardRestrictedBaseController { postLogAudit(request); } } - DeploymentHandlerClient deploymentHandlerClient = null; try { - deploymentHandlerClient = getDeploymentHandlerClient(); - DeploymentResponse resp = deploymentHandlerClient.putDeployment(depName, - deploymentRequestObject.getTenant(), + DeploymentResponse resp = + deploymentHandlerClient.putDeployment(depName, deploymentRequestObject.getTenant(), new DeploymentRequest(srvcTypeId, deploymentRequestObject.getInputs())); DeploymentResponseLinks deplLinks = resp.getLinks(); String deplStatus = deplLinks.getStatus(); @@ -800,16 +809,6 @@ public class CommonApiController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Deployment failed!"); logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Deployment Handler"); - MDC.put("TargetServiceName", "Deployment Handler"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); - json = "{ \"error\" : \"" + jpe.toString() + "\"}"; } catch (Throwable t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Deployment Handler"); @@ -863,12 +862,10 @@ public class CommonApiController extends DashboardRestrictedBaseController { } finally { postLogAudit(request); } - DeploymentHandlerClient deploymentHandlerClient = null; try { - deploymentHandlerClient = getDeploymentHandlerClient(); - json = objectMapper.writeValueAsString( - deploymentHandlerClient.updateDeployment(deploymentId, deploymentRequestObject.getTenant(), - new DeploymentRequest(srvcTypeId, deploymentRequestObject.getInputs()))); + json = objectMapper.writeValueAsString(deploymentHandlerClient.updateDeployment( + deploymentId, deploymentRequestObject.getTenant(), + new DeploymentRequest(srvcTypeId, deploymentRequestObject.getInputs()))); } catch (BadRequestException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Deployment Handler"); @@ -948,12 +945,10 @@ public class CommonApiController extends DashboardRestrictedBaseController { preLogAudit(request); ECTransportModel result = null; try { - String cloudPrimTenant = getAppProperties().getProperty(DashboardProperties.CLOUDIFY_TENANT_PRIM); if (tenant == null) { - tenant = cloudPrimTenant; + throw new Exception("tenant name is missing"); } - CloudifyClient restClient = getCloudifyRestClient(); - result = restClient.getExecutionsSummary(deploymentId, tenant); + result = cloudifyClient.getExecutionsSummary(deploymentId, tenant); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -995,7 +990,7 @@ public class CommonApiController extends DashboardRestrictedBaseController { preLogAudit(request); String json = "{\"202\": \"OK\"}"; try { - InventoryClient inventoryClient = getInventoryClient(); + // InventoryClient inventoryClient = getInventoryClient(); ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); if (srvcRefs != null && srvcRefs.totalCount > 0) { @@ -1045,15 +1040,20 @@ public class CommonApiController extends DashboardRestrictedBaseController { * @return * @throws Exception */ - @RequestMapping(value = { - DEPLOYMENTS_PATH + "/{deploymentId}" }, method = RequestMethod.DELETE, produces = "application/json") - public String deleteDeployment(@PathVariable("deploymentId") String deploymentId, HttpServletRequest request, - @RequestParam("tenant") String tenant, HttpServletResponse response) throws Exception { + @RequestMapping( + value = {DEPLOYMENTS_PATH + "/{deploymentId}"}, + method = RequestMethod.DELETE, + produces = "application/json") + public String deleteDeployment(@PathVariable("deploymentId") String deploymentId, + HttpServletRequest request, @RequestParam(value = "tenant", required = true) String tenant, + HttpServletResponse response) throws Exception { preLogAudit(request); String json = null; StringBuffer status = new StringBuffer(); try { - DeploymentHandlerClient deploymentHandlerClient = getDeploymentHandlerClient(); + if (tenant == null) { + throw new Exception("tenant name is missing"); + } deploymentHandlerClient.deleteDeployment(deploymentId, tenant); String self = request.getRequestURL().toString().split("\\?")[0]; status.append(self).append("/executions?tenant=").append(tenant); @@ -1097,16 +1097,6 @@ public class CommonApiController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Deployment Handler"); - MDC.put("TargetServiceName", "Deployment Handler"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); - json = "{ \"error\" : \"" + jpe.toString() + "\"}"; } catch (Throwable t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Deployment Handler"); @@ -1143,8 +1133,7 @@ public class CommonApiController extends DashboardRestrictedBaseController { List<String> tenant = null; try { tenant = headers.get("tenant"); - CloudifyClient restClient = getCloudifyRestClient(); - result = restClient.cancelExecution(id, parameters, tenant.get(0)); + result = cloudifyClient.cancelExecution(id, parameters, tenant.get(0)); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -1177,8 +1166,6 @@ public class CommonApiController extends DashboardRestrictedBaseController { MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); - // logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, - // APP_NAME); } private void postLogAudit(HttpServletRequest request) { @@ -1188,7 +1175,7 @@ public class CommonApiController extends DashboardRestrictedBaseController { MDC.put("TargetServiceName", "Deployment Handler"); MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(end)); MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, logDateFormat.format(end)); - MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); + //MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI()); } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ConsulController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ConsulController.java index feb8dc5..28f7520 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ConsulController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ConsulController.java @@ -21,7 +21,6 @@ *******************************************************************************/ package org.onap.ccsdk.dashboard.controller; -import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -45,6 +44,7 @@ import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.web.support.UserUtils; import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -67,6 +67,9 @@ public class ConsulController extends DashboardRestrictedBaseController { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulController.class); + @Autowired + ConsulClient consulClient; + /** * Enum for selecting an item type. */ @@ -118,28 +121,28 @@ public class ConsulController extends DashboardRestrictedBaseController { * @return JSON block as String, see above. * @throws Exception On any error; e.g., Network failure. */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - private String getItemListForPage(long userId, ConsulDataItem option, int pageNum, int pageSize, String dc) - throws Exception { - ConsulClient restClient = getConsulRestClient(userId); + @SuppressWarnings({"unchecked", "rawtypes"}) + private String getItemListForPage(long userId, ConsulDataItem option, int pageNum, int pageSize, + String dc) throws Exception { List itemList = null; switch (option) { - case NODES: - itemList = restClient.getNodes(dc); - Collections.sort(itemList, nodeHealthComparator); - break; - case DATACENTERS: - itemList = restClient.getDatacenters(); - break; - default: - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Consul"); - MDC.put("TargetServiceName", "Consul"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting page of items failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPage caught exception"); - throw new Exception("getItemListForPage failed: unimplemented case: " + option.name()); + case NODES: + itemList = consulClient.getNodes(dc); + Collections.sort(itemList, nodeHealthComparator); + break; + case DATACENTERS: + itemList = consulClient.getDatacenters(); + break; + default: + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "Consul"); + MDC.put("TargetServiceName", "Consul"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting page of items failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPage caught exception"); + throw new Exception( + "getItemListForPage failed: unimplemented case: " + option.name()); } final int totalItems = itemList.size(); // Shrink if needed @@ -204,9 +207,8 @@ public class ConsulController extends DashboardRestrictedBaseController { preLogAudit(request); Object result = null; try { - ConsulClient restClient = getConsulRestClient(request); - result = restClient.getServiceHealth(dc, serviceId); - } catch (Throwable t) { + result = consulClient.getServiceHealth(dc, serviceId); + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Consul"); MDC.put("TargetServiceName", "Consul"); @@ -240,10 +242,9 @@ public class ConsulController extends DashboardRestrictedBaseController { ECTransportModel result = null; try { List<ConsulServiceHealth> itemList = new ArrayList<>(); - ConsulClient restClient = getConsulRestClient(request); - List<ConsulServiceInfo> svcInfoList = restClient.getServices(dc); + List<ConsulServiceInfo> svcInfoList = consulClient.getServices(dc); for (ConsulServiceInfo csi : svcInfoList) { - List<ConsulServiceHealth> csh = restClient.getServiceHealth(dc, csi.name); + List<ConsulServiceHealth> csh = consulClient.getServiceHealth(dc, csi.name); itemList.addAll(csh); } Collections.sort(itemList, serviceHealthComparator); @@ -256,7 +257,7 @@ public class ConsulController extends DashboardRestrictedBaseController { if (totalItems > pageSize) itemList = getPageOfList(pageNum, pageSize, itemList); result = new RestResponsePage<>(totalItems, pageCount, itemList); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Consul"); MDC.put("TargetServiceName", "Consul"); @@ -301,9 +302,8 @@ public class ConsulController extends DashboardRestrictedBaseController { preLogAudit(request); Object result = null; try { - ConsulClient restClient = getConsulRestClient(request); - result = restClient.getNodeServicesHealth(dc, nodeName); - } catch (Throwable t) { + result = consulClient.getNodeServicesHealth(dc, nodeName); + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Consul"); MDC.put("TargetServiceName", "Consul"); @@ -365,8 +365,7 @@ public class ConsulController extends DashboardRestrictedBaseController { throw new Exception("Required fields : [endpoint, interval] in checks"); } } - ConsulClient restClient = getConsulRestClient(request); - result = new RestResponseSuccess(restClient.registerService(registration)); + result = new RestResponseSuccess(consulClient.registerService(registration)); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Consul"); @@ -376,7 +375,7 @@ public class ConsulController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Registering service failed!"); logger.error(EELFLoggerDelegate.errorLogger, "registerService caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Consul"); MDC.put("TargetServiceName", "Consul"); @@ -406,9 +405,9 @@ public class ConsulController extends DashboardRestrictedBaseController { preLogAudit(request); ECTransportModel result = null; try { - ConsulClient restClient = getConsulRestClient(request); - int code = restClient.deregisterService(serviceName); - result = new RestResponseSuccess("Deregistration yielded code " + Integer.toString(code)); + int code = consulClient.deregisterService(serviceName); + result = + new RestResponseSuccess("Deregistration yielded code " + Integer.toString(code)); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Consul"); diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardHomeController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardHomeController.java index c5a624e..2b50b5b 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardHomeController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardHomeController.java @@ -2,22 +2,22 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 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. + * 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========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ package org.onap.ccsdk.dashboard.controller; @@ -31,19 +31,14 @@ import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; -import org.onap.ccsdk.dashboard.domain.ControllerEndpoint; import org.onap.ccsdk.dashboard.domain.EcdComponent; -import org.onap.ccsdk.dashboard.model.ControllerEndpointCredentials; -import org.onap.ccsdk.dashboard.model.ControllerEndpointTransport; -import org.onap.ccsdk.dashboard.model.ControllerOpsTools; import org.onap.ccsdk.dashboard.model.EcdAppComponent; import org.onap.ccsdk.dashboard.model.RestResponseError; import org.onap.ccsdk.dashboard.model.RestResponseSuccess; import org.onap.ccsdk.dashboard.service.ControllerEndpointService; -import org.onap.portalsdk.core.domain.User; +import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.portalsdk.core.web.support.UserUtils; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @@ -75,10 +70,8 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { private final ObjectMapper mapper; private static Date begin, end; - private static final String CONTROLLERS_PATH = "controllers"; private static final String COMPONENTS_PATH = "components"; private static final String USER_APPS_PATH = "user-apps"; - private static final String OPS_PATH = "ops"; private static final String APP_LABEL = "app-label"; /** @@ -94,7 +87,7 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { * @return View name key, which is resolved to a file using an Apache tiles * "definitions.xml" file. */ - @RequestMapping(value = { "/ecd" }, method = RequestMethod.GET) + @RequestMapping(value = {"/ecd"}, method = RequestMethod.GET) public ModelAndView dbcDefaultController() { // a model is only useful for JSP; this app is angular. return new ModelAndView("ecd_home_tdkey"); @@ -106,13 +99,17 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { * @param request HttpServletRequest * @return List of component name strings, or an error on failure */ - @RequestMapping(value = { COMPONENTS_PATH }, method = RequestMethod.GET, produces = "application/json") + @RequestMapping( + value = {COMPONENTS_PATH}, + method = RequestMethod.GET, + produces = "application/json") @ResponseBody public String getComponents(HttpServletRequest request) { preLogAudit(request); - String outboundJson = ""; // "['MSO','CLAMP','APPC','ECOMPSCHEDULER','POLICY']"; + String outboundJson = ""; try { HttpSession session = request.getSession(true); + @SuppressWarnings("unchecked") Set<String> userApps = (Set<String>) session.getAttribute("authComponents"); if (userApps == null) { userApps = new TreeSet<String>(); @@ -122,19 +119,21 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { List<EcdComponent> dbResult = controllerEndpointService.getComponents(); - List dcaeCompList = (List) dbResult.stream().filter(s -> ((EcdComponent) s).contains("dcae")) - .collect(Collectors.toList()); + List dcaeCompList = (List) dbResult.stream() + .filter(s -> ((EcdComponent) s).contains("dcae")).collect(Collectors.toList()); if (!userApps.isEmpty()) { // non-admin role level for (String userRole : userApps) { if (userRole.equalsIgnoreCase("dcae")) { if (dcaeCompList != null && !dcaeCompList.isEmpty()) { - EcdAppComponent dcaeAppComponent = new EcdAppComponent("DCAE", dcaeCompList); + EcdAppComponent dcaeAppComponent = + new EcdAppComponent("DCAE", dcaeCompList); ecdApps.add(dcaeAppComponent); } } else { - List tmpItemList = (List) dbResult.stream().filter(s -> ((EcdComponent) s).contains(userRole)) - .collect(Collectors.toList()); + List tmpItemList = (List) dbResult.stream() + .filter(s -> ((EcdComponent) s).contains(userRole)) + .collect(Collectors.toList()); if (tmpItemList != null) { logger.debug(">>>> adding filtered items"); filterList.addAll(tmpItemList); @@ -177,11 +176,11 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { * Get the application label - name + environment * */ - @RequestMapping(value = { APP_LABEL }, method = RequestMethod.GET, produces = "application/json") + @RequestMapping(value = {APP_LABEL}, method = RequestMethod.GET, produces = "application/json") @ResponseBody public String getAppLabel(HttpServletRequest request) throws Exception { - return mapper.writeValueAsString(appProperties.getPropertyDef(appProperties.CONTROLLER_IN_ENV, "NA")); - // return mapper.writeValueAsString(systemProperties.getAppDisplayName()); + return mapper.writeValueAsString( + DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_IN_ENV, "NA")); } /** @@ -191,11 +190,14 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { * @return List of component name strings, or an error on failure */ @SuppressWarnings("unchecked") - @RequestMapping(value = { USER_APPS_PATH }, method = RequestMethod.GET, produces = "application/json") + @RequestMapping( + value = {USER_APPS_PATH}, + method = RequestMethod.GET, + produces = "application/json") @ResponseBody public String getUserApps(HttpServletRequest request) { preLogAudit(request); - String outboundJson = ""; // "['MSO','CLAMP','APPC','ECOMPSCHEDULER','POLICY']"; + String outboundJson = ""; try { HttpSession session = request.getSession(true); Set<String> userApps = (Set<String>) session.getAttribute("authComponents"); @@ -222,146 +224,23 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { /** * Sets the controller endpoint selection for the user. * - * @param request HttpServletRequest - * @param endpoint Body with endpoint details - * @return Result indicating success or failure - * @throws Exception if application user is not found - */ - @RequestMapping(value = { COMPONENTS_PATH }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String insertComponent(HttpServletRequest request, @RequestBody EcdComponent newComponent) throws Exception { - preLogAudit(request); - String outboundJson = null; - controllerEndpointService.insertComponent(newComponent); - RestResponseSuccess success = new RestResponseSuccess( - "Inserted new component with name " + newComponent.getCname()); - outboundJson = mapper.writeValueAsString(success); - postLogAudit(request); - return outboundJson; - } - - /** - * Gets the OPS Tools URLs from dashboard properties - * - * @param request HttpServletRequest - * @return List of ControllerOpsTools objects, or an error on failure - * @throws Exception - */ - @RequestMapping(value = { OPS_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getOpsToolUrls(HttpServletRequest request) { - preLogAudit(request); - String outboundJson = null; - try { - List<ControllerOpsTools> opsList = getControllerOpsTools(); - outboundJson = mapper.writeValueAsString(opsList); - } catch (Exception ex) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DashboardHomeController"); - MDC.put("TargetServiceName", "DashboardHomeController"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Get Ops Tools URLs failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "Failed to get Ops Tools URL list"); - RestResponseError response = new RestResponseError("Failed to get Ops Tools URL list", ex); - outboundJson = response.toJson(); - } finally { - postLogAudit(request); - } - return outboundJson; - } - - // get sites - // get cfy, cnsl URLs - // get cfy tenants - // get cfy secret value for k8s ip per tenant - // construct models TenantOpsCluster, SiteOpsToolLinks - // return final model - /** - * Gets the available controller endpoints. - * * @param request HttpServletRequest - * @return List of ControllerEndpointTransport objects, or an error on failure - * @throws Exception if application user is not found - */ - @RequestMapping(value = { CONTROLLERS_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getControllers(HttpServletRequest request) { - preLogAudit(request); - String outboundJson = null; - // Static data - ControllerEndpointCredentials[] configured = getControllerEndpoints(); - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DashboardHomeController"); - MDC.put("TargetServiceName", "DashboardHomeController"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Get controllers failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "Failed to get application user"); - throw new Exception("getControllers: Failed to get application user"); - } - ControllerEndpointCredentials selectedInDb = getOrSetControllerEndpointSelection(appUser.getId()); - // Built result from properties - ArrayList<ControllerEndpointTransport> list = new ArrayList<>(); - for (ControllerEndpointCredentials ctrl : configured) { - // Check if this is the selected endpoint in DB - boolean selected = (selectedInDb != null && selectedInDb.getUrl() != null - && selectedInDb.getUrl().equals(ctrl.getUrl())); - // Result has no privileged information - ControllerEndpointTransport transport = new ControllerEndpointTransport(selected, ctrl.getName(), - ctrl.getUrl(), ctrl.getInventoryUrl(), ctrl.getDhandlerUrl(), ctrl.getConsulUrl()); - list.add(transport); - } - outboundJson = mapper.writeValueAsString(list); - } catch (Exception ex) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DashboardHomeController"); - MDC.put("TargetServiceName", "DashboardHomeController"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Get controllers failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "Failed to get controller endpoint list"); - RestResponseError response = new RestResponseError("Failed to get controller endpoint list", ex); - outboundJson = response.toJson(); - } finally { - postLogAudit(request); - } - return outboundJson; - } - - /** - * Sets the controller endpoint selection for the user. - * - * @param request HttpServletRequest * @param endpoint Body with endpoint details * @return Result indicating success or failure * @throws Exception if application user is not found */ - @RequestMapping(value = { CONTROLLERS_PATH }, method = RequestMethod.POST, produces = "application/json") + @RequestMapping( + value = {COMPONENTS_PATH}, + method = RequestMethod.POST, + produces = "application/json") @ResponseBody - public String setControllerSelection(HttpServletRequest request, @RequestBody ControllerEndpointTransport endpoint) - throws Exception { + public String insertComponent(HttpServletRequest request, + @RequestBody EcdComponent newComponent) throws Exception { preLogAudit(request); String outboundJson = null; - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DashboardHomeController"); - MDC.put("TargetServiceName", "DashboardHomeController"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Set controllers failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "Failed to get application user"); - postLogAudit(request); - throw new Exception("setControllerSelection: Failed to get application user"); - } - ControllerEndpoint dbEntry = new ControllerEndpoint(appUser.getId(), endpoint.getName(), endpoint.getUrl(), - endpoint.getInventoryUrl(), endpoint.getDhandlerUrl()); - controllerEndpointService.updateControllerEndpointSelection(dbEntry); - RestResponseSuccess success = new RestResponseSuccess("Updated selection to " + endpoint.getName()); + controllerEndpointService.insertComponent(newComponent); + RestResponseSuccess success = + new RestResponseSuccess("Inserted new component with name " + newComponent.getCname()); outboundJson = mapper.writeValueAsString(success); postLogAudit(request); return outboundJson; @@ -372,7 +251,6 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); - // logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); } public void postLogAudit(HttpServletRequest request) { @@ -384,6 +262,7 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, logDateFormat.format(end)); MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI()); + logger.info(EELFLoggerDelegate.metricsLogger, + request.getMethod() + request.getRequestURI()); } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardRestrictedBaseController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardRestrictedBaseController.java index 441b529..f3b6147 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardRestrictedBaseController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardRestrictedBaseController.java @@ -23,30 +23,13 @@ package org.onap.ccsdk.dashboard.controller; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; -import org.onap.ccsdk.dashboard.domain.ControllerEndpoint; -import org.onap.ccsdk.dashboard.model.ControllerEndpointCredentials; -import org.onap.ccsdk.dashboard.model.ControllerOpsTools; -import org.onap.ccsdk.dashboard.rest.CloudifyClient; -import org.onap.ccsdk.dashboard.rest.CloudifyMockClientImpl; -import org.onap.ccsdk.dashboard.rest.CloudifyRestClientImpl; -import org.onap.ccsdk.dashboard.rest.ConsulClient; -import org.onap.ccsdk.dashboard.rest.ConsulMockClientImpl; -import org.onap.ccsdk.dashboard.rest.ConsulRestClientImpl; -import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; -import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClientImpl; -import org.onap.ccsdk.dashboard.rest.InventoryClient; -import org.onap.ccsdk.dashboard.rest.RestInventoryClientImpl; -import org.onap.ccsdk.dashboard.rest.RestInventoryClientMockImpl; import org.onap.ccsdk.dashboard.service.ControllerEndpointService; import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.domain.User; -import org.onap.portalsdk.core.web.support.UserUtils; import org.springframework.beans.factory.annotation.Autowired; import com.fasterxml.jackson.annotation.JsonInclude; @@ -164,306 +147,4 @@ public class DashboardRestrictedBaseController extends RestrictedBaseController int toIndex = firstIndexOnNextPage < itemList.size() ? firstIndexOnNextPage : itemList.size(); return itemList.subList(fromIndex, toIndex); } - - /** - * Gets all configured controllers from properties. - * - * @return Array of ControllerEndpointRestricted objects - * @throws IllegalStateException if a required property is not found - */ - protected ControllerEndpointCredentials[] getControllerEndpoints() { - final String[] controllerKeys = DashboardProperties.getCsvListProperty(DashboardProperties.CONTROLLER_KEY_LIST); - ControllerEndpointCredentials[] controllers = new ControllerEndpointCredentials[controllerKeys.length]; - for (int i = 0; i < controllerKeys.length; ++i) { - String key = controllerKeys[i]; - final String name = DashboardProperties.getControllerProperty(key, - DashboardProperties.CONTROLLER_SUBKEY_NAME); - final String url = DashboardProperties.getControllerProperty(key, - DashboardProperties.CONTROLLER_SUBKEY_URL); - final String inventoryUrl = DashboardProperties.getControllerProperty(key, - DashboardProperties.CONTROLLER_SUBKEY_INVENTORY_URL); - final String dhandlerUrl = DashboardProperties.getControllerProperty(key, - DashboardProperties.CONTROLLER_SUBKEY_DHANDLER_URL); - final String consulUrl = DashboardProperties.getControllerProperty(key, - DashboardProperties.CONTROLLER_SUBKEY_CONSUL_URL); - final String user = DashboardProperties.getControllerProperty(key, - DashboardProperties.CONTROLLER_SUBKEY_USERNAME); - final String pass = DashboardProperties.getControllerProperty(key, - DashboardProperties.CONTROLLER_SUBKEY_PASS); - final boolean encr = Boolean.parseBoolean( - DashboardProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_ENCRYPTED)); - controllers[i] = new ControllerEndpointCredentials(false, name, url, inventoryUrl, dhandlerUrl, consulUrl, - user, pass, encr); - } - return controllers; - } - - /** - * Get the list of configured OPS Tools URLs from dashboard properties - * - * @return Array of ControllerOpsTools objects - * @throws IllegalStateException if a required property is not found - */ - protected List<ControllerOpsTools> getControllerOpsTools() { - List<ControllerOpsTools> opsList = new ArrayList<>(); - final String[] controllerKeys = DashboardProperties.getCsvListProperty(DashboardProperties.CONTROLLER_KEY_LIST); - String key = controllerKeys[0]; - final String cfyId = DashboardProperties.OPS_CLOUDIFY_URL.split("\\.")[1]; - final String cfyUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_CLOUDIFY_URL); - final String k8Id = DashboardProperties.OPS_K8S_URL.split("\\.")[1]; - final String k8Url = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_K8S_URL); - final String grfId = DashboardProperties.OPS_GRAFANA_URL.split("\\.")[1]; - final String grfUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_GRAFANA_URL); - final String cnslId = DashboardProperties.OPS_CONSUL_URL.split("\\.")[1]; - final String cnslUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_CONSUL_URL); - final String promId = DashboardProperties.OPS_PROMETHEUS_URL.split("\\.")[1]; - final String promUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_PROMETHEUS_URL); - final String dbclId = DashboardProperties.OPS_DBCL_URL.split("\\.")[1]; - final String dbclUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_DBCL_URL); - opsList.add(new ControllerOpsTools(cfyId, cfyUrl)); - opsList.add(new ControllerOpsTools(k8Id, k8Url)); - opsList.add(new ControllerOpsTools(grfId, grfUrl)); - opsList.add(new ControllerOpsTools(cnslId, cnslUrl)); - opsList.add(new ControllerOpsTools(promId, promUrl)); - opsList.add(new ControllerOpsTools(dbclId, dbclUrl)); - - return opsList; - } - - /** - * Gets the controller endpoint for the specified user ID. Chooses the first one - * from properties if the user has not selected one previously. - * - * @param userId Database User ID - * @return ControllerEndpointCredentials for the specified user - */ - protected ControllerEndpointCredentials getOrSetControllerEndpointSelection(long userId) { - // Always need the complete list from properties - ControllerEndpointCredentials[] configured = getControllerEndpoints(); - // See if the database has an entry for this user - ControllerEndpoint dbEntry = controllerEndpointService.getControllerEndpointSelection(userId); - // If no row found DAO returns an object with null entries. - if (dbEntry == null || dbEntry.getName() == null) { - // Arbitrarily choose the first one - ControllerEndpointCredentials first = configured[0]; - dbEntry = new ControllerEndpoint(userId, first.getName(), first.getUrl(), first.getInventoryUrl(), - first.getDhandlerUrl()); - controllerEndpointService.updateControllerEndpointSelection(dbEntry); - } - // Fetch complete details for the selected item - ControllerEndpointCredentials selected = null; - for (ControllerEndpointCredentials cec : configured) { - if (dbEntry.getUrl().equals(cec.getUrl())) { - selected = cec; - break; - } - } - // Defend against a stale database entry. - if (selected == null) { - selected = configured[0]; - dbEntry = new ControllerEndpoint(userId, selected.getName(), selected.getUrl(), selected.getInventoryUrl(), - selected.getDhandlerUrl()); - controllerEndpointService.updateControllerEndpointSelection(dbEntry); - } - return selected; - } - - protected ControllerEndpointCredentials getOrSetControllerEndpointSelection() { - ControllerEndpointCredentials[] configured = getControllerEndpoints(); - return configured[0]; - } - - /** - * Convenience method that gets the user ID from the session and fetches the - * REST client. Factors code out of subclass methods. - * - * @param request HttpServletRequest - * @return REST client appropriate for the user - */ - protected CloudifyClient getCloudifyRestClient(HttpServletRequest request) throws Exception { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getId() == null) - throw new Exception("getCloudifyRestClient: Failed to get application user"); - return getCloudifyRestClient(appUser.getId()); - } - - /** - * Gets a REST client; either a mock client (returns canned data), or a real - * client with appropriate credentials from properties. - * - * @return REST client. - */ - protected CloudifyClient getCloudifyRestClient(long userId) throws Exception { - CloudifyClient result = null; - // Be robust to missing development-only property - boolean mock = false; - if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA)) - mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA); - if (mock) { - result = new CloudifyMockClientImpl(); - } else { - ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId); - final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); - result = new CloudifyRestClientImpl(details.getUrl(), details.getUsername(), clearText); - } - return result; - } - - /** - * Gets a REST client; either a mock client (returns canned data), or a real - * client with appropriate credentials from properties. - * - * @return REST client. - */ - protected CloudifyClient getCloudifyRestClient() throws Exception { - CloudifyClient result = null; - // Be robust to missing development-only property - boolean mock = false; - if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA)) - mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA); - if (mock) { - result = new CloudifyMockClientImpl(); - } else { - ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(); - final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); - result = new CloudifyRestClientImpl(details.getUrl(), details.getUsername(), clearText); - } - return result; - } - - /** - * Convenience method that gets the user ID from the session and fetches the - * REST client. Factors code out of subclass methods. - * - * @param request HttpServletRequest - * @return REST client appropriate for the user - */ - protected ConsulClient getConsulRestClient(HttpServletRequest request) throws Exception { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getId() == null) - throw new Exception("getControllerRestClient: Failed to get application user"); - return getConsulRestClient(appUser.getId()); - } - - /** - * Gets a REST client; either a mock client (returns canned data), or a real - * client with appropriate credentials from properties. - * - * @return REST client. - */ - protected ConsulClient getConsulRestClient(long userId) throws Exception { - ConsulClient result = null; - // Be robust to missing development-only property - boolean mock = false; - if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA)) - mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA); - if (mock) { - result = new ConsulMockClientImpl(); - } else { - ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(); - final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); - result = new ConsulRestClientImpl(details.getConsulUrl(), details.getUsername(), clearText); - } - return result; - } - - /** - * Gets a REST client; either a mock client (returns canned data), or a real - * client with appropriate credentials from properties. - * - * @return REST client. - */ - protected ConsulClient getConsulRestClient() throws Exception { - ConsulClient result = null; - // Be robust to missing development-only property - boolean mock = false; - if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA)) - mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA); - if (mock) { - result = new ConsulMockClientImpl(); - } else { - ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(); - final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); - result = new ConsulRestClientImpl(details.getConsulUrl(), details.getUsername(), clearText); - } - return result; - } - - /** - * Convenience method that gets the user ID from the session and fetches the - * Inventory client. Factors code out of subclass methods. - * - * @param request HttpServletRequest - * @return Inventory client appropriate for the user - */ - protected InventoryClient getInventoryClient(HttpServletRequest request) throws Exception { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getId() == null) - throw new Exception("getControllerRestClient: Failed to get application user"); - return getInventoryClient(appUser.getId()); - } - - /** - * Gets an Inventory client with appropriate credentials from properties. - * - * @return Inventory Client. - */ - protected InventoryClient getInventoryClient(long userId) throws Exception { - InventoryClient result = null; - boolean mock = false; - if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA)) - mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA); - if (mock) { - result = new RestInventoryClientMockImpl(); - } else { - ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId); - final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); - result = new RestInventoryClientImpl(details.getInventoryUrl(), details.getUsername(), clearText); - } - return result; - } - - protected InventoryClient getInventoryClient() throws Exception { - InventoryClient result = null; - ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(); - final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); - result = new RestInventoryClientImpl(details.getInventoryUrl(), details.getUsername(), clearText); - return result; - } - - /** - * Convenience method that gets the user ID from the session and fetches the - * Deployment Handler client. Factors code out of subclass methods. - * - * @param request HttpServletRequest - * @return Deployment Handler client appropriate for the user - */ - protected DeploymentHandlerClient getDeploymentHandlerClient(HttpServletRequest request) throws Exception { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getId() == null) - throw new Exception("getControllerRestClient: Failed to get application user"); - return getDeploymentHandlerClient(appUser.getId()); - } - - /** - * Gets a Deployment Handler client with appropriate credentials from - * properties. - * - * @return Deployment Handler Client. - */ - protected DeploymentHandlerClient getDeploymentHandlerClient(long userId) throws Exception { - DeploymentHandlerClient result = null; - ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId); - final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); - result = new DeploymentHandlerClientImpl(details.getDhandlerUrl(), details.getUsername(), clearText); - return result; - } - - protected DeploymentHandlerClient getDeploymentHandlerClient() throws Exception { - DeploymentHandlerClient result = null; - ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(); - final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword(); - result = new DeploymentHandlerClientImpl(details.getDhandlerUrl(), details.getUsername(), clearText); - return result; - } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerController.java index 1c3ac8f..0346ad7 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerController.java @@ -41,6 +41,7 @@ import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -60,7 +61,11 @@ import com.fasterxml.jackson.core.JsonProcessingException; @RequestMapping("/deploymenthandler") public class DeploymentHandlerController extends DashboardRestrictedBaseController { - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DeploymentHandlerController.class); + private static EELFLoggerDelegate logger = + EELFLoggerDelegate.getLogger(DeploymentHandlerController.class); + + @Autowired + DeploymentHandlerClient deploymentHandlerClient; private static final String DEPLOYMENTS_PATH = "dcae-deployments"; @@ -74,7 +79,6 @@ public class DeploymentHandlerController extends DashboardRestrictedBaseControll preLogAudit(request); String json = null; try { - DeploymentHandlerClient deploymentHandlerClient = getDeploymentHandlerClient(request); if (deploymentRequestObject.getMethod().equals("create")) { json = objectMapper.writeValueAsString(deploymentHandlerClient.putDeployment( deploymentRequestObject.getDeploymentId(), deploymentRequestObject.getTenant(), @@ -121,18 +125,9 @@ public class DeploymentHandlerController extends DashboardRestrictedBaseControll MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Deployment failed! Downstream Exception"); logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("Downstream Exception " + e.getMessage())); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Deployment Handler"); - MDC.put("TargetServiceName", "Deployment Handler"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deployment failed! Json Processing Exception"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); - json = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } catch (Throwable t) { + json = objectMapper.writeValueAsString( + new RestResponseError("Downstream Exception " + e.getMessage())); + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Deployment Handler"); MDC.put("TargetServiceName", "Deployment Handler"); @@ -156,7 +151,8 @@ public class DeploymentHandlerController extends DashboardRestrictedBaseControll String json = null; StringBuffer status = new StringBuffer(); try { - DeploymentHandlerClient deploymentHandlerClient = getDeploymentHandlerClient(request); + // DeploymentHandlerClient deploymentHandlerClient = + // getDeploymentHandlerClient(request); deploymentHandlerClient.deleteDeployment(deploymentId, tenant); String self = request.getRequestURL().toString().split("\\?")[0]; status.append(self).append("/executions?tenant=").append(tenant); @@ -200,17 +196,7 @@ public class DeploymentHandlerController extends DashboardRestrictedBaseControll MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Deployment Handler"); - MDC.put("TargetServiceName", "Deployment Handler"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); - json = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Deployment Handler"); MDC.put("TargetServiceName", "Deployment Handler"); diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnController.java index c2330f4..9d28be7 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnController.java @@ -244,6 +244,9 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { } catch (RestClientException ex) { logger.debug("isPortalAvailable failed", ex); avail = false; + } catch (Exception e) { + logger.debug("isPortalAvailable failed", e); + avail = false; } return avail; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/HealthCheckController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/HealthCheckController.java index df5ec64..5087ad1 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/HealthCheckController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/HealthCheckController.java @@ -22,26 +22,11 @@ package org.onap.ccsdk.dashboard.controller; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.UnknownHostException; -import java.util.Date; -import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.http.HttpStatus; -import org.onap.ccsdk.dashboard.model.ControllerEndpointCredentials; import org.onap.ccsdk.dashboard.model.HealthStatus; -import org.onap.portalsdk.core.domain.App; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.objectcache.AbstractCacheManager; -import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.util.SystemProperties; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.web.bind.annotation.RequestMapping; @@ -58,24 +43,12 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/") public class HealthCheckController extends DashboardRestrictedBaseController { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthCheckController.class); - /** * Application name */ protected static final String APP_NAME = "ecd-app"; - private static Date begin, end; private static final String APP_HEALTH_CHECK_PATH = "/health"; - private static final String APP_SRVC_HEALTH_CHECK_PATH = "/health-info"; - - private static final String APP_DB_QRY = "from App where id = 1"; - public static final String APP_METADATA = "APP.METADATA"; - - @Autowired - private DataAccessService dataAccessService; - - private AbstractCacheManager cacheManager; /** * application health by simply responding with a JSON object indicating status @@ -85,187 +58,7 @@ public class HealthCheckController extends DashboardRestrictedBaseController { */ @RequestMapping(value = { APP_HEALTH_CHECK_PATH }, method = RequestMethod.GET, produces = "application/json") public HealthStatus healthCheck(HttpServletRequest request, HttpServletResponse response) { - return new HealthStatus(200, - SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + " health check passed "); - } - - /** - * Checks application health by executing a sample query with local DB - * - * @param request HttpServletRequest - * @return 200 if database access succeeds, 500 if it fails. - */ - /* - * public HealthStatus healthCheck(HttpServletRequest request, - * HttpServletResponse response) { //preLogAudit(request); HealthStatus - * healthStatus = new HealthStatus(200, - * SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + - * " health check passed "); try { logger.debug(EELFLoggerDelegate.debugLogger, - * "Performing health check"); App app; Object appObj = - * getCacheManager().getObject(APP_METADATA); if (appObj == null) { app = - * findApp(); if (app != null) { getCacheManager().putObject(APP_METADATA, app); - * } else { healthStatus = new HealthStatus(503, - * SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + - * " health check failed to query App from database"); } } - * - * if (isDbConnUp()) { healthStatus = new HealthStatus(200, - * SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + - * " health check passed "); } else { healthStatus = new HealthStatus(503, - * SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + - * " health check failed to run db query"); } } catch (Exception ex) { - * MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", - * "Health Check"); MDC.put("TargetServiceName", "Health Check"); - * MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - * MDC.put("ErrorDescription", "Health check failed!"); - * logger.error(EELFLoggerDelegate.errorLogger, - * "Failed to perform health check"); healthStatus = new HealthStatus(503, - * "health check failed: " + ex.toString()); } finally { postLogAudit(request); - * } if (healthStatus.getStatusCode() != 200) { - * response.setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE); - * response.sendError(HttpStatus.SC_SERVICE_UNAVAILABLE, - * objectMapper.writeValueAsString(healthStatus)); } - * - * return healthStatus; } - */ - /** - * Checks application health and availability of dependent services - * - * @param request HttpServletRequest - * @return 200 if database access succeeds, 500 if it fails. - */ - @RequestMapping(value = { APP_SRVC_HEALTH_CHECK_PATH }, method = RequestMethod.GET, produces = "application/json") - public HealthStatus srvcHealthCheck(HttpServletRequest request, HttpServletResponse response) throws Exception { - preLogAudit(request); - HealthStatus healthStatus = null; - StringBuffer sb = new StringBuffer(); - try { - logger.debug(EELFLoggerDelegate.debugLogger, "Performing health check"); - if (isDbConnUp()) { - sb.append(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)) - .append(" health check passed; "); - healthStatus = new HealthStatus(200, - SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + sb.toString()); - } else { - sb.append(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)) - .append(" health check failed to run db query; "); - healthStatus = new HealthStatus(503, - SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + sb.toString()); - } - ControllerEndpointCredentials[] cec = getControllerEndpoints(); - - for (int i = 0; i < cec.length; ++i) { - // Check if API Handler is reachable - if (!isServiceReachable(cec[i].getUrl())) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Handler"); - MDC.put("TargetServiceName", "API Handler"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "API Handler unreachable!"); - sb.append(" API Handler unreachable; "); - logger.error(EELFLoggerDelegate.errorLogger, "Failed to ping API Handler"); - } - // Check if Inventory is reachable - if (!isServiceReachable(cec[i].getInventoryUrl() + "/dcae-services")) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "DCAE Inventory unreachable!"); - sb.append(" DCAE Inventory unreachable; "); - logger.error(EELFLoggerDelegate.errorLogger, "Failed to ping DCAE Inventory"); - } - // Check if Deployment Handler is reachable - if (!isServiceReachable(cec[i].getDhandlerUrl())) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Deployment Handler"); - MDC.put("TargetServiceName", "Deployment Handler"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deployment Handler unreachable!"); - sb.append(" Deployment Handler unreachable; "); - logger.error(EELFLoggerDelegate.errorLogger, "Failed to ping Deployment Handler"); - } - } - } catch (Exception ex) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Health Check"); - MDC.put("TargetServiceName", "Health Check"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Health check failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check"); - sb.append(" "); - sb.append(ex.toString()); - healthStatus = new HealthStatus(503, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) - + " health check failed: " + sb.toString()); - } finally { - postLogAudit(request); - } - if (healthStatus.getStatusCode() != 200) { - response.setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE); - response.sendError(HttpStatus.SC_SERVICE_UNAVAILABLE, objectMapper.writeValueAsString(healthStatus)); - } - return healthStatus; - } - - private boolean isDbConnUp() { - @SuppressWarnings("unchecked") - List<App> list = dataAccessService.executeQuery(APP_DB_QRY, null); - if (list.size() > 0) { - return true; - } else { - return false; - } - } - - private App findApp() { - @SuppressWarnings("unchecked") - List<App> list = dataAccessService.executeQuery(APP_DB_QRY, null); - return (list == null || list.isEmpty()) ? null : (App) list.get(0); - } - - public static boolean isServiceReachable(String targetUrl) throws IOException { - HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL(targetUrl).openConnection(); - httpUrlConnection.setRequestMethod("HEAD"); - - try { - int responseCode = httpUrlConnection.getResponseCode(); - return responseCode == HttpURLConnection.HTTP_OK; - } catch (UnknownHostException noInternetConnection) { - return false; - } - } - - @Autowired - public void setCacheManager(AbstractCacheManager cacheManager) { - this.cacheManager = cacheManager; - } - - public AbstractCacheManager getCacheManager() { - return cacheManager; - } - - public void preLogAudit(HttpServletRequest request) { - begin = new Date(); - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, - DashboardRestrictedBaseController.logDateFormat.format(begin)); - MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, - DashboardRestrictedBaseController.logDateFormat.format(begin)); - MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); - // logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME); - } - - public void postLogAudit(HttpServletRequest request) { - end = new Date(); - MDC.put("AlertSeverity", "0"); - MDC.put("TargetEntity", "Health Check"); - MDC.put("TargetServiceName", "Health Check"); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DashboardRestrictedBaseController.logDateFormat.format(end)); - MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, DashboardRestrictedBaseController.logDateFormat.format(end)); - MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI()); + return new HealthStatus(200, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + + " health check passed "); } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/InventoryController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/InventoryController.java index 135b650..4251212 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/InventoryController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/InventoryController.java @@ -2,27 +2,26 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 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. + * 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========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ package org.onap.ccsdk.dashboard.controller; -import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -30,7 +29,6 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Optional; -import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; @@ -40,12 +38,10 @@ import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceAlreadyDeactivatedException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; -import org.onap.ccsdk.dashboard.model.CloudifyTenant; -import org.onap.ccsdk.dashboard.model.ECTransportModel; import org.onap.ccsdk.dashboard.model.RestResponseError; import org.onap.ccsdk.dashboard.model.RestResponsePage; import org.onap.ccsdk.dashboard.model.inventory.Blueprint; @@ -56,15 +52,14 @@ import org.onap.ccsdk.dashboard.model.inventory.ServiceType; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeServiceMap; -import org.onap.ccsdk.dashboard.rest.CloudifyClient; import org.onap.ccsdk.dashboard.rest.InventoryClient; -import org.onap.ccsdk.dashboard.util.DashboardProperties; -import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.web.support.AppUtils; -import org.onap.portalsdk.core.web.support.UserUtils; +import org.onap.ccsdk.dashboard.util.DashboardProperties; + import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -84,7 +79,11 @@ import com.fasterxml.jackson.core.JsonProcessingException; @RequestMapping("/inventory") public class InventoryController extends DashboardRestrictedBaseController { - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(InventoryController.class); + private static EELFLoggerDelegate logger = + EELFLoggerDelegate.getLogger(InventoryController.class); + + @Autowired + InventoryClient inventoryClient; /** * Enum for selecting an item type. @@ -97,34 +96,115 @@ public class InventoryController extends DashboardRestrictedBaseController { private static final String SERVICES_PATH = "dcae-services"; private static final String SERVICE_TYPES_PATH = "dcae-service-types"; private static final String VIEW_SERVICE_TYPE_BLUEPRINT_PATH = "dcae-service-type-blueprint"; - private static final String DEPLOY_ROLE = ".k8.dev"; private static final String DEP_IDS_FOR_TYPE = "dcae-services/typeIds"; /** - * ATT version with user role auth Gets one page of objects and supporting + * Gets one page of objects and supporting information via the REST client. On + * success, returns a PaginatedRestResponse object as String. + * + * @param option Specifies which item list type to get + * @param pageNum Page number of results + * @param pageSize Number of items per browser page + * @return JSON block as String, see above. + * @throws Exception On any error; e.g., Network failure. + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + private String getItemListForPage(HttpServletRequest request, InventoryDataItem option, + int pageNum, int pageSize, String sortBy, String searchBy) throws Exception { + List itemList = null; + switch (option) { + case SERVICES: + itemList = inventoryClient.getServices().collect(Collectors.toList()); + if (searchBy != null) { + itemList = (List) itemList.stream() + .filter(s -> ((Service) s).contains(searchBy)).collect(Collectors.toList()); + } + for (Service bp : (List<Service>) itemList) { + bp.setCanDeploy(Optional.of(true)); + } + if (sortBy != null) { + if (sortBy.equals("deploymentRef")) { + Collections.sort(itemList, serviceDeploymentRefComparator); + } else if (sortBy.equals("serviceId")) { + Collections.sort(itemList, serviceIdComparator); + } else if (sortBy.equals("created")) { + Collections.sort(itemList, serviceCreatedComparator); + } else if (sortBy.equals("modified")) { + Collections.sort(itemList, serviceModifiedComparator); + } + } + break; + case SERVICE_TYPES: + itemList = inventoryClient.getServiceTypes().collect(Collectors.toList()); + if (searchBy != null) { + itemList = + (List) itemList.stream().filter(s -> ((ServiceType) s).contains(searchBy)) + .collect(Collectors.toList()); + } + for (ServiceType bp : (List<ServiceType>) itemList) { + bp.setCanDeploy(Optional.of(true)); + } + if (sortBy != null) { + if (sortBy.equals("owner")) { + Collections.sort(itemList, serviceTypeOwnerComparator); + } else if (sortBy.equals("typeId")) { + Collections.sort(itemList, serviceTypeIdComparator); + } else if (sortBy.equals("typeName")) { + Collections.sort(itemList, serviceTypeNameComparator); + } else if (sortBy.equals("typeVersion")) { + Collections.sort(itemList, serviceTypeVersionComparator); + } else if (sortBy.equals("created")) { + Collections.sort(itemList, serviceTypeCreatedComparator); + } else if (sortBy.equals("application")) { + Collections.sort(itemList, serviceTypeApplComparator); + } else if (sortBy.equals("component")) { + Collections.sort(itemList, serviceTypeCompComparator); + } + } + break; + default: + MDC.put(SystemProperties.STATUS_CODE, "ERROR"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); + MDC.put("ErrorCode", "300"); + MDC.put("ErrorCategory", "ERROR"); + MDC.put("ErrorDescription", "Getting page of items failed!"); + throw new Exception( + "getItemListForPage failed: unimplemented case: " + option.name()); + } + + // Shrink if needed + final int totalItems = itemList.size(); + final int pageCount = (int) Math.ceil((double) totalItems / pageSize); + if (totalItems > pageSize) + itemList = getPageOfList(pageNum, pageSize, itemList); + + RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); + String outboundJson = objectMapper.writeValueAsString(model); + return outboundJson; + } + + /** + * version with user role auth Gets one page of objects and supporting * information via the REST client. On success, returns a PaginatedRestResponse * object as String. * - * @param option Specifies which item list type to get - * @param pageNum Page number of results + * @param option Specifies which item list type to get + * @param pageNum Page number of results * @param pageSize Number of items per browser page * @return JSON block as String, see above. * @throws Exception On any error; e.g., Network failure. */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - private String getItemListForPageAuth(HttpServletRequest request, InventoryDataItem option, int pageNum, - int pageSize, String sortBy, String searchBy) throws Exception { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getId() == null) - throw new Exception("getControllerRestClient: Failed to get application user"); - InventoryClient inventoryClient = getInventoryClient(appUser.getId()); - + @SuppressWarnings({"rawtypes", "unchecked"}) + private String getItemListForPageAuth(HttpServletRequest request, InventoryDataItem option, + int pageNum, int pageSize, String sortBy, String searchBy) throws Exception { HttpSession session = AppUtils.getSession(request); - HashMap<String, Boolean> comp_deploy_tab = (HashMap<String, Boolean>) session.getAttribute("comp_access"); + HashMap<String, Boolean> comp_deploy_tab = + (HashMap<String, Boolean>) session.getAttribute("comp_access"); String roleLevel = (String) session.getAttribute("role_level"); if (roleLevel == null) { - roleLevel = "app"; + roleLevel = "dev"; } if (comp_deploy_tab == null) { comp_deploy_tab = new HashMap<String, Boolean>(); @@ -139,287 +219,166 @@ public class InventoryController extends DashboardRestrictedBaseController { List<ServiceType> filterList = new ArrayList<ServiceType>(); List<Service> authDepList = new ArrayList<Service>(); switch (option) { - case SERVICES: - itemList = inventoryClient.getServices().collect(Collectors.toList()); - if (roleLevel.equals("app")) { - for (String userRole : userApps) { - logger.debug(">>>> check component type from deployment: " + userRole); - for (Service cont : (List<Service>) itemList) { - String deplRef = cont.getDeploymentRef().toLowerCase(); - logger.debug(">>>> container deployment name: " + deplRef); - if (deplRef.contains(userRole)) { - logger.debug(">>>> adding deployment item to filtered subset"); - authDepList.add(cont); + case SERVICES: + itemList = inventoryClient.getServices().collect(Collectors.toList()); + if (roleLevel.equals("app")) { + for (String userRole : userApps) { + logger.debug(">>>> check component type from deployment: " + userRole); + for (Service cont : (List<Service>) itemList) { + String deplRef = cont.getDeploymentRef().toLowerCase(); + logger.debug(">>>> container deployment name: " + deplRef); + if (deplRef.contains(userRole)) { + logger.debug(">>>> adding deployment item to filtered subset"); + authDepList.add(cont); + } } } } - } - if (searchBy != null) { - if (!roleLevel.equals("app")) { - itemList = (List) itemList.stream().filter(s -> ((Service) s).contains(searchBy)) - .collect(Collectors.toList()); - } else { - if (!authDepList.isEmpty()) { - authDepList = (List) authDepList.stream().filter(s -> ((Service) s).contains(searchBy)) + if (searchBy != null) { + if (!roleLevel.equals("app")) { + itemList = + (List) itemList.stream().filter(s -> ((Service) s).contains(searchBy)) .collect(Collectors.toList()); - } - } - } - if (roleLevel.equals("app")) { - logger.debug(">>>> update response with authorized content"); - itemList.clear(); - itemList.addAll(authDepList); - } - - // check for authorization to perform delete deployed blueprints - - if (!roleLevel.equals("ops")) { - for (Service bp : (List<Service>) itemList) { - String deplRef = bp.getDeploymentRef().split("_")[0].toLowerCase(); - logger.debug(">>>> deployment reference: " + deplRef); - if (comp_deploy_tab.containsKey(deplRef)) { - boolean enableDeploy = comp_deploy_tab.get(deplRef); - logger.debug(">>>> enable deploy button: " + enableDeploy); - bp.setCanDeploy(Optional.of(enableDeploy)); } else { - bp.setCanDeploy(Optional.of(false)); + if (!authDepList.isEmpty()) { + authDepList = (List) authDepList.stream() + .filter(s -> ((Service) s).contains(searchBy)) + .collect(Collectors.toList()); + } } } - } else { - for (Service bp : (List<Service>) itemList) { - bp.setCanDeploy(Optional.of(true)); + if (roleLevel.equals("app")) { + logger.debug(">>>> update response with authorized content"); + itemList.clear(); + itemList.addAll(authDepList); } - } - if (sortBy != null) { - if (sortBy.equals("deploymentRef")) { - Collections.sort(itemList, serviceDeploymentRefComparator); - } else if (sortBy.equals("serviceId")) { - Collections.sort(itemList, serviceIdComparator); - } else if (sortBy.equals("created")) { - Collections.sort(itemList, serviceCreatedComparator); - } else if (sortBy.equals("modified")) { - Collections.sort(itemList, serviceModifiedComparator); - } - } - break; - case SERVICE_TYPES: - ServiceTypeQueryParams serviceQueryParams = null; - serviceQueryParams = new ServiceTypeQueryParams.Builder().onlyLatest(false).build(); - itemList = inventoryClient.getServiceTypes(serviceQueryParams).collect(Collectors.toList()); - if (roleLevel.equals("app")) { - for (String userApp : userApps) { - logger.debug(">>>> check component type from BP: " + userApp); - for (ServiceType bp : (List<ServiceType>) itemList) { - String bpComp = bp.getComponent(); - String bpOwner = bp.getOwner(); // for backward compatibility - logger.debug(">>>> BP component name: " + bpComp); - if ((bpComp != null && bpComp.equalsIgnoreCase(userApp)) || bpOwner.contains(userApp)) { - logger.debug(">>>> adding item to filtered subset"); - filterList.add(bp); + // check for authorization to perform delete deployed blueprints + + if (!roleLevel.equals("ops")) { + for (Service bp : (List<Service>) itemList) { + String deplRef = bp.getDeploymentRef().split("_")[0].toLowerCase(); + logger.debug(">>>> deployment reference: " + deplRef); + if (comp_deploy_tab.containsKey(deplRef)) { + boolean enableDeploy = comp_deploy_tab.get(deplRef); + logger.debug(">>>> enable deploy button: " + enableDeploy); + bp.setCanDeploy(Optional.of(enableDeploy)); + } else { + bp.setCanDeploy(Optional.of(false)); } } - } - } - if (searchBy != null) { - if (!roleLevel.equals("app")) { - itemList = (List) itemList.stream().filter(s -> ((ServiceType) s).contains(searchBy)) - .collect(Collectors.toList()); } else { - if (!filterList.isEmpty()) { - filterList = (List) filterList.stream().filter(s -> ((ServiceType) s).contains(searchBy)) - .collect(Collectors.toList()); + for (Service bp : (List<Service>) itemList) { + bp.setCanDeploy(Optional.of(true)); } } - } - if (roleLevel.equals("app")) { - logger.debug(">>>> update response with authorized content"); - itemList.clear(); - itemList.addAll(filterList); - } - // check for authorization to perform update/delete/deploy blueprints - if (!roleLevel.equals("ops")) { - for (ServiceType bp : (List<ServiceType>) itemList) { - String bpComp = bp.getComponent(); - if (bpComp != null && bpComp.length() > 0) { - bpComp = bpComp.toLowerCase(); - } else { - String bpOwner = bp.getOwner(); // for backward compatibility - if (bpOwner != null && bpOwner.contains(":")) { - bpComp = bp.getOwner().split(":")[0].toLowerCase(); + if (sortBy != null) { + if (sortBy.equals("deploymentRef")) { + Collections.sort(itemList, serviceDeploymentRefComparator); + } else if (sortBy.equals("serviceId")) { + Collections.sort(itemList, serviceIdComparator); + } else if (sortBy.equals("created")) { + Collections.sort(itemList, serviceCreatedComparator); + } else if (sortBy.equals("modified")) { + Collections.sort(itemList, serviceModifiedComparator); + } + } + break; + case SERVICE_TYPES: + ServiceTypeQueryParams serviceQueryParams = + new ServiceTypeQueryParams.Builder().onlyLatest(false).build(); + itemList = inventoryClient.getServiceTypes(serviceQueryParams) + .collect(Collectors.toList()); + if (roleLevel.equals("app")) { + for (String userApp : userApps) { + logger.debug(">>>> check component type from BP: " + userApp); + for (ServiceType bp : (List<ServiceType>) itemList) { + String bpComp = bp.getComponent(); + String bpOwner = bp.getOwner(); // for backward compatibility + logger.debug(">>>> BP component name: " + bpComp); + if ((bpComp != null && bpComp.equalsIgnoreCase(userApp)) + || bpOwner.contains(userApp)) { + logger.debug(">>>> adding item to filtered subset"); + filterList.add(bp); + } } } - logger.debug(">>>> BP component name: " + bpComp); - if (comp_deploy_tab.containsKey(bpComp)) { - boolean enableDeploy = comp_deploy_tab.get(bpComp); - logger.debug(">>>> enable deploy button: " + enableDeploy); - bp.setCanDeploy(Optional.of(enableDeploy)); + } + if (searchBy != null) { + if (!roleLevel.equals("app")) { + itemList = (List) itemList.stream() + .filter(s -> ((ServiceType) s).contains(searchBy)) + .collect(Collectors.toList()); } else { - bp.setCanDeploy(Optional.of(false)); + if (!filterList.isEmpty()) { + filterList = (List) filterList.stream() + .filter(s -> ((ServiceType) s).contains(searchBy)) + .collect(Collectors.toList()); + } } } - } else { - for (ServiceType bp : (List<ServiceType>) itemList) { - bp.setCanDeploy(Optional.of(true)); + if (roleLevel.equals("app")) { + logger.debug(">>>> update response with authorized content"); + itemList.clear(); + itemList.addAll(filterList); } - } - if (sortBy != null) { - if (sortBy.equals("owner")) { - Collections.sort(itemList, serviceTypeOwnerComparator); - } else if (sortBy.equals("typeId")) { - Collections.sort(itemList, serviceTypeIdComparator); - } else if (sortBy.equals("typeName")) { - Collections.sort(itemList, serviceTypeNameComparator); - } else if (sortBy.equals("typeVersion")) { - Collections.sort(itemList, serviceTypeVersionComparator); - } else if (sortBy.equals("created")) { - Collections.sort(itemList, serviceTypeCreatedComparator); - } else if (sortBy.equals("application")) { - Collections.sort(itemList, serviceTypeApplComparator); - } else if (sortBy.equals("component")) { - Collections.sort(itemList, serviceTypeCompComparator); + // check for authorization to perform update/delete/deploy blueprints + if (!roleLevel.equals("ops")) { + for (ServiceType bp : (List<ServiceType>) itemList) { + String bpComp = bp.getComponent(); + if (bpComp != null && bpComp.length() > 0) { + bpComp = bpComp.toLowerCase(); + } else { + String bpOwner = bp.getOwner(); // for backward compatibility + if (bpOwner != null && bpOwner.contains(":")) { + bpComp = bp.getOwner().split(":")[0].toLowerCase(); + } + } + logger.debug(">>>> BP component name: " + bpComp); + if (comp_deploy_tab.containsKey(bpComp)) { + boolean enableDeploy = comp_deploy_tab.get(bpComp); + logger.debug(">>>> enable deploy button: " + enableDeploy); + bp.setCanDeploy(Optional.of(enableDeploy)); + } else { + bp.setCanDeploy(Optional.of(false)); + } + } + } else { + for (ServiceType bp : (List<ServiceType>) itemList) { + bp.setCanDeploy(Optional.of(true)); + } } - } - break; - default: - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting page of items failed!"); - throw new Exception("getItemListForPage failed: unimplemented case: " + option.name()); - } - // Shrink if needed - final int totalItems = itemList.size(); - final int pageCount = (int) Math.ceil((double) totalItems / pageSize); - if (totalItems > pageSize) - itemList = getPageOfList(pageNum, pageSize, itemList); - - RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); - String outboundJson = objectMapper.writeValueAsString(model); - return outboundJson; - } - - /** - * Gets one page of objects and supporting information via the REST client. On - * success, returns a PaginatedRestResponse object as String. - * - * @param option Specifies which item list type to get - * @param pageNum Page number of results - * @param pageSize Number of items per browser page - * @return JSON block as String, see above. - * @throws Exception On any error; e.g., Network failure. - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - private String getItemListForPage(HttpServletRequest request, InventoryDataItem option, int pageNum, int pageSize, - String sortBy, String searchBy) throws Exception { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getId() == null) - throw new Exception("getControllerRestClient: Failed to get application user"); - InventoryClient inventoryClient = getInventoryClient(appUser.getId()); - - List itemList = null; - switch (option) { - case SERVICES: - itemList = inventoryClient.getServices().collect(Collectors.toList()); - // Get the tenant names for all the deployments from Cloudify/API handler - ECTransportModel result = null; - List<CloudifyDeployedTenant> tenantList = new ArrayList<CloudifyDeployedTenant>(); - try { - CloudifyClient restClient = getCloudifyRestClient(request); - List<CloudifyTenant> cldfyTen = restClient.getTenants().items; - for (CloudifyTenant ct : (List<CloudifyTenant>) cldfyTen) { - result = restClient.getTenantInfoFromDeploy(ct.name); - tenantList.addAll(((CloudifyDeployedTenantList) result).items); + if (sortBy != null) { + if (sortBy.equals("owner")) { + Collections.sort(itemList, serviceTypeOwnerComparator); + } else if (sortBy.equals("typeId")) { + Collections.sort(itemList, serviceTypeIdComparator); + } else if (sortBy.equals("typeName")) { + Collections.sort(itemList, serviceTypeNameComparator); + } else if (sortBy.equals("typeVersion")) { + Collections.sort(itemList, serviceTypeVersionComparator); + } else if (sortBy.equals("created")) { + Collections.sort(itemList, serviceTypeCreatedComparator); + } else if (sortBy.equals("application")) { + Collections.sort(itemList, serviceTypeApplComparator); + } else if (sortBy.equals("component")) { + Collections.sort(itemList, serviceTypeCompComparator); + } } - } catch (HttpStatusCodeException e) { + break; + default: MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); + MDC.put("TargetEntity", "DCAE Inventory"); + MDC.put("TargetServiceName", "DCAE Inventory"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting deployments failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getTenantInfoFromDeploy caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting deployments failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); - result = new RestResponseError("getTenantInfoFromDeploy failed", t); - } finally { - postLogAudit(request); - } - for (Service depl : (List<Service>) itemList) { - for (CloudifyDeployedTenant deplTen : tenantList) { - if (depl.getDeploymentRef().equals(deplTen.id)) { - depl.setTenant(deplTen.tenant_name); - break; - } - } - } - if (searchBy != null) { - itemList = (List) itemList.stream().filter(s -> ((Service) s).contains(searchBy)) - .collect(Collectors.toList()); - } - for (Service bp : (List<Service>) itemList) { - bp.setCanDeploy(Optional.of(true)); - } - if (sortBy != null) { - if (sortBy.equals("deploymentRef")) { - Collections.sort(itemList, serviceDeploymentRefComparator); - } else if (sortBy.equals("serviceId")) { - Collections.sort(itemList, serviceIdComparator); - } else if (sortBy.equals("created")) { - Collections.sort(itemList, serviceCreatedComparator); - } else if (sortBy.equals("modified")) { - Collections.sort(itemList, serviceModifiedComparator); - } - } - break; - case SERVICE_TYPES: - itemList = inventoryClient.getServiceTypes().collect(Collectors.toList()); - if (searchBy != null) { - itemList = (List) itemList.stream().filter(s -> ((ServiceType) s).contains(searchBy)) - .collect(Collectors.toList()); - } - for (ServiceType bp : (List<ServiceType>) itemList) { - bp.setCanDeploy(Optional.of(true)); - } - if (sortBy != null) { - if (sortBy.equals("owner")) { - Collections.sort(itemList, serviceTypeOwnerComparator); - } else if (sortBy.equals("typeId")) { - Collections.sort(itemList, serviceTypeIdComparator); - } else if (sortBy.equals("typeName")) { - Collections.sort(itemList, serviceTypeNameComparator); - } else if (sortBy.equals("typeVersion")) { - Collections.sort(itemList, serviceTypeVersionComparator); - } else if (sortBy.equals("created")) { - Collections.sort(itemList, serviceTypeCreatedComparator); - } else if (sortBy.equals("application")) { - Collections.sort(itemList, serviceTypeApplComparator); - } else if (sortBy.equals("component")) { - Collections.sort(itemList, serviceTypeCompComparator); - } - } - break; - default: - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting page of items failed!"); - throw new Exception("getItemListForPage failed: unimplemented case: " + option.name()); + MDC.put("ErrorDescription", "Getting page of items failed!"); + throw new Exception( + "getItemListForPage failed: unimplemented case: " + option.name()); } // Shrink if needed @@ -438,22 +397,25 @@ public class InventoryController extends DashboardRestrictedBaseController { * constructs an appropriate JSON block to report errors. * * @param request Inbound request - * @param option Item type to get + * @param option Item type to get * @return JSON with one page of objects; or an error. */ - protected String getItemListForPageWrapper(HttpServletRequest request, InventoryDataItem option, String sortBy, - String searchBy) { + protected String getItemListForPageWrapper(HttpServletRequest request, InventoryDataItem option, + String sortBy, String searchBy) { preLogAudit(request); String outboundJson = null; try { int pageNum = getRequestPageNumber(request); int pageSize = getRequestPageSize(request); String appEnv = "os"; - appEnv = getAppProperties().getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "att"); + appEnv = + DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth"); if (appEnv.equals("os")) { - outboundJson = getItemListForPage(request, option, pageNum, pageSize, sortBy, searchBy); + outboundJson = + getItemListForPage(request, option, pageNum, pageSize, sortBy, searchBy); } else { - outboundJson = getItemListForPageAuth(request, option, pageNum, pageSize, sortBy, searchBy); + outboundJson = + getItemListForPageAuth(request, option, pageNum, pageSize, sortBy, searchBy); } } catch (Exception ex) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -462,10 +424,12 @@ public class InventoryController extends DashboardRestrictedBaseController { MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Getting page of items failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception"); + logger.error(EELFLoggerDelegate.errorLogger, + "getItemListForPageWrapper caught exception"); RestResponseError result = null; if (ex instanceof HttpStatusCodeException) - result = new RestResponseError(((HttpStatusCodeException) ex).getResponseBodyAsString()); + result = + new RestResponseError(((HttpStatusCodeException) ex).getResponseBodyAsString()); else result = new RestResponseError("Failed to get " + option.name(), ex); try { @@ -483,32 +447,35 @@ public class InventoryController extends DashboardRestrictedBaseController { /** * Supports sorting service types by owner */ - private static Comparator<ServiceType> serviceTypeOwnerComparator = new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getOwner().compareToIgnoreCase(o2.getOwner()); - } - }; + private static Comparator<ServiceType> serviceTypeOwnerComparator = + new Comparator<ServiceType>() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getOwner().compareToIgnoreCase(o2.getOwner()); + } + }; /** * Supports sorting service types by application */ - private static Comparator<ServiceType> serviceTypeApplComparator = new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getApplication().compareToIgnoreCase(o2.getApplication()); - } - }; + private static Comparator<ServiceType> serviceTypeApplComparator = + new Comparator<ServiceType>() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getApplication().compareToIgnoreCase(o2.getApplication()); + } + }; /** * Supports sorting service types by component */ - private static Comparator<ServiceType> serviceTypeCompComparator = new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getComponent().compareToIgnoreCase(o2.getComponent()); - } - }; + private static Comparator<ServiceType> serviceTypeCompComparator = + new Comparator<ServiceType>() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getComponent().compareToIgnoreCase(o2.getComponent()); + } + }; /** * Supports sorting service types by type id @@ -523,32 +490,35 @@ public class InventoryController extends DashboardRestrictedBaseController { /** * Supports sorting service types by type name */ - private static Comparator<ServiceType> serviceTypeNameComparator = new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getTypeName().compareToIgnoreCase(o2.getTypeName()); - } - }; + private static Comparator<ServiceType> serviceTypeNameComparator = + new Comparator<ServiceType>() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getTypeName().compareToIgnoreCase(o2.getTypeName()); + } + }; /** * Supports sorting service types by type version */ - private static Comparator<ServiceType> serviceTypeVersionComparator = new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getTypeVersion().compareTo(o2.getTypeVersion()); - } - }; + private static Comparator<ServiceType> serviceTypeVersionComparator = + new Comparator<ServiceType>() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getTypeVersion().compareTo(o2.getTypeVersion()); + } + }; /** * Supports sorting service types by created date */ - private static Comparator<ServiceType> serviceTypeCreatedComparator = new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getCreated().get().compareToIgnoreCase(o2.getCreated().get()); - } - }; + private static Comparator<ServiceType> serviceTypeCreatedComparator = + new Comparator<ServiceType>() { + @Override + public int compare(ServiceType o1, ServiceType o2) { + return o1.getCreated().get().compareToIgnoreCase(o2.getCreated().get()); + } + }; /** * Supports sorting services by deploymentRef @@ -596,46 +566,30 @@ public class InventoryController extends DashboardRestrictedBaseController { * @param request HttpServletRequest * @return List of ServiceTypes objects */ - @RequestMapping(value = { SERVICE_TYPES_PATH }, method = RequestMethod.GET, produces = "application/json") + @RequestMapping( + value = {SERVICE_TYPES_PATH}, + method = RequestMethod.GET, + produces = "application/json") @ResponseBody public String getServiceTypesByPage(HttpServletRequest request) { preLogAudit(request); - String json = null; - // json = getMockDataContent("/serviceTypesList.json"); - json = getItemListForPageWrapper(request, InventoryDataItem.SERVICE_TYPES, request.getParameter("sortBy"), - request.getParameter("searchBy")); + String json = getItemListForPageWrapper(request, InventoryDataItem.SERVICE_TYPES, + request.getParameter("sortBy"), request.getParameter("searchBy")); postLogAudit(request); return json; } - private String getMockDataContent(final String path) { - String result = null; - try { - InputStream is = getClass().getResourceAsStream(path); - if (is == null) - throw new Exception("Failed to find resource at path " + path); - Scanner scanner = new Scanner(is, "UTF-8"); - result = scanner.useDelimiter("\\A").next(); - scanner.close(); - is.close(); - } catch (Exception ex) { - logger.error("getMockDataContent failed", ex); - throw new RuntimeException(ex); - } - return result; - } - /** * Query Service objects matching a service type ID * */ - @RequestMapping(value = { DEP_IDS_FOR_TYPE }, method = RequestMethod.POST, produces = "application/json") - public String getServicesForType(HttpServletRequest request, @RequestBody String[] typeList) throws Exception { + @RequestMapping( + value = {DEP_IDS_FOR_TYPE}, + method = RequestMethod.POST, + produces = "application/json") + public String getServicesForType(HttpServletRequest request, @RequestBody String[] typeList) + throws Exception { preLogAudit(request); - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getId() == null) - throw new Exception("getControllerRestClient: Failed to get application user"); - InventoryClient inventoryClient = getInventoryClient(appUser.getId()); List<ServiceTypeServiceMap> result = new ArrayList<ServiceTypeServiceMap>(); for (String typeId : typeList) { ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); @@ -653,13 +607,16 @@ public class InventoryController extends DashboardRestrictedBaseController { * * @return List of Service objects */ - @RequestMapping(value = { SERVICES_PATH }, method = RequestMethod.GET, produces = "application/json") + @RequestMapping( + value = {SERVICES_PATH}, + method = RequestMethod.GET, + produces = "application/json") @ResponseBody public String getServicesByPage(HttpServletRequest request) { // preLogAudit(request); String json = null; - json = getItemListForPageWrapper(request, InventoryDataItem.SERVICES, request.getParameter("sortBy"), - request.getParameter("searchBy")); + json = getItemListForPageWrapper(request, InventoryDataItem.SERVICES, + request.getParameter("sortBy"), request.getParameter("searchBy")); postLogAudit(request); return json; } @@ -667,21 +624,22 @@ public class InventoryController extends DashboardRestrictedBaseController { /** * Gets the specified blueprint content for viewing. * - * @param id Blueprint ID + * @param id Blueprint ID * @param request HttpServletRequest * @return Blueprint as YAML; or error. * @throws Exception on serialization error * */ - @RequestMapping(value = { - VIEW_SERVICE_TYPE_BLUEPRINT_PATH + "/{typeid}" }, method = RequestMethod.GET, produces = "application/yaml") + @RequestMapping( + value = {VIEW_SERVICE_TYPE_BLUEPRINT_PATH + "/{typeid}"}, + method = RequestMethod.GET, + produces = "application/yaml") @ResponseBody - public String viewServiceTypeBlueprintContentById(@PathVariable("typeid") String typeId, HttpServletRequest request) - throws Exception { + public String viewServiceTypeBlueprintContentById(@PathVariable("typeid") String typeId, + HttpServletRequest request) throws Exception { preLogAudit(request); String json = null; try { - InventoryClient inventoryClient = getInventoryClient(request); json = objectMapper.writeValueAsString(inventoryClient.getServiceType(typeId).get()); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -690,27 +648,21 @@ public class InventoryController extends DashboardRestrictedBaseController { MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Viewing service type " + typeId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "viewServiceTypeBlueprintContentById caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); - } catch (JsonProcessingException jpe) { - // Should never, ever happen + logger.error(EELFLoggerDelegate.errorLogger, + "viewServiceTypeBlueprintContentById caught exception"); + json = + objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "DCAE Inventory"); MDC.put("TargetServiceName", "DCAE Inventory"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Viewing service type " + typeId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "viewServiceTypeBlueprintContentById caught exception"); - json = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Viewing service type " + typeId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "viewServiceTypeBlueprintContentById caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("getBlueprintContentById failed", t)); + logger.error(EELFLoggerDelegate.errorLogger, + "viewServiceTypeBlueprintContentById caught exception"); + json = objectMapper + .writeValueAsString(new RestResponseError("getBlueprintContentById failed", t)); } finally { postLogAudit(request); } @@ -720,23 +672,24 @@ public class InventoryController extends DashboardRestrictedBaseController { /** * Deletes the specified blueprint. * - * @param id Blueprint ID - * @param request HttpServletRequest + * @param id Blueprint ID + * @param request HttpServletRequest * @param response HttpServletResponse * @return status code on success; error on failure. * @throws Exception On serialization failure */ - @RequestMapping(value = { - SERVICE_TYPES_PATH + "/{typeid}" }, method = RequestMethod.DELETE, produces = "application/json") + @RequestMapping( + value = {SERVICE_TYPES_PATH + "/{typeid}"}, + method = RequestMethod.DELETE, + produces = "application/json") @ResponseBody - public String deleteServiceType(@PathVariable("typeid") String typeid, HttpServletRequest request, - HttpServletResponse response) throws Exception { + public String deleteServiceType(@PathVariable("typeid") String typeid, + HttpServletRequest request, HttpServletResponse response) throws Exception { preLogAudit(request); String json = "{\"202\": \"OK\"}"; try { - InventoryClient inventoryClient = getInventoryClient(request); inventoryClient.deleteServiceType(typeid); - } catch (ServiceTypeNotFoundException e) { + } catch (ServiceTypeNotFoundException | ServiceTypeAlreadyDeactivatedException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "DCAE Inventory"); MDC.put("TargetServiceName", "DCAE Inventory"); @@ -745,7 +698,7 @@ public class InventoryController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Deleting service type " + typeid + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (ServiceTypeAlreadyDeactivatedException e) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "DCAE Inventory"); MDC.put("TargetServiceName", "DCAE Inventory"); @@ -753,16 +706,8 @@ public class InventoryController extends DashboardRestrictedBaseController { MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Deleting service type " + typeid + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting service type " + typeid + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("deleteDeployment failed", t)); + json = objectMapper + .writeValueAsString(new RestResponseError("deleteDeployment failed", t)); } finally { postLogAudit(request); } @@ -772,32 +717,24 @@ public class InventoryController extends DashboardRestrictedBaseController { /** * Deletes the specified service i.e. deployment from inventory * - * @param id Service ID - * @param request HttpServletRequest + * @param id Service ID + * @param request HttpServletRequest * @param response HttpServletResponse * @return status code on success; error on failure. * @throws Exception On serialization failure */ - @RequestMapping(value = { - SERVICES_PATH + "/{serviceId}" }, method = RequestMethod.DELETE, produces = "application/json") + @RequestMapping( + value = {SERVICES_PATH + "/{serviceId}"}, + method = RequestMethod.DELETE, + produces = "application/json") @ResponseBody - public String deleteService(@PathVariable("serviceId") String serviceId, HttpServletRequest request, - HttpServletResponse response) throws Exception { + public String deleteService(@PathVariable("serviceId") String serviceId, + HttpServletRequest request, HttpServletResponse response) throws Exception { preLogAudit(request); String json = "{\"202\": \"OK\"}"; try { - InventoryClient inventoryClient = getInventoryClient(request); inventoryClient.deleteService(serviceId); - } catch (ServiceTypeNotFoundException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting service " + serviceId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (ServiceTypeAlreadyDeactivatedException e) { + } catch (ServiceNotFoundException | ServiceAlreadyDeactivatedException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "DCAE Inventory"); MDC.put("TargetServiceName", "DCAE Inventory"); @@ -806,7 +743,7 @@ public class InventoryController extends DashboardRestrictedBaseController { MDC.put("ErrorDescription", "Deleting service " + serviceId + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "DCAE Inventory"); MDC.put("TargetServiceName", "DCAE Inventory"); @@ -814,7 +751,8 @@ public class InventoryController extends DashboardRestrictedBaseController { MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Deleting service " + serviceId + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("deleteDeployment failed", t)); + json = objectMapper + .writeValueAsString(new RestResponseError("deleteDeployment failed", t)); } finally { postLogAudit(request); } @@ -824,22 +762,24 @@ public class InventoryController extends DashboardRestrictedBaseController { /** * Processes request to update a blueprint currently existing in DCAE Inventory. * - * @param request HttpServletRequest + * @param request HttpServletRequest * @param blueprint Cloudify blueprint * @return Blueprint as uploaded; or error. * @throws Exception on serialization error */ - @RequestMapping(value = { - SERVICE_TYPES_PATH + "/update" }, method = RequestMethod.POST, produces = "application/json") + @RequestMapping( + value = {SERVICE_TYPES_PATH + "/update"}, + method = RequestMethod.POST, + produces = "application/json") @ResponseBody - public String updateServiceTypeBlueprint(HttpServletRequest request, @RequestBody ServiceType serviceType) - throws Exception { + public String updateServiceTypeBlueprint(HttpServletRequest request, + @RequestBody ServiceType serviceType) throws Exception { preLogAudit(request); String json = "{\"201\": \"OK\"}"; try { // Verify that the Service Type can be parsed for inputs. Blueprint.parse(serviceType.getBlueprintTemplate()); - InventoryClient inventoryClient = getInventoryClient(request); + // InventoryClient inventoryClient = getInventoryClient(request); inventoryClient.addServiceType(serviceType); } catch (BlueprintParseException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -848,8 +788,10 @@ public class InventoryController extends DashboardRestrictedBaseController { MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Updating service type failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("Invalid blueprint format.", e)); + logger.error(EELFLoggerDelegate.errorLogger, + "updateServiceTypeBlueprint caught exception"); + json = objectMapper + .writeValueAsString(new RestResponseError("Invalid blueprint format.", e)); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "DCAE Inventory"); @@ -857,17 +799,21 @@ public class InventoryController extends DashboardRestrictedBaseController { MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Updating service type failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); - } catch (Throwable t) { + logger.error(EELFLoggerDelegate.errorLogger, + "updateServiceTypeBlueprint caught exception"); + json = + objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "DCAE Inventory"); MDC.put("TargetServiceName", "DCAE Inventory"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Updating service type failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("updateServiceTypeBlueprint failed", t)); + logger.error(EELFLoggerDelegate.errorLogger, + "updateServiceTypeBlueprint caught exception"); + json = objectMapper + .writeValueAsString(new RestResponseError("updateServiceTypeBlueprint failed", t)); } finally { postLogAudit(request); } @@ -877,21 +823,23 @@ public class InventoryController extends DashboardRestrictedBaseController { /** * Processes request to update a blueprint currently existing in DCAE Inventory. * - * @param request HttpServletRequest + * @param request HttpServletRequest * @param blueprint Cloudify blueprint * @return Blueprint as uploaded; or error. * @throws Exception on serialization error */ - @RequestMapping(value = { - SERVICE_TYPES_PATH + "/upload" }, method = RequestMethod.POST, produces = "application/json") + @RequestMapping( + value = {SERVICE_TYPES_PATH + "/upload"}, + method = RequestMethod.POST, + produces = "application/json") @ResponseBody public String uploadServiceTypeBlueprint(HttpServletRequest request, - @RequestBody ServiceTypeRequest serviceTypeRequest) throws Exception { + @RequestBody ServiceTypeRequest serviceTypeRequest) throws Exception { preLogAudit(request); String json = "{\"201\": \"OK\"}"; try { Blueprint.parse(serviceTypeRequest.getBlueprintTemplate()); - InventoryClient inventoryClient = getInventoryClient(request); + // InventoryClient inventoryClient = getInventoryClient(request); inventoryClient.addServiceType(serviceTypeRequest); } catch (BlueprintParseException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -900,8 +848,10 @@ public class InventoryController extends DashboardRestrictedBaseController { MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Updating service type failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("Invalid blueprint format.", e)); + logger.error(EELFLoggerDelegate.errorLogger, + "updateServiceTypeBlueprint caught exception"); + json = objectMapper + .writeValueAsString(new RestResponseError("Invalid blueprint format.", e)); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "DCAE Inventory"); @@ -909,17 +859,21 @@ public class InventoryController extends DashboardRestrictedBaseController { MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Updating service type failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); - } catch (Throwable t) { + logger.error(EELFLoggerDelegate.errorLogger, + "updateServiceTypeBlueprint caught exception"); + json = + objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "DCAE Inventory"); MDC.put("TargetServiceName", "DCAE Inventory"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); MDC.put("ErrorDescription", "Updating service type failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("updateServiceTypeBlueprint failed", t)); + logger.error(EELFLoggerDelegate.errorLogger, + "updateServiceTypeBlueprint caught exception"); + json = objectMapper + .writeValueAsString(new RestResponseError("updateServiceTypeBlueprint failed", t)); } finally { postLogAudit(request); } @@ -943,6 +897,7 @@ public class InventoryController extends DashboardRestrictedBaseController { MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, logDateFormat.format(end)); MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI()); + logger.info(EELFLoggerDelegate.metricsLogger, + request.getMethod() + request.getRequestURI()); } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRequest.java index ecb1da0..46b3351 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRequest.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRequest.java @@ -65,8 +65,10 @@ public class ServiceRequest { final Collection<ServiceComponent> serviceComponents = service.getComponents(); final Collection<ServiceComponentRequest> serviceComponentRequests = new ArrayList<ServiceComponentRequest>(); - for (ServiceComponent sc : serviceComponents) { - serviceComponentRequests.add(ServiceComponentRequest.from(sc)); + if (serviceComponents != null) { + for (ServiceComponent sc : serviceComponents) { + serviceComponentRequests.add(ServiceComponentRequest.from(sc)); + } } return new ServiceRequest(typeId, service.getVnfId(), service.getVnfType(), service.getVnfLocation(), diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyClient.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyClient.java index 4173f5e..1ffab54 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyClient.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyClient.java @@ -23,12 +23,9 @@ package org.onap.ccsdk.dashboard.rest; import java.util.Map; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintContent; import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintUpload; import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentRequest; import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateResponse; import org.onap.ccsdk.dashboard.model.CloudifyEventList; @@ -37,7 +34,6 @@ import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; -import org.onap.ccsdk.dashboard.model.CloudifySecret; import org.onap.ccsdk.dashboard.model.CloudifyTenantList; /** @@ -106,16 +102,6 @@ public interface CloudifyClient { public CloudifyNodeInstanceIdList getNodeInstanceId(String id, String tenant); /** - * Query execution information for a deployment ID and execution ID passed as - * inputs - * - * @param executionId - * @param deploymentId - * @return - */ - public CloudifyExecutionList getExecution(String executionId, String deploymentId); - - /** * Initiate a deployment update in cloudify * * @param execution @@ -161,23 +147,6 @@ public interface CloudifyClient { public CloudifyNodeInstanceList getNodeInstanceVersion(String bp_id, String tenant); /** - * Start Uninstall execution workflow in cloudify - * - * @param id - * @param ignoreLiveNodes - * @return - */ - public int deleteDeployment(String id, boolean ignoreLiveNodes); - - /** - * Start install execution workflow in cloudify - * - * @param deployment - * @return - */ - public CloudifyDeploymentList createDeployment(CloudifyDeploymentRequest deployment); - - /** * Query deployment object from cloudify * * @param id @@ -201,30 +170,6 @@ public interface CloudifyClient { public CloudifyDeploymentList getDeployments(); /** - * Remove blueprint referred by ID from cloudify - * - * @param id - * @return - */ - public int deleteBlueprint(String id); - - /** - * Upload blueprint into cloudify - * - * @param blueprint - * @return - */ - public CloudifyBlueprintList uploadBlueprint(CloudifyBlueprintUpload blueprint); - - /** - * View blueprint YAML text - * - * @param id - * @return - */ - public CloudifyBlueprintContent viewBlueprint(String id); - - /** * Query a blueprint object matching the blueprint ID in cloudify * * @param id @@ -234,13 +179,6 @@ public interface CloudifyClient { public CloudifyBlueprintList getBlueprint(String id, String tenant); /** - * Query all the blueprints in cloudify - * - * @return - */ - public CloudifyBlueprintList getBlueprints(); - - /** * Query deployment inputs for a deployment ID in the cloudify tenant * * @param id @@ -248,13 +186,4 @@ public interface CloudifyClient { * @return */ public CloudifyDeploymentList getDeploymentInputs(String id, String tenant); - - /** - * Query a secret object matching the input secret name in the cloudify tenant - * - * @param secretName - * @param tenant - * @return - */ - public CloudifySecret getSecret(String secretName, String tenant); } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyMockClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyMockClientImpl.java deleted file mode 100644 index bd9100e..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyMockClientImpl.java +++ /dev/null @@ -1,233 +0,0 @@ -/******************************************************************************* -* =============LICENSE_START========================================================= -* -* ================================================================================= -* Copyright (c) 2019 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========================================================= -* -* ECOMP is a trademark and service mark of AT&T Intellectual Property. -*******************************************************************************/ -package org.onap.ccsdk.dashboard.rest; - -import java.io.InputStream; -import java.util.Map; -import java.util.Scanner; - -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintContent; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintUpload; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentRequest; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateResponse; -import org.onap.ccsdk.dashboard.model.CloudifyEventList; -import org.onap.ccsdk.dashboard.model.CloudifyExecution; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; -import org.onap.ccsdk.dashboard.model.CloudifySecret; -import org.onap.ccsdk.dashboard.model.CloudifyTenantList; -import org.onap.ccsdk.dashboard.model.ECTransportModel; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * Provides mock implementations that return contents of files on the classpath. - */ -public class CloudifyMockClientImpl implements CloudifyClient { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CloudifyMockClientImpl.class); - - /** - * For mock outputs - */ - private final ObjectMapper objectMapper = new ObjectMapper(); - - private String getMockDataContent(final String path) { - String result = null; - try { - InputStream is = getClass().getResourceAsStream(path); - if (is == null) - throw new Exception("Failed to find resource at path " + path); - Scanner scanner = new Scanner(is, "UTF-8"); - result = scanner.useDelimiter("\\A").next(); - scanner.close(); - is.close(); - } catch (Exception ex) { - logger.error("getMockDataContent failed", ex); - throw new RuntimeException(ex); - } - return result; - } - - /** - * Creates an input stream using the specified path and requests the mapper - * create an object of the specified type. - * - * @param modelClass Model class - * @param path Path to classpath resource - * @return Instance of modelClass - */ - private ECTransportModel getMockData(final Class<? extends ECTransportModel> modelClass, final String path) { - ECTransportModel result = null; - String json = getMockDataContent(path); - try { - result = (ECTransportModel) objectMapper.readValue(json, modelClass); - } catch (Exception ex) { - logger.error("getMockData failed", ex); - throw new RuntimeException(ex); - } - return result; - } - - @Override - public CloudifyTenantList getTenants() { - return (CloudifyTenantList) getMockData(CloudifyTenantList.class, "/tenantsList.json"); - } - - @Override - public CloudifyDeployedTenantList getTenantInfoFromDeploy(String tenant) { - return (CloudifyDeployedTenantList) getMockData(CloudifyDeployedTenantList.class, "/serviceTenantList.json"); - - } - - @Override - public CloudifyNodeInstanceIdList getNodeInstanceId(String deploymentId, String nodeId, String tenant) { - return null; - } - - @Override - public CloudifyNodeInstanceIdList getNodeInstanceId(String deploymentId, String tenant) { - return null; - } - - @Override - public CloudifyNodeInstanceList getNodeInstanceVersion(String bpId, String tenant) { - return null; - } - - @Override - public CloudifyNodeInstanceList getNodeInstanceVersion(String deploymentId, String nodeId, String tenant) { - return null; - } - - @Override - public CloudifyDeploymentUpdateResponse updateDeployment(CloudifyDeploymentUpdateRequest execution) { - return null; - } - - @Override - public CloudifyEventList getEventlogs(String executionId, String tenant) { - return null; - } - - public CloudifyDeploymentList createDeployment(CloudifyDeploymentRequest deployment) { - logger.debug(EELFLoggerDelegate.debugLogger, "createDeployment: {}", deployment.toString()); - return new CloudifyDeploymentList(null, null); - } - - @Override - public CloudifyExecutionList getExecutions(final String deploymentId, final String tenant) { - return (CloudifyExecutionList) getMockData(CloudifyExecutionList.class, "/listExecutionForDeploymentID.json"); - } - - @Override - public CloudifyExecutionList getExecutionsSummary(final String deploymentId, final String tenant) { - return (CloudifyExecutionList) getMockData(CloudifyExecutionList.class, "/listExecutionForDeploymentID.json"); - } - - @Override - public CloudifyExecutionList getExecution(String executionId, String deploymentId) { - return (CloudifyExecutionList) getMockData(CloudifyExecutionList.class, "/listExecutionForDeploymentID.json"); - } - - @Override - public CloudifyExecution startExecution(CloudifyExecutionRequest execution) { - logger.debug(EELFLoggerDelegate.debugLogger, "startExecution: {}", execution.toString()); - return new CloudifyExecution(null, null, null, null, null, null, null, null, null, null, null, null); - } - - @Override - public CloudifyExecution cancelExecution(final String executionId, Map<String, String> parameters, - final String tenant) { - return null; - } - - public int deleteDeployment(String id, boolean ignoreLiveNodes) { - return 0; - } - - public CloudifyDeploymentList getDeployment(String id, String tenant) { - return null; - } - - public CloudifyDeploymentList getDeployment(String id) { - return null; - } - - public CloudifyDeploymentList getDeployments() { - return null; - } - - public int deleteBlueprint(String id) { - return 0; - } - - public CloudifyBlueprintList uploadBlueprint(CloudifyBlueprintUpload blueprint) { - return null; - } - - public CloudifyBlueprintContent viewBlueprint(String id) { - return null; - } - - public CloudifyBlueprintList getBlueprint(String id, String tenant) { - return null; - } - - public CloudifyBlueprintList getBlueprints() { - return null; - } - - /** - * Get the a cloudify secret - * - * @return CloudifySecret - */ - @Override - public CloudifySecret getSecret(String secretName, String tenant) { - return null; - } - - /** - * Simple test - * - * @param args blueprint ID - * @throws Exception On any failure - */ - public static void main(String[] args) throws Exception { - System.out.println("Testing paths and parsing mock data"); - } - - @Override - public CloudifyDeploymentList getDeploymentInputs(String id, String tenant) { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImpl.java index 3a4f2b1..28bd87c 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImpl.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImpl.java @@ -25,13 +25,12 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.Map; +import javax.annotation.PostConstruct; + import org.json.JSONObject; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintContent; import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintUpload; import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentRequest; import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateResponse; import org.onap.ccsdk.dashboard.model.CloudifyEventList; @@ -41,8 +40,8 @@ import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; import org.onap.ccsdk.dashboard.model.CloudifyNodeIdList; import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; -import org.onap.ccsdk.dashboard.model.CloudifySecret; import org.onap.ccsdk.dashboard.model.CloudifyTenantList; +import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; @@ -50,44 +49,45 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; +@org.springframework.stereotype.Service public class CloudifyRestClientImpl extends RestClientBase implements CloudifyClient { - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CloudifyRestClientImpl.class); - private final String baseUrl; - private final ObjectMapper objectMapper = new ObjectMapper(); - + private static EELFLoggerDelegate logger = + EELFLoggerDelegate.getLogger(CloudifyRestClientImpl.class); + private String baseUrl; private static final String BLUEPRINTS = "blueprints"; - private static final String VIEW_BLUEPRINTS = "viewblueprints"; private static final String DEPLOYMENTS = "deployments"; private static final String EXECUTIONS = "executions"; private static final String TENANTS = "tenants"; private static final String NODES = "nodes"; private static final String NODE_INSTANCES = "node-instances"; private static final String UPDATE_DEPLOYMENT = "update-deployment"; - private static final String SECRETS = "secrets"; private static final String EVENTS = "events"; private static final String TENANT = "tenant_name"; - public CloudifyRestClientImpl(String webapiUrl, String user, String pass) { - super(); - if (webapiUrl == null) + @PostConstruct + public void init() { + String webapiUrl = DashboardProperties.getControllerProperty("dev", + DashboardProperties.CONTROLLER_SUBKEY_URL); + if (webapiUrl == null) { throw new IllegalArgumentException("Null URL not permitted"); - + } + String user = DashboardProperties.getControllerProperty("dev", + DashboardProperties.CONTROLLER_SUBKEY_USERNAME); + String pass = DashboardProperties.getControllerProperty("dev", + DashboardProperties.CONTROLLER_SUBKEY_PASS); URL url = null; - String urlScheme = "http"; try { url = new URL(webapiUrl); baseUrl = url.toExternalForm(); } catch (MalformedURLException ex) { throw new RuntimeException("Failed to parse URL", ex); } - - urlScheme = webapiUrl.split(":")[0]; - createRestTemplate(url, user, pass, urlScheme); + String urlScheme = webapiUrl.split(":")[0]; + if (restTemplate == null) { + createRestTemplate(url, user, pass, urlScheme); + } } @Override @@ -151,10 +151,8 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl @Override public CloudifyNodeInstanceIdList getNodeInstanceId(final String bpId, String tenant) { - // GET - // /api/v3.1/nodes?deployment_id=clamp_967&type=onap.nodes.component&_include=id - String url = buildUrl(new String[] { baseUrl, NODES }, - new String[] { "deployment_id", bpId, "type", "onap.nodes.component", "_include", "id" }); + String url = buildUrl(new String[] {baseUrl, NODES}, + new String[] {"deployment_id", bpId, "type", "onap.nodes.component", "_include", "id"}); logger.debug(EELFLoggerDelegate.debugLogger, "getNodeInstanceId: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); ResponseEntity<CloudifyNodeIdList> response = restTemplate.exchange(url, HttpMethod.GET, entity, @@ -202,18 +200,6 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl } @Override - public CloudifyExecutionList getExecution(String executionId, String deploymentId) { - String url = buildUrl(new String[] { baseUrl, EXECUTIONS, executionId }, - new String[] { "deployment_id", deploymentId }); - logger.debug(EELFLoggerDelegate.debugLogger, "getExecution: url {}", url); - - ResponseEntity<CloudifyExecutionList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<CloudifyExecutionList>() { - }); - return response.getBody(); - } - - @Override public CloudifyExecution startExecution(CloudifyExecutionRequest execution) { String url = buildUrl(new String[] { baseUrl, EXECUTIONS }, null); logger.debug(EELFLoggerDelegate.debugLogger, "startExecution: url {}", url); @@ -243,19 +229,8 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl headers.set("Tenant", tenant); headers.set("Content-Type", "application/json"); HttpEntity<String> entity = new HttpEntity<String>(requestJson.toString(), headers); - ResponseEntity<CloudifyExecution> response = restTemplate.exchange(url, HttpMethod.POST, entity, - new ParameterizedTypeReference<CloudifyExecution>() { - }); - return response.getBody(); // getStatusCode().value(); - } - - @Override - public CloudifyBlueprintList getBlueprints() { - String url = buildUrl(new String[] { baseUrl, BLUEPRINTS }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "getBlueprints: url {}", url); - ResponseEntity<CloudifyBlueprintList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<CloudifyBlueprintList>() { - }); + ResponseEntity<CloudifyExecution> response = restTemplate.exchange(url, HttpMethod.POST, + entity, new ParameterizedTypeReference<CloudifyExecution>() {}); return response.getBody(); } @@ -271,32 +246,6 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl } @Override - public CloudifyBlueprintContent viewBlueprint(final String id) { - String url = buildUrl(new String[] { baseUrl, VIEW_BLUEPRINTS }, new String[] { "id", id }); - logger.debug(EELFLoggerDelegate.debugLogger, "viewBlueprint: url {}", url); - ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class); - String yaml = response.getBody(); - return new CloudifyBlueprintContent(id, yaml); - } - - @Override - public CloudifyBlueprintList uploadBlueprint(CloudifyBlueprintUpload blueprint) { - String url = buildUrl(new String[] { baseUrl, BLUEPRINTS }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "uploadBlueprint: url {}", url); - return restTemplate.postForObject(url, blueprint, CloudifyBlueprintList.class); - } - - @Override - public int deleteBlueprint(final String id) { - String url = buildUrl(new String[] { baseUrl, BLUEPRINTS, id }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteBlueprint: url {}", url); - ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, null, - new ParameterizedTypeReference<String>() { - }); - return response.getStatusCode().value(); - } - - @Override public CloudifyDeploymentList getDeployments() { String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, null); logger.debug(EELFLoggerDelegate.debugLogger, "getDeployments: url {}", url); @@ -332,43 +281,8 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, new String[] { "id", id, "_include", "inputs" }); logger.debug(EELFLoggerDelegate.debugLogger, "getDeployment: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyDeploymentList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyDeploymentList>() { - }); - return response.getBody(); - } - - @Override - public CloudifyDeploymentList createDeployment(CloudifyDeploymentRequest deployment) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "createDeployment: url {}", url); - return restTemplate.postForObject(url, deployment, CloudifyDeploymentList.class); - } - - @Override - public int deleteDeployment(final String id, boolean ignoreLiveNodes) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS, id }, - new String[] { "ignore_live_nodes", Boolean.toString(ignoreLiveNodes) }); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteDeployment: url {}", url); - ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, null, - new ParameterizedTypeReference<String>() { - }); - return response.getStatusCode().value(); - } - - /** - * Get a cloudify secret - * - * @return CloudifySecret - */ - @Override - public CloudifySecret getSecret(String secretName, String tenant) { - String url = buildUrl(new String[] { baseUrl, SECRETS, secretName }, new String[] { TENANT, tenant }); - logger.debug(EELFLoggerDelegate.debugLogger, "getSecrets: url {}", url); - ResponseEntity<CloudifySecret> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<CloudifySecret>() { - }); + ResponseEntity<CloudifyDeploymentList> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyDeploymentList>() {}); return response.getBody(); } - } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulMockClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulMockClientImpl.java deleted file mode 100644 index 30b1f30..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulMockClientImpl.java +++ /dev/null @@ -1,126 +0,0 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2019 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.rest; - -import java.io.InputStream; -import java.util.List; -import java.util.Scanner; - -import org.onap.ccsdk.dashboard.model.ConsulDatacenter; -import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; -import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; -import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; -import org.onap.ccsdk.dashboard.model.ECTransportModel; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class ConsulMockClientImpl implements ConsulClient { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulMockClientImpl.class); - - /** - * For mock outputs - */ - private final ObjectMapper objectMapper = new ObjectMapper(); - - private String getMockDataContent(final String path) { - String result = null; - try { - InputStream is = getClass().getResourceAsStream(path); - if (is == null) - throw new Exception("Failed to find resource at path " + path); - Scanner scanner = new Scanner(is, "UTF-8"); - result = scanner.useDelimiter("\\A").next(); - scanner.close(); - is.close(); - } catch (Exception ex) { - logger.error("getMockDataContent failed", ex); - throw new RuntimeException(ex); - } - return result; - } - - /** - * Creates an input stream using the specified path and requests the mapper - * create an object of the specified type. - * - * @param modelClass Model class - * @param path Path to classpath resource - * @return Instance of modelClass - */ - private ECTransportModel getMockData(final Class<? extends ECTransportModel> modelClass, final String path) { - ECTransportModel result = null; - String json = getMockDataContent(path); - try { - result = (ECTransportModel) objectMapper.readValue(json, modelClass); - } catch (Exception ex) { - logger.error("getMockData failed", ex); - throw new RuntimeException(ex); - } - return result; - } - - @Override - public List<ConsulServiceInfo> getServices(String datacenter) { - - return null; - } - - @Override - public List<ConsulServiceHealth> getServiceHealth(String datacenter, String srvcName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List<ConsulNodeInfo> getNodes(String datacenter) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List<ConsulServiceHealth> getNodeServicesHealth(String datacenter, String nodeId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List<ConsulDatacenter> getDatacenters() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String registerService(ConsulHealthServiceRegistration registration) { - // TODO Auto-generated method stub - return null; - } - - @Override - public int deregisterService(String serviceName) { - // TODO Auto-generated method stub - return 0; - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImpl.java index b48b8d4..2567577 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImpl.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImpl.java @@ -27,11 +27,14 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import javax.annotation.PostConstruct; + import org.json.JSONArray; import org.json.JSONObject; import org.onap.ccsdk.dashboard.model.ConsulDatacenter; import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration.EndpointCheck; +import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; @@ -46,10 +49,12 @@ import org.springframework.http.ResponseEntity; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +@org.springframework.stereotype.Service public class ConsulRestClientImpl extends RestClientBase implements ConsulClient { - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulRestClientImpl.class); - private final String baseUrl; + private static EELFLoggerDelegate logger = + EELFLoggerDelegate.getLogger(ConsulRestClientImpl.class); + private String baseUrl; private final ObjectMapper objectMapper = new ObjectMapper(); private static final String API_VER = "v1"; @@ -57,24 +62,24 @@ public class ConsulRestClientImpl extends RestClientBase implements ConsulClient private static final String SERVICES = "services"; private static final String HEALTH = "health"; private static final String CHECKS = "checks"; - private static final String HEALTH_SERVICES = "healthservices"; - public ConsulRestClientImpl(String webapiUrl, String user, String pass) { - super(); + @PostConstruct + public void init() { + String webapiUrl = DashboardProperties.getControllerProperty("dev", + DashboardProperties.CONTROLLER_SUBKEY_CONSUL_URL); if (webapiUrl == null) throw new IllegalArgumentException("Null URL not permitted"); - URL url = null; - String urlScheme = "http"; try { url = new URL(webapiUrl); baseUrl = url.toExternalForm(); } catch (MalformedURLException ex) { throw new RuntimeException("Failed to parse URL", ex); } - - urlScheme = webapiUrl.split(":")[0]; - createRestTemplate(url, user, pass, urlScheme); + String urlScheme = webapiUrl.split(":")[0]; + if (restTemplate == null) { + createRestTemplate(url, null, null, urlScheme); + } } @Override diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImpl.java index c03dff6..6e9ecb4 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImpl.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImpl.java @@ -26,6 +26,8 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.stream.Stream; +import javax.annotation.PostConstruct; + import org.onap.ccsdk.dashboard.exceptions.BadRequestException; import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; import org.onap.ccsdk.dashboard.exceptions.DownstreamException; @@ -36,6 +38,7 @@ import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentLink; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentsListResponse; +import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -49,45 +52,34 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; +@org.springframework.stereotype.Service public class DeploymentHandlerClientImpl extends RestClientBase implements DeploymentHandlerClient { - private final String baseUrl; - // private final RestTemplate restTemplate; + private String baseUrl; + private static final String DEPLOYMENTS = "dcae-deployments"; private static final String UPDATE_PATH = "dcae-deployment-update"; protected final ObjectMapper objectMapper = new ObjectMapper(); - public DeploymentHandlerClientImpl(String webapiUrl) { - this(webapiUrl, null, null); - } - - /** - * Builds a restTemplate. If username and password are supplied, uses basic HTTP - * authentication. - * - * @param webapiUrl URL of the web endpoint - * @param user user name; ignored if null - * @param pass password - */ - public DeploymentHandlerClientImpl(String webapiUrl, String user, String pass) { - super(); + @PostConstruct + public void init() { + String webapiUrl = DashboardProperties.getControllerProperty("dev", + DashboardProperties.CONTROLLER_SUBKEY_DHANDLER_URL); if (webapiUrl == null) throw new IllegalArgumentException("Null URL not permitted"); URL url = null; - String urlScheme = "http"; try { url = new URL(webapiUrl); baseUrl = url.toExternalForm(); } catch (MalformedURLException ex) { throw new RuntimeException("Failed to parse URL", ex); } - urlScheme = webapiUrl.split(":")[0]; - createRestTemplate(url, user, pass, urlScheme); - // Do not serialize null values - objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - // Register Jdk8Module() for Stream and Optional types - objectMapper.registerModule(new Jdk8Module()); + String urlScheme = webapiUrl.split(":")[0]; + if (restTemplate == null) { + createRestTemplate(url, null, null, urlScheme); + } + } public Stream<DeploymentLink> getDeployments() { diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/InventoryClient.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/InventoryClient.java index 0e93a39..1b93bc7 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/InventoryClient.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/InventoryClient.java @@ -148,9 +148,9 @@ public interface InventoryClient { * * @return Set<InventoryProperty> */ - - public Set<InventoryProperty> getPropertiesOfServices(String propertyName); - + /* + * public Set<InventoryProperty> getPropertiesOfServices(String propertyName); + */ /** * Gets a single DCAE Service object corresponding to the specified serviceId. * diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImpl.java index ebe7e4f..c1296f0 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImpl.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImpl.java @@ -33,6 +33,8 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +import javax.annotation.PostConstruct; + import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceAlreadyDeactivatedException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; @@ -51,34 +53,26 @@ import org.onap.ccsdk.dashboard.model.inventory.ServiceType; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeList; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; +import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; +@org.springframework.stereotype.Service public class RestInventoryClientImpl extends RestClientBase implements InventoryClient { - private final String baseUrl; - // private final RestTemplate restTemplate; + private String baseUrl; public static final String SERVICE_TYPES = "dcae-service-types"; public static final String SERVICES = "dcae-services"; public static final String SERVICES_GROUPBY = "dcae-services-groupby"; - public RestInventoryClientImpl(String webapiUrl) { - this(webapiUrl, null, null); - } - - /** - * Builds a restTemplate. If username and password are supplied, uses basic HTTP - * authentication. - * - * @param webapiUrl URL of the web endpoint - * @param user user name; ignored if null - * @param pass password - */ - public RestInventoryClientImpl(String webapiUrl, String user, String pass) { - super(); + @PostConstruct + public void init() { + String webapiUrl = DashboardProperties.getControllerProperty("dev", + DashboardProperties.CONTROLLER_SUBKEY_INVENTORY_URL); if (webapiUrl == null) throw new IllegalArgumentException("Null URL not permitted"); URL url = null; @@ -90,7 +84,10 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory throw new RuntimeException("Failed to parse URL", ex); } urlScheme = webapiUrl.split(":")[0]; - createRestTemplate(url, user, pass, urlScheme); + if (restTemplate == null) { + createRestTemplate(url, null, null, urlScheme); + } + } public Stream<ServiceType> getServiceTypes() { @@ -311,14 +308,14 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory return collection.stream(); } - public Set<InventoryProperty> getPropertiesOfServices(String propertyName) { - String url = buildUrl(new String[] { baseUrl, SERVICES_GROUPBY, propertyName }, null); - ResponseEntity<ServiceGroupByResults> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceGroupByResults>() { - }); - return response.getBody().propertyValues; - } - + /* + * public Set<InventoryProperty> getPropertiesOfServices(String propertyName) { + * String url = buildUrl(new String[] {baseUrl, SERVICES_GROUPBY, propertyName}, + * null); ResponseEntity<ServiceGroupByResults> response = + * restTemplate.exchange(url, HttpMethod.GET, null, new + * ParameterizedTypeReference<ServiceGroupByResults>() { }); return + * response.getBody().propertyValues; } + */ public Optional<Service> getService(String serviceId) { String url = buildUrl(new String[] { baseUrl, SERVICES, serviceId }, null); ResponseEntity<Service> response = restTemplate.exchange(url, HttpMethod.GET, null, diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientMockImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientMockImpl.java deleted file mode 100644 index 5a422c0..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientMockImpl.java +++ /dev/null @@ -1,189 +0,0 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2019 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.rest; - -import java.io.InputStream; -import java.util.Collection; -import java.util.Optional; -import java.util.Scanner; -import java.util.Set; -import java.util.stream.Stream; - -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceAlreadyDeactivatedException; -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException; -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException; -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; -import org.onap.ccsdk.dashboard.model.ECTransportModel; -import org.onap.ccsdk.dashboard.model.inventory.InventoryProperty; -import org.onap.ccsdk.dashboard.model.inventory.Service; -import org.onap.ccsdk.dashboard.model.inventory.ServiceList; -import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; -import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; -import org.onap.ccsdk.dashboard.model.inventory.ServiceType; -import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeList; -import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; -import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; - -public class RestInventoryClientMockImpl implements InventoryClient { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestInventoryClientMockImpl.class); - /** - * For mock outputs - */ - private final ObjectMapper objectMapper = new ObjectMapper(); - - public RestInventoryClientMockImpl() { - // Do not serialize null values - objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - // Register Jdk8Module() for Stream and Optional types - objectMapper.registerModule(new Jdk8Module()); - } - - private String getMockDataContent(final String path) { - String result = null; - try { - InputStream is = getClass().getResourceAsStream(path); - if (is == null) - throw new Exception("Failed to find resource at path " + path); - Scanner scanner = new Scanner(is, "UTF-8"); - result = scanner.useDelimiter("\\A").next(); - scanner.close(); - is.close(); - } catch (Exception ex) { - logger.error("getMockDataContent failed", ex); - throw new RuntimeException(ex); - } - return result; - } - - /** - * Creates an input stream using the specified path and requests the mapper - * create an object of the specified type. - * - * @param modelClass Model class - * @param path Path to classpath resource - * @return Instance of modelClass - */ - private ECTransportModel getMockData(final Class<? extends ECTransportModel> modelClass, final String path) { - ECTransportModel result = null; - String json = getMockDataContent(path); - try { - result = (ECTransportModel) objectMapper.readValue(json, modelClass); - } catch (Exception ex) { - logger.error("getMockData failed", ex); - throw new RuntimeException(ex); - } - return result; - } - - @Override - public Stream<ServiceType> getServiceTypes() { - ServiceTypeList mockData = (ServiceTypeList) getMockData(ServiceTypeList.class, "/serviceTypesList.json"); - Collection<ServiceType> collection = mockData.items; - - return collection.stream(); - } - - @Override - public Stream<ServiceType> getServiceTypes(ServiceTypeQueryParams serviceTypeQueryParams) { - ServiceTypeList mockData = (ServiceTypeList) getMockData(ServiceTypeList.class, "/serviceTypesList.json"); - Collection<ServiceType> collection = mockData.items; - - return collection.stream(); - } - - @Override - public ServiceRefList getServicesForType(ServiceQueryParams serviceQueryParams) { - return null; - } - - @Override - public ServiceType addServiceType(ServiceType serviceType) throws ServiceTypeActiveException { - // TODO Auto-generated method stub - return null; - } - - @Override - public ServiceType addServiceType(ServiceTypeRequest serviceTypeRequest) throws ServiceTypeActiveException { - // TODO Auto-generated method stub - return null; - } - - @Override - public Optional<ServiceType> getServiceType(String typeId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void deleteServiceType(String typeId) - throws ServiceTypeNotFoundException, ServiceTypeAlreadyDeactivatedException { - // TODO Auto-generated method stub - - } - - @Override - public Stream<Service> getServices() { - ServiceList mockData = (ServiceList) getMockData(ServiceList.class, "/serviceList.json"); - Collection<Service> collection = mockData.items; - - return collection.stream(); - } - - @Override - public Stream<Service> getServices(ServiceQueryParams serviceQueryParams) { - ServiceList mockData = (ServiceList) getMockData(ServiceList.class, "/serviceList.json"); - Collection<Service> collection = mockData.items; - - return collection.stream(); - } - - @Override - public Set<InventoryProperty> getPropertiesOfServices(String propertyName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Optional<Service> getService(String serviceId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void putService(String typeId, Service service) { - // TODO Auto-generated method stub - - } - - @Override - public void deleteService(String serviceId) throws ServiceNotFoundException, ServiceAlreadyDeactivatedException { - // TODO Auto-generated method stub - - } -} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java index 0a5fe93..d6e1fb0 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java @@ -2,110 +2,526 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 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. + * 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========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ + package org.onap.ccsdk.dashboard.controller; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; +import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.ccsdk.dashboard.core.MockUser; +import org.onap.ccsdk.dashboard.core.MockitoTestSuite; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprint; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; +import org.onap.ccsdk.dashboard.model.CloudifyDeployment; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateResponse; +import org.onap.ccsdk.dashboard.model.CloudifyEvent; +import org.onap.ccsdk.dashboard.model.CloudifyEventList; +import org.onap.ccsdk.dashboard.model.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstance; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceId; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; +import org.onap.ccsdk.dashboard.model.CloudifyTenant; import org.onap.ccsdk.dashboard.model.CloudifyTenantList; import org.onap.ccsdk.dashboard.rest.CloudifyClient; -import org.onap.ccsdk.dashboard.core.MockitoTestSuite; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.web.support.UserUtils; -import org.springframework.test.web.servlet.RequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; + import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.http.MediaType; +public class CloudifyControllerTest extends MockitoTestSuite { + @Mock + private CloudifyClient restClient; -public class CloudifyControllerTest extends MockitoTestSuite { + @InjectMocks + private CloudifyController subject = new CloudifyController(); + + protected final ObjectMapper objectMapper = new ObjectMapper(); + + @Mock + UserUtils userUtils = new UserUtils(); + + @Mock + User epuser; + + MockUser mockUser = new MockUser(); + + HttpClientErrorException httpException; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + objectMapper.registerModule(new Jdk8Module()); + httpException = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "statusText"); + } + + @SuppressWarnings("unchecked") + @Test + public final void testGetTenants() throws Exception { + String tenantsList = + "{\"items\": [{\"id\": 1, \"name\": \"default_tenant\", \"dName\": \"default_tenant\" }, " + + "{\"id\": 2, \"name\": \"dyh1b1902\", \"dName\": \"dyh1b1902\"}], " + + "\"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; + CloudifyTenantList sampleData = null; + try { + sampleData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); + } catch (Exception e) { + } + + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(restClient.getTenants()).thenReturn(sampleData).thenThrow(Exception.class); + /* + * RequestBuilder request = MockMvcRequestBuilders. get("/tenants"). + * accept(MediaType.APPLICATION_JSON); + */ + String tenantStr = subject.getTenants(mockedRequest); + assertTrue(tenantStr.contains("dyh1b")); + + tenantStr = subject.getTenants(mockedRequest); + assertTrue(tenantStr.contains("error")); + } + + @SuppressWarnings({"unchecked", "unchecked"}) + @Test + public final void testGetBlueprintById() throws Exception { + + CloudifyBlueprint cldBp = + new CloudifyBlueprint("file1", "description1", "343242", "3423423", "id1", null); + + List<CloudifyBlueprint> items = new ArrayList<CloudifyBlueprint>(); + items.add(cldBp); + + CloudifyBlueprintList.Metadata.Pagination pageObj = + new CloudifyBlueprintList.Metadata.Pagination(1, 0, 1); + + CloudifyBlueprintList.Metadata metadata = new CloudifyBlueprintList.Metadata(pageObj); + + CloudifyBlueprintList cldBpList = new CloudifyBlueprintList(items, metadata); + + when(restClient.getBlueprint(Mockito.any(), Mockito.any())).thenReturn(cldBpList) + .thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = subject.getBlueprintById("id1", "tenant1", mockedRequest); + assertTrue(actualResult.contains("id1")); + + actualResult = subject.getBlueprintById("id1", "tenant1", mockedRequest); + assertTrue(actualResult.contains("error")); + + actualResult = subject.getBlueprintById("id1", "tenant1", mockedRequest); + assertTrue(actualResult.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetDeploymentById() throws Exception { + + CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id1", null, null, null, null, null, null, null, "tenant1"); + + List<CloudifyDeployment> items = new ArrayList<CloudifyDeployment>(); + items.add(cldDepl); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); + + when(restClient.getDeployment(Mockito.any(), Mockito.any())).thenReturn(cldDeplList) + .thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = subject.getDeploymentById("id1", "tenant1", mockedRequest); + assertTrue(actualResult.contains("id1")); + + actualResult = subject.getDeploymentById("id1", "tenant1", mockedRequest); + assertTrue(actualResult.contains("error")); + + actualResult = subject.getDeploymentById("id1", "tenant1", mockedRequest); + assertTrue(actualResult.contains("error")); + + when(restClient.getDeployment(Mockito.any())).thenReturn(cldDeplList) + .thenThrow(Exception.class).thenThrow(httpException); + + actualResult = subject.getDeploymentById("id1", "", mockedRequest); + assertTrue(actualResult.contains("id1")); + + actualResult = subject.getDeploymentById("id1", null, mockedRequest); + assertTrue(actualResult.contains("error")); + + actualResult = subject.getDeploymentById("id1", null, mockedRequest); + assertTrue(actualResult.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetTenantStatusForService() throws Exception { + + String[] deplIds = {"id1", "id2"}; + + CloudifyDeployedTenant cldDeplTenant = new CloudifyDeployedTenant("id1", "bp1", "tenant1"); + + List<CloudifyDeployedTenant> cldDeplTenantList = new ArrayList<CloudifyDeployedTenant>(); + + cldDeplTenantList.add(cldDeplTenant); + + CloudifyDeployedTenantList cldDeployedTenantList = + new CloudifyDeployedTenantList(cldDeplTenantList, null); + + CloudifyTenant cldTenant = new CloudifyTenant("tenant1", "tenant1", "tenant_id1"); + + List<CloudifyTenant> cldfyTenantList = new ArrayList<CloudifyTenant>(); + cldfyTenantList.add(cldTenant); + + CloudifyTenantList cloudifyTenantList = new CloudifyTenantList(cldfyTenantList, null); + + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null, false, false); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + Map<String, Object> plan = new HashMap<String, Object>(); + HashMap<String, String> plugins_to_install = new HashMap<String, String>(); + plugins_to_install.put("name", "helm-plugin"); + ArrayList<HashMap<String, String>> deployment_plugins_to_install = + new ArrayList<HashMap<String, String>>(); + + deployment_plugins_to_install.add(plugins_to_install); + plan.put("deployment_plugins_to_install", deployment_plugins_to_install); + + Map<String, String> workflows = new HashMap<String, String>(); + workflows.put("status", "workflowshelm"); + plan.put("workflows", workflows); + + CloudifyBlueprint cldBp = + new CloudifyBlueprint("file1", "description1", "343242", "3423423", "id1", plan); + + List<CloudifyBlueprint> items = new ArrayList<CloudifyBlueprint>(); + items.add(cldBp); + + CloudifyBlueprintList.Metadata.Pagination pageObj = + new CloudifyBlueprintList.Metadata.Pagination(1, 0, 1); + + CloudifyBlueprintList.Metadata metadata = new CloudifyBlueprintList.Metadata(pageObj); + + CloudifyBlueprintList cldBpList = new CloudifyBlueprintList(items, metadata); + + when(restClient.getTenants()).thenReturn(cloudifyTenantList); + + when(restClient.getTenantInfoFromDeploy(Mockito.any())).thenReturn(cldDeployedTenantList); + + when(restClient.getExecutionsSummary(Mockito.any(), Mockito.any())) + .thenReturn(cloudifyExecutionList); + + when(restClient.getBlueprint(Mockito.any(), Mockito.any())).thenReturn(cldBpList) + .thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = subject.getTenantStatusForService(mockedRequest, deplIds); + assertTrue(actualResult.contains("successful")); + + actualResult = subject.getTenantStatusForService(mockedRequest, deplIds); + assertTrue(actualResult.contains("error")); + + actualResult = subject.getTenantStatusForService(mockedRequest, deplIds); + assertTrue(actualResult.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetExecutionsByPage() throws Exception { + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null, false, false); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); + + List<CloudifyDeployment> cfyDeployItems = new ArrayList<CloudifyDeployment>(); + cfyDeployItems.add(cldDeployment); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); + + when(restClient.getDeployments()).thenReturn(cldDeployList); + when(restClient.getExecutions(Mockito.any(), Mockito.any())) + .thenReturn(cloudifyExecutionList).thenThrow(Exception.class) + .thenReturn(cloudifyExecutionList); + + String actualResult = + subject.getExecutionsByPage(mockedRequest, "id1", "successful", "tenant1"); + assertTrue(actualResult.contains("successful")); + + actualResult = subject.getExecutionsByPage(mockedRequest, "id1", "successful", "tenant1"); + assertTrue(actualResult.contains("error")); + + actualResult = subject.getExecutionsByPage(mockedRequest, null, "successful", "tenant1"); + assertTrue(actualResult.contains("successful")); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetExecutionByIdAndDeploymentId() throws Exception { + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null, false, false); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + when(restClient.getExecutions(Mockito.any(), Mockito.any())) + .thenReturn(cloudifyExecutionList).thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = subject.getExecutionByIdAndDeploymentId("execution_id", + "deployment_id", "tenant", mockedRequest); + assertTrue(actualResult.contains("successful")); + + actualResult = subject.getExecutionByIdAndDeploymentId("execution_id", "deployment_id", + "tenant", mockedRequest); + assertTrue(actualResult.contains("error")); + + actualResult = subject.getExecutionByIdAndDeploymentId("execution_id", "deployment_id", + "tenant", mockedRequest); + assertTrue(actualResult.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetExecutionEventsById() throws Exception { + + CloudifyEvent cfyEvent1 = new CloudifyEvent("blueprint_id", "deployment_id", null, "log", + "execution_id", "debug", "logger", "message", "node_instance_id", "node_name", + "operation", "reported_timestamp", "timestamp", "cloudify_log", "workflow_id"); + CloudifyEvent cfyEvent2 = new CloudifyEvent("blueprint_id", "deployment_id", null, "log", + "execution_id", "debug", "logger", "message", "node_instance_id", "node_name", + "operation", "reported_timestamp", "timestamp", "type2", "workflow_id"); + + List<CloudifyEvent> cfyEventItems = new ArrayList<CloudifyEvent>(); + cfyEventItems.add(cfyEvent1); + cfyEventItems.add(cfyEvent2); + + CloudifyEventList cfyEventsList = new CloudifyEventList(cfyEventItems, null); + + when(restClient.getEventlogs(Mockito.any(), Mockito.any())).thenReturn(cfyEventsList) + .thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = + subject.getExecutionEventsById("execution1", "false", "tenant", mockedRequest); + assertTrue(actualResult.contains("execution_id")); + + actualResult = + subject.getExecutionEventsById("execution1", "false", "tenant", mockedRequest); + assertTrue(actualResult.contains("error")); + + actualResult = + subject.getExecutionEventsById("execution1", "false", "tenant", mockedRequest); + assertTrue(actualResult.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public void testStartExecution() throws Exception { + CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "install", + false, "bp1", "id1", "tenant1", "error", "execution_id1", null, false, false); + + Map<String, Object> params = new HashMap<String, Object>(); + params.put("key1", "value1"); + + CloudifyExecutionRequest cfyExecReq = new CloudifyExecutionRequest("deployment_id", + "upgrade", false, false, "tenant1", params); + + CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); + + List<CloudifyNodeInstanceId> cfyNodeInstItems = new ArrayList<CloudifyNodeInstanceId>(); + + cfyNodeInstItems.add(cfyNodeInst); + + CloudifyNodeInstanceIdList cfyNodeInstList = + new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); + + when(restClient.getNodeInstanceId(Mockito.any(), Mockito.any())) + .thenReturn(cfyNodeInstList); + + when(restClient.startExecution(Matchers.<CloudifyExecutionRequest>any())) + .thenReturn(cfyExecObj).thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = subject.startExecution(mockedRequest, cfyExecReq); + assertTrue(actualResult.contains("execution_id1")); + + actualResult = subject.startExecution(mockedRequest, cfyExecReq); + assertTrue(actualResult.contains("error")); + + actualResult = subject.startExecution(mockedRequest, cfyExecReq); + assertTrue(actualResult.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public void testUpdateDeployment() throws Exception { + + CloudifyDeploymentUpdateRequest cfyDeployUpdateReq = + new CloudifyDeploymentUpdateRequest("deployment_id", "update", false, false, + "node_instance_id1", "4", "1000", "image", 2, "my_container"); + + CloudifyDeploymentUpdateResponse cfyDeployUpdateResp = new CloudifyDeploymentUpdateResponse( + "terminated", "created_at", "update", false, "blueprint_id", "deployment_id", "", "id1", + null, "tenant1", "junit", false, "resource_availability"); + + when(restClient.updateDeployment(Matchers.<CloudifyDeploymentUpdateRequest>any())) + .thenReturn(cfyDeployUpdateResp).thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = subject.updateDeployment(mockedRequest, cfyDeployUpdateReq); + assertTrue(actualResult.contains("terminated")); + + actualResult = subject.updateDeployment(mockedRequest, cfyDeployUpdateReq); + assertTrue(actualResult.contains("error")); + + actualResult = subject.updateDeployment(mockedRequest, cfyDeployUpdateReq); + assertTrue(actualResult.contains("error")); + + } + + @SuppressWarnings("unchecked") + @Test + public void testGetNodeInstanceId() throws Exception { + + CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); + + List<CloudifyNodeInstanceId> cfyNodeInstItems = new ArrayList<CloudifyNodeInstanceId>(); + + cfyNodeInstItems.add(cfyNodeInst); + + CloudifyNodeInstanceIdList cfyNodeInstList = + new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); + + when(restClient.getNodeInstanceId(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(cfyNodeInstList).thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = + subject.getNodeInstanceId("deploymentId", "tenant", "nodeId", mockedRequest); + assertTrue(actualResult.contains("node_instance_id1")); + + actualResult = subject.getNodeInstanceId("deploymentId", "tenant", "nodeId", mockedRequest); + assertTrue(actualResult.contains("error")); + + actualResult = subject.getNodeInstanceId("deploymentId", "tenant", "nodeId", mockedRequest); + assertTrue(actualResult.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetDeploymentRevisions() throws Exception { + + CloudifyNodeInstance cfyNodeInstance = new CloudifyNodeInstance("id1", null); + + List<CloudifyNodeInstance> cfyNodeInstanceItems = new ArrayList<CloudifyNodeInstance>(); + cfyNodeInstanceItems.add(cfyNodeInstance); + + CloudifyNodeInstanceList cfyNodeInstList = + new CloudifyNodeInstanceList(cfyNodeInstanceItems, null); + + when(restClient.getNodeInstanceVersion(Mockito.any(), Mockito.any())) + .thenReturn(cfyNodeInstList).thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = + subject.getDeploymentRevisions("deploymentId", "tenant", mockedRequest); + assertTrue(actualResult.contains("id1")); + + actualResult = subject.getDeploymentRevisions("deploymentId", "tenant", mockedRequest); + assertTrue(actualResult.contains("error")); + + actualResult = subject.getDeploymentRevisions("deploymentId", "tenant", mockedRequest); + assertTrue(actualResult.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public void testCancelExecution() throws Exception { + List<String> tenants = new ArrayList<String>(); + tenants.add("tenant1"); + + HttpHeaders httpHeader = new HttpHeaders(); + httpHeader.put("tenant", tenants); + + CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "cancel", + false, "bp1", "id1", "tenant1", "error", "execution_id1", null, false, false); + + when(restClient.cancelExecution(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(cfyExecObj).thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = + subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); + assertTrue(actualResult.contains("execution_id1")); - @Mock - private CloudifyClient restClient; - - @InjectMocks - private CloudifyController subject = new CloudifyController(); - - protected final ObjectMapper objectMapper = new ObjectMapper(); - - @Mock - UserUtils userUtils = new UserUtils(); - - @Mock - User epuser; - - MockUser mockUser = new MockUser(); - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - objectMapper.registerModule(new Jdk8Module()); - } - - @Test - public final void testGetControllerEndpoints_stubbed() { - - } - - @Test - public final void testGetTenants_stubbed() throws Exception { - - String tenantsList = - "{\"items\": [{\"id\": 1, \"name\": \"default_tenant\", \"dName\": \"default_tenant\" }, " - + "{\"id\": 2, \"name\": \"dyh1b1902\", \"dName\": \"dyh1b1902\"}], " - + "\"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; - CloudifyTenantList sampleData = null; - try { - sampleData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); - } catch (Exception e) { - } - - User user = mockUser.mockUser(); - user.setLoginId("tester"); - MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - - Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - Mockito.when(restClient.getTenants()).thenReturn(sampleData); - - RequestBuilder request = MockMvcRequestBuilders. - get("/tenants"). - accept(MediaType.APPLICATION_JSON); - - String tenantStr = - subject.getTenants(mockedRequest); - - assertNotNull(tenantStr); - assertTrue(tenantStr.contains("dyh1b")); - - - } + actualResult = + subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); + assertTrue(actualResult.contains("error")); + actualResult = + subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); + assertTrue(actualResult.contains("error")); + } } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CommonApiControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CommonApiControllerTest.java new file mode 100644 index 0000000..7097275 --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CommonApiControllerTest.java @@ -0,0 +1,791 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.controller; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.dashboard.core.MockUser; +import org.onap.ccsdk.dashboard.core.MockitoTestSuite; +import org.onap.ccsdk.dashboard.domain.EcdComponent; +import org.onap.ccsdk.dashboard.exceptions.BadRequestException; +import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.DownstreamException; +import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; +import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; +import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; +import org.onap.ccsdk.dashboard.model.CloudifyDeployment; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; +import org.onap.ccsdk.dashboard.model.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstance; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceId; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; +import org.onap.ccsdk.dashboard.model.CloudifyTenant; +import org.onap.ccsdk.dashboard.model.CloudifyTenantList; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentInput; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponseLinks; +import org.onap.ccsdk.dashboard.model.inventory.Service; +import org.onap.ccsdk.dashboard.model.inventory.ServiceList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRef; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceType; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeUploadRequest; +import org.onap.ccsdk.dashboard.rest.CloudifyClient; +import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; +import org.onap.ccsdk.dashboard.rest.InventoryClient; +import org.onap.ccsdk.dashboard.service.ControllerEndpointService; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.client.HttpStatusCodeException; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +public class CommonApiControllerTest extends MockitoTestSuite { + + @Mock + private CloudifyClient cfyClient; + + @Mock + private InventoryClient inventoryClient; + + @Mock + DeploymentHandlerClient deploymentHandlerClient; + + @Mock + ControllerEndpointService controllerEndpointService; + + @InjectMocks + CommonApiController subject = new CommonApiController(); + + private HttpStatusCodeException httpException = + new HttpServerErrorException(HttpStatus.BAD_GATEWAY); + + protected final ObjectMapper objectMapper = new ObjectMapper(); + + HttpServletRequest mockedRequest; + HttpServletResponse mockedResponse; + + MockUser mockUser = new MockUser(); + ServiceList deplList = null; + Service deplItem = null; + + ServiceType bpItem = null; + ServiceType bpItem2 = null; + ServiceTypeList bpList = null; + ServiceTypeList bpList2 = null; + + ServiceTypeRequest bpUploadItem = null; + + BadRequestException badReqError; + ServiceAlreadyExistsException srvcExistError; + ServerErrorException serverError; + DownstreamException downStrmError; + JsonProcessingException jsonError; + DeploymentNotFoundException notFoundError; + private ServiceTypeNotFoundException serviceTypeException = + new ServiceTypeNotFoundException("Invalid blueprint"); + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + objectMapper.registerModule(new Jdk8Module()); + getExpectedDeployments(); + getExpectedBueprints(); + createBpUploadItem(); + mockedRequest = getMockedRequest(); + mockedResponse = getMockedResponse(); + badReqError = new BadRequestException("bad request"); + srvcExistError = new ServiceAlreadyExistsException("service already exists"); + serverError = new ServerErrorException("Error occured in server"); + downStrmError = new DownstreamException("error occured in downstream"); + notFoundError = new DeploymentNotFoundException("item not found"); + } + + public void getExpectedDeployments() + throws JsonParseException, JsonMappingException, IOException { + + deplItem = new Service("dcae_dtiapi_1902", null, "1552335532348", "1552335532348", null, + "dummyVnfId", null, "dummyVnfType", "dummyLocation", "dcae_dtiapi_1902", null); + Collection<Service> items = new ArrayList<Service>(); + items.add(deplItem); + + String pageLinks = + "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; + ServiceList.PaginationLinks paginationLinks = + objectMapper.readValue(pageLinks, ServiceList.PaginationLinks.class); + int totalCount = 1; + deplList = new ServiceList(items, totalCount, paginationLinks); + + } + + public void getExpectedBueprints() + throws JsonParseException, JsonMappingException, IOException { + bpItem = new ServiceType.Builder("xyz1731", "xyz1731-helm-1906", 1906, + "tosca_definitions_version: cloudify_dsl_1_3", "", "app1", "comp1").build(); + + Collection<ServiceType> items = new ArrayList<ServiceType>(); + items.add(bpItem); + + String pageLinks2 = + "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; + ServiceTypeList.PaginationLinks paginationLinks = + objectMapper.readValue(pageLinks2, ServiceTypeList.PaginationLinks.class); + int totalCount = 1; + bpList = new ServiceTypeList(items, totalCount, paginationLinks); + + bpItem2 = new ServiceType("xyz1731", "xyz1731-helm-1907", 1906, + "tosca_definitions_version: cloudify_dsl_1_3\\r\\nimports:\\r\\n - http://www.getcloudify.org/spec/cloudify/4.2/types.yaml\\r\\n", + "app1", "comp1", null, null, null, null, null, null, "typeId", null, "created", null, + true); + + Collection<ServiceType> items2 = new ArrayList<ServiceType>(); + items2.add(bpItem2); + + bpList2 = new ServiceTypeList(items2, totalCount, paginationLinks); + } + + public void createBpUploadItem() { + bpUploadItem = ServiceTypeRequest.from(bpItem); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public final void testInsertComponent() throws Exception { + EcdComponent component1 = new EcdComponent(); + + component1.setCname("comp1"); + component1.setCompId(100L); + component1.setDname("COMP1"); + + doNothing().when(controllerEndpointService).insertComponent(component1); + + String actualResult = subject.insertComponent(mockedRequest, component1); + assertTrue(actualResult.contains("Inserted")); + } + + @Test + public final void testGetComponents() throws Exception { + EcdComponent component1 = new EcdComponent(); + EcdComponent component2 = new EcdComponent(); + + component1.setCname("comp1"); + component1.setCompId(100L); + component1.setDname("COMP1"); + + component2.setCname("comp2"); + component2.setCompId(200L); + component2.setDname("COMP2"); + + List<EcdComponent> compsList = new ArrayList<EcdComponent>(); + compsList.add(component1); + compsList.add(component2); + + when(controllerEndpointService.getComponents()).thenReturn(compsList); + + String actualResult = subject.getComponents(mockedRequest); + assertTrue(actualResult.contains("comp1")); + } + + @Test + public final void testGetTenants() throws Exception { + String tenantsList = + "{\"items\": [{\"id\": 1, \"name\": \"default_tenant\", \"dName\": \"default_tenant\" }, " + + "{\"id\": 2, \"name\": \"dyh1b1902\", \"dName\": \"dyh1b1902\"}], " + + "\"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; + CloudifyTenantList sampleData = null; + try { + sampleData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); + } catch (Exception e) { + } + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + + Mockito.when(cfyClient.getTenants()).thenReturn(sampleData); + + String tenantStr = subject.getTenants(mockedRequest); + assertTrue(tenantStr.contains("dyh1b")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testGetTenantStatusForService() throws Exception { + String[] deplIds = {"id1", "id2"}; + + CloudifyDeployedTenant cldDeplTenant = new CloudifyDeployedTenant("id1", "bp1", "tenant1"); + + List<CloudifyDeployedTenant> cldDeplTenantList = new ArrayList<CloudifyDeployedTenant>(); + + cldDeplTenantList.add(cldDeplTenant); + + CloudifyDeployedTenantList cldDeployedTenantList = + new CloudifyDeployedTenantList(cldDeplTenantList, null); + + CloudifyTenant cldTenant = new CloudifyTenant("tenant1", "tenant1", "tenant_id1"); + + List<CloudifyTenant> cldfyTenantList = new ArrayList<CloudifyTenant>(); + cldfyTenantList.add(cldTenant); + + CloudifyTenantList cloudifyTenantList = new CloudifyTenantList(cldfyTenantList, null); + + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null, false, false); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + when(cfyClient.getTenants()).thenReturn(cloudifyTenantList); + + when(cfyClient.getTenantInfoFromDeploy(Mockito.any())).thenReturn(cldDeployedTenantList); + + when(cfyClient.getExecutionsSummary(Mockito.any(), Mockito.any())) + .thenReturn(cloudifyExecutionList).thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = subject.getTenantStatusForService(mockedRequest, deplIds); + assertTrue(actualResult.contains("successful")); + + actualResult = subject.getTenantStatusForService(mockedRequest, deplIds); + assertTrue(actualResult.contains("error")); + + actualResult = subject.getTenantStatusForService(mockedRequest, deplIds); + assertTrue(actualResult.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testCreateBlueprint() throws Exception { + ServiceTypeUploadRequest bpUploadReq = ServiceTypeUploadRequest.from(bpItem); + + when(inventoryClient.addServiceType(Matchers.<ServiceTypeRequest>any())) + .thenThrow(BlueprintParseException.class).thenThrow(httpException) + .thenThrow(Exception.class).thenReturn(bpItem); + + String actual1 = subject.createBlueprint(mockedRequest, bpUploadReq); + assertTrue(actual1.contains("error")); + + String actual2 = subject.createBlueprint(mockedRequest, bpUploadReq); + assertTrue(actual2.contains("error")); + + String actual3 = subject.createBlueprint(mockedRequest, bpUploadReq); + assertTrue(actual3.contains("error")); + + String actual = subject.createBlueprint(mockedRequest, bpUploadReq); + assertTrue(actual.contains("app1")); + + } + + @SuppressWarnings("unchecked") + @Test + public final void testGetBlueprintsByPage() { + MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); + mockedRequest1.addParameter("_include", "typeName,typeId,typeVersion"); + mockedRequest1.addParameter("name", "xyz"); + + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream1).thenThrow(Exception.class).thenThrow(httpException); + + String result = subject.getBlueprintsByPage(mockedRequest1); + assertTrue(result.contains("xyz")); + + result = subject.getBlueprintsByPage(mockedRequest1); + assertTrue(result.contains("error")); + + result = subject.getBlueprintsByPage(mockedRequest1); + assertTrue(result.contains("error")); + + } + + @SuppressWarnings("unchecked") + @Test + public final void testQueryBlueprintFilter() { + MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); + mockedRequest1.addParameter("_include", "typeName,typeId,typeVersion"); + mockedRequest1.addParameter("name", "xyz"); + + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream1).thenThrow(Exception.class).thenThrow(httpException); + + String result = subject.queryBlueprintFilter(mockedRequest1); + assertTrue(result.contains("xyz")); + + result = subject.queryBlueprintFilter(mockedRequest1); + assertTrue(result.contains("error")); + + result = subject.queryBlueprintFilter(mockedRequest1); + assertTrue(result.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testGetDeploymentsByPage() { + CloudifyDeployedTenant cldDeplTenant = + new CloudifyDeployedTenant("dcae_dtiapi_1902", "dcae_dtiapi_1902", "tenant1"); + + List<CloudifyDeployedTenant> cldDeplTenantList = new ArrayList<CloudifyDeployedTenant>(); + + cldDeplTenantList.add(cldDeplTenant); + + CloudifyDeployedTenantList cldDeployedTenantList = + new CloudifyDeployedTenantList(cldDeplTenantList, null); + + CloudifyTenant cldTenant = new CloudifyTenant("tenant1", "tenant1", "tenant_id1"); + + List<CloudifyTenant> cldfyTenantList = new ArrayList<CloudifyTenant>(); + cldfyTenantList.add(cldTenant); + + CloudifyTenantList cloudifyTenantList = new CloudifyTenantList(cldfyTenantList, null); + + MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); + mockedRequest1.addParameter("_include", "id"); + mockedRequest1.addParameter("searchBy", "dti"); + + Collection<Service> items = deplList.items; + + when(cfyClient.getTenants()).thenReturn(cloudifyTenantList); + + when(cfyClient.getTenantInfoFromDeploy(Mockito.any())).thenReturn(cldDeployedTenantList) + .thenThrow(Exception.class).thenThrow(httpException).thenReturn(cldDeployedTenantList) + .thenReturn(cldDeployedTenantList); + + Stream<Service> sampleStream1 = items.stream(); + Stream<Service> sampleStream2 = items.stream(); + Stream<Service> sampleStream3 = items.stream(); + + Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream1) + .thenReturn(sampleStream2).thenReturn(sampleStream3).thenThrow(Exception.class) + .thenThrow(httpException); + + String result = subject.getDeploymentsByPage("dcae_dtiapi_1902", mockedRequest1); + assertTrue(result.contains("dti")); + + result = subject.getDeploymentsByPage("dcae_dtiapi_1902", mockedRequest1); + assertTrue(result.contains("dti")); + + result = subject.getDeploymentsByPage("dcae_dtiapi_1902", mockedRequest1); + assertTrue(result.contains("dti")); + + result = subject.getDeploymentsByPage("dcae_dtiapi_1902", mockedRequest1); + assertTrue(result.contains("error")); + + result = subject.getDeploymentsByPage("dcae_dtiapi_1902", mockedRequest1); + assertTrue(result.contains("error")); + + } + + @SuppressWarnings("unchecked") + @Test + public final void testGetAllDeploymentsByPage() { + CloudifyDeployedTenant cldDeplTenant = + new CloudifyDeployedTenant("dcae_dtiapi_1902", "dcae_dtiapi_1902", "tenant1"); + + List<CloudifyDeployedTenant> cldDeplTenantList = new ArrayList<CloudifyDeployedTenant>(); + + cldDeplTenantList.add(cldDeplTenant); + + CloudifyDeployedTenantList cldDeployedTenantList = + new CloudifyDeployedTenantList(cldDeplTenantList, null); + + CloudifyTenant cldTenant = new CloudifyTenant("tenant1", "tenant1", "tenant_id1"); + + List<CloudifyTenant> cldfyTenantList = new ArrayList<CloudifyTenant>(); + cldfyTenantList.add(cldTenant); + + CloudifyTenantList cloudifyTenantList = new CloudifyTenantList(cldfyTenantList, null); + + MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); + mockedRequest1.addParameter("_include", "id"); + mockedRequest1.addParameter("searchBy", "dti"); + + Collection<Service> items = deplList.items; + + when(cfyClient.getTenants()).thenReturn(cloudifyTenantList); + + when(cfyClient.getTenantInfoFromDeploy(Mockito.any())).thenReturn(cldDeployedTenantList) + .thenThrow(Exception.class).thenThrow(httpException).thenReturn(cldDeployedTenantList) + .thenReturn(cldDeployedTenantList); + + Stream<Service> sampleStream1 = items.stream(); + Stream<Service> sampleStream2 = items.stream(); + Stream<Service> sampleStream3 = items.stream(); + + Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream1) + .thenReturn(sampleStream2).thenReturn(sampleStream3).thenThrow(Exception.class) + .thenThrow(httpException); + + String result = subject.getAllDeploymentsByPage(mockedRequest1); + assertTrue(result.contains("dti")); + + result = subject.getAllDeploymentsByPage(mockedRequest1); + assertTrue(result.contains("dti")); + + result = subject.getAllDeploymentsByPage(mockedRequest1); + assertTrue(result.contains("dti")); + + result = subject.getAllDeploymentsByPage(mockedRequest1); + assertTrue(result.contains("error")); + + result = subject.getAllDeploymentsByPage(mockedRequest1); + assertTrue(result.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testGetDeploymentRevisions() throws Exception { + CloudifyNodeInstance cfyNodeInstance = new CloudifyNodeInstance("id1", null); + + List<CloudifyNodeInstance> cfyNodeInstanceItems = new ArrayList<CloudifyNodeInstance>(); + cfyNodeInstanceItems.add(cfyNodeInstance); + + CloudifyNodeInstanceList cfyNodeInstList = + new CloudifyNodeInstanceList(cfyNodeInstanceItems, null); + + when(cfyClient.getNodeInstanceVersion(Mockito.any(), Mockito.any())) + .thenReturn(cfyNodeInstList).thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = + subject.getDeploymentRevisions("deploymentId", "tenant", mockedRequest); + assertTrue(actualResult.contains("id1")); + + actualResult = subject.getDeploymentRevisions("deploymentId", "tenant", mockedRequest); + assertTrue(actualResult.contains("error")); + + actualResult = subject.getDeploymentRevisions("deploymentId", "tenant", mockedRequest); + assertTrue(actualResult.contains("error")); + } + + @Test + public final void testGetDeploymentInputs() throws Exception { + + Map<String, Object> inputHash = new HashMap<String, Object>(); + inputHash.put("key1", "value1"); + + CloudifyDeployment cldDeployment = + new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", "id", + inputHash, null, null, null, null, null, null, "tenant"); + + List<CloudifyDeployment> cfyDeployItems = new ArrayList<CloudifyDeployment>(); + cfyDeployItems.add(cldDeployment); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); + + when(cfyClient.getDeploymentInputs(Matchers.any(), Matchers.any())) + .thenReturn(cldDeployList); + + String actualResult = subject.getDeploymentInputs("deploymentId", "tenant", mockedRequest); + assertTrue(actualResult.contains("blueprint_id")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testModifyDeployment() throws Exception { + CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "install", + false, "bp1", "id1", "tenant1", "error", "execution_id1", null, false, false); + + Map<String, Object> params = new HashMap<String, Object>(); + params.put("tenant", "tenant1"); + params.put("workflow", "upgrade"); + + CloudifyExecutionRequest cfyExecReq = new CloudifyExecutionRequest("deployment_id", + "upgrade", false, false, "tenant1", params); + + CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); + + List<CloudifyNodeInstanceId> cfyNodeInstItems = new ArrayList<CloudifyNodeInstanceId>(); + + cfyNodeInstItems.add(cfyNodeInst); + + CloudifyNodeInstanceIdList cfyNodeInstList = + new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); + + when(cfyClient.getNodeInstanceId(Mockito.any(), Mockito.any())).thenReturn(cfyNodeInstList); + + when(cfyClient.startExecution(Matchers.<CloudifyExecutionRequest>any())) + .thenReturn(cfyExecObj).thenThrow(Exception.class).thenThrow(httpException); + + String inputParamStr = "{\"tenant\": \"tenant1\", \"workflow\":\"upgrade\"}"; + + InputStream is = new ByteArrayInputStream(inputParamStr.getBytes()); + + String actualResult = subject.modifyDeployment("depId", mockedRequest, is); + assertTrue(actualResult.contains("execution_id1")); + + actualResult = subject.modifyDeployment("depId", mockedRequest, is); + assertTrue(actualResult.contains("error")); + + actualResult = subject.modifyDeployment("depId", mockedRequest, is); + assertTrue(actualResult.contains("error")); + + } + + @Test + public final void testGetServicesForType() throws Exception { + ServiceRef expectedSrvc = new ServiceRef("dcae_dtiapi_1902", "432423", "433434"); + Collection<ServiceRef> expectedSrvcIds = new ArrayList<ServiceRef>(); + expectedSrvcIds.add(expectedSrvc); + ServiceRefList expectedSrvcRefList = new ServiceRefList(expectedSrvcIds, 1); + + when(inventoryClient.getServicesForType(Matchers.<ServiceQueryParams>any())) + .thenReturn(expectedSrvcRefList); + String actual = subject.getServicesForType(mockedRequest, "typeId1"); + assertTrue(actual.contains("typeId1")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testCreateDeployment() throws Exception { + DeploymentInput deployInput1 = new DeploymentInput("component1", "tag1", + "xyz1731-helm-1906", 1906, "blueprintId", null, "tenant1"); + + DeploymentInput deployInput2 = new DeploymentInput("component1", "tag1", + "xyz1731-helm-1906", 1906, null, null, "tenant1"); + + DeploymentResponseLinks expectLink = new DeploymentResponseLinks("self", "status"); + DeploymentResponse expectResp = new DeploymentResponse("req1", expectLink); + + Collection<ServiceType> items = bpList2.items; + Stream<ServiceType> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream1); + + String actualResp0 = subject.createDeployment(mockedRequest, deployInput2); + assertTrue(actualResp0.contains("error")); + + StringBuffer expectedStrBuff = new StringBuffer(); + expectedStrBuff.append("http://oom.s2.com"); + when(mockedRequest.getRequestURL()).thenReturn(expectedStrBuff); + + when(deploymentHandlerClient.putDeployment(Matchers.anyString(), Matchers.anyString(), + Matchers.<DeploymentRequest>any())).thenReturn(expectResp).thenThrow(badReqError) + .thenThrow(srvcExistError).thenThrow(serverError).thenThrow(downStrmError) + .thenThrow(Exception.class); + + String actualResp = subject.createDeployment(mockedRequest, deployInput1); + assertTrue(actualResp.contains("component1")); + + actualResp = subject.createDeployment(mockedRequest, deployInput1); + assertTrue(actualResp.contains("error")); + + actualResp = subject.createDeployment(mockedRequest, deployInput1); + assertTrue(actualResp.contains("error")); + + actualResp = subject.createDeployment(mockedRequest, deployInput1); + assertTrue(actualResp.contains("error")); + + actualResp = subject.createDeployment(mockedRequest, deployInput1); + assertTrue(actualResp.contains("error")); + + actualResp = subject.createDeployment(mockedRequest, deployInput1); + assertTrue(actualResp.contains("error")); + + } + + @SuppressWarnings("unchecked") + @Test + public final void testUpdateDeployment() throws Exception { + + DeploymentInput deployInput1 = new DeploymentInput("component1", "tag1", + "xyz1731-helm-1906", 1906, "blueprintId", null, "tenant1"); + + DeploymentResponseLinks expectLink = new DeploymentResponseLinks("self", "status"); + DeploymentResponse expectResp = new DeploymentResponse("req1", expectLink); + + Collection<ServiceType> items = bpList2.items; + Stream<ServiceType> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream1); + + when(deploymentHandlerClient.updateDeployment(Matchers.anyString(), Matchers.anyString(), + Matchers.<DeploymentRequest>any())).thenReturn(expectResp).thenThrow(badReqError) + .thenThrow(srvcExistError).thenThrow(serverError).thenThrow(downStrmError) + .thenThrow(Exception.class); + + String actualResp = subject.updateDeployment("id1", mockedRequest, deployInput1); + assertTrue(actualResp.contains("req1")); + + actualResp = subject.updateDeployment("id1", mockedRequest, deployInput1); + assertTrue(actualResp.contains("error")); + + actualResp = subject.updateDeployment("id1", mockedRequest, deployInput1); + assertTrue(actualResp.contains("error")); + + actualResp = subject.updateDeployment("id1", mockedRequest, deployInput1); + assertTrue(actualResp.contains("error")); + + actualResp = subject.updateDeployment("id1", mockedRequest, deployInput1); + assertTrue(actualResp.contains("error")); + + actualResp = subject.updateDeployment("id1", mockedRequest, deployInput1); + assertTrue(actualResp.contains("error")); + } + + @Test + public final void testGetExecutionByDeploymentId() throws Exception { + + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null, false, false); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + when(cfyClient.getExecutionsSummary(Mockito.any(), Mockito.any())) + .thenReturn(cloudifyExecutionList); + + String actualResult = + subject.getExecutionByDeploymentId("dep_id", "tenant1", mockedRequest); + assertTrue(actualResult.contains("execution_id1")); + } + + @Test + public final void testDeleteBlueprint() throws Exception { + String expected = "{\"202\": \"OK\"}"; + doNothing().doThrow(serviceTypeException).doThrow(Exception.class).when(inventoryClient) + .deleteServiceType(Matchers.anyString()); + + String actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse); + assertEquals(expected, actual); + + actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse); + assertTrue(actual.contains("error")); + } + + @Test + public final void testDeleteDeployment() throws Exception { + doNothing().doThrow(badReqError).doThrow(serverError).doThrow(downStrmError) + .doThrow(notFoundError).doThrow(Exception.class).when(deploymentHandlerClient) + .deleteDeployment(Matchers.anyString(), Matchers.anyString()); + + StringBuffer expectedStrBuff = new StringBuffer(); + expectedStrBuff.append("http://oom.s2.com"); + when(mockedRequest.getRequestURL()).thenReturn(expectedStrBuff); + + String actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); + assertFalse(actual.contains("error")); + + actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testCancelExecution() throws Exception { + List<String> tenants = new ArrayList<String>(); + tenants.add("tenant1"); + + HttpHeaders httpHeader = new HttpHeaders(); + httpHeader.put("tenant", tenants); + + CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "cancel", + false, "bp1", "id1", "tenant1", "error", "execution_id1", null, false, false); + + when(cfyClient.cancelExecution(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(cfyExecObj).thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = + subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); + assertTrue(actualResult.contains("execution_id1")); + + actualResult = + subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); + assertTrue(actualResult.contains("error")); + + actualResult = + subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); + assertTrue(actualResult.contains("error")); + } + +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ConsulControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ConsulControllerTest.java new file mode 100644 index 0000000..3d71a2e --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ConsulControllerTest.java @@ -0,0 +1,315 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.controller; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.dashboard.core.MockUser; +import org.onap.ccsdk.dashboard.core.MockitoTestSuite; +import org.onap.ccsdk.dashboard.model.ConsulDatacenter; +import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; +import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; +import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; +import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; +import org.onap.ccsdk.dashboard.model.RestResponseSuccess; +import org.onap.ccsdk.dashboard.rest.ConsulClient; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +public class ConsulControllerTest extends MockitoTestSuite { + + @Mock + ConsulClient consulClient; + + @InjectMocks + ConsulController subject = new ConsulController(); + + protected final ObjectMapper objectMapper = new ObjectMapper(); + + MockUser mockUser = new MockUser(); + HttpClientErrorException httpException; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + objectMapper.registerModule(new Jdk8Module()); + mockedRequest = getMockedRequest(); + mockedResponse = getMockedResponse(); + httpException = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "statusText"); + } + + @After + public void tearDown() throws Exception { + } + + @SuppressWarnings("unchecked") + @Test + public final void testGetServiceHealthDetails() throws Exception { + ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", + "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", + "This is a pgaas1_Service_ID health check", + "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", + "pgaas1_Service_ID", "pgaasServer1", 190199, 199395); + + List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); + expectedCnslSrvcHlth.add(consulSrvcHlth); + + when(consulClient.getServiceHealth(Matchers.anyString(), Matchers.anyString())) + .thenReturn(expectedCnslSrvcHlth).thenThrow(Exception.class); + + String actualResult = subject.getServiceHealthDetails(mockedRequest, "dc1", "srvc1"); + assertTrue(actualResult.contains("pgaasServer1")); + + actualResult = subject.getServiceHealthDetails(mockedRequest, "dc1", "srvc1"); + assertTrue(actualResult.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testGetServicesHealth() throws Exception { + + List<String> srvcIps = new ArrayList<String>(); + srvcIps.add("135.91.224.136"); + srvcIps.add("135.91.224.138"); + ConsulServiceInfo consulSrvcInfo = new ConsulServiceInfo("pgaasServer1", srvcIps); + + List<ConsulServiceInfo> expectedCnslSrvcs = new ArrayList<ConsulServiceInfo>(); + expectedCnslSrvcs.add(consulSrvcInfo); + + ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", + "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", + "This is a pgaas1_Service_ID health check", + "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", + "pgaas1_Service_ID", "pgaasServer1", 190199, 199395); + + List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); + expectedCnslSrvcHlth.add(consulSrvcHlth); + + when(consulClient.getServices(Matchers.anyString())).thenReturn(expectedCnslSrvcs); + when(consulClient.getServiceHealth(Matchers.anyString(), Matchers.anyString())) + .thenReturn(expectedCnslSrvcHlth).thenThrow(Exception.class); + + String actualResult = subject.getServicesHealth(mockedRequest, "dc1"); + assertTrue(actualResult.contains("pgaasServer1")); + + actualResult = subject.getServicesHealth(mockedRequest, "dc1"); + assertTrue(actualResult.contains("error")); + } + + @Test + public final void testGetNodesInfo() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + user.setId(1000L); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + + ConsulNodeInfo cnslNode = new ConsulNodeInfo("a2788806-6e2e-423e-8ee7-6cad6f3d3de6", + "cjlvmcnsl00", "10.170.8.13", null, null, 6, 17980); + + List<ConsulNodeInfo> cnslNodeList = new ArrayList<ConsulNodeInfo>(); + cnslNodeList.add(cnslNode); + + when(consulClient.getNodes(Matchers.anyString())).thenReturn(cnslNodeList); + + String actualResult = subject.getNodesInfo(mockedRequest, "dc1"); + assertTrue(actualResult.contains("cjlvmcnsl00")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testGetNodeServicesHealth() throws Exception { + ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", + "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", + "This is a pgaas1_Service_ID health check", + "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", + "pgaas1_Service_ID", "pgaasServer1", 190199, 199395); + + List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); + expectedCnslSrvcHlth.add(consulSrvcHlth); + + when(consulClient.getNodeServicesHealth(Matchers.anyString(), Matchers.anyString())) + .thenReturn(expectedCnslSrvcHlth).thenThrow(Exception.class); + + String actualResult = subject.getNodeServicesHealth(mockedRequest, "dc1", "node1"); + assertTrue(actualResult.contains("pgaasServer1")); + + actualResult = subject.getNodeServicesHealth(mockedRequest, "dc1", "node1"); + assertTrue(actualResult.contains("error")); + } + + @Test + public final void testGetDatacentersHealth() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + user.setId(1000L); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + + ConsulDatacenter cnslDc = new ConsulDatacenter("dc1"); + + List<ConsulDatacenter> cnslDcList = new ArrayList<ConsulDatacenter>(); + cnslDcList.add(cnslDc); + + when(consulClient.getDatacenters()).thenReturn(cnslDcList); + + String actualResult = subject.getDatacentersHealth(mockedRequest); + assertTrue(actualResult.contains("dc1")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testRegisterService() throws Exception { + ConsulHealthServiceRegistration.EndpointCheck endPoint = + new ConsulHealthServiceRegistration.EndpointCheck("endpoint1", "interval1", + "description1", "name1"); + List<ConsulHealthServiceRegistration.EndpointCheck> endPointList = + new ArrayList<ConsulHealthServiceRegistration.EndpointCheck>(); + endPointList.add(endPoint); + + List<String> tagList = new ArrayList<String>(); + tagList.add("tag1"); + tagList.add("tag2"); + + ConsulHealthServiceRegistration.ConsulServiceRegistration servcReg = + new ConsulHealthServiceRegistration.ConsulServiceRegistration("id1", "name1", + "address1", "port1", tagList, endPointList); + List<ConsulHealthServiceRegistration.ConsulServiceRegistration> servcRegList = + new ArrayList<ConsulHealthServiceRegistration.ConsulServiceRegistration>(); + servcRegList.add(servcReg); + + ConsulHealthServiceRegistration chsrObj = new ConsulHealthServiceRegistration(servcRegList); + + RestResponseSuccess expectedResp = new RestResponseSuccess("Registration yielded code 0"); + String expectedResult = objectMapper.writeValueAsString(expectedResp); + + String expectedStr = "Registration yielded code 0"; + when(consulClient.registerService(Matchers.<ConsulHealthServiceRegistration>any())) + .thenReturn(expectedStr).thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = subject.registerService(mockedRequest, chsrObj); + assertTrue(actualResult.equals(expectedResult)); + + actualResult = subject.registerService(mockedRequest, chsrObj); + assertTrue(actualResult.contains("error")); + + actualResult = subject.registerService(mockedRequest, chsrObj); + assertTrue(actualResult.contains("error")); + } + + @Test + public final void testRegisterService_SrvcError() throws Exception { + ConsulHealthServiceRegistration chsrObj = new ConsulHealthServiceRegistration(null); + + String actualResult = subject.registerService(mockedRequest, chsrObj); + assertTrue(actualResult.contains("error")); + } + + @Test + @Ignore + public final void testRegisterService_invalidSrvcError() throws Exception { + ConsulHealthServiceRegistration.EndpointCheck endPoint = + new ConsulHealthServiceRegistration.EndpointCheck("endpoint1", "interval1", + "description1", "name1"); + List<ConsulHealthServiceRegistration.EndpointCheck> endPointList = + new ArrayList<ConsulHealthServiceRegistration.EndpointCheck>(); + endPointList.add(endPoint); + + List<String> tagList = new ArrayList<String>(); + tagList.add("tag1"); + tagList.add("tag2"); + + ConsulHealthServiceRegistration.ConsulServiceRegistration servcReg = + new ConsulHealthServiceRegistration.ConsulServiceRegistration("id1", "name2", + "address2", "port1", tagList, endPointList); + List<ConsulHealthServiceRegistration.ConsulServiceRegistration> servcRegList = + new ArrayList<ConsulHealthServiceRegistration.ConsulServiceRegistration>(); + servcRegList.add(servcReg); + + ConsulHealthServiceRegistration chsrObj = new ConsulHealthServiceRegistration(servcRegList); + + String actualResult = subject.registerService(mockedRequest, chsrObj); + assertTrue(actualResult.contains("error")); + } + + @Test + public final void testRegisterService_invalidEndptError() throws Exception { + ConsulHealthServiceRegistration.EndpointCheck endPoint = + new ConsulHealthServiceRegistration.EndpointCheck("", "", "description1", "name1"); + List<ConsulHealthServiceRegistration.EndpointCheck> endPointList = + new ArrayList<ConsulHealthServiceRegistration.EndpointCheck>(); + endPointList.add(endPoint); + + List<String> tagList = new ArrayList<String>(); + tagList.add("tag1"); + tagList.add("tag2"); + + ConsulHealthServiceRegistration.ConsulServiceRegistration servcReg = + new ConsulHealthServiceRegistration.ConsulServiceRegistration("id1", "", "", "port1", + tagList, endPointList); + List<ConsulHealthServiceRegistration.ConsulServiceRegistration> servcRegList = + new ArrayList<ConsulHealthServiceRegistration.ConsulServiceRegistration>(); + servcRegList.add(servcReg); + + ConsulHealthServiceRegistration chsrObj = new ConsulHealthServiceRegistration(servcRegList); + + String actualResult = subject.registerService(mockedRequest, chsrObj); + assertTrue(actualResult.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testDeregisterService() throws Exception { + RestResponseSuccess expectedResp = new RestResponseSuccess("Deregistration yielded code 0"); + String expectedResult = objectMapper.writeValueAsString(expectedResp); + + when(consulClient.deregisterService(Mockito.any())).thenReturn(0).thenThrow(Exception.class) + .thenThrow(httpException); + + String actualResult = subject.deregisterService(mockedRequest, "srvc1"); + assertTrue(actualResult.equals(expectedResult)); + + actualResult = subject.deregisterService(mockedRequest, "srvc1"); + assertTrue(actualResult.contains("error")); + + actualResult = subject.deregisterService(mockedRequest, "srvc1"); + assertTrue(actualResult.contains("error")); + } + +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerControllerTest.java new file mode 100644 index 0000000..6517b68 --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerControllerTest.java @@ -0,0 +1,184 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.controller; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.dashboard.core.MockitoTestSuite; +import org.onap.ccsdk.dashboard.exceptions.BadRequestException; +import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.DownstreamException; +import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; +import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequestObject; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponseLinks; +import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +public class DeploymentHandlerControllerTest extends MockitoTestSuite { + + @Mock + DeploymentHandlerClient restClient; + + @InjectMocks + DeploymentHandlerController subject = new DeploymentHandlerController(); + + protected final ObjectMapper objectMapper = new ObjectMapper(); + + BadRequestException badReqError; + ServiceAlreadyExistsException srvcExistError; + ServerErrorException serverError; + DownstreamException downStrmError; + JsonProcessingException jsonError; + DeploymentNotFoundException notFoundError; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + objectMapper.registerModule(new Jdk8Module()); + mockedRequest = getMockedRequest(); + mockedResponse = getMockedResponse(); + badReqError = new BadRequestException("bad request"); + srvcExistError = new ServiceAlreadyExistsException("service already exists"); + serverError = new ServerErrorException("Error occured in server"); + downStrmError = new DownstreamException("error occured in downstream"); + notFoundError = new DeploymentNotFoundException("item not found"); + } + + @After + public void tearDown() throws Exception { + } + + @SuppressWarnings("unchecked") + @Test + public final void testPutDeployment_create() throws Exception { + DeploymentRequestObject expectReq = + new DeploymentRequestObject("dep1", "dep1", null, "tenant1", "create"); + + DeploymentResponseLinks expectLink = new DeploymentResponseLinks("self", "status"); + DeploymentResponse expectResp = new DeploymentResponse("req1", expectLink); + + when(restClient.putDeployment(Matchers.anyString(), Matchers.anyString(), + Matchers.<DeploymentRequest>any())).thenReturn(expectResp).thenThrow(badReqError) + .thenThrow(srvcExistError).thenThrow(serverError).thenThrow(downStrmError) + .thenThrow(Exception.class); + + String actualResp = subject.putDeployment(mockedRequest, expectReq); + assertTrue(actualResp.contains("req1")); + + actualResp = subject.putDeployment(mockedRequest, expectReq); + assertTrue(actualResp.contains("error")); + + actualResp = subject.putDeployment(mockedRequest, expectReq); + assertTrue(actualResp.contains("error")); + + actualResp = subject.putDeployment(mockedRequest, expectReq); + assertTrue(actualResp.contains("error")); + + actualResp = subject.putDeployment(mockedRequest, expectReq); + assertTrue(actualResp.contains("error")); + + actualResp = subject.putDeployment(mockedRequest, expectReq); + assertTrue(actualResp.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testPutDeployment_update() throws Exception { + DeploymentRequestObject expectReq = + new DeploymentRequestObject("dep1", "dep1", null, "tenant1", "update"); + + DeploymentResponseLinks expectLink = new DeploymentResponseLinks("self", "status"); + DeploymentResponse expectResp = new DeploymentResponse("req1", expectLink); + + when(restClient.updateDeployment(Matchers.anyString(), Matchers.anyString(), + Matchers.<DeploymentRequest>any())).thenReturn(expectResp).thenThrow(badReqError) + .thenThrow(srvcExistError).thenThrow(serverError).thenThrow(downStrmError) + .thenThrow(Exception.class); + + String actualResp = subject.putDeployment(mockedRequest, expectReq); + assertTrue(actualResp.contains("req1")); + + actualResp = subject.putDeployment(mockedRequest, expectReq); + assertTrue(actualResp.contains("error")); + + actualResp = subject.putDeployment(mockedRequest, expectReq); + assertTrue(actualResp.contains("error")); + + actualResp = subject.putDeployment(mockedRequest, expectReq); + assertTrue(actualResp.contains("error")); + + actualResp = subject.putDeployment(mockedRequest, expectReq); + assertTrue(actualResp.contains("error")); + + actualResp = subject.putDeployment(mockedRequest, expectReq); + assertTrue(actualResp.contains("error")); + } + + @Test + public final void testDeleteDeployment() throws Exception { + + doNothing().doThrow(badReqError).doThrow(serverError).doThrow(downStrmError) + .doThrow(notFoundError).doThrow(Exception.class).when(restClient) + .deleteDeployment(Matchers.anyString(), Matchers.anyString()); + + StringBuffer expectedStrBuff = new StringBuffer(); + expectedStrBuff.append("http://oom.s2.com"); + when(mockedRequest.getRequestURL()).thenReturn(expectedStrBuff); + + String actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); + assertFalse(actual.contains("error")); + + actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + } + +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnControllerTest.java new file mode 100644 index 0000000..771c085 --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnControllerTest.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.controller; + +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.onap.ccsdk.dashboard.core.MockitoTestSuite; +import org.springframework.web.servlet.ModelAndView; + +public class ECDSingleSignOnControllerTest extends MockitoTestSuite { + + @InjectMocks + ECDSingleSignOnController subject = new ECDSingleSignOnController(); + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + } + + @Test + public final void testSingleSignOnLogin() throws Exception { + + mockedRequest.addParameter("forwardURL", "ecd#"); + ModelAndView actualResult = subject.singleSignOnLogin(mockedRequest, mockedResponse); + assertTrue(actualResult.getViewName().contains("login")); + + } + +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/HealthCheckControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/HealthCheckControllerTest.java new file mode 100644 index 0000000..4e44c39 --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/HealthCheckControllerTest.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.controller; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.dashboard.core.MockitoTestSuite; +import org.onap.ccsdk.dashboard.model.HealthStatus; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({SystemProperties.class}) +public class HealthCheckControllerTest extends MockitoTestSuite { + + @InjectMocks + HealthCheckController subject = new HealthCheckController(); + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + mockedRequest = getMockedRequest(); + mockedResponse = getMockedResponse(); + PowerMockito.mockStatic(SystemProperties.class); + when(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)) + .thenReturn("oom-dash"); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public final void testHealthCheck() { + String messg = "oom-dash health check passed"; + HealthStatus actualResult = subject.healthCheck(mockedRequest, mockedResponse); + assertTrue(actualResult.statusCode == 200); + } + +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/InventoryControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/InventoryControllerTest.java new file mode 100644 index 0000000..01858ed --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/InventoryControllerTest.java @@ -0,0 +1,788 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.controller; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Stream; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.dashboard.core.MockUser; +import org.onap.ccsdk.dashboard.core.MockitoTestSuite; +import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; +import org.onap.ccsdk.dashboard.model.inventory.Service; +import org.onap.ccsdk.dashboard.model.inventory.ServiceList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRef; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceType; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; +import org.onap.ccsdk.dashboard.rest.CloudifyClient; +import org.onap.ccsdk.dashboard.rest.InventoryClient; +import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.web.support.AppUtils; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.client.RestClientException; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({DashboardProperties.class}) +public class InventoryControllerTest extends MockitoTestSuite { + + @Mock + private CloudifyClient restClient; + + @Mock + private InventoryClient inventoryClient; + + @InjectMocks + private InventoryController subject = new InventoryController(); + + protected final ObjectMapper objectMapper = new ObjectMapper(); + + private HttpServerErrorException httpException = + new HttpServerErrorException(HttpStatus.BAD_GATEWAY); + + private ServiceNotFoundException serviceException = + new ServiceNotFoundException("Invalid deployment"); + + private ServiceTypeNotFoundException serviceTypeException = + new ServiceTypeNotFoundException("Invalid blueprint"); + + @Mock + UserUtils userUtils = new UserUtils(); + + @Mock + User epuser; + + @Mock + AppUtils appUtils = new AppUtils(); + + HttpServletRequest mockedRequest; + HttpServletResponse mockedResponse; + + MockUser mockUser = new MockUser(); + ServiceList deplList = null; + Service deplItem = null; + + ServiceType bpItem = null; + ServiceTypeList bpList = null; + + ServiceTypeRequest bpUploadItem = null; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + objectMapper.registerModule(new Jdk8Module()); + getExpectedDeployments(); + getExpectedBueprints(); + createBpUploadItem(); + mockedRequest = getMockedRequest(); + mockedResponse = getMockedResponse(); + } + + public void getExpectedDeployments() + throws JsonParseException, JsonMappingException, IOException { + + deplItem = new Service("dcae_dtiapi_1902", null, "1552335532348", "1552335532348", null, + "dummyVnfId", null, "dummyVnfType", "dummyLocation", "dcae_dtiapi_1902", null); + Collection<Service> items = new ArrayList<Service>(); + items.add(deplItem); + + String pageLinks = + "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; + ServiceList.PaginationLinks paginationLinks = + objectMapper.readValue(pageLinks, ServiceList.PaginationLinks.class); + int totalCount = 1; + deplList = new ServiceList(items, totalCount, paginationLinks); + + } + + public void getExpectedBueprints() + throws JsonParseException, JsonMappingException, IOException { + bpItem = new ServiceType.Builder("xyz1731", "xyz1731-helm-1906", 1906, + "tosca_definitions_version: cloudify_dsl_1_3", "", "app1", "comp1").build(); + Collection<ServiceType> items = new ArrayList<ServiceType>(); + items.add(bpItem); + + String pageLinks2 = + "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; + ServiceTypeList.PaginationLinks paginationLinks = + objectMapper.readValue(pageLinks2, ServiceTypeList.PaginationLinks.class); + int totalCount = 1; + bpList = new ServiceTypeList(items, totalCount, paginationLinks); + } + + public void createBpUploadItem() { + bpUploadItem = ServiceTypeRequest.from(bpItem); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public final void testGetServiceTypesByPage() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("searchBy", "xyz"); + mockedRequest.addParameter("sortBy", "owner"); + + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + + Collection<ServiceType> items = bpList.items; + + Stream<ServiceType> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("xyz")); + + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + + HttpSession session = mockedRequest.getSession(); + HashMap<String, Boolean> comp_deploy_tab = new HashMap<String, Boolean>(); + comp_deploy_tab.put("comp1", true); + + Set<String> userApps = new TreeSet<String>(); + userApps.add("comp1"); + + when(session.getAttribute("comp_access")).thenReturn(comp_deploy_tab); + when(session.getAttribute("role_level")).thenReturn("app"); + when(session.getAttribute("authComponents")).thenReturn(userApps); + + Stream<ServiceType> sampleStream2 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream2); + String result2 = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result2.contains("xyz")); + } + + @Test + public final void testGetServiceTypesByPage_appl() { + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sortBy", "application"); + + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> sampleStream1 = items.stream(); + + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("xyz")); + + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + + Stream<ServiceType> sampleStream2 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream2); + String result2 = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result2.contains("xyz")); + } + + @Test + public final void testGetServiceTypesByPage_comp() { + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sortBy", "component"); + + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> sampleStream1 = items.stream(); + + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("xyz")); + + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + + Stream<ServiceType> sampleStream2 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream2); + String result2 = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result2.contains("xyz")); + } + + @Test + public final void testGetServiceTypesByPage_typeId() { + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sortBy", "typeId"); + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> sampleStream1 = items.stream(); + + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("xyz")); + + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + + Stream<ServiceType> sampleStream2 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream2); + String result2 = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result2.contains("xyz")); + } + + @Test + public final void testGetServiceTypesByPage_typeName() { + + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sortBy", "typeName"); + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> sampleStream1 = items.stream(); + + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("xyz")); + + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + + Stream<ServiceType> sampleStream2 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream2); + String result2 = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result2.contains("xyz")); + + } + + @Test + public final void testGetServiceTypesByPage_typeVer() { + + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sortBy", "typeVersion"); + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> sampleStream1 = items.stream(); + + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("xyz")); + + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + + Stream<ServiceType> sampleStream2 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream2); + String result2 = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result2.contains("xyz")); + + } + + @Test + public final void testGetServiceTypesByPage_created() { + + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sortBy", "created"); + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> sampleStream1 = items.stream(); + + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("xyz")); + + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + + Stream<ServiceType> sampleStream2 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream2); + String result2 = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result2.contains("xyz")); + } + + @Test + public final void testGetServiceTypesByPage_Auth() { + + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("searchBy", "xyz"); + + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> sampleStream = items.stream(); + + HttpSession session = mockedRequest.getSession(); + HashMap<String, Boolean> comp_deploy_tab = new HashMap<String, Boolean>(); + comp_deploy_tab.put("comp1", true); + + Set<String> userApps = new TreeSet<String>(); + userApps.add("comp1"); + + when(session.getAttribute("comp_access")).thenReturn(comp_deploy_tab); + when(session.getAttribute("role_level")).thenReturn("ops"); + when(session.getAttribute("authComponents")).thenReturn(userApps); + + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream); + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("xyz")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testGetServiceTypesByPage_Exception() { + PowerMockito.mockStatic(DashboardProperties.class); + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> sampleStream = items.stream(); + when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + when(inventoryClient.getServiceTypes()).thenThrow(RestClientException.class) + .thenThrow(httpException).thenReturn(sampleStream); + + String errResp = subject.getServiceTypesByPage(mockedRequest); + assertTrue(errResp.contains("error")); + + errResp = subject.getServiceTypesByPage(mockedRequest); + assertTrue(errResp.contains("error")); + + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("xyz")); + } + + @Test + public final void testGetServiceTypesByPage_Filter() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("searchBy", "xyz"); + PowerMockito.mockStatic(DashboardProperties.class); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> sampleStream = items.stream(); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream); + + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("xyz")); + } + + @Test + public final void testGetServicesByPage_auth() throws IOException { + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); + mockedRequest1.addParameter("searchBy", "dti"); + + Collection<Service> items = deplList.items; + + HttpSession session = mockedRequest1.getSession(); + HashMap<String, Boolean> comp_deploy_tab = new HashMap<String, Boolean>(); + comp_deploy_tab.put("dcae", true); + + Set<String> userApps = new TreeSet<String>(); + userApps.add("dcae"); + + when(session.getAttribute("comp_access")).thenReturn(comp_deploy_tab); + when(session.getAttribute("role_level")).thenReturn("app"); + when(session.getAttribute("authComponents")).thenReturn(userApps); + + Stream<Service> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream1); + + String result1 = subject.getServicesByPage(mockedRequest1); + assertTrue(result1.contains("dti")); + + } + + @Test + public final void testGetServicesByPage_auth_ops() throws IOException { + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); + mockedRequest1.addParameter("searchBy", "dti"); + + Collection<Service> items = deplList.items; + + HttpSession session = mockedRequest1.getSession(); + HashMap<String, Boolean> comp_deploy_tab = new HashMap<String, Boolean>(); + comp_deploy_tab.put("dcae", true); + + Set<String> userApps = new TreeSet<String>(); + userApps.add("dcae"); + + when(session.getAttribute("comp_access")).thenReturn(comp_deploy_tab); + when(session.getAttribute("role_level")).thenReturn("ops"); + when(session.getAttribute("authComponents")).thenReturn(userApps); + + Stream<Service> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream1); + + String result1 = subject.getServicesByPage(mockedRequest1); + assertTrue(result1.contains("dti")); + + } + + @Test + public final void testGetServicesByPage() throws IOException { + /* + * User user = mockUser.mockUser(); user.setLoginId("tester"); + */ + MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); + mockedRequest1.addParameter("searchBy", "dti"); + mockedRequest1.addParameter("sortBy", "deploymentRef"); + + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + + Collection<Service> items = deplList.items; + + Stream<Service> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream1); + + String result1 = subject.getServicesByPage(mockedRequest1); + assertTrue(result1.contains("dti")); + } + + @Test + public final void testGetServicesByPage_sort_serviceId() throws IOException { + + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sortBy", "serviceId"); + + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + + Collection<Service> items = deplList.items; + + Stream<Service> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream1); + + String result = subject.getServicesByPage(mockedRequest); + assertTrue(result.contains("dti")); + + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + + Stream<Service> sampleStream2 = items.stream(); + Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream2); + + String result2 = subject.getServicesByPage(mockedRequest); + assertTrue(result2.contains("dti")); + } + + @Test + public final void testGetServicesByPage_sort_created() throws IOException { + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sortBy", "created"); + + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + + Collection<Service> items = deplList.items; + + Stream<Service> sampleStream = items.stream(); + Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream); + + String result = subject.getServicesByPage(mockedRequest); + assertTrue(result.contains("dti")); + + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + + Stream<Service> sampleStream2 = items.stream(); + Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream2); + + String result2 = subject.getServicesByPage(mockedRequest); + assertTrue(result2.contains("dti")); + + } + + @Test + public final void testGetServicesByPage_sort_modified() throws IOException { + + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sortBy", "modified"); + + PowerMockito.mockStatic(DashboardProperties.class); + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("os"); + + Collection<Service> items = deplList.items; + + Stream<Service> sampleStream = items.stream(); + Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream); + + String result = subject.getServicesByPage(mockedRequest); + assertTrue(result.contains("dti")); + + Mockito + .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) + .thenReturn("auth"); + + Stream<Service> sampleStream2 = items.stream(); + Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream2); + + String result2 = subject.getServicesByPage(mockedRequest); + assertTrue(result2.contains("dti")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testUploadServiceTypeBlueprint() throws Exception { + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + String expected = "{\"201\": \"OK\"}"; + when(inventoryClient.addServiceType(Matchers.<ServiceTypeRequest>any())) + .thenThrow(BlueprintParseException.class).thenThrow(httpException) + .thenThrow(Exception.class).thenReturn(null); + + String actual1 = subject.uploadServiceTypeBlueprint(mockedRequest, bpUploadItem); + assertTrue(actual1.contains("error")); + + String actual2 = subject.uploadServiceTypeBlueprint(mockedRequest, bpUploadItem); + assertTrue(actual2.contains("error")); + + String actual3 = subject.uploadServiceTypeBlueprint(mockedRequest, bpUploadItem); + assertTrue(actual3.contains("error")); + + String actual = subject.uploadServiceTypeBlueprint(mockedRequest, bpUploadItem); + assertEquals(expected, actual); + + } + + @SuppressWarnings("unchecked") + @Test + public final void testUpdateServiceTypeBlueprint() throws Exception { + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + String expected = "{\"201\": \"OK\"}"; + Mockito.when(inventoryClient.addServiceType(Matchers.<ServiceType>any())) + .thenThrow(BlueprintParseException.class).thenThrow(httpException) + .thenThrow(Exception.class).thenReturn(null); + + String actual1 = subject.updateServiceTypeBlueprint(mockedRequest, bpItem); + assertTrue(actual1.contains("error")); + + String actual2 = subject.updateServiceTypeBlueprint(mockedRequest, bpItem); + assertTrue(actual2.contains("error")); + + String actual3 = subject.updateServiceTypeBlueprint(mockedRequest, bpItem); + assertTrue(actual3.contains("error")); + + String actual = subject.updateServiceTypeBlueprint(mockedRequest, bpItem); + assertEquals(expected, actual); + } + + @Test + public final void testDeleteService() throws Exception { + String expected = "{\"202\": \"OK\"}"; + doNothing().doThrow(serviceException).doThrow(Exception.class).when(inventoryClient) + .deleteService(Matchers.anyString()); + + String actual = subject.deleteService("srvcId", mockedRequest, mockedResponse); + assertEquals(expected, actual); + + actual = subject.deleteService("srvcId", mockedRequest, mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteService("srvcId", mockedRequest, mockedResponse); + assertTrue(actual.contains("error")); + } + + @Test + public final void testDeleteServiceType() throws Exception { + String expected = "{\"202\": \"OK\"}"; + doNothing().doThrow(serviceTypeException).doThrow(Exception.class).when(inventoryClient) + .deleteServiceType(Matchers.anyString()); + + String actual = subject.deleteServiceType("srvcId", mockedRequest, mockedResponse); + assertEquals(expected, actual); + + actual = subject.deleteServiceType("srvcId", mockedRequest, mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteServiceType("srvcId", mockedRequest, mockedResponse); + assertTrue(actual.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testViewServiceTypeBlueprintContentById() throws Exception { + Optional<ServiceType> expected = Optional.of(bpItem); + when(inventoryClient.getServiceType(Matchers.anyString())).thenReturn(expected) + .thenThrow(httpException).thenThrow(Exception.class); + + String result = subject.viewServiceTypeBlueprintContentById("typeId", mockedRequest); + assertTrue(result.contains("xyz")); + + result = subject.viewServiceTypeBlueprintContentById("typeId", mockedRequest); + assertTrue(result.contains("error")); + + result = subject.viewServiceTypeBlueprintContentById("typeId", mockedRequest); + assertTrue(result.contains("error")); + } + + @Test + public final void testGetServicesForType() throws Exception { + String[] testTypeIds = {"44234234"}; + ServiceRef expectedSrvc = new ServiceRef("dcae_dtiapi_1902", "432423", "433434"); + Collection<ServiceRef> expectedSrvcIds = new ArrayList<ServiceRef>(); + expectedSrvcIds.add(expectedSrvc); + ServiceRefList expectedSrvcRefList = new ServiceRefList(expectedSrvcIds, 1); + + when(inventoryClient.getServicesForType(Matchers.<ServiceQueryParams>any())) + .thenReturn(expectedSrvcRefList); + String actual = subject.getServicesForType(mockedRequest, testTypeIds); + assertTrue(actual.contains(testTypeIds[0])); + } + + /* + * @Test public final void testGetItemListForPageWrapper() { + * fail("Not yet implemented"); // TODO } + * + * @Test public final void testGetServicesForType() { + * fail("Not yet implemented"); // TODO } + * + * + * + * @Test public final void testViewServiceTypeBlueprintContentById() { + * fail("Not yet implemented"); // TODO } + * + * @Test public final void testDeleteServiceType() { + * fail("Not yet implemented"); // TODO } + * + * @Test public final void testDeleteService() { fail("Not yet implemented"); // + * TODO } + * + * @Test public final void testUpdateServiceTypeBlueprint() { + * fail("Not yet implemented"); // TODO } + * + * @Test public final void testUploadServiceTypeBlueprint() { + * fail("Not yet implemented"); // TODO } + * + * @Test public final void testGetAppProperties() { fail("Not yet implemented"); + * // TODO } + * + * @Test public final void testGetOrSetControllerEndpointSelectionLong() { + * fail("Not yet implemented"); // TODO } + * + * @Test public final void testGetOrSetControllerEndpointSelection() { + * fail("Not yet implemented"); // TODO } + * + * @Test public final void testGetInventoryClientHttpServletRequest() { + * fail("Not yet implemented"); // TODO } + * + * @Test public final void testGetInventoryClientLong() { + * fail("Not yet implemented"); // TODO } + */ +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockUser.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockUser.java index 0a331e0..050e3eb 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockUser.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockUser.java @@ -2,23 +2,24 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 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. + * 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========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ + package org.onap.ccsdk.dashboard.core; import java.util.Date; @@ -27,60 +28,60 @@ import org.onap.portalsdk.core.domain.User; public class MockUser { - public User mockUser() { + public User mockUser() { - User ePUser = new User(); - ePUser.setOrgId(null); - ePUser.setManagerId(null); - ePUser.setFirstName("test"); - ePUser.setLastName("test"); - ePUser.setMiddleInitial(null); - ePUser.setPhone(null); - ePUser.setFax(null); - ePUser.setCellular(null); - ePUser.setEmail(null); - ePUser.setAddressId(null); - ePUser.setAlertMethodCd(null); - ePUser.setHrid(null); - ePUser.setOrgUserId("guestT"); - ePUser.setOrgCode(null); - ePUser.setAddress1(null); - ePUser.setAddress2(null); - ePUser.setCity(null); - ePUser.setState(null); - ePUser.setZipCode(null); - ePUser.setCountry(null); - ePUser.setOrgManagerUserId(null); - ePUser.setLocationClli(null); - ePUser.setBusinessCountryCode(null); - ePUser.setBusinessCountryName(null); - ePUser.setBusinessUnit(null); - ePUser.setBusinessUnitName(null); - ePUser.setDepartment(null); - ePUser.setDepartmentName(null); - ePUser.setCompanyCode(null); - ePUser.setCompany(null); - ePUser.setZipCodeSuffix(null); - ePUser.setJobTitle(null); - ePUser.setCommandChain(null); - ePUser.setSiloStatus(null); - ePUser.setCostCenter(null); - ePUser.setFinancialLocCode(null); + User ePUser = new User(); + ePUser.setOrgId(null); + ePUser.setManagerId(null); + ePUser.setFirstName("test"); + ePUser.setLastName("test"); + ePUser.setMiddleInitial(null); + ePUser.setPhone(null); + ePUser.setFax(null); + ePUser.setCellular(null); + ePUser.setEmail(null); + ePUser.setAddressId(null); + ePUser.setAlertMethodCd(null); + ePUser.setHrid(null); + ePUser.setOrgUserId("guestT"); + ePUser.setOrgCode(null); + ePUser.setAddress1(null); + ePUser.setAddress2(null); + ePUser.setCity(null); + ePUser.setState(null); + ePUser.setZipCode(null); + ePUser.setCountry(null); + ePUser.setOrgManagerUserId(null); + ePUser.setLocationClli(null); + ePUser.setBusinessCountryCode(null); + ePUser.setBusinessCountryName(null); + ePUser.setBusinessUnit(null); + ePUser.setBusinessUnitName(null); + ePUser.setDepartment(null); + ePUser.setDepartmentName(null); + ePUser.setCompanyCode(null); + ePUser.setCompany(null); + ePUser.setZipCodeSuffix(null); + ePUser.setJobTitle(null); + ePUser.setCommandChain(null); + ePUser.setSiloStatus(null); + ePUser.setCostCenter(null); + ePUser.setFinancialLocCode(null); - ePUser.setLoginId(null); - ePUser.setLoginPwd(null); - Date date = new Date(); - ePUser.setLastLoginDate(date); - ePUser.setActive(true); - ePUser.setInternal(false); - ePUser.setSelectedProfileId(null); - ePUser.setTimeZoneId(null); - ePUser.setOnline(true); - ePUser.setChatId(null); - ePUser.setUserApps(null); - ePUser.setPseudoRoles(null); + ePUser.setLoginId(null); + ePUser.setLoginPwd(null); + Date date = new Date(); + ePUser.setLastLoginDate(date); + ePUser.setActive(true); + ePUser.setInternal(false); + ePUser.setSelectedProfileId(null); + ePUser.setTimeZoneId(null); + ePUser.setOnline(true); + ePUser.setChatId(null); + ePUser.setUserApps(null); + ePUser.setPseudoRoles(null); - ePUser.setId((long) -1); - return ePUser; - } + ePUser.setId((long) -1); + return ePUser; + } } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockitoTestSuite.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockitoTestSuite.java index c251a5c..e211b35 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockitoTestSuite.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/core/MockitoTestSuite.java @@ -3,7 +3,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -38,6 +38,10 @@ */ package org.onap.ccsdk.dashboard.core; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; @@ -51,45 +55,77 @@ import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class MockitoTestSuite { - - public MockHttpServletRequestWrapper mockedRequest = new MockHttpServletRequestWrapper( - Mockito.mock(HttpServletRequest.class)); - public HttpServletResponse mockedResponse = Mockito.mock(HttpServletResponse.class); - - public MockHttpServletRequestWrapper getMockedRequest() { - return mockedRequest; - } - - public HttpServletResponse getMockedResponse() { - return mockedResponse; - } - - public class MockHttpServletRequestWrapper extends HttpServletRequestWrapper { - - HttpSession session = Mockito.mock(HttpSession.class); - - public MockHttpServletRequestWrapper(HttpServletRequest request) { - super(request); - - } - - @Override - public HttpSession getSession() { - - return session; - } - - @Override - public HttpSession getSession(boolean create) { - - return session; - } - - } - - @Test - public void test() - { - assert(true); - } -}
\ No newline at end of file + public MockHttpServletRequestWrapper mockedRequest = + new MockHttpServletRequestWrapper(Mockito.mock(HttpServletRequest.class)); + public HttpServletResponse mockedResponse = Mockito.mock(HttpServletResponse.class); + + public MockHttpServletRequestWrapper getMockedRequest() { + return mockedRequest; + } + + public HttpServletResponse getMockedResponse() { + return mockedResponse; + } + + public class MockHttpServletRequestWrapper extends HttpServletRequestWrapper { + + HashMap<String, String> params = new HashMap<>(); + + HttpSession session = Mockito.mock(HttpSession.class); + + public MockHttpServletRequestWrapper(HttpServletRequest request) { + super(request); + + } + + @Override + public HttpSession getSession() { + return session; + } + + @Override + public HttpSession getSession(boolean create) { + + return session; + } + + @Override + public String getParameter(final String name) { + // if we added one with the given name, return that one + if (params.get(name) != null) { + return (String) params.get(name); + } else { + // otherwise return what's in the original request + return super.getParameter(name); + } + } + + public void addParameter(String name, String value) { + params.put(name, value); + } + + @Override + public Map<String, String[]> getParameterMap() { + return super.getParameterMap(); + } + + @Override + public Enumeration<String> getParameterNames() { + // defaulf impl, should be overridden for an approprivate map of request params + // names + return super.getParameterNames(); + } + + @Override + public String[] getParameterValues(final String name) { + // defaulf impl, should be overridden for an approprivate map of request params + // values + return super.getParameterValues(name); + } + } + + @Test + public void test() { + assert (true); + } +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java index 5f4f737..a5c5cf8 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java @@ -2,38 +2,39 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 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. + * 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========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ package org.onap.ccsdk.dashboard.rest; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -42,11 +43,31 @@ import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.onap.ccsdk.dashboard.model.CloudifyErrorCause; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprint; +import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; +import org.onap.ccsdk.dashboard.model.CloudifyDeployment; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; +import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateResponse; import org.onap.ccsdk.dashboard.model.CloudifyEvent; import org.onap.ccsdk.dashboard.model.CloudifyEventList; import org.onap.ccsdk.dashboard.model.CloudifyEventList.Metadata; +import org.onap.ccsdk.dashboard.model.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; +import org.onap.ccsdk.dashboard.model.CloudifyNodeId; +import org.onap.ccsdk.dashboard.model.CloudifyNodeIdList; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstance; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceId; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; import org.onap.ccsdk.dashboard.model.CloudifyTenantList; +import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; @@ -60,81 +81,396 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; +@RunWith(PowerMockRunner.class) +@PrepareForTest({DashboardProperties.class}) public class CloudifyRestClientImplTest { - @Mock - RestTemplate mockRest; - - @InjectMocks - CloudifyRestClientImpl subject = - new CloudifyRestClientImpl("https://www.orcl.com/v3.1", "", ""); - - protected final ObjectMapper objectMapper = new ObjectMapper(); - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - objectMapper.registerModule(new Jdk8Module()); - } - - @Test - public final void getEventlogsTest() throws JsonParseException, JsonMappingException, IOException { - String executionId = "123a123a"; - String tenant = "thisTenant"; - List<CloudifyEvent> items = new ArrayList<CloudifyEvent>(); - CloudifyEvent aMockEvent = new CloudifyEvent("dcae_dtieventproc_idns-k8s-svc-blueprint_02_28_02", "dcae_dtieventproc_idns-k8s-svc-blueprint_02_28_02", - null, "workflow_succeeded", "5f8a2e05-e187-4925-90de-ece9160aa517", "warning", "ctx.7a10e191-f12b-4142-aa5d-6e5766ebb1d4", - "install workflow execution succeeded", "publish_l36bhr", "publish", "cloudify.interfaces.lifecycle.create", - "2019-02-28T23:17:49.228Z", "2019-02-28T23:17:49.700Z", "cloudify_event", "install"); - items.add(aMockEvent); - items.add( - new CloudifyEvent("dcae_dtieventproc_idns-k8s-svc-blueprint_02_28_02", "dcae_dtieventproc_idns-k8s-svc-blueprint_02_28_02", - null, "workflow_node_event", "5f8a2e05-e187-4925-90de-ece9160aa517", "warning", "ctx.7a10e191-f12b-4142-aa5d-6e5766ebb1d4", - "Starting node", "publish_l36bhr", "publish", "cloudify.interfaces.lifecycle.create", - "2019-02-28T23:17:48.391Z", "2019-02-28T23:17:48.516Z", "cloudify_event", "install")); - - String metaInfo = "metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}"; - Metadata metadata = null; - //metadata = objectMapper.readValue(metaInfo, Metadata.class); - - CloudifyEventList expected = new CloudifyEventList(items, metadata); - - ResponseEntity<CloudifyEventList> response = new ResponseEntity<CloudifyEventList>(expected, HttpStatus.OK); - Mockito.when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyEventList>>any())).thenReturn(response); - CloudifyEventList actual = subject.getEventlogs(executionId, tenant); - - assertTrue(actual.items.size() == 2); - - } - @Test - public final void testGetTenants_GetData() { - // define the entity you want the exchange to return - String tenantsList = "{\"items\": [{\"id\": 1, \"dName\": null, \"name\": \"default_tenant\"}, {\"id\": 2, \"dName\": null, \"name\": \"dyh1b1902\"}], \"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; - CloudifyTenantList sampleData = null; - try { - sampleData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); - } catch (Exception e) { - } - - ResponseEntity<CloudifyTenantList> response = new ResponseEntity<CloudifyTenantList>(sampleData, HttpStatus.OK); - Mockito.when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyTenantList>>any())).thenReturn(response); - - CloudifyTenantList res = subject.getTenants(); - assertNotNull(res); - assertThat(res.items.get(1).name, is("dyh1b1902")); - // Assert.assertEquals(myobjectA, res.get(0)); - } - - @Test(expected = RestClientException.class) - public final void testGetTenants_withException() { - // define the entity you want the exchange to return - Mockito.when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyTenantList>>any())).thenThrow(RestClientException.class); - - subject.getTenants(); - - - } + @Mock + RestTemplate mockRest; + + @InjectMocks + CloudifyRestClientImpl subject = new CloudifyRestClientImpl(); + + protected final ObjectMapper objectMapper = new ObjectMapper(); + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + objectMapper.registerModule(new Jdk8Module()); + PowerMockito.mockStatic(DashboardProperties.class); + when(DashboardProperties.getControllerProperty("dev", + DashboardProperties.CONTROLLER_SUBKEY_URL)).thenReturn("https://orcl.com"); + this.subject.init(); + } + + @Test + public final void getEventlogsTest() + throws JsonParseException, JsonMappingException, IOException { + String executionId = "123a123a"; + String tenant = "thisTenant"; + List<CloudifyEvent> items = new ArrayList<CloudifyEvent>(); + CloudifyEvent aMockEvent = new CloudifyEvent( + "dcae_dtieventproc_idns-k8s-svc-blueprint_02_28_02", + "dcae_dtieventproc_idns-k8s-svc-blueprint_02_28_02", null, "workflow_succeeded", + "5f8a2e05-e187-4925-90de-ece9160aa517", "warning", + "ctx.7a10e191-f12b-4142-aa5d-6e5766ebb1d4", "install workflow execution succeeded", + "publish_l36bhr", "publish", "cloudify.interfaces.lifecycle.create", + "2019-02-28T23:17:49.228Z", "2019-02-28T23:17:49.700Z", "cloudify_event", "install"); + items.add(aMockEvent); + items.add(new CloudifyEvent("dcae_dtieventproc_idns-k8s-svc-blueprint_02_28_02", + "dcae_dtieventproc_idns-k8s-svc-blueprint_02_28_02", null, "workflow_node_event", + "5f8a2e05-e187-4925-90de-ece9160aa517", "warning", + "ctx.7a10e191-f12b-4142-aa5d-6e5766ebb1d4", "Starting node", "publish_l36bhr", + "publish", "cloudify.interfaces.lifecycle.create", "2019-02-28T23:17:48.391Z", + "2019-02-28T23:17:48.516Z", "cloudify_event", "install")); + + String metaInfo = + "metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}"; + Metadata metadata = null; + + CloudifyEventList expected = new CloudifyEventList(items, metadata); + + ResponseEntity<CloudifyEventList> response = + new ResponseEntity<CloudifyEventList>(expected, HttpStatus.OK); + Mockito + .when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyEventList>>any())) + .thenReturn(response); + CloudifyEventList actual = subject.getEventlogs(executionId, tenant); + assertTrue(actual.items.size() == 2); + + } + + @Test + public final void testGetTenants_GetData() { + // define the entity you want the exchange to return + String tenantsList = + "{\"items\": [{\"id\": 1, \"dName\": null, \"name\": \"default_tenant\"}, {\"id\": 2, \"dName\": null, \"name\": \"dyh1b1902\"}], \"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; + CloudifyTenantList sampleData = null; + try { + sampleData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); + } catch (Exception e) { + } + + ResponseEntity<CloudifyTenantList> response = + new ResponseEntity<CloudifyTenantList>(sampleData, HttpStatus.OK); + Mockito + .when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyTenantList>>any())) + .thenReturn(response); + + CloudifyTenantList res = subject.getTenants(); + assertNotNull(res); + assertThat(res.items.get(1).name, is("dyh1b1902")); + } + + @SuppressWarnings("unchecked") + @Test(expected = RestClientException.class) + public final void testGetTenants_withException() { + // define the entity you want the exchange to return + Mockito + .when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyTenantList>>any())) + .thenThrow(RestClientException.class); + subject.getTenants(); + } + + @Test + public final void testGetNodeInstanceId() { + CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); + List<CloudifyNodeInstanceId> cfyNodeInstItems = new ArrayList<CloudifyNodeInstanceId>(); + cfyNodeInstItems.add(cfyNodeInst); + CloudifyNodeInstanceIdList cfyNodeInstList = + new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); + + ResponseEntity<CloudifyNodeInstanceIdList> response = + new ResponseEntity<CloudifyNodeInstanceIdList>(cfyNodeInstList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyNodeInstanceIdList>>any())) + .thenReturn(response); + + CloudifyNodeInstanceIdList actualResult = + subject.getNodeInstanceId("deploymentId", "nodeId", "tenant"); + assertTrue(actualResult.items.get(0).id.equals("node_instance_id1")); + } + + @Test + public final void testGetNodeInstanceVersion() { + CloudifyNodeInstance cfyNodeInstance = new CloudifyNodeInstance("id1", null); + + List<CloudifyNodeInstance> cfyNodeInstanceItems = new ArrayList<CloudifyNodeInstance>(); + cfyNodeInstanceItems.add(cfyNodeInstance); + + CloudifyNodeInstanceList cfyNodeInstList = + new CloudifyNodeInstanceList(cfyNodeInstanceItems, null); + + ResponseEntity<CloudifyNodeInstanceList> response = + new ResponseEntity<CloudifyNodeInstanceList>(cfyNodeInstList, HttpStatus.OK); + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyNodeInstanceList>>any())) + .thenReturn(response); + + CloudifyNodeInstanceList actualResult = + subject.getNodeInstanceVersion("deploymentId", "nodeId", "tenant"); + assertTrue(actualResult.items.get(0).id.equals("id1")); + } + + @Test + public final void testGetNodeInstanceVersion_blueprint() { + CloudifyNodeId cfyNodeId = new CloudifyNodeId("node_id"); + List<CloudifyNodeId> cfyNodeIdItems = new ArrayList<CloudifyNodeId>(); + cfyNodeIdItems.add(cfyNodeId); + CloudifyNodeIdList cfyNodeIdList = new CloudifyNodeIdList(cfyNodeIdItems, null); + + ResponseEntity<CloudifyNodeIdList> response1 = + new ResponseEntity<CloudifyNodeIdList>(cfyNodeIdList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.contains("nodes"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyNodeIdList>>any())).thenReturn(response1); + + CloudifyNodeInstance cfyNodeInstance = new CloudifyNodeInstance("id1", null); + + List<CloudifyNodeInstance> cfyNodeInstanceItems = new ArrayList<CloudifyNodeInstance>(); + cfyNodeInstanceItems.add(cfyNodeInstance); + + CloudifyNodeInstanceList cfyNodeInstList = + new CloudifyNodeInstanceList(cfyNodeInstanceItems, null); + + ResponseEntity<CloudifyNodeInstanceList> response2 = + new ResponseEntity<CloudifyNodeInstanceList>(cfyNodeInstList, HttpStatus.OK); + when(mockRest.exchange(Matchers.contains("node-instances"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyNodeInstanceList>>any())) + .thenReturn(response2); + + CloudifyNodeInstanceList actualResult = + subject.getNodeInstanceVersion("blueprintId", "tenant"); + assertTrue(actualResult.items.get(0).id.equals("id1")); + } + + @Test + public final void testGetNodeInstanceId_blueprint() { + CloudifyNodeId cfyNodeId = new CloudifyNodeId("node_id"); + List<CloudifyNodeId> cfyNodeIdItems = new ArrayList<CloudifyNodeId>(); + cfyNodeIdItems.add(cfyNodeId); + CloudifyNodeIdList cfyNodeIdList = new CloudifyNodeIdList(cfyNodeIdItems, null); + + ResponseEntity<CloudifyNodeIdList> response1 = + new ResponseEntity<CloudifyNodeIdList>(cfyNodeIdList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.contains("nodes"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyNodeIdList>>any())).thenReturn(response1); + + CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); + List<CloudifyNodeInstanceId> cfyNodeInstItems = new ArrayList<CloudifyNodeInstanceId>(); + cfyNodeInstItems.add(cfyNodeInst); + CloudifyNodeInstanceIdList cfyNodeInstList = + new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); + + ResponseEntity<CloudifyNodeInstanceIdList> response = + new ResponseEntity<CloudifyNodeInstanceIdList>(cfyNodeInstList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.contains("node-instances"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyNodeInstanceIdList>>any())) + .thenReturn(response); + + CloudifyNodeInstanceIdList actualResult = subject.getNodeInstanceId("bpId", "tenant"); + assertTrue(actualResult.items.get(0).id.equals("node_instance_id1")); + } + + @Test + public final void testGetTenantInfoFromDeploy() { + + CloudifyDeployedTenant cldDeplTenant = new CloudifyDeployedTenant("id1", "bp1", "tenant1"); + List<CloudifyDeployedTenant> cldDeplTenantItems = new ArrayList<CloudifyDeployedTenant>(); + cldDeplTenantItems.add(cldDeplTenant); + CloudifyDeployedTenantList cldDeployedTenantList = + new CloudifyDeployedTenantList(cldDeplTenantItems, null); + + ResponseEntity<CloudifyDeployedTenantList> response = + new ResponseEntity<CloudifyDeployedTenantList>(cldDeployedTenantList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.contains("deployments"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyDeployedTenantList>>any())) + .thenReturn(response); + + CloudifyDeployedTenantList actualResults = subject.getTenantInfoFromDeploy("tenant1"); + assertTrue(actualResults.items.get(0).blueprint_id.equals("bp1")); + } + + @Test + public void testGetExecutions() { + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null, false, false); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + ResponseEntity<CloudifyExecutionList> response = + new ResponseEntity<CloudifyExecutionList>(cloudifyExecutionList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.contains("deployment_id"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyExecutionList>>any())) + .thenReturn(response); + + CloudifyExecutionList actualResult = subject.getExecutions("deploymentId1", "tenant1"); + assertTrue(actualResult.items.get(0).id.contains("id1")); + } + + @Test + public void testGetExecutionsSummary() { + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null, false, false); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + ResponseEntity<CloudifyExecutionList> response = + new ResponseEntity<CloudifyExecutionList>(cloudifyExecutionList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.contains("include"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyExecutionList>>any())) + .thenReturn(response); + + CloudifyExecutionList actualResult = + subject.getExecutionsSummary("deploymentId1", "tenant1"); + assertTrue(actualResult.items.get(0).id.contains("id1")); + } + + @Test + public void testStartExecution() { + CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "install", + false, "bp1", "id1", "tenant1", "error", "execution_id1", null, false, false); + + Map<String, Object> params = new HashMap<String, Object>(); + params.put("key1", "value1"); + + CloudifyExecutionRequest cfyExecReq = new CloudifyExecutionRequest("deployment_id", + "upgrade", false, false, "tenant1", params); + + when(mockRest.postForObject(Matchers.anyString(), Matchers.<HttpEntity<?>>any(), + Matchers.<Class<CloudifyExecution>>any())).thenReturn(cfyExecObj); + + CloudifyExecution actualResult = subject.startExecution(cfyExecReq); + assertTrue(actualResult.status.equals("successful")); + } + + @Test + public void testUpdateDeployment() { + CloudifyDeploymentUpdateRequest cfyDeployUpdateReq = + new CloudifyDeploymentUpdateRequest("deployment_id", "update", false, false, + "node_instance_id1", "4", "1000", "image", 2, "my_container"); + + CloudifyDeploymentUpdateResponse cfyDeployUpdateResp = new CloudifyDeploymentUpdateResponse( + "terminated", "created_at", "update", false, "blueprint_id", "deployment_id", "", "id1", + null, "tenant1", "junit", false, "resource_availability"); + + when(mockRest.postForObject(Matchers.anyString(), Matchers.<HttpEntity<?>>any(), + Matchers.<Class<CloudifyDeploymentUpdateResponse>>any())) + .thenReturn(cfyDeployUpdateResp); + + CloudifyDeploymentUpdateResponse actualResult = + subject.updateDeployment(cfyDeployUpdateReq); + assertTrue(actualResult.status.equals("terminated")); + } + + @Test + @Ignore + public void testCancelExecution() { + CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "install", + false, "bp1", "id1", "tenant1", "error", "execution_id1", null, false, false); + + Map<String, Object> params = new HashMap<String, Object>(); + params.put("key1", "value1"); + + ResponseEntity<CloudifyExecution> response = + new ResponseEntity<CloudifyExecution>(cfyExecObj, HttpStatus.OK); + + when(mockRest.exchange(Matchers.contains("executions"), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<?>>any(), Matchers.<Class<CloudifyExecution>>any())) + .thenReturn(response); + + Map<String, String> parameters = new HashMap<String, String>(); + parameters.put("key1", "value1"); + + CloudifyExecution actualResult = + subject.cancelExecution("executionId", parameters, "tenant"); + assertTrue(actualResult.id.equals("execution_id1")); + } + + @Test + @Ignore + public void testGetBlueprint() { + CloudifyBlueprint cldBp = + new CloudifyBlueprint("file1", "description1", "343242", "3423423", "id1", null); + + List<CloudifyBlueprint> items = new ArrayList<CloudifyBlueprint>(); + items.add(cldBp); + + CloudifyBlueprintList.Metadata.Pagination pageObj = + new CloudifyBlueprintList.Metadata.Pagination(1, 0, 1); + + CloudifyBlueprintList.Metadata metadata = new CloudifyBlueprintList.Metadata(pageObj); + + CloudifyBlueprintList cldBpList = new CloudifyBlueprintList(items, metadata); + + ResponseEntity<CloudifyBlueprintList> response = + new ResponseEntity<CloudifyBlueprintList>(cldBpList, HttpStatus.OK); + + doReturn(response).when(mockRest).exchange(Matchers.anyString(), + Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), + Matchers.<Class<CloudifyBlueprintList>>any()); + + CloudifyBlueprintList actualResult = subject.getBlueprint("id1", "tenant1"); + assertTrue(actualResult.items.get(0).id.equals("id1")); + } + + @Test + @Ignore + public void testGetDeployments() { + + CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); + + List<CloudifyDeployment> cfyDeployItems = new ArrayList<CloudifyDeployment>(); + cfyDeployItems.add(cldDeployment); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); + + ResponseEntity<CloudifyDeploymentList> response = + new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.contains("deploy"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), Matchers.<Class<CloudifyDeploymentList>>any())) + .thenReturn(response); + + CloudifyDeploymentList actualResult = subject.getDeployments(); + assertTrue(actualResult.items.get(0).id.equals("id")); + } } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImplTest.java new file mode 100644 index 0000000..f90afa9 --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImplTest.java @@ -0,0 +1,212 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.rest; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.json.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.dashboard.model.ConsulDatacenter; +import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; +import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; +import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; +import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({DashboardProperties.class}) +public class ConsulRestClientImplTest { + + @Mock + RestTemplate mockRest; + + @InjectMocks + ConsulRestClientImpl subject = new ConsulRestClientImpl(); + + protected final ObjectMapper objectMapper = new ObjectMapper(); + HttpClientErrorException httpException; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + objectMapper.registerModule(new Jdk8Module()); + httpException = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "statusText"); + PowerMockito.mockStatic(DashboardProperties.class); + when(DashboardProperties.getControllerProperty("dev", + DashboardProperties.CONTROLLER_SUBKEY_CONSUL_URL)).thenReturn("https://invt.com"); + this.subject.init(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public final void testGetServiceHealth() { + ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", + "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", + "This is a pgaas1_Service_ID health check", + "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", + "pgaas1_Service_ID", "pgaasServer1", 190199, 199395); + + List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); + expectedCnslSrvcHlth.add(consulSrvcHlth); + + ResponseEntity<List<ConsulServiceHealth>> response = + new ResponseEntity<List<ConsulServiceHealth>>(expectedCnslSrvcHlth, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<List<ConsulServiceHealth>>>any())) + .thenReturn(response); + + List<ConsulServiceHealth> actualCnslSrvcHlth = subject.getServiceHealth("dc1", "srvc1"); + assertTrue(actualCnslSrvcHlth.get(0).node.equals("cjlvmcnsl00")); + } + + @Test + @Ignore + public final void testGetServices() { + List<String> srvcIps = new ArrayList<String>(); + srvcIps.add("135.91.224.136"); + srvcIps.add("135.91.224.138"); + ConsulServiceInfo consulSrvcInfo = new ConsulServiceInfo("pgaasServer1", srvcIps); + + List<ConsulServiceInfo> expectedCnslSrvcs = new ArrayList<ConsulServiceInfo>(); + expectedCnslSrvcs.add(consulSrvcInfo); + + // ResponseEntity<Map<String, Object>> response = new ResponseEntity<Map<String, + // Object>>(consulSrvcInfo); + + subject.getServices("dc1"); + } + + @Test + public final void testGetNodes() { + ConsulNodeInfo cnslNode = new ConsulNodeInfo("a2788806-6e2e-423e-8ee7-6cad6f3d3de6", + "cjlvmcnsl00", "10.170.8.13", null, null, 6, 17980); + + List<ConsulNodeInfo> cnslNodeList = new ArrayList<ConsulNodeInfo>(); + cnslNodeList.add(cnslNode); + + ResponseEntity<List<ConsulNodeInfo>> response = + new ResponseEntity<List<ConsulNodeInfo>>(cnslNodeList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<List<ConsulNodeInfo>>>any())).thenReturn(response); + + List<ConsulNodeInfo> actualNodeList = subject.getNodes("dc1"); + assertTrue(actualNodeList.get(0).node.equals("cjlvmcnsl00")); + + } + + @Test + public final void testGetNodeServicesHealth() { + ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", + "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", + "This is a pgaas1_Service_ID health check", + "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", + "pgaas1_Service_ID", "pgaasServer1", 190199, 199395); + + List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); + expectedCnslSrvcHlth.add(consulSrvcHlth); + + ResponseEntity<List<ConsulServiceHealth>> response = + new ResponseEntity<List<ConsulServiceHealth>>(expectedCnslSrvcHlth, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<List<ConsulServiceHealth>>>any())) + .thenReturn(response); + + List<ConsulServiceHealth> actualNodeHlthList = + subject.getNodeServicesHealth("dc1", "nodeId1"); + assertTrue(actualNodeHlthList.get(0).node.equals("cjlvmcnsl00")); + } + + @Test + public final void testGetDatacenters() { + ConsulDatacenter cnslDc = new ConsulDatacenter("dc1"); + + List<ConsulDatacenter> cnslDcList = new ArrayList<ConsulDatacenter>(); + cnslDcList.add(cnslDc); + List<String> dcItems = new ArrayList<String>(); + dcItems.add("dc1"); + + ResponseEntity<List<String>> response = + new ResponseEntity<List<String>>(dcItems, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<List<String>>>any())).thenReturn(response); + List<ConsulDatacenter> actualDcList = subject.getDatacenters(); + assertTrue(actualDcList.get(0).name.equals("dc1")); + } + + @Test + @Ignore + public final void testRegisterService() { + fail("Not yet implemented"); // TODO + } + + @Test + public final void testDeregisterService() { + + JSONObject jsonResp = new JSONObject(); + + ResponseEntity<JSONObject> result = new ResponseEntity<JSONObject>(jsonResp, HttpStatus.OK); + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<JSONObject>>any())) + .thenReturn(result); + + int actualCode = subject.deregisterService("service1"); + assertTrue(actualCode == 200); + } + +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImplTest.java new file mode 100644 index 0000000..7bd085b --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImplTest.java @@ -0,0 +1,366 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.rest; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.stream.Stream; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.onap.ccsdk.dashboard.exceptions.BadRequestException; +import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.DownstreamException; +import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; +import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentLink; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponseLinks; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentsListResponse; +import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.client.RestTemplate; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({DashboardProperties.class}) +public class DeploymentHandlerClientImplTest { + + @Mock + RestTemplate mockRest; + + @InjectMocks + DeploymentHandlerClientImpl subject; + + @Before + public void setUp() throws Exception { + PowerMockito.mockStatic(DashboardProperties.class); + when(DashboardProperties.getControllerProperty("dev", + DashboardProperties.CONTROLLER_SUBKEY_DHANDLER_URL)).thenReturn("https://dplh.com"); + this.subject.init(); + + } + + @After + public void tearDown() throws Exception { + } + + @Test + public final void testGetDeployments() { + Collection<DeploymentLink> expectedDeplRefs = new ArrayList<DeploymentLink>(); + expectedDeplRefs.add(new DeploymentLink("http://dplh.com/dpl1")); + expectedDeplRefs.add(new DeploymentLink("http://dplh.com/dpl11")); + + DeploymentsListResponse expectedDeplList = + new DeploymentsListResponse("req1", expectedDeplRefs); + + ResponseEntity<DeploymentsListResponse> response = + new ResponseEntity<DeploymentsListResponse>(expectedDeplList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentsListResponse>>any())) + .thenReturn(response); + + Stream<DeploymentLink> actualResult = subject.getDeployments(); + assertTrue(actualResult.findFirst().get().getHref().contains("dpl1")); + } + + @Test + public final void testGetDeploymentsString() { + Collection<DeploymentLink> expectedDeplRefs = new ArrayList<DeploymentLink>(); + expectedDeplRefs.add(new DeploymentLink("http://dplh.com/dpl1")); + expectedDeplRefs.add(new DeploymentLink("http://dplh.com/dpl11")); + + DeploymentsListResponse expectedDeplList = + new DeploymentsListResponse("req1", expectedDeplRefs); + + ResponseEntity<DeploymentsListResponse> response = + new ResponseEntity<DeploymentsListResponse>(expectedDeplList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentsListResponse>>any())) + .thenReturn(response); + + Stream<DeploymentLink> actualResult = subject.getDeployments("serviceTypeId"); + assertTrue(actualResult.findFirst().get().getHref().contains("dpl1")); + } + + @Test + public final void testPutDeployment() throws Exception { + DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); + + DeploymentResponseLinks newDeplItemLink = + new DeploymentResponseLinks("selfUrl", "statusUrl"); + DeploymentResponse expectedDeplItem = new DeploymentResponse("req1", newDeplItemLink); + + ResponseEntity<DeploymentResponse> response = + new ResponseEntity<DeploymentResponse>(expectedDeplItem, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())).thenReturn(response); + + DeploymentResponse actualResponse = subject.putDeployment("dpl12", "tenant12", deplReq); + assertTrue(actualResponse.getRequestId().equals("req1")); + } + + @Test(expected = DownstreamException.class) + public final void testPutDeployment_downstreamError() throws Exception { + DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); + + HttpServerErrorException httpException = + new HttpServerErrorException(HttpStatus.BAD_GATEWAY, "statusText"); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) + .thenThrow(httpException); + + subject.putDeployment("dpl12", "tenant12", deplReq); + } + + @Test(expected = BadRequestException.class) + public final void testPutDeployment_badReqError() throws Exception { + DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); + + HttpClientErrorException httpException = + new HttpClientErrorException(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "statusText"); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) + .thenThrow(httpException); + + subject.putDeployment("dpl12", "tenant12", deplReq); + } + + @Test(expected = ServiceAlreadyExistsException.class) + public final void testPutDeployment_srvcExistError() throws Exception { + + DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); + + HttpClientErrorException httpException = + new HttpClientErrorException(HttpStatus.CONFLICT, "statusText"); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) + .thenThrow(httpException); + + subject.putDeployment("dpl12", "tenant12", deplReq); + } + + @Test(expected = ServerErrorException.class) + public final void testPutDeployment_srvcError() throws Exception { + + DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); + + HttpServerErrorException httpException = + new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "statusText"); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) + .thenThrow(httpException); + + subject.putDeployment("dpl12", "tenant12", deplReq); + } + + @Test + public final void testUpdateDeployment() throws Exception { + DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); + + DeploymentResponseLinks newDeplItemLink = + new DeploymentResponseLinks("selfUrl", "statusUrl"); + DeploymentResponse expectedDeplItem = new DeploymentResponse("req1", newDeplItemLink); + + ResponseEntity<DeploymentResponse> response = + new ResponseEntity<DeploymentResponse>(expectedDeplItem, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())).thenReturn(response); + + DeploymentResponse actualResponse = subject.updateDeployment("dpl12", "tenant12", deplReq); + assertTrue(actualResponse.getRequestId().equals("req1")); + } + + @Test(expected = DownstreamException.class) + public final void testUpdateDeployment_downstreamError() throws Exception { + + DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); + + HttpServerErrorException httpException = + new HttpServerErrorException(HttpStatus.BAD_GATEWAY, "statusText"); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) + .thenThrow(httpException); + + subject.updateDeployment("dpl12", "tenant12", deplReq); + + } + + @Test(expected = BadRequestException.class) + public final void testUpdateDeployment_badReqError() throws Exception { + + DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); + + HttpClientErrorException httpException = + new HttpClientErrorException(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "statusText"); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) + .thenThrow(httpException); + + subject.updateDeployment("dpl12", "tenant12", deplReq); + + } + + @Test(expected = ServiceAlreadyExistsException.class) + public final void testUpdateDeployment_srvcExistError() throws Exception { + + DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); + + HttpClientErrorException httpException = + new HttpClientErrorException(HttpStatus.CONFLICT, "statusText"); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) + .thenThrow(httpException); + + subject.updateDeployment("dpl12", "tenant12", deplReq); + + } + + @Test(expected = ServerErrorException.class) + public final void testUpdateDeployment_srvcError() throws Exception { + + DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); + + HttpServerErrorException httpException = + new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "statusText"); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) + .thenThrow(httpException); + + subject.updateDeployment("dpl12", "tenant12", deplReq); + + } + + @Test + public final void testDeleteDeployment() throws Exception { + DeploymentResponseLinks newDeplItemLink = + new DeploymentResponseLinks("selfUrl", "statusUrl"); + DeploymentResponse expectedDeplItem = new DeploymentResponse("req1", newDeplItemLink); + + ResponseEntity<DeploymentResponse> response = + new ResponseEntity<DeploymentResponse>(expectedDeplItem, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())).thenReturn(response); + + subject.deleteDeployment("deploymentId", "tenant"); + } + + @Test(expected = ServerErrorException.class) + public final void testDeleteDeployment_serverError() throws Exception { + HttpServerErrorException httpException = + new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "statusText"); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) + .thenThrow(httpException); + + subject.deleteDeployment("deploymentId", "tenant"); + } + + @Test(expected = DeploymentNotFoundException.class) + public final void testDeleteDeployment_notFoundError() throws Exception { + + HttpServerErrorException httpException = + new HttpServerErrorException(HttpStatus.NOT_FOUND, "statusText"); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) + .thenThrow(httpException); + + subject.deleteDeployment("deploymentId", "tenant"); + } + + @Test(expected = BadRequestException.class) + public final void testDeleteDeployment_badReqError() throws Exception { + + HttpClientErrorException httpException = + new HttpClientErrorException(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "statusText"); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) + .thenThrow(httpException); + + subject.deleteDeployment("deploymentId", "tenant"); + } + + @Test(expected = DownstreamException.class) + public final void testDeleteDeployment_downstreamError() throws Exception { + + HttpServerErrorException httpException = + new HttpServerErrorException(HttpStatus.BAD_GATEWAY, "statusText"); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) + .thenThrow(httpException); + + subject.deleteDeployment("deploymentId", "tenant"); + } + +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImplTest.java new file mode 100644 index 0000000..d4c5e14 --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImplTest.java @@ -0,0 +1,361 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2019 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.rest; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Optional; +import java.util.stream.Stream; + +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.dashboard.model.inventory.ApiResponseMessage; +import org.onap.ccsdk.dashboard.model.inventory.Service; +import org.onap.ccsdk.dashboard.model.inventory.ServiceList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRef; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceType; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; +import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({DashboardProperties.class}) +public class RestInventoryClientImplTest { + + @Mock + RestTemplate mockRest; + + @InjectMocks + RestInventoryClientImpl subject = new RestInventoryClientImpl(); + + protected final ObjectMapper objectMapper = new ObjectMapper(); + + ServiceList deplList = null; + ServiceList deplListNext = null; + Service deplItem = null; + + ServiceType bpItem = null; + ServiceTypeList bpList = null; + ServiceTypeList bpListNext = null; + + ServiceTypeRequest bpUploadItem = null; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + objectMapper.registerModule(new Jdk8Module()); + getExpectedBueprints(); + getExpectedDeployments(); + PowerMockito.mockStatic(DashboardProperties.class); + when(DashboardProperties.getControllerProperty("dev", + DashboardProperties.CONTROLLER_SUBKEY_INVENTORY_URL)).thenReturn("https://invt.com"); + this.subject.init(); + } + + @After + public void tearDown() throws Exception { + } + + public void getExpectedDeployments() + throws JsonParseException, JsonMappingException, IOException { + deplItem = new Service("dcae_dtiapi_1902", null, "1552335532348", "1552335532348", null, + "dummyVnfId", null, "dummyVnfType", "dummyLocation", "dcae_dtiapi_1902", null); + Collection<Service> items = new ArrayList<Service>(); + items.add(deplItem); + + String pageLinks = + "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; + String pageLinks2 = "{\"previousLink\":null,\"nextLink\":null}"; + + ServiceList.PaginationLinks paginationLinks = + objectMapper.readValue(pageLinks, ServiceList.PaginationLinks.class); + ServiceList.PaginationLinks paginationLinks2 = + objectMapper.readValue(pageLinks2, ServiceList.PaginationLinks.class); + + int totalCount = 2; + deplList = new ServiceList(items, totalCount, paginationLinks); + deplListNext = new ServiceList(items, totalCount, paginationLinks2); + } + + public void getExpectedBueprints() + throws JsonParseException, JsonMappingException, IOException { + bpItem = new ServiceType.Builder("xyz1731", "xyz1731-helm-1906", 1906, + "tosca_definitions_version: cloudify_dsl_1_3", "", "app1", "comp1").build(); + Collection<ServiceType> items = new ArrayList<ServiceType>(); + items.add(bpItem); + + String pageLinks = + "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; + String pageLinks2 = "{\"previousLink\":null,\"nextLink\":null}"; + ServiceTypeList.PaginationLinks paginationLinks = + objectMapper.readValue(pageLinks, ServiceTypeList.PaginationLinks.class); + ServiceTypeList.PaginationLinks paginationLinks2 = + objectMapper.readValue(pageLinks2, ServiceTypeList.PaginationLinks.class); + + int totalCount = 2; + bpList = new ServiceTypeList(items, totalCount, paginationLinks); + bpListNext = new ServiceTypeList(items, totalCount, paginationLinks2); + } + + @Test + @Ignore + public final void testInit() { + fail("Not yet implemented"); // TODO + } + + @Test + public final void testGetServiceTypes() { + /* + * String serviceTypeStr = + * "{\"paginationLinks\":{\"previousLink\":null,\"nextLink\":null}},\"totalCount\":32,\"items\":[{\"owner\":\"xyz1731\",\"typeName\":\"xyz1731-helm-1906\",\"typeVersion\":1906,\"blueprintTemplate\":\"tosca_definitions_version: cloudify_dsl_1_3\\nimports:\\n - http://www.getcloudify.org/spec/cloudify/4.2/types.yaml\\n - http://dockercentral.it.att.com:8093/nexus/repository/rawcentral/com.att.dcae.controller/type_files/helm/3.0.1/helm-type.yaml\\ninputs:\\n deployment-description:\\n default: ''\\n chart-name:\\n default: ''\\n tiller-server:\\n default: ''\\n tiller-server-port:\\n default: ''\\n namespace:\\n default: ''\\n chart-repo-url:\\n default: http://32.68.14.161/charts\\n chart-version :\\n default: ''\\n config-url:\\n default: ''\\n config-format:\\n default: ''\\n tls-enable:\\n description: enable helm TSL\\n type: boolean\\n default: false\\n config-dir:\\n description: config dir\\n type: string\\n default: '/opt/manager/resources/'\\n stable-repo-url:\\n description: URL for stable repository\\n type: string\\n default: 'http://32.68.14.161/stable'\\nnode_templates:\\n ecompcomponent:\\n type: onap.nodes.component\\n properties:\\n tiller-server-ip: { get_input: tiller-server }\\n tiller-server-port: { get_input: tiller-server-port }\\n component-name: { get_input: chart-name }\\n chart-repo-url: { concat: [ 'http://', { get_secret: controller_helm_user }, ':', { get_secret: controller_helm_password }, '@', { get_input: chart-repo-url } ] }\\n chart-version: { get_input: chart-version }\\n namespace: { get_input: namespace }\\n config-url: { concat: [ 'http://', { get_secret: controller_helm_user }, ':', { get_secret: controller_helm_password }, '@', { get_input: config-url } ] }\\n config-format: { get_input: config-format}\\n tls-enable: { get_input: tls-enable}\\n ca: { get_secret: ca_value}\\n cert: { get_secret: cert_value}\\n key: { get_secret: key_value}\\n config-dir: { get_input: config-dir}\\n stable-repo-url: { concat: [ 'http://', { get_secret: controller_helm_user }, ':', { get_secret: controller_helm_password }, '@', { get_input: stable-repo-url } ] }\\noutputs:\\n ecompcomponent-helm-output:\\n description: helm value and helm history\\n value:\\n helm-value: { get_attribute: [ecompcomponent, current-helm-value] }\\n helm-history: { get_attribute: [ecompcomponent, helm-history] }\",\"serviceIds\":[],\"vnfTypes\":[],\"serviceLocations\":[],\"asdcServiceId\":\"\",\"asdcResourceId\":\"\",\"asdcServiceURL\":null,\"application\":\"ECOMP\",\"component\":\"controller\",\"typeId\":\"72b8577a-5043-43ab-9aa5-6808b8f53967\",\"selfLink\":{\"rel\":\"self\",\"href\":\"https://ecompc-invt-dev-s5.ecomp.idns.cip.att.com:30123/dcae-service-types/72b8577a-5043-43ab-9aa5-6808b8f53967\"},\"created\":1551214264536,\"deactivated\":null}]" + * ; ServiceTypeList sampleData = null; try { sampleData = + * objectMapper.readValue(serviceTypeStr, ServiceTypeList.class); } catch + * (Exception e) { } + */ + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> expectedResult = items.stream(); + + ResponseEntity<ServiceTypeList> response = + new ResponseEntity<ServiceTypeList>(bpList, HttpStatus.OK); + + ResponseEntity<ServiceTypeList> response2 = + new ResponseEntity<ServiceTypeList>(bpListNext, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<ServiceTypeList>>any())).thenReturn(response) + .thenReturn(response2); + + Stream<ServiceType> actualResult = subject.getServiceTypes(); + assertNotNull(actualResult); + assertTrue(expectedResult.count() == actualResult.count()); + } + + @Test + public final void testGetServiceTypesServiceTypeQueryParams() { + ServiceTypeQueryParams qryParms = new ServiceTypeQueryParams.Builder() + .asdcResourceId("asdcResourceId").asdcServiceId("asdcServiceId").onlyActive(true) + .onlyLatest(false).serviceId("serviceId").serviceLocation("serviceLocation") + .typeName("typeName").vnfType("vnfType").build(); + Collection<ServiceType> items = bpList.items; + Stream<ServiceType> expectedResult = items.stream(); + + ResponseEntity<ServiceTypeList> response = + new ResponseEntity<ServiceTypeList>(bpList, HttpStatus.OK); + + ResponseEntity<ServiceTypeList> response2 = + new ResponseEntity<ServiceTypeList>(bpListNext, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<ServiceTypeList>>any())).thenReturn(response) + .thenReturn(response2); + + Stream<ServiceType> actualResult = subject.getServiceTypes(qryParms); + assertNotNull(actualResult); + assertTrue(expectedResult.count() == actualResult.count()); + } + + @Test + public final void testGetServiceType() { + Optional<ServiceType> expectedResult = Optional.of(bpItem); + + ResponseEntity<ServiceType> response = + new ResponseEntity<ServiceType>(bpItem, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<ServiceType>>any())) + .thenReturn(response); + + Optional<ServiceType> actualResult = subject.getServiceType("432432423"); + assertTrue(expectedResult.get().getTypeName().equals(actualResult.get().getTypeName())); + } + + @Test + public final void testAddServiceTypeServiceType() { + + when(mockRest.postForObject(Matchers.anyString(), Matchers.<HttpEntity<?>>any(), + Matchers.<Class<ServiceType>>any())).thenReturn(bpItem); + + ServiceType actualResult = subject.addServiceType(bpItem); + assertTrue(actualResult.getTypeName().contains("xyz")); + } + + @Test + public final void testAddServiceTypeServiceTypeRequest() { + ServiceTypeRequest srvcReq = ServiceTypeRequest.from(bpItem); + + when(mockRest.postForObject(Matchers.anyString(), Matchers.<HttpEntity<?>>any(), + Matchers.<Class<ServiceType>>any())).thenReturn(bpItem); + + ServiceType actualResult = subject.addServiceType(srvcReq); + assertTrue(actualResult.getTypeName().contains("xyz")); + } + + @Test + public final void testDeleteServiceType() throws Exception { + ResponseEntity<ApiResponseMessage> response = + new ResponseEntity<ApiResponseMessage>(HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<ApiResponseMessage>>any())).thenReturn(response); + + subject.deleteServiceType("4243234"); + } + + @Test + public final void testGetServices() { + + Collection<Service> items = deplList.items; + Stream<Service> expectedResult = items.stream(); + + ResponseEntity<ServiceList> response = + new ResponseEntity<ServiceList>(deplList, HttpStatus.OK); + + ResponseEntity<ServiceList> response2 = + new ResponseEntity<ServiceList>(deplListNext, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<ServiceList>>any())) + .thenReturn(response).thenReturn(response2); + + Stream<Service> actualResult = subject.getServices(); + assertNotNull(actualResult); + assertTrue(expectedResult.count() == actualResult.count()); + + } + + @Test + public final void testGetServicesForType() { + ResponseEntity<ServiceList> response = + new ResponseEntity<ServiceList>(deplList, HttpStatus.OK); + + ResponseEntity<ServiceList> response2 = + new ResponseEntity<ServiceList>(deplListNext, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<ServiceList>>any())) + .thenReturn(response).thenReturn(response2); + ServiceQueryParams qryParms = new ServiceQueryParams.Builder().typeId("typeId").build(); + + ServiceRefList actualResult = subject.getServicesForType(qryParms); + assertTrue(actualResult.items.size() == 2); + ServiceRef actualSrvcItem = (ServiceRef) actualResult.items.toArray()[0]; + assertTrue(actualSrvcItem.getServiceId().contains("dtiapi")); + + } + + @Test + public final void testGetServicesServiceQueryParams() { + ServiceQueryParams qryParms = new ServiceQueryParams.Builder().typeId("typeId") + .vnfId("vnfId").vnfLocation("vnfLocation").vnfType("vnfType") + .componentType("componentType").shareable(false).created("43443423").build(); + + Collection<Service> items = deplList.items; + Stream<Service> expectedResult = items.stream(); + + ResponseEntity<ServiceList> response = + new ResponseEntity<ServiceList>(deplList, HttpStatus.OK); + + ResponseEntity<ServiceList> response2 = + new ResponseEntity<ServiceList>(deplListNext, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<ServiceList>>any())) + .thenReturn(response).thenReturn(response2); + + Stream<Service> actualResult = subject.getServices(qryParms); + assertTrue(expectedResult.count() == actualResult.count()); + } + + @Test + public final void testGetService() { + Optional<Service> expectedResult = Optional.of(deplItem); + + ResponseEntity<Service> response = new ResponseEntity<Service>(deplItem, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<Service>>any())) + .thenReturn(response); + + Optional<Service> actualResult = subject.getService("432432423"); + assertTrue( + expectedResult.get().getDeploymentRef().equals(actualResult.get().getDeploymentRef())); + } + + @Test + public final void testPutService() { + + ResponseEntity<Service> response = new ResponseEntity<Service>(deplItem, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<Service>>any())) + .thenReturn(response); + + subject.putService("423423", deplItem); + } + + @Test + public final void testDeleteService() throws Exception { + ResponseEntity<ApiResponseMessage> response = + new ResponseEntity<ApiResponseMessage>(HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<ApiResponseMessage>>any())).thenReturn(response); + + subject.deleteService("4243234"); + } + +} |