diff options
Diffstat (limited to 'ccsdk-app-common/src/main')
20 files changed, 947 insertions, 2717 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 - - } -} |