diff options
author | Kotagiri, Ramprasad (rp5662) <rp5662@att.com> | 2020-08-21 08:40:37 -0400 |
---|---|---|
committer | Kotagiri, Ramprasad (rp5662) <rp5662@att.com> | 2020-08-21 08:52:29 -0400 |
commit | 47b65efd69c5158d958261846803d2e15adfb448 (patch) | |
tree | d0f3752b551a31cf39a36cbee16392bbcc36c72b /ccsdk-app-common/src | |
parent | c32511155acad5b70dcc3cf29e9bfa36276f3894 (diff) |
java 11 upgrade and sonar scan fixes
Recompile java source code using jdk11
Run in ojdk11 JRE
tomcat container upgrade
alpine base image
Issue-ID: DCAEGEN2-2298
Change-Id: Ic4bf2626e5805508589cafe52b7c4e91d7ae3580
Signed-off-by: Kotagiri, Ramprasad (rp5662) <rp5662@att.com>
Diffstat (limited to 'ccsdk-app-common/src')
109 files changed, 6170 insertions, 6490 deletions
diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/ApiBaseController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/ApiBaseController.java index ec30b92..4584270 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/ApiBaseController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/ApiBaseController.java @@ -2,22 +2,23 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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========================================================= * *******************************************************************************/ + package org.onap.ccsdk.api.controller; import java.text.DateFormat; @@ -37,22 +38,23 @@ import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; public class ApiBaseController extends UnRestrictedBaseController { /** - * Application name + * Application name. */ protected static final String APP_NAME = "ecd-app"; /** - * EELF-approved format + * EELF-approved format. */ - protected static final DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + protected final DateFormat logDateFormat = + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); /** - * Query parameter for desired page number + * Query parameter for desired page number. */ protected static final String PAGE_NUM_QUERY_PARAM = "page"; /** - * Query parameter for desired items per page + * Query parameter for desired items per page. */ protected static final String PAGE_SIZE_QUERY_PARAM = "size"; @@ -67,7 +69,6 @@ public class ApiBaseController extends UnRestrictedBaseController { @Autowired protected DashboardProperties appProperties; - /** * Hello Spring, here's your no-arg constructor. */ @@ -94,13 +95,14 @@ public class ApiBaseController extends UnRestrictedBaseController { * * @param request HttpServletRequest * @return Value of query parameter {@link #PAGE_NUM_QUERY_PARAM}; 1 if not - * found. + * found. */ protected int getRequestPageNumber(HttpServletRequest request) { int pageNum = 1; String param = request.getParameter(PAGE_NUM_QUERY_PARAM); - if (param != null) + if (param != null) { pageNum = Integer.parseInt(param); + } return pageNum; } @@ -111,33 +113,37 @@ public class ApiBaseController extends UnRestrictedBaseController { * * @param request HttpServletRequest * @return Value of query parameter {@link #PAGE_SIZE_QUERY_PARAM}; 50 if not - * found. + * found. */ protected int getRequestPageSize(HttpServletRequest request) { int pageSize = 25; String param = request.getParameter(PAGE_SIZE_QUERY_PARAM); - if (param != null) + if (param != null) { pageSize = Integer.parseInt(param); + } return pageSize; } /** * Gets the items for the specified page from the specified list. * - * @param pageNum Page number requested by user, indexed from 1 + * @param pageNum Page number requested by user, indexed from 1 * @param pageSize Number of items per page * @param itemList List of items to adjust * @return List of items; empty list if from==to */ @SuppressWarnings("rawtypes") - protected static List getPageOfList(final int pageNum, final int pageSize, final List itemList) { + protected static List getPageOfList(final int pageNum, final int pageSize, + final List itemList) { int firstIndexOnThisPage = pageSize * (pageNum - 1); int firstIndexOnNextPage = pageSize * pageNum; - int fromIndex = firstIndexOnThisPage < itemList.size() ? firstIndexOnThisPage : itemList.size(); - int toIndex = firstIndexOnNextPage < itemList.size() ? firstIndexOnNextPage : itemList.size(); + int fromIndex = + firstIndexOnThisPage < itemList.size() ? firstIndexOnThisPage : itemList.size(); + int toIndex = + firstIndexOnNextPage < itemList.size() ? firstIndexOnNextPage : itemList.size(); return itemList.subList(fromIndex, toIndex); } - + @Override public boolean isRESTfulCall() { return true; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/NbApiController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/NbApiController.java index 525711d..301164b 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/NbApiController.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/NbApiController.java @@ -28,7 +28,6 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.NoSuchElementException; import java.util.Optional; import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; @@ -58,6 +57,7 @@ import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployment; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionRequest; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyTenant; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentInput; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResource; @@ -70,10 +70,10 @@ import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; import org.onap.ccsdk.dashboard.model.inventory.ServiceRef; import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; import org.onap.ccsdk.dashboard.model.inventory.ServiceType; -import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummary; 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.model.inventory.ServiceTypeSummary; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeUploadRequest; import org.onap.ccsdk.dashboard.rest.CloudifyClient; import org.onap.ccsdk.dashboard.rest.ConsulClient; @@ -86,7 +86,11 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.http.HttpHeaders; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; @@ -110,6 +114,21 @@ public class NbApiController extends ApiBaseController { private static final String EXECUTIONS_PATH = "executions"; private static final String TENANTS_PATH = "tenants"; private static final String SERVICE_HEALTH_PATH = "health"; + private static final String TARGET_ENTITY_KEY = "TargetEntity"; + private static final String TARGET_SERVICE_KEY = "TargetServiceName"; + private static final String INV_BP_ENTITY = "DCAE Blueprint"; + private static final String INV_TARGET_SERVICE = "DCAE Inventory"; + private static final String CFY_DEP_ENTITY = "DCAE Deployment"; + private static final String CFY_TARGET_SERVICE = "DCAE Cloudify"; + private static final String CFY_EXEC_ENTITY = "Executions"; + private static final String CNSL_SVC_ENTITY = "Consul Service"; + private static final String CNSL_TARGET_SERVICE = "Consul API"; + private static final String ERROR_RESPONSE = "ERROR"; + private static final String ERROR_CODE_KEY = "ErrorCode"; + private static final String ERROR_CODE = "300"; + private static final String ERROR_CATEGORY_KEY = "ErrorCategory"; + private static final String ERROR_CATEGORY = "ERROR"; + private static final String ERROR_DESCRIPTION_KEY = "ErrorDescription"; @Autowired InventoryClient inventoryClient; @@ -144,48 +163,81 @@ public class NbApiController extends ApiBaseController { DEPLOYMENTS, BLUEPRINTS, SERVICES_GROUPBY; } - private static Date begin, end; - /** - * get the tenants list + * get the tenants list. * * @param request HttpServletRequest * @return List of CloudifyDeployment objects */ - @SuppressWarnings("rawtypes") - @RequestMapping( - value = {TENANTS_PATH}, - method = RequestMethod.GET, - produces = "application/json") - @ResponseBody + @SuppressWarnings({"unchecked"}) + @GetMapping(value = TENANTS_PATH, produces = "application/json") public String getTenants(HttpServletRequest request) throws Exception { preLogAudit(request); - List itemList = cloudifyClient.getTenants().items; + List<CloudifyTenant> itemList = cloudifyClient.getTenants().items; final int totalItems = itemList.size(); final int pageSize = 20; final int pageNum = 1; final int pageCount = (int) Math.ceil((double) totalItems / pageSize); - if (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; + } + RestResponsePage<List<CloudifyTenant>> model = + new RestResponsePage<>(totalItems, pageCount, itemList); + return objectMapper.writeValueAsString(model); } - private boolean isAuthorized(HttpServletRequest request, String component) { - boolean auth = true; - return auth; + private boolean isAuthorized() { + return true; } - @RequestMapping( - value = {SERVICE_TYPES_PATH}, - method = RequestMethod.POST, - produces = "application/json") + private String getSelfLink(String uriSelf) { + StringBuffer selfSb = new StringBuffer(); + selfSb.append("<").append(uriSelf).append(">; rel=\"self\""); + return selfSb.toString(); + } + + private String getAllLink(String uriAll) { + StringBuffer allSb = new StringBuffer(); + allSb.append("<").append(uriAll).append(">; rel=\"current\""); + return allSb.toString(); + } + + private void publishResponseHeader(ServletUriComponentsBuilder uriBuilder, + HttpServletResponse response, int page, int pageCount, int size) { + try { + uriBuilder = ServletUriComponentsBuilder.fromCurrentRequest(); + eventPub.publishEvent(new PaginatedResultsRetrievedEvent<String>(String.class, + uriBuilder, response, page, pageCount, size)); + } catch (Exception e) { + // skip exception + } + } + + private String getJsonErr(String errStr) { + final String errJsonStr = "{ \"error\" : \""; + StringBuffer errJson = new StringBuffer(); + errJson.append(errJsonStr).append(errStr).append("\"}"); + return errJson.toString(); + } + + /** + * Upload new blueprint to inventory. + * + * @param request + * @param response + * @param serviceTypeUplReq + * @param uriBuilder + * @return + * @throws Exception + */ + @PostMapping(value = {SERVICE_TYPES_PATH}, produces = "application/json") public String createBlueprint(HttpServletRequest request, HttpServletResponse response, @RequestBody ServiceTypeUploadRequest serviceTypeUplReq, ServletUriComponentsBuilder uriBuilder) throws Exception { preLogAudit(request); String json = null; + final String errDescrStr = "Uploading service type failed!"; + final String errLogStr = "Uploading service type caught exception"; try { Blueprint.parse(serviceTypeUplReq.getBlueprintTemplate()); @@ -196,17 +248,9 @@ public class NbApiController extends ApiBaseController { "Component name missing in blueprint request body"); return json; } - - if (!isAuthorized(request, serviceTypeUplReq.component)) { - response.setStatus(HttpStatus.SC_FORBIDDEN); - json = objectMapper.writeValueAsString( - new RestResponseError("Un-authorized to perform this operation")); - return json; - } - - Collection<String> serviceIds = new ArrayList<String>(); - Collection<String> vnfTypes = new ArrayList<String>(); - Collection<String> serviceLocations = new ArrayList<String>(); + Collection<String> serviceIds = new ArrayList<>(); + Collection<String> vnfTypes = new ArrayList<>(); + Collection<String> serviceLocations = new ArrayList<>(); Optional<String> asdcServiceId = null; Optional<String> asdcResourceId = null; Optional<String> asdcServiceURL = null; @@ -220,53 +264,48 @@ public class NbApiController extends ApiBaseController { json = objectMapper.writeValueAsString(apiResponse); String uri = request.getRequestURI(); if (uri != null) { - String uri_all = uriBuilder.replacePath(uri).build().toUriString(); - String uri_self = - uriBuilder.path("/" + apiResponse.getTypeId().get()).build().toUriString(); - StringBuffer linkHeader = new StringBuffer(); - String linkStr_all = "<" + uri_all + ">; rel=\"" + "current" + "\""; - String linkStr_self = "<" + uri_self + ">; rel=\"" + "self" + "\""; - linkHeader.append(linkStr_self); - if (linkHeader.length() > 0) { - linkHeader.append(", "); - } - linkHeader.append(linkStr_all); - response.addHeader("Link", linkHeader.toString()); + String uriAll = uriBuilder.replacePath(uri).build().toUriString(); + StringBuffer linkHeader = new StringBuffer(); + String currTypeId = apiResponse.getTypeId().orElse("missingId"); + String uriSelf = uriBuilder.path("/" + currTypeId).build().toUriString(); + linkHeader.append(getSelfLink(uriSelf)); + if (linkHeader.length() > 0) { + linkHeader.append(", "); + } + linkHeader.append(getAllLink(uriAll)); + response.addHeader("Link", linkHeader.toString()); } } catch (BlueprintParseException e) { response.setStatus(HttpStatus.SC_BAD_REQUEST); - 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"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, INV_BP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, INV_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errDescrStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); json = objectMapper .writeValueAsString(new RestResponseError("Invalid blueprint format.", e)); } catch (HttpStatusCodeException e) { response.setStatus(HttpStatus.SC_BAD_GATEWAY); - 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"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, INV_BP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, INV_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errDescrStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); json = objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); - } catch (Throwable t) { + } catch (Exception t) { response.setStatus(HttpStatus.SC_BAD_REQUEST); - 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"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, INV_BP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, INV_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errDescrStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); json = objectMapper .writeValueAsString(new RestResponseError("updateServiceTypeBlueprint failed", t)); } finally { @@ -275,17 +314,26 @@ public class NbApiController extends ApiBaseController { return json; } - @SuppressWarnings("unchecked") - @RequestMapping( - value = {SERVICE_TYPES_PATH}, - method = RequestMethod.GET, - produces = "application/json") + /** + * Query all blueprints from inventory, follows pagination. + * + * @param request + * @param page + * @param size + * @param uriBuilder + * @param response + * @return + */ + @GetMapping(value = {SERVICE_TYPES_PATH}, produces = "application/json") public String getBlueprintsByPage(HttpServletRequest request, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, ServletUriComponentsBuilder uriBuilder, HttpServletResponse response) { preLogAudit(request); String json = null; + RestResponseError result = null; + final String errDescrStr = "Getting page of blueprints items failed!"; + final String errLogStr = "getBlueprintsByPage caught exception"; if (page == null || page == 0) { page = 1; } @@ -296,152 +344,121 @@ public class NbApiController extends ApiBaseController { int totalItems = 0; List itemList = null; try { - itemList = getItemListForPageWrapper(request, InventoryDataItem.BLUEPRINTS); + itemList = getItemListForPageWrapper(request); // Shrink if needed if (itemList != null) { totalItems = itemList.size(); } final int pageCount = (int) Math.ceil((double) totalItems / size); - if (totalItems > size) + if (totalItems > size) { itemList = getPageOfList(pageNum, size, itemList); - + } RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); json = objectMapper.writeValueAsString(model); - + publishResponseHeader(uriBuilder, response, page, pageCount, size); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, INV_BP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, INV_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errDescrStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + result = new RestResponseError((e).getResponseBodyAsString()); try { - uriBuilder = ServletUriComponentsBuilder.fromCurrentRequest(); - eventPub.publishEvent(new PaginatedResultsRetrievedEvent<String>(String.class, - uriBuilder, response, page, pageCount, size)); - } catch (Exception e) { - // skip exception + json = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + json = getJsonErr(jpe.toString()); } } catch (Exception e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting page of blueprints items failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getBlueprintsByPage caught exception"); - RestResponseError result = null; - if (e instanceof HttpStatusCodeException) - result = - new RestResponseError(((HttpStatusCodeException) e).getResponseBodyAsString()); - else - result = new RestResponseError("Failed to get blueprints", e); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, INV_BP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, INV_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errDescrStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + result = new RestResponseError("Failed to get blueprints", e); try { json = objectMapper.writeValueAsString(result); } catch (JsonProcessingException jpe) { - // Should never, ever happen - json = "{ \"error\" : \"" + jpe.toString() + "\"}"; + json = getJsonErr(jpe.toString()); } - return json; } finally { postLogAudit(request); } return json; } - private List getItemListForPageWrapper(HttpServletRequest request, InventoryDataItem option) { - Set<String> userRoleSet = (Set<String>) request.getAttribute("userRoles"); - Set<String> userApps = (Set<String>) request.getAttribute("userApps"); - String sort = request.getParameter("sort"); - - Predicate<String> adminPred = - p -> p.contains("System_Administrator") || p.contains("Write_Access"); - - Predicate<String> ecompSuperPred = - p -> p.contains("ECOMPC_WRITE") || p.contains("ECOMPC_READ"); - - ReadWriteLock lock = new ReentrantReadWriteLock(); - List itemList = null; - try { - lock.readLock().lock(); - itemList = (List<ServiceTypeSummary>) getCacheManager().getObject("dcae-service-types"); - lock.readLock().unlock(); - if (itemList == null) { - ServiceTypeQueryParams serviceQueryParams = null; - itemList = inventoryClient.getServiceTypes().collect(Collectors.toList()); - } - if (userRoleSet != null) { - if (userRoleSet.stream().noneMatch(adminPred)) { - if (userRoleSet.stream().noneMatch(ecompSuperPred)) { - itemList = (List<ServiceTypeSummary>) itemList.stream() - .filter(s -> userApps.stream() - .anyMatch(appFilter -> (((ServiceTypeSummary) s).getComponent() != null - && ((ServiceTypeSummary) s).getComponent() - .equalsIgnoreCase(appFilter)))) - .collect(Collectors.<ServiceTypeSummary>toList()); - } else { - Predicate<ServiceTypeSummary> appFilter = - p -> p.getComponent() != null && !p.getComponent().equalsIgnoreCase("dcae"); - itemList = (List<ServiceTypeSummary>) itemList.stream().filter(appFilter) - .collect(Collectors.toList()); - } - } - } - // Handle request filter object - String filters = request.getParameter("filters"); - if (filters != null) { - JSONObject filterJson = new JSONObject(filters); - - if (filterJson.has("owner")) { - String ownFilter = filterJson.getString("owner"); - Predicate<ServiceTypeSummary> ownPred = - p -> p.getOwner() != null && p.getOwner().contains(ownFilter); - itemList = (List<ServiceTypeSummary>) itemList.stream().filter(ownPred) - .collect(Collectors.toList()); - } + private List<ServiceTypeSummary> processRequestFilters(HttpServletRequest request, + List<ServiceTypeSummary> itemList) { + String filters = request.getParameter("filters"); + final String ownerStr = "owner"; + if (filters != null) { + JSONObject filterJson = new JSONObject(filters); + if (filterJson.has(ownerStr)) { + String ownFilter = filterJson.getString(ownerStr); + Predicate<ServiceTypeSummary> ownPred = + p -> p.getOwner() != null && p.getOwner().contains(ownFilter); + itemList = itemList.stream().filter(ownPred).collect(Collectors.toList()); + } + if (filterJson.has("name")) { + String bpNameFilter = filterJson.getString("name"); + Predicate<ServiceTypeSummary> bpNamePred = + p -> p.getTypeName() != null && p.getTypeName().contains(bpNameFilter); + itemList = itemList.stream().filter(bpNamePred).collect(Collectors.toList()); + } + if (filterJson.has("id")) { + String bpIdFilter = filterJson.getString("id"); + Predicate<ServiceTypeSummary> bpIdPred = + p -> p.getTypeId().get().contains(bpIdFilter); + itemList = itemList.stream().filter(bpIdPred).collect(Collectors.toList()); + } + } + return itemList; + } - if (filterJson.has("name")) { - String bpNameFilter = filterJson.getString("name"); - Predicate<ServiceTypeSummary> bpNamePred = - p -> p.getTypeName() != null && p.getTypeName().contains(bpNameFilter); - itemList = (List<ServiceTypeSummary>) itemList.stream().filter(bpNamePred) - .collect(Collectors.toList()); - } + @SuppressWarnings("unchecked") + private List getItemListForPageWrapper(HttpServletRequest request) throws Exception { + String sort = request.getParameter("sort"); + ReadWriteLock lock = new ReentrantReadWriteLock(); + List<ServiceTypeSummary> itemList = null; + try { + lock.readLock().lock(); + itemList = (List<ServiceTypeSummary>) getCacheManager().getObject("dcae-service-types"); + lock.readLock().unlock(); + if (itemList == null) { + itemList = inventoryClient.getServiceTypes().collect(Collectors.toList()); + } + // Handle request filter object + itemList = processRequestFilters(request, itemList); - if (filterJson.has("id")) { - String bpIdFilter = filterJson.getString("id"); - Predicate<ServiceTypeSummary> bpIdPred = - p -> p.getTypeId().get().contains(bpIdFilter); - itemList = (List<ServiceTypeSummary>) itemList.stream().filter(bpIdPred) - .collect(Collectors.toList()); - } - } - if (sort != null) { - if (sort.equals("owner")) { - ((List<ServiceTypeSummary>) itemList).sort((ServiceTypeSummary o1, - ServiceTypeSummary o2) -> o1.getOwner().compareTo(o2.getOwner())); - } else if (sort.equals("typeId")) { - ((List<ServiceTypeSummary>) itemList) - .sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getTypeId().get() - .compareTo(o2.getTypeId().get())); - } else if (sort.equals("typeName")) { - ((List<ServiceTypeSummary>) itemList).sort((ServiceTypeSummary o1, - ServiceTypeSummary o2) -> o1.getTypeName().compareTo(o2.getTypeName())); - } else if (sort.equals("typeVersion")) { - ((List<ServiceTypeSummary>) itemList) - .sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getTypeVersion() - .compareTo(o2.getTypeVersion())); - } else if (sort.equals("created")) { - ((List<ServiceTypeSummary>) itemList) - .sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getCreated() - .get().compareTo(o2.getCreated().get())); - } - } - } catch (Exception e) { - throw e; - } finally { - postLogAudit(request); + if (sort != null) { + if (sort.equals("owner")) { + (itemList).sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getOwner() + .compareTo(o2.getOwner())); + } else if (sort.equals("typeId")) { + (itemList).sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getTypeId() + .get().compareTo(o2.getTypeId().get())); + } else if (sort.equals("typeName")) { + (itemList).sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1 + .getTypeName().compareTo(o2.getTypeName())); + } else if (sort.equals("typeVersion")) { + (itemList).sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1 + .getTypeVersion().compareTo(o2.getTypeVersion())); + } else if (sort.equals("created")) { + (itemList).sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1 + .getCreated().get().compareTo(o2.getCreated().get())); } - return itemList; + } + } finally { + postLogAudit(request); + } + return itemList; } - @RequestMapping( - value = {DEPLOYMENTS_PATH + "/{deploymentId}"}, - method = RequestMethod.GET, - produces = "application/json") + @GetMapping(value = {DEPLOYMENTS_PATH + "/{deploymentId}"}, produces = "application/json") public String getDeployment(@PathVariable("deploymentId") String deploymentId, HttpServletRequest request) { preLogAudit(request); @@ -449,19 +466,25 @@ public class NbApiController extends ApiBaseController { try { List<CloudifyDeployment> items = cloudifyClient.getDeployment(deploymentId).items; json = objectMapper.writeValueAsString(items); + } catch (HttpStatusCodeException gen) { + logger.error(EELFLoggerDelegate.errorLogger, "getDeployment caught exception"); + RestResponseError result = null; + result = new RestResponseError(gen.getResponseBodyAsString()); + try { + json = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + json = getJsonErr(jpe.toString()); + } } catch (Exception gen) { logger.error(EELFLoggerDelegate.errorLogger, "getDeployment caught exception"); RestResponseError result = null; - if (gen instanceof HttpStatusCodeException) - result = new RestResponseError( - ((HttpStatusCodeException) gen).getResponseBodyAsString()); - else - result = new RestResponseError("Failed to get deployment", gen); + result = new RestResponseError("Failed to get deployment", gen); try { json = objectMapper.writeValueAsString(result); } catch (JsonProcessingException jpe) { // Should never, ever happen - json = "{ \"error\" : \"" + jpe.toString() + "\"}"; + json = getJsonErr(jpe.toString()); } } finally { postLogAudit(request); @@ -470,10 +493,7 @@ public class NbApiController extends ApiBaseController { } @SuppressWarnings("unchecked") - @RequestMapping( - value = {DEPLOYMENTS_PATH}, - method = RequestMethod.GET, - produces = "application/json") + @GetMapping(value = {DEPLOYMENTS_PATH}, produces = "application/json") public String getDeploymentsByPage(HttpServletRequest request, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @@ -502,42 +522,47 @@ public class NbApiController extends ApiBaseController { } RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); outboundJson = objectMapper.writeValueAsString(model); + publishResponseHeader(uriBuilder, response, page, pageCount, size); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, "Getting page of deployments items failed!"); + logger.error(EELFLoggerDelegate.errorLogger, + "getAllDeploymentsByPage caught exception"); + RestResponseError result = null; + result = new RestResponseError(e.getResponseBodyAsString()); try { - uriBuilder = ServletUriComponentsBuilder.fromCurrentRequest(); - eventPub.publishEvent(new PaginatedResultsRetrievedEvent<String>(String.class, - uriBuilder, response, page, pageCount, size)); - } catch (Exception e) { - // skip the pagination links logic + outboundJson = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + outboundJson = getJsonErr(jpe.toString()); } - return outboundJson; } catch (Exception e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting page of deployments items failed!"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, "Getting page of deployments items failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getAllDeploymentsByPage caught exception"); RestResponseError result = null; - if (e instanceof HttpStatusCodeException) - result = - new RestResponseError(((HttpStatusCodeException) e).getResponseBodyAsString()); - else - result = new RestResponseError("Failed to get deployments", e); + result = new RestResponseError("Failed to get deployments", e); try { outboundJson = objectMapper.writeValueAsString(result); } catch (JsonProcessingException jpe) { // Should never, ever happen - outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; + outboundJson = getJsonErr(jpe.toString()); } - return outboundJson; } finally { postLogAudit(request); } + return outboundJson; } - @SuppressWarnings({"rawtypes", "unchecked"}) private ServiceTypeSummary getBlueprintItem(String searchBy, Optional<Integer> version, String typeId) throws Exception { ServiceTypeQueryParams serviceQueryParams = null; @@ -549,16 +574,15 @@ public class NbApiController extends ApiBaseController { serviceQueryParams = new ServiceTypeQueryParams.Builder().typeName(searchBy).build(); } - List itemList = + List<ServiceTypeSummary> itemList = inventoryClient.getServiceTypes(serviceQueryParams).collect(Collectors.toList()); if (version.isPresent()) { - itemList = (List) itemList.stream() - .filter(s -> ((ServiceTypeSummary) s).contains(version.get().toString())) + itemList = itemList.stream().filter(s -> (s).contains(version.get().toString())) .collect(Collectors.toList()); } if (typeId != null && typeId.equals("typeId")) { - item = (ServiceTypeSummary) ((List) itemList).get(0); + item = itemList.get(0); } return item; } @@ -572,46 +596,40 @@ public class NbApiController extends ApiBaseController { * @return * @throws Exception */ - @RequestMapping( + @GetMapping( value = {DEPLOYMENTS_PATH + "/{deploymentId}/inputs"}, - method = RequestMethod.GET, produces = "application/json") public String getDeploymentInputs(@PathVariable("deploymentId") String deploymentId, @RequestParam(value = "tenant", required = true) String tenant, HttpServletRequest request) - throws Exception { + throws Exception { preLogAudit(request); ECTransportModel result = null; String json = ""; + String errDescrStr = "Getting inputs for deployment failed: " + deploymentId; + String errLogStr = "getDeploymentInputs caught exception"; try { - if (tenant == null) { - throw new Exception("tenant name is missing"); - } List<CloudifyDeployment> response = cloudifyClient.getDeploymentInputs(deploymentId, tenant).items; json = objectMapper.writeValueAsString(response); } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API controller"); - MDC.put("TargetServiceName", "API controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", - "Getting executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, - "getExecutionByIdAndDeploymentId caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errDescrStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError(e.getResponseBodyAsString()); json = objectMapper.writeValueAsString(result); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API controller"); - MDC.put("TargetServiceName", "API controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", - "Getting executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, - "getExecutionByIdAndDeploymentId caught exception"); - result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errDescrStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + result = new RestResponseError("getDeploymentInputs failed", t); json = objectMapper.writeValueAsString(result); } finally { postLogAudit(request); @@ -627,14 +645,13 @@ public class NbApiController extends ApiBaseController { * @return Information about the execution * @throws Exception on serialization failure */ - @RequestMapping( - value = {DEPLOYMENTS_PATH + "/{deploymentId}"}, - method = RequestMethod.PUT, - produces = "application/json") + @PutMapping(value = {DEPLOYMENTS_PATH + "/{deploymentId}"}, produces = "application/json") public String modifyDeployment(@PathVariable("deploymentId") String deploymentId, HttpServletRequest request, InputStream upgParams) throws Exception { preLogAudit(request); ECTransportModel result = null; + final String errDescStr = "Updating deployment failed!"; + final String errLogStr = "updateDeployment caught exception"; try { String nodeInstId = ""; Map<String, Object> parameters = @@ -651,32 +668,32 @@ public class NbApiController extends ApiBaseController { } parameters.put("node_instance_id", nodeInstId); if (workflow.equals("upgrade")) { - String repo_user = cloudifyClient.getSecret("controller_helm_user", tenant).value; - String repo_user_password = + String repoUser = cloudifyClient.getSecret("controller_helm_user", tenant).value; + String repoUserPassword = cloudifyClient.getSecret("controller_helm_password", tenant).value; - parameters.put("repo_user", repo_user); - parameters.put("repo_user_password", repo_user_password); + parameters.put("repo_user", repoUser); + parameters.put("repo_user_password", repoUserPassword); } 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", "API controller"); - MDC.put("TargetServiceName", "API controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Updating deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateDeployment caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_EXEC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errDescStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API controller"); - MDC.put("TargetServiceName", "API controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Updating Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateDeployment caught exception"); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_EXEC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errDescStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError("updateDeployment failed", t); } finally { postLogAudit(request); @@ -684,14 +701,13 @@ public class NbApiController extends ApiBaseController { return objectMapper.writeValueAsString(result); } - @RequestMapping( + @GetMapping( value = {SERVICE_TYPES_PATH + "/{typeid}" + "/deployments"}, - method = RequestMethod.GET, produces = "application/json") public String getServicesForType(HttpServletRequest request, @PathVariable("typeid") String typeId) throws Exception { preLogAudit(request); - List<ServiceTypeServiceMap> result = new ArrayList<ServiceTypeServiceMap>(); + List<ServiceTypeServiceMap> result = new ArrayList<>(); ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); ServiceTypeServiceMap srvcMap = new ServiceTypeServiceMap(typeId, srvcRefs); @@ -722,17 +738,12 @@ public class NbApiController extends ApiBaseController { } else { dataSet.put(key, val); } - } catch (NumberFormatException ne) { - dataSet.put(key, val); - } catch (Exception e) { + } catch (Exception ne) { dataSet.put(key, val); } } - @RequestMapping( - value = {DEPLOYMENTS_PATH}, - method = RequestMethod.POST, - produces = "application/json") + @PostMapping(value = {DEPLOYMENTS_PATH}, produces = "application/json") public String createDeployment(HttpServletRequest request, HttpServletResponse response, @RequestBody DeploymentInput deploymentRequestObject) throws Exception { preLogAudit(request); @@ -747,6 +758,7 @@ public class NbApiController extends ApiBaseController { String tag = deploymentRequestObject.getTag(); String depName = cName + "_" + tag; Map<String, BlueprintInput> bpInputDefs = null; + final String errLogStr = "createDeployment caught exception"; if (cName == null || cName.isEmpty()) { json = objectMapper.writeValueAsString( @@ -755,85 +767,23 @@ public class NbApiController extends ApiBaseController { "Component name missing in deployment request body"); return json; } - - if (!isAuthorized(request, cName)) { - response.setStatus(HttpStatus.SC_FORBIDDEN); - json = objectMapper.writeValueAsString( - new RestResponseError("Un-authorized to perform this operation")); - return json; - } - - if (deploymentRequestObject.getBlueprintVersion().isPresent()) { - bpVersion = deploymentRequestObject.getBlueprintVersion(); - } - if (deploymentRequestObject.getBlueprintId().isPresent()) { - srvcTypeId = deploymentRequestObject.getBlueprintId().get(); - } - if (srvcTypeId == null) { - // get the serviceTypeId from inventory using the blueprint name - try { + try { + bpVersion = Optional.of(deploymentRequestObject.getBlueprintVersion().orElse(1)); + srvcTypeId = deploymentRequestObject.getBlueprintId().orElse(""); + if (srvcTypeId.isEmpty()) { + // get the serviceTypeId from inventory using the blueprint name bpSummItem = getBlueprintItem(bpName, bpVersion, "typeId"); - srvcTypeId = bpSummItem.getTypeId().get(); - bpItem = inventoryClient.getServiceType(srvcTypeId).get(); - } catch (Exception ex) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API controller"); - MDC.put("TargetServiceName", "API controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting blueprint ID failed!"); - logger.error(EELFLoggerDelegate.errorLogger, - "getItemListForPageWrapper caught exception"); - RestResponseError result = null; - if (ex instanceof HttpStatusCodeException) - result = new RestResponseError( - ((HttpStatusCodeException) ex).getResponseBodyAsString()); - else - result = new RestResponseError("Failed to get blueprint", ex); - try { - json = objectMapper.writeValueAsString(result); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - json = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } - return json; - } finally { - postLogAudit(request); - } - } else { - try { - bpItem = inventoryClient.getServiceType(srvcTypeId).get(); - } catch (Exception ex) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API controller"); - MDC.put("TargetServiceName", "API controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting blueprint failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "createDeployment caught exception"); - RestResponseError result = null; - if (ex instanceof HttpStatusCodeException) - result = new RestResponseError( - ((HttpStatusCodeException) ex).getResponseBodyAsString()); - else - result = new RestResponseError("Failed to get blueprint", ex); - try { - json = objectMapper.writeValueAsString(result); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - json = "{ \"error\" : \"" + jpe.toString() + "\"}"; + if (bpSummItem != null && bpSummItem.getTypeId().isPresent()) { + srvcTypeId = bpSummItem.getTypeId().get(); } - return json; - } finally { - postLogAudit(request); } - } - try { + bpItem = inventoryClient.getServiceType(srvcTypeId).orElseThrow(); + // process the JSON inputs - Map<String, Object> processedInputs = new HashMap<String, Object>(); - Map<String, Object> mergedInputs = new HashMap<String, Object>(); + Map<String, Object> processedInputs = new HashMap<>(); + Map<String, Object> mergedInputs = new HashMap<>(); deploymentRequestObject.getInputs() - .forEach((k, v) -> translateInputData(processedInputs, k, v)); + .forEach((k, v) -> translateInputData(processedInputs, k, v)); // merge the user inputs with BP input list bpInputDefs = bpItem.getBlueprintInputs(); bpInputDefs.forEach((k, v) -> mergeInputData(mergedInputs, processedInputs, k, v)); @@ -847,56 +797,30 @@ public class NbApiController extends ApiBaseController { } String self = request.getRequestURL().append("/").append(depName).toString(); status.append(self).append("/executions?tenant=") - .append(deploymentRequestObject.getTenant()); + .append(deploymentRequestObject.getTenant()); DeploymentResource deplRsrc = new DeploymentResource(depName, new DeploymentResourceLinks(self, deplStatus, status.toString())); JSONObject statObj = new JSONObject(deplRsrc); json = statObj.toString(); response.setStatus(HttpStatus.SC_ACCEPTED); - } catch (BadRequestException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API controller"); - MDC.put("TargetServiceName", "API controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "createDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (ServiceAlreadyExistsException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API controller"); - MDC.put("TargetServiceName", "API controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "createDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (ServerErrorException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API controller"); - MDC.put("TargetServiceName", "API controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "createDeployment caught exception"); + } catch (HttpStatusCodeException | BadRequestException | ServiceAlreadyExistsException + | ServerErrorException | DownstreamException e) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errLogStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (DownstreamException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API controller"); - MDC.put("TargetServiceName", "API controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "createDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API controller"); - MDC.put("TargetServiceName", "API controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "createDeployment caught exception"); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errLogStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); json = objectMapper.writeValueAsString(new RestResponseError("putDeployment failed", t)); } finally { @@ -914,42 +838,35 @@ public class NbApiController extends ApiBaseController { * @return CloudifyExecutionList * @throws Exception on serialization failure */ - @RequestMapping( + @GetMapping( value = {DEPLOYMENTS_PATH + "/{deploymentId}" + "/" + EXECUTIONS_PATH}, - method = RequestMethod.GET, produces = "application/json") - @ResponseBody public String getExecutionByDeploymentId(@PathVariable("deploymentId") String deploymentId, @RequestParam(value = "tenant", required = true) String tenant, HttpServletRequest request) - throws Exception { + throws Exception { preLogAudit(request); ECTransportModel result = null; + final String errDescStr = "Get execution failed for deployment: " + deploymentId; + final String errLogStr = "getExecutionByIdAndDeploymentId caught exception"; try { - if (tenant == null) { - throw new Exception("tenant name is missing"); - } result = cloudifyClient.getExecutionsSummary(deploymentId, tenant); } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", - "Getting executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, - "getExecutionByIdAndDeploymentId caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_EXEC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errDescStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", - "Getting executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, - "getExecutionByIdAndDeploymentId caught exception"); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_EXEC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errDescStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); } finally { postLogAudit(request); @@ -966,39 +883,34 @@ public class NbApiController extends ApiBaseController { * @return String * @throws Exception on serialization failure */ - @RequestMapping( + @GetMapping( value = {DEPLOYMENTS_PATH + "/{deploymentId}" + "/" + SERVICE_HEALTH_PATH}, - method = RequestMethod.GET, produces = "application/json") - @ResponseBody public String getServiceHealthByDeploymentId(@PathVariable("deploymentId") String deploymentId, HttpServletRequest request) throws Exception { preLogAudit(request); Object result = null; + final String errStr = "Getting service health for deployment failed: " + deploymentId; try { result = consulClient.getServiceHealthByDeploymentId(deploymentId); } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", - "Getting executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, - "getExecutionByIdAndDeploymentId caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CNSL_SVC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CNSL_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errStr); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", - "Getting executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, - "getExecutionByIdAndDeploymentId caught exception"); - result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CNSL_SVC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CNSL_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errStr); + result = new RestResponseError("getServiceHealthByDeploymentId failed", t); } finally { postLogAudit(request); } @@ -1015,15 +927,12 @@ public class NbApiController extends ApiBaseController { * @throws Exception On serialization failure */ @SuppressWarnings("unchecked") - @RequestMapping( - value = {SERVICE_TYPES_PATH + "/{typeid}"}, - method = RequestMethod.GET, - produces = "application/json") - @ResponseBody + @GetMapping(value = {SERVICE_TYPES_PATH + "/{typeid}"}, produces = "application/json") public String queryBlueprint(@PathVariable("typeid") String typeId, HttpServletRequest request, HttpServletResponse response, ServletUriComponentsBuilder uriBuilder) throws Exception { String json = ""; Optional<ServiceType> resultItem = null; + final String errStr = "Failed to get blueprint for ID: " + typeId; try { resultItem = inventoryClient.getServiceType(typeId); if (resultItem.isPresent()) { @@ -1031,33 +940,33 @@ public class NbApiController extends ApiBaseController { } String uri = request.getRequestURI(); if (uri != null && !uri.isEmpty()) { - String uri_depl = - uriBuilder.replacePath(uri).path("/deployments").build().toUriString(); - StringBuffer linkHeader = new StringBuffer(); - String linkStr_depl = "<" + uri_depl + ">; rel=\"" + "deployments" + "\""; - linkHeader.append(linkStr_depl); - response.addHeader("Link", linkHeader.toString()); + String uriDepl = + uriBuilder.replacePath(uri).path("/deployments").build().toUriString(); + StringBuffer linkHeader = new StringBuffer(); + String linkStrDepl = "<" + uriDepl + ">; rel=\"" + DEPLOYMENTS_PATH + "\""; + linkHeader.append(linkStrDepl); + response.addHeader("Link", linkHeader.toString()); } + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, INV_BP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, INV_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errStr); + RestResponseError result = new RestResponseError(e.getResponseBodyAsString()); + json = objectMapper.writeValueAsString(result); } catch (Exception e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting page of blueprints items failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getBlueprintsByPage caught exception"); - RestResponseError result = null; - if (e instanceof HttpStatusCodeException) - result = - new RestResponseError(((HttpStatusCodeException) e).getResponseBodyAsString()); - else - result = new RestResponseError("Failed to get blueprints", e); - try { - json = objectMapper.writeValueAsString(result); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - json = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, INV_BP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, INV_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errStr); + RestResponseError result = new RestResponseError("Failed to get blueprints", e); + json = objectMapper.writeValueAsString(result); } return json; } @@ -1072,70 +981,53 @@ public class NbApiController extends ApiBaseController { * @throws Exception On serialization failure */ @SuppressWarnings("unchecked") - @RequestMapping( - value = {SERVICE_TYPES_PATH + "/{typeid}"}, - method = RequestMethod.DELETE, + @DeleteMapping( + value = {SERVICE_TYPES_PATH + "/{typeId:.+}"}, produces = "application/json") - @ResponseBody - public String deleteBlueprint(@PathVariable("typeid") String typeId, HttpServletRequest request, + public String deleteBlueprint(@PathVariable("typeId") String typeId, HttpServletRequest request, HttpServletResponse response, ServletUriComponentsBuilder uriBuilder) throws Exception { preLogAudit(request); String json = "{\"204\": \"Blueprint deleted\"}"; - String bpComp = ""; + final String errStr = "Deleting service type failed: " + typeId; boolean allow = true; ReadWriteLock lock = new ReentrantReadWriteLock(); lock.readLock().lock(); - @SuppressWarnings("unchecked") - List itemList = - (List<ServiceTypeSummary>) getCacheManager().getObject("dcae-service-types"); + List<ServiceTypeSummary> itemList = + (List<ServiceTypeSummary>) getCacheManager().getObject("dcae-service-types"); lock.readLock().unlock(); + ServiceType itemFull = null; + ServiceTypeSummary item = null; try { if (itemList != null) { Predicate<ServiceTypeSummary> idFilter = p -> p.getTypeId().get().equals(typeId); - - itemList = (List<ServiceTypeSummary>) itemList.stream().filter(idFilter) - .collect(Collectors.toList()); - bpComp = ((ServiceTypeSummary) itemList.get(0)).getComponent(); - } else { - try { - ServiceType item = inventoryClient.getServiceType(typeId).get(); - bpComp = ((ServiceType) item).getComponent(); - } catch (NoSuchElementException nse) { - throw new ServiceTypeNotFoundException("invalid blueprint ID given in query"); + itemList = itemList.stream().filter(idFilter).collect(Collectors.toList()); + if (!itemList.isEmpty()) { + item = itemList.get(0); } + } else { + itemFull = inventoryClient.getServiceType(typeId).get(); } - if (!isAuthorized(request, bpComp)) { - response.setStatus(HttpStatus.SC_FORBIDDEN); - json = objectMapper.writeValueAsString( - new RestResponseError("Un-authorized to perform this operation")); - return json; - } - /* - ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); - ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); - if (srvcRefs != null && srvcRefs.totalCount > 0) { - throw new Exception( - "Services exist for the service type template, delete not permitted"); - } - */ - - // check if these dep_ids exist in cloudify - List<CloudifyDeployedTenant> deplForBp = - cloudifyClient.getDeploymentForBlueprint("TID-"+typeId); - if (deplForBp.size() > 0 ) { - allow = false; - } else { - ServiceQueryParams qryParams = - new ServiceQueryParams.Builder().typeId(typeId).build(); - ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); - Set<String> dep_ids = srvcRefs.items.stream().map(x -> ((ServiceRef)x).id).collect(Collectors.toSet()); - if (dep_ids.size() > 0) { - // now check again if these dep_ids still exist in cloudify - List<String> allDepNames = cloudifyClient.getDeploymentNamesWithFilter(request); - for (String str: dep_ids) { - if (allDepNames.stream().anyMatch(s->s.equalsIgnoreCase(str))) { - allow = false; - break; + if (item != null || itemFull != null) { + // check if these dep_ids exist in cloudify + List<CloudifyDeployedTenant> deplForBp = + cloudifyClient.getDeploymentForBlueprint("TID-" + typeId); + if (!deplForBp.isEmpty()) { + allow = false; + } else { + ServiceQueryParams qryParams = + new ServiceQueryParams.Builder().typeId(typeId).build(); + ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); + Set<String> depIds = + srvcRefs.items.stream().map(x -> x.id).collect(Collectors.toSet()); + if (!depIds.isEmpty()) { + // now check again if these dep_ids still exist in cloudify + List<String> allDepNames = + cloudifyClient.getDeploymentNamesWithFilter(request); + for (String str : depIds) { + if (allDepNames.stream().anyMatch(s -> s.equalsIgnoreCase(str))) { + allow = false; + break; + } } } } @@ -1144,55 +1036,37 @@ public class NbApiController extends ApiBaseController { response.setStatus(HttpStatus.SC_BAD_REQUEST); json = objectMapper.writeValueAsString( new RestResponseError("ERROR: Deployments exist for this blueprint")); - /* - PrintWriter out = response.getWriter(); - response.setContentType("application/json"); - response.setCharacterEncoding("UTF-8"); - out.print(json); - out.flush(); - */ return json; } else { inventoryClient.deleteServiceType(typeId); String uri = request.getRequestURI(); if (uri != null && !uri.isEmpty()) { - String uri_str = uri.substring(0, uri.lastIndexOf("/")); - String uri_all = uriBuilder.replacePath(uri_str).build().toUriString(); + String uriStr = uri.substring(0, uri.lastIndexOf("/")); + String uriAll = uriBuilder.replacePath(uriStr).build().toUriString(); StringBuffer linkHeader = new StringBuffer(); - String linkStr = "<" + uri_all + ">; rel=\"" + "current" + "\""; + String linkStr = "<" + uriAll + ">; rel=\"" + "current" + "\""; linkHeader.append(linkStr); response.addHeader("Link", linkHeader.toString()); } } - } catch (ServiceTypeNotFoundException e) { - response.setStatus(HttpStatus.SC_GONE); - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting service type " + typeId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (ServiceTypeAlreadyDeactivatedException e) { + } catch (ServiceTypeNotFoundException | ServiceTypeAlreadyDeactivatedException e) { response.setStatus(HttpStatus.SC_GONE); - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting service type " + typeId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, INV_BP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, INV_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errStr); json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (Throwable t) { - response.setStatus(HttpStatus.SC_BAD_GATEWAY); - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting service type " + typeId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, INV_BP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, INV_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errStr); json = objectMapper.writeValueAsString(new RestResponseError("deleteBlueprint failed", t)); } finally { @@ -1212,30 +1086,23 @@ public class NbApiController extends ApiBaseController { * @throws Exception */ @SuppressWarnings("unchecked") - @RequestMapping( - value = {DEPLOYMENTS_PATH + "/{deploymentId}"}, - method = RequestMethod.DELETE, - produces = "application/json") + @DeleteMapping(value = {DEPLOYMENTS_PATH + "/{deploymentId:.+}"}, 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; + final String errStr = "Deleting deployment failed: " + deploymentId; StringBuffer status = new StringBuffer(); try { - if (tenant == null) { - throw new Exception("tenant name is missing"); - } ReadWriteLock lock = new ReentrantReadWriteLock(); lock.readLock().lock(); - @SuppressWarnings("unchecked") - List itemList = (List<CloudifyDeployment>) getCacheManager() - .getObject("service-list" + ":" + tenant); + List<CloudifyDeployment> itemList = (List<CloudifyDeployment>) getCacheManager() + .getObject("service-list" + ":" + tenant); lock.readLock().unlock(); if (itemList != null) { Predicate<CloudifyDeployment> idFilter = p -> p.id.equals(deploymentId); - itemList = (List<CloudifyDeployment>) itemList.stream().filter(idFilter) - .collect(Collectors.toList()); + itemList = itemList.stream().filter(idFilter).collect(Collectors.toList()); } else { CloudifyDeploymentList cfyDeplList = cloudifyClient.getDeployment(deploymentId, tenant); @@ -1246,11 +1113,10 @@ public class NbApiController extends ApiBaseController { if (itemList != null && !itemList.isEmpty()) { String depItem = ((CloudifyDeployment) itemList.get(0)).id; if (depItem.contains("_")) { - String depComp = depItem.split("_")[0]; - if (!isAuthorized(request, depComp)) { + if (!isAuthorized()) { response.setStatus(HttpStatus.SC_FORBIDDEN); - json = objectMapper.writeValueAsString( - new RestResponseError("Un-authorized to perform this operation")); + json = + objectMapper.writeValueAsString(new RestResponseError("UNAUTH_ERROR")); return json; } deploymentHandlerClient.deleteDeployment(deploymentId, tenant); @@ -1262,50 +1128,24 @@ public class NbApiController extends ApiBaseController { json = statObj.toString(); } } - } catch (BadRequestException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (ServerErrorException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (DownstreamException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + } catch (BadRequestException | ServerErrorException | DownstreamException + | DeploymentNotFoundException e) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errStr); json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (DeploymentNotFoundException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteDeployment caught exception"); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errStr); json = objectMapper .writeValueAsString(new RestResponseError("deleteDeployment failed", t)); } finally { @@ -1325,67 +1165,64 @@ public class NbApiController extends ApiBaseController { * @return Passes thru HTTP status code from remote endpoint; no body on success * @throws Exception on serialization failure */ - @RequestMapping( - value = {EXECUTIONS_PATH + "/{id}"}, - method = RequestMethod.POST, - produces = "application/json") - @ResponseBody + @PostMapping(value = {EXECUTIONS_PATH + "/{id}"}, produces = "application/json") public String cancelExecution(@RequestHeader HttpHeaders headers, @PathVariable("id") String id, @RequestBody Map<String, String> parameters, HttpServletRequest request, HttpServletResponse response) throws Exception { preLogAudit(request); ECTransportModel result = null; List<String> tenant = null; + String errStr = "Cancelling execution failed: " + id; try { tenant = headers.get("tenant"); result = cloudifyClient.cancelExecution(id, parameters, tenant.get(0)); } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Cancelling execution " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_EXEC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errStr); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Cancelling execution " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); - result = new RestResponseError("cancelExecution failed on ID " + id, t); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_EXEC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errStr); + result = new RestResponseError(errStr, t); } finally { postLogAudit(request); } - if (result == null) + if (result == null) { return null; - else + } else { return objectMapper.writeValueAsString(result); + } } private void preLogAudit(HttpServletRequest request) { - begin = new Date(); + Date begin = new Date(); MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); String user = null; if (request instanceof CadiWrap) { user = ((CadiWrap) request).getUser(); - } + } logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME, user, user); } private void postLogAudit(HttpServletRequest request) { - end = new Date(); + Date end = new Date(); MDC.put("AlertSeverity", "0"); - MDC.put("TargetEntity", "API Controller"); - MDC.put("TargetServiceName", "API Controller"); + MDC.put(TARGET_ENTITY_KEY, "API Controller"); + MDC.put(TARGET_SERVICE_KEY, "API Controller"); 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()))); logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + " " + request.getRequestURI()); logger.info(EELFLoggerDelegate.metricsLogger, 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 ae0e849..3277ce1 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 @@ -2,29 +2,28 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.controller; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -79,14 +78,15 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.HttpStatusCodeException; import com.fasterxml.jackson.core.JsonProcessingException; @@ -95,7 +95,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; * Methods serve Ajax requests made by Angular scripts on pages that show * content. */ -@Controller +@RestController @RequestMapping("/") public class CloudifyController extends DashboardRestrictedBaseController { @@ -116,8 +116,6 @@ public class CloudifyController extends DashboardRestrictedBaseController { BLUEPRINT, DEPLOYMENT, EXECUTION, TENANT, SERVICE_ID, SERVICE_ID_COUNT; } - private static Date begin; - private static Date end; private static final String BLUEPRINTS_PATH = "blueprints"; private static final String DEPLOYMENTS_PATH = "deployments"; private static final String EXECUTIONS_PATH = "executions"; @@ -129,9 +127,20 @@ public class CloudifyController extends DashboardRestrictedBaseController { private static final String PLUGINS_PATH = "plugins"; private static final String PLUGIN_COUNT = "plugins-count"; private static final String SERVICE_TYPES = "dcae-service-types"; + private static final String TARGET_ENTITY_KEY = "TargetEntity"; + private static final String TARGET_SERVICE_KEY = "TargetServiceName"; + private static final String CFY_DEP_ENTITY = "DCAE Deployment"; + private static final String CFY_TARGET_SERVICE = "DCAE Cloudify"; + private static final String ERROR_RESPONSE = "ERROR"; + private static final String ERROR_CODE_KEY = "ErrorCode"; + private static final String ERROR_CODE = "300"; + private static final String ERROR_CATEGORY_KEY = "ErrorCategory"; + private static final String ERROR_DESCRIPTION_KEY = "ErrorDescription"; + private static final String SORT_BY = "sortBy"; + private static final String SEARCH_BY = "searchBy"; - private AbstractCacheManager cacheManager; - + private AbstractCacheManager cacheManager; + @Autowired public void setCacheManager(AbstractCacheManager cacheManager) { this.cacheManager = cacheManager; @@ -140,79 +149,52 @@ public class CloudifyController extends DashboardRestrictedBaseController { public AbstractCacheManager getCacheManager() { return cacheManager; } - - /** - * Supports sorting events by timestamp - */ - private static Comparator<CloudifyEvent> eventComparator = new Comparator<CloudifyEvent>() { - @Override - public int compare(CloudifyEvent o1, CloudifyEvent o2) { - return o1.reported_timestamp.compareTo(o2.reported_timestamp); - } - }; - - /** - * Supports sorting executions by timestamp - */ - private static Comparator<CloudifyExecution> executionComparator = new Comparator<CloudifyExecution>() { - @Override - public int compare(CloudifyExecution o1, CloudifyExecution o2) { - return o1.created_at.compareTo(o2.created_at); - } - }; private void updateBpOwnerId(List<CloudifyDeployment> itemList, Map<String, List<CloudifyDeployedTenant>> ownerDepMap) { - for (CloudifyDeployment srvc: (List<CloudifyDeployment>)itemList) { - for (Map.Entry<String, List<CloudifyDeployedTenant>> entry : - ownerDepMap.entrySet()) { - List<CloudifyDeployedTenant> deplExtItems = - entry.getValue().stream().filter((Predicate<? super CloudifyDeployedTenant>) s->s.id.equals(srvc.id)). - collect(Collectors.toList()); - if (deplExtItems != null && deplExtItems.size() > 0) { + for (CloudifyDeployment srvc : (List<CloudifyDeployment>) itemList) { + for (Map.Entry<String, List<CloudifyDeployedTenant>> entry : ownerDepMap.entrySet()) { + List<CloudifyDeployedTenant> deplExtItems = entry.getValue().stream() + .filter((Predicate<? super CloudifyDeployedTenant>) s -> s.id.equals(srvc.id)) + .collect(Collectors.toList()); + if (deplExtItems != null && !deplExtItems.isEmpty()) { srvc.owner = entry.getKey(); break; } } } } + + private String getJsonErr(String errStr) { + final String errJsonStr = "{ \"error\" : \""; + StringBuffer errJson = new StringBuffer(); + errJson.append(errJsonStr).append(errStr).append("\"}"); + return errJson.toString(); + } - private void updateWorkflowHelmStatus(List<CloudifyDeployment> itemList, - List<CloudifyDeploymentExt> cfyDeplExt, - List<CloudifyDeploymentHelm> cfyDeplHelm) { - for (CloudifyDeployment srvc: (List<CloudifyDeployment>)itemList) { + private void updateWorkflowHelmStatus(List<CloudifyDeployment> itemList, + List<CloudifyDeploymentExt> cfyDeplExt, List<CloudifyDeploymentHelm> cfyDeplHelm) { + for (CloudifyDeployment srvc : (List<CloudifyDeployment>) itemList) { // correlate the cached data for deployments and deployment extensions - List<CloudifyDeploymentExt> deplExtItems = - cfyDeplExt.stream().filter((Predicate<? super CloudifyDeploymentExt>) s->s.id.equals(srvc.id)). - collect(Collectors.toList()); - if (deplExtItems != null && deplExtItems.size() > 0) { - srvc.lastExecution = deplExtItems.get(0).lastExecution; - } + List<CloudifyDeploymentExt> deplExtItems = cfyDeplExt.stream() + .filter((Predicate<? super CloudifyDeploymentExt>) s -> s.id.equals(srvc.id)) + .collect(Collectors.toList()); + if (deplExtItems != null && deplExtItems.size() > 0) { + srvc.lastExecution = deplExtItems.get(0).lastExecution; + } } - for (CloudifyDeployment srvc: (List<CloudifyDeployment>)itemList) { + for (CloudifyDeployment srvc : (List<CloudifyDeployment>) itemList) { // correlate the cached data for deployments and deployment helm info - List<CloudifyDeploymentHelm> deplHelmItems = - cfyDeplHelm.stream().filter((Predicate<? super CloudifyDeploymentHelm>) s->s.id.equals(srvc.id)). - collect(Collectors.toList()); - if (deplHelmItems != null && deplHelmItems.size() > 0) { - srvc.helmStatus = deplHelmItems.get(0).helmStatus; - srvc.isHelm = deplHelmItems.get(0).isHelm; - } - } - } - - private void updateHelmInfo(List<CloudifyDeployment> itemList, - List<CloudifyDeploymentExt> cfyDeplExt) { - for (CloudifyDeployment srvc: (List<CloudifyDeployment>)itemList) { - // correlate the cached data for deployments and deployment extensions - List<CloudifyDeploymentExt> deplExtItems = - cfyDeplExt.stream().filter((Predicate<? super CloudifyDeploymentExt>) s->s.id.equals(srvc.id)). - collect(Collectors.toList()); - srvc.helmStatus = deplExtItems.get(0).helmStatus; - srvc.isHelm = deplExtItems.get(0).isHelm; + List<CloudifyDeploymentHelm> deplHelmItems = cfyDeplHelm.stream() + .filter((Predicate<? super CloudifyDeploymentHelm>) s -> s.id.equals(srvc.id)) + .collect(Collectors.toList()); + if (deplHelmItems != null && deplHelmItems.size() > 0) { + srvc.helmStatus = deplHelmItems.get(0).helmStatus; + srvc.isHelm = deplHelmItems.get(0).isHelm; + } } } - + /** * Gets one page of objects and supporting information via the REST client. On * success, returns a PaginatedRestResponse object as String. @@ -224,12 +206,12 @@ public class CloudifyController extends DashboardRestrictedBaseController { * @throws Exception On any error; e.g., Network failure. */ @SuppressWarnings({"rawtypes", "unchecked"}) - private String getItemListForPage(HttpServletRequest request, long userId, - CloudifyDataItem option, int pageNum, int pageSize, String sortBy, String searchBy) - throws Exception { - HttpSession session = AppUtils.getSession(request); + private String getItemListForPage(HttpServletRequest request, + CloudifyDataItem option, int pageNum, int pageSize, String sortBy, String searchBy) + throws Exception { + HttpSession session = AppUtils.getSession(request); String user = UserUtils.getUserSession(request).getLoginId(); - HashMap<String, Boolean> comp_deploy_tab = + HashMap<String, Boolean> compDeployTab = (HashMap<String, Boolean>) session.getAttribute("comp_access"); String roleLevel = (String) session.getAttribute("role_level"); String roleAuth = (String) session.getAttribute("auth_role"); @@ -239,8 +221,8 @@ public class CloudifyController extends DashboardRestrictedBaseController { if (roleLevel == null) { roleLevel = "dev"; } - if (comp_deploy_tab == null) { - comp_deploy_tab = new HashMap<String, Boolean>(); + if (compDeployTab == null) { + compDeployTab = new HashMap<String, Boolean>(); } Set<String> userApps = (Set<String>) session.getAttribute("authComponents"); if (userApps == null) { @@ -252,64 +234,60 @@ public class CloudifyController extends DashboardRestrictedBaseController { int deplPgSize = 500; int deplPgOffset = 0; String tenantFilterStr = ""; - String cacheFilterStr = "true"; - String userFilterStr = "false"; String svcRefFilterStr = ""; String statusFilterStr = ""; String helmFilterStr = ""; String ownerFilterStr = ""; ReadWriteLock lock = new ReentrantReadWriteLock(); List<CloudifyDeploymentExt> cfyDeplExt = null; - List<CloudifyDeploymentExt> cfyDepExList = new ArrayList<CloudifyDeploymentExt>(); + List<CloudifyDeploymentExt> cfyDepExList = new ArrayList<>(); List<CloudifyDeploymentHelm> cfyDeplHelm = null; - List<CloudifyDeploymentHelm> cfyDeplHelmList = new ArrayList<CloudifyDeploymentHelm>(); + List<CloudifyDeploymentHelm> cfyDeplHelmList = new ArrayList<>(); boolean useCache = true; boolean userLevel = false; List<CloudifyTenant> cfyTenantList = null; // apply tenant search filter if (searchBy != null && !searchBy.isEmpty()) { - // parse the search filters string - List<String> searchFilters = - new ArrayList<String>(Arrays.asList(searchBy.split(";"))); - if (searchFilters.stream().anyMatch(s->s.startsWith("tenant"))) { - List<String> tenantsList = searchFilters.stream().filter(s->s.startsWith("tenant")). - collect(Collectors.toList()); + // parse the search filters string + List<String> searchFilters = new ArrayList<String>(Arrays.asList(searchBy.split(";"))); + if (searchFilters.stream().anyMatch(s -> s.startsWith("tenant"))) { + List<String> tenantsList = searchFilters.stream() + .filter(s -> s.startsWith("tenant")).collect(Collectors.toList()); if (tenantsList.get(0).split(":").length > 1) { tenantFilterStr = tenantsList.get(0).split(":")[1]; } } - if (searchFilters.stream().anyMatch(s->s.startsWith("cache"))) { - List<String> cacheStr = searchFilters.stream().filter(s->s.startsWith("cache")). - collect(Collectors.toList()); - cacheFilterStr = cacheStr.get(0).split(":")[1]; - useCache = Boolean.parseBoolean(cacheFilterStr); + if (searchFilters.stream().anyMatch(s -> s.startsWith("cache"))) { + List<String> cacheStr = searchFilters.stream().filter(s -> s.startsWith("cache")) + .collect(Collectors.toList()); + useCache = Boolean.parseBoolean(cacheStr.get(0).split(":")[1]); } - if (searchFilters.stream().anyMatch(s->s.startsWith("user"))) { - List<String> userStr = searchFilters.stream().filter(s->s.startsWith("user")). - collect(Collectors.toList()); - userFilterStr = userStr.get(0).split(":")[1]; - userLevel = Boolean.parseBoolean(userFilterStr); + if (searchFilters.stream().anyMatch(s -> s.startsWith("user"))) { + List<String> userStr = searchFilters.stream().filter(s -> s.startsWith("user")) + .collect(Collectors.toList()); + userLevel = Boolean.parseBoolean(userStr.get(0).split(":")[1]); } - if (searchFilters.stream().anyMatch(s->s.startsWith("owner"))) { - List<String> ownerList = searchFilters.stream().filter(s->s.startsWith("owner")). - collect(Collectors.toList()); + if (searchFilters.stream().anyMatch(s -> s.startsWith("owner"))) { + List<String> ownerList = searchFilters.stream().filter(s -> s.startsWith("owner")) + .collect(Collectors.toList()); ownerFilterStr = ownerList.get(0).split(":")[1]; } } lock.readLock().lock(); - Map<String, List<CloudifyDeployedTenant>> deplPerOwner = - (Map<String, List<CloudifyDeployedTenant>>) getCacheManager().getObject("owner_deploy_map"); + Map<String, List<CloudifyDeployedTenant>> deplPerOwner = + (Map<String, List<CloudifyDeployedTenant>>) getCacheManager() + .getObject("owner_deploy_map"); lock.readLock().unlock(); switch (option) { case SERVICE_ID_COUNT: List items = null; if (!ownerFilterStr.isEmpty()) { if (deplPerOwner != null) { - List<CloudifyDeployedTenant> ownerDeplList = deplPerOwner.get(user); + List<CloudifyDeployedTenant> ownerDeplList = deplPerOwner.get(user); items = ownerDeplList; } } else { - List<CloudifyDeployment> itemsList = + List<CloudifyDeployment> itemsList = cloudifyClient.getDeploymentsWithFilter(request); items = itemsList; } @@ -317,33 +295,34 @@ public class CloudifyController extends DashboardRestrictedBaseController { items = new ArrayList<CloudifyDeployment>(); } totalItems = items.size(); - RestResponsePage<List> model = - new RestResponsePage<>(totalItems, 1, items); + RestResponsePage<List> model = new RestResponsePage<>(totalItems, 1, items); String outboundJson = objectMapper.writeValueAsString(model); return outboundJson; - case SERVICE_ID: + case SERVICE_ID: final String svcIdTenant = tenantFilterStr; if (useCache) { lock.readLock().lock(); - itemList = - (List<CloudifyDeployment>)getCacheManager().getObject(SERVICE_ID + ":" + svcIdTenant); + itemList = (List<CloudifyDeployment>) getCacheManager() + .getObject(SERVICE_ID + ":" + svcIdTenant); lock.readLock().unlock(); } if (itemList == null) { - itemList = cloudifyClient.getDeployments(tenantFilterStr, deplPgSize, deplPgOffset, true); + itemList = cloudifyClient.getDeployments(tenantFilterStr, deplPgSize, + deplPgOffset, true); } Set<String> svcIdList = new HashSet<String>(); if (itemList != null) { - svcIdList = - (Set) itemList.stream().map(x -> ((CloudifyDeployment)x).id).collect(Collectors.toSet()); + svcIdList = (Set) itemList.stream().map(x -> ((CloudifyDeployment) x).id) + .collect(Collectors.toSet()); // apply role based filtering if (roleLevel.equals("app")) { @SuppressWarnings("unchecked") - List<String> myApps = new ArrayList(userApps); - svcIdList = svcIdList.stream().filter(s -> myApps.stream() - .anyMatch(roleFilter -> ((String)s).toLowerCase().startsWith(roleFilter))) - .collect(Collectors.toSet()); - } + List<String> myApps = new ArrayList<String>(userApps); + svcIdList = svcIdList.stream() + .filter(s -> myApps.stream().anyMatch( + roleFilter -> s.toLowerCase().startsWith(roleFilter))) + .collect(Collectors.toSet()); + } } return objectMapper.writeValueAsString(svcIdList); case DEPLOYMENT: @@ -352,179 +331,199 @@ public class CloudifyController extends DashboardRestrictedBaseController { List<CloudifyDeployment> cfyDepList = null; try { if (tenantFilterStr.isEmpty()) { - cfyDepList = new ArrayList<CloudifyDeployment>(); + cfyDepList = new ArrayList<>(); if (useCache) { lock.readLock().lock(); - cfyTenantList = (List<CloudifyTenant>)getCacheManager().getObject(TENANTS_PATH); - for (CloudifyTenant cfyTenObj: cfyTenantList) { - cfyDepPerTntList = (List<CloudifyDeployment>)getCacheManager().getObject(SERVICE_ID + ":" + cfyTenObj.name); + cfyTenantList = + (List<CloudifyTenant>) getCacheManager().getObject(TENANTS_PATH); + for (CloudifyTenant cfyTenObj : cfyTenantList) { + cfyDepPerTntList = (List<CloudifyDeployment>) getCacheManager() + .getObject(SERVICE_ID + ":" + cfyTenObj.name); cfyDepList.addAll(cfyDepPerTntList); } lock.readLock().unlock(); } else { - cfyTenantList = (List<CloudifyTenant>)cloudifyClient.getTenants().items; - for (CloudifyTenant cfyTenObj: cfyTenantList) { - cfyDepPerTntList = cloudifyClient.getDeployments(cfyTenObj.name, deplPgSize, deplPgOffset, true, false); + cfyTenantList = + cloudifyClient.getTenants().items; + for (CloudifyTenant cfyTenObj : cfyTenantList) { + cfyDepPerTntList = cloudifyClient.getDeployments(cfyTenObj.name, + deplPgSize, deplPgOffset, true, false); cfyDepList.addAll(cfyDepPerTntList); } - } + } } else { if (useCache) { lock.readLock().lock(); - cfyDepList = (List<CloudifyDeployment>)getCacheManager().getObject(SERVICE_ID + ":" + tenantFilterStr); + cfyDepList = (List<CloudifyDeployment>) getCacheManager() + .getObject(SERVICE_ID + ":" + tenantFilterStr); lock.readLock().unlock(); } if (cfyDepList == null) { - cfyDepList = cloudifyClient.getDeployments(tenantFilterStr, deplPgSize, deplPgOffset, true, false); + cfyDepList = cloudifyClient.getDeployments(tenantFilterStr, deplPgSize, + deplPgOffset, true, false); } } totalItems = cfyDepList.size(); - + if (useCache) { lock.readLock().lock(); - cfyDeplExt = - (List<CloudifyDeploymentExt>)getCacheManager().getObject(SERVICE_ID + ":" + tenantFilterStr + ":ext"); + cfyDeplExt = (List<CloudifyDeploymentExt>) getCacheManager() + .getObject(SERVICE_ID + ":" + tenantFilterStr + ":ext"); if (cfyDeplExt != null) { cfyDepExList.addAll(cfyDeplExt); } - cfyDeplHelm = - (List<CloudifyDeploymentHelm>)getCacheManager().getObject(SERVICE_ID + ":" + tenantFilterStr + ":helm"); + cfyDeplHelm = (List<CloudifyDeploymentHelm>) getCacheManager() + .getObject(SERVICE_ID + ":" + tenantFilterStr + ":helm"); if (cfyDeplHelm != null) { cfyDeplHelmList.addAll(cfyDeplHelm); } - lock.readLock().unlock(); + lock.readLock().unlock(); } - + if (roleLevel.equals("app") && !userLevel) { @SuppressWarnings("unchecked") List<String> myApps = new ArrayList(userApps); - cfyDepList = (List) cfyDepList.stream().filter(s -> myApps.stream() - .anyMatch(roleFilter -> ((CloudifyDeployment)s).id.toLowerCase().startsWith(roleFilter))) - .collect(Collectors.toList()); - } + cfyDepList = + cfyDepList.stream() + .filter(s -> myApps.stream() + .anyMatch(roleFilter -> s.id + .toLowerCase().startsWith(roleFilter))) + .collect(Collectors.toList()); + } // apply user search filters if (searchBy != null && !searchBy.isEmpty()) { - // parse the search filters string - // look for service name patterns - List<String> searchFilters = - new ArrayList<String>(Arrays.asList(searchBy.split(";"))); - if (searchFilters.stream().anyMatch(s->s.startsWith("serviceRef"))) { - List<String> svcRefsList = searchFilters.stream().filter(s->s.startsWith("serviceRef")). - collect(Collectors.toList()); + // parse the search filters string + // look for service name patterns + List<String> searchFilters = + new ArrayList<>(Arrays.asList(searchBy.split(";"))); + if (searchFilters.stream().anyMatch(s -> s.startsWith("serviceRef"))) { + List<String> svcRefsList = + searchFilters.stream().filter(s -> s.startsWith("serviceRef")) + .collect(Collectors.toList()); svcRefFilterStr = svcRefsList.get(0).split(":")[1]; } - if (searchFilters.stream().anyMatch(s->s.startsWith("status"))) { - List<String> statusList = searchFilters.stream().filter(s->s.startsWith("status")). - collect(Collectors.toList()); + if (searchFilters.stream().anyMatch(s -> s.startsWith("status"))) { + List<String> statusList = searchFilters.stream() + .filter(s -> s.startsWith("status")).collect(Collectors.toList()); statusFilterStr = statusList.get(0).split(":")[1]; } - if (searchFilters.stream().anyMatch(s->s.startsWith("helm"))) { - List<String> helmList = searchFilters.stream().filter(s->s.startsWith("helm")). - collect(Collectors.toList()); + if (searchFilters.stream().anyMatch(s -> s.startsWith("helm"))) { + List<String> helmList = searchFilters.stream() + .filter(s -> s.startsWith("helm")).collect(Collectors.toList()); helmFilterStr = helmList.get(0).split(":")[1]; - } + } if (!ownerFilterStr.isEmpty()) { - List ownerFilterList = - new ArrayList<String>(Arrays.asList(ownerFilterStr.split(","))); - if (ownerFilterList.size() == 1 && ownerFilterList.get(0).equals("undefined")) { + List<String> ownerFilterList = + new ArrayList<>(Arrays.asList(ownerFilterStr.split(","))); + if (ownerFilterList.size() == 1 + && ownerFilterList.get(0).equals("undefined")) { ownerFilterList.clear(); ownerFilterList.add(user); } if (deplPerOwner != null && cfyDepList != null) { - List<CloudifyDeployedTenant> ownerDeplList = new ArrayList<CloudifyDeployedTenant>(); - Stream<Map.Entry<String, List<CloudifyDeployedTenant>>> deplOwnerEntriesStream = - deplPerOwner.entrySet().stream(); - Set<Map.Entry<String, List<CloudifyDeployedTenant>>> deplOwnerSet = - deplOwnerEntriesStream.filter(m -> ownerFilterList.stream(). - anyMatch(ownFilter -> m.getKey().equalsIgnoreCase((String) ownFilter))).collect(Collectors.toSet()); - deplOwnerSet.stream().forEach(e -> ownerDeplList.addAll(e.getValue())); - if (ownerDeplList.size() > 0) { - Predicate<CloudifyDeployment> In2 = - s -> ownerDeplList.stream().anyMatch(mc -> s.id.equals(mc.id)); - cfyDepList = cfyDepList.stream().filter(In2).collect(Collectors.toList()); + List<CloudifyDeployedTenant> ownerDeplList = + new ArrayList<>(); + Stream<Map.Entry<String, List<CloudifyDeployedTenant>>> deplOwnerEntriesStream = + deplPerOwner.entrySet().stream(); + Set<Map.Entry<String, List<CloudifyDeployedTenant>>> deplOwnerSet = + deplOwnerEntriesStream + .filter(m -> ownerFilterList.stream() + .anyMatch(ownFilter -> m.getKey() + .equalsIgnoreCase(ownFilter))) + .collect(Collectors.toSet()); + deplOwnerSet.stream() + .forEach(e -> ownerDeplList.addAll(e.getValue())); + if (!ownerDeplList.isEmpty()) { + Predicate<CloudifyDeployment> In2 = s -> ownerDeplList.stream() + .anyMatch(mc -> s.id.equals(mc.id)); + cfyDepList = cfyDepList.stream().filter(In2) + .collect(Collectors.toList()); } else { - cfyDepList = new ArrayList<CloudifyDeployment>(); + cfyDepList = new ArrayList<>(); } } } if (!svcRefFilterStr.isEmpty()) { - List<String> svcFilterList = + List<String> svcFilterList = new ArrayList<String>(Arrays.asList(svcRefFilterStr.split(","))); if (!svcFilterList.isEmpty()) { - cfyDepList = (List) cfyDepList.stream().filter(s -> svcFilterList.stream() - .anyMatch(svcFilter -> ((CloudifyDeployment) s).id.toLowerCase().contains(svcFilter.toLowerCase()))) + cfyDepList = cfyDepList.stream() + .filter(s -> svcFilterList.stream() + .anyMatch(svcFilter -> s.id + .toLowerCase().contains(svcFilter.toLowerCase()))) .collect(Collectors.toList()); } } if (!statusFilterStr.isEmpty()) { - List<String> statusFilterList = - new ArrayList<String>(Arrays.asList(statusFilterStr.split(","))); + List<String> statusFilterList = + new ArrayList<String>(Arrays.asList(statusFilterStr.split(","))); Predicate<CloudifyDeployment> srvcFilter = p -> p.lastExecution.status != null; - Stream<CloudifyDeployment> svcStream = cfyDepList.stream(); + Stream<CloudifyDeployment> svcStream = cfyDepList.stream(); if (cfyDepExList == null || cfyDepExList.isEmpty()) { cfyDepExList = cloudifyClient.updateWorkflowStatus(cfyDepList); } if (cfyDepExList != null) { updateWorkflowHelmStatus(cfyDepList, cfyDepExList, cfyDeplHelmList); - cfyDepList = svcStream.filter( srvcFilter.and( - s -> statusFilterList.stream() - .anyMatch(statusFilter ->((CloudifyDeployment) s).lastExecution.status.equalsIgnoreCase(statusFilter)))) - .collect(Collectors.toList()); + cfyDepList = svcStream + .filter(srvcFilter.and(s -> statusFilterList.stream().anyMatch( + statusFilter -> s.lastExecution.status + .equalsIgnoreCase(statusFilter)))) + .collect(Collectors.toList()); } - } + } if (!helmFilterStr.isEmpty()) { - Predicate<CloudifyDeployment> helmFilter = - p -> p.helmStatus != null; + Predicate<CloudifyDeployment> helmFilter = p -> p.helmStatus != null; boolean isHelm = Boolean.parseBoolean(helmFilterStr); if (cfyDeplHelmList == null || cfyDeplHelmList.isEmpty()) { cfyDeplHelmList = cloudifyClient.updateHelmInfo(cfyDepList); } - if (cfyDeplHelmList != null && isHelm ) { + if (cfyDeplHelmList != null && isHelm) { updateWorkflowHelmStatus(cfyDepList, cfyDepExList, cfyDeplHelmList); - cfyDepList = (List) cfyDepList.stream().filter(helmFilter.and( - s -> ((CloudifyDeployment) s).isHelm == true)) - .collect(Collectors.toList()); + cfyDepList = (List) cfyDepList.stream() + .filter(helmFilter + .and(s -> s.isHelm)) + .collect(Collectors.toList()); } - } - } + } + } itemList.addAll(cfyDepList); } catch (Exception cfyDepErr) { logger.error(EELFLoggerDelegate.errorLogger, cfyDepErr.getMessage()); } if (sortBy != null) { if (sortBy.equals("id")) { - ((List<CloudifyDeployment>)itemList).sort( - (CloudifyDeployment o1, CloudifyDeployment o2) -> o1.id.compareTo(o2.id)); + ((List<CloudifyDeployment>) itemList).sort((CloudifyDeployment o1, + CloudifyDeployment o2) -> o1.id.compareTo(o2.id)); } else if (sortBy.equals("blueprint_id")) { - ((List<CloudifyDeployment>)itemList).sort( - (CloudifyDeployment o1, CloudifyDeployment o2) -> o1.blueprint_id.compareTo(o2.blueprint_id)); + ((List<CloudifyDeployment>) itemList).sort((CloudifyDeployment o1, + CloudifyDeployment o2) -> o1.blueprint_id.compareTo(o2.blueprint_id)); } else if (sortBy.equals("created_at")) { - ((List<CloudifyDeployment>)itemList).sort( - (CloudifyDeployment o1, CloudifyDeployment o2) -> o1.created_at.compareTo(o2.created_at)); + ((List<CloudifyDeployment>) itemList).sort((CloudifyDeployment o1, + CloudifyDeployment o2) -> o1.created_at.compareTo(o2.created_at)); } else if (sortBy.equals("updated_at")) { - ((List<CloudifyDeployment>)itemList).sort( - (CloudifyDeployment o1, CloudifyDeployment o2) -> o1.updated_at.compareTo(o2.updated_at)); + ((List<CloudifyDeployment>) itemList).sort((CloudifyDeployment o1, + CloudifyDeployment o2) -> o1.updated_at.compareTo(o2.updated_at)); } } - break; + break; case TENANT: lock.readLock().lock(); - cfyTenantList = (List<CloudifyTenant>)getCacheManager().getObject(TENANTS_PATH); + cfyTenantList = (List<CloudifyTenant>) getCacheManager().getObject(TENANTS_PATH); lock.readLock().unlock(); if (cfyTenantList == null || cfyTenantList.isEmpty()) { - cfyTenantList = (List<CloudifyTenant>)cloudifyClient.getTenants().items; + cfyTenantList = (List<CloudifyTenant>) cloudifyClient.getTenants().items; } - + itemList = cfyTenantList; 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!"); + default: + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, "Getting page of items failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPage caught exception"); throw new Exception( "getItemListForPage failed: unimplemented case: " + option.name()); @@ -540,7 +539,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { if (option.equals(CloudifyDataItem.DEPLOYMENT)) { // update blueprint owner for each deployment record - if (deplPerOwner != null ) { + if (deplPerOwner != null) { updateBpOwnerId(itemList, deplPerOwner); } if (cfyDepExList == null || cfyDepExList.isEmpty()) { @@ -549,29 +548,32 @@ public class CloudifyController extends DashboardRestrictedBaseController { if (cfyDeplHelmList == null || cfyDeplHelmList.isEmpty()) { cfyDeplHelmList = cloudifyClient.updateHelmInfo(itemList); } - for (CloudifyDeployment srvc: (List<CloudifyDeployment>)itemList) { + for (CloudifyDeployment srvc : (List<CloudifyDeployment>) itemList) { try { - ConsulDeploymentHealth serviceHealth = + ConsulDeploymentHealth serviceHealth = consulClient.getServiceHealthByDeploymentId(srvc.id); if (serviceHealth != null) { srvc.healthStatus = serviceHealth.getStatus(); } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "consul getServiceHealth caught exception"); + logger.error(EELFLoggerDelegate.errorLogger, + "consul getServiceHealth caught exception"); } - // correlate the cached data for deployments and deployment extensions + // correlate the cached data for deployments and deployment extensions if (cfyDepExList != null) { - List<CloudifyDeploymentExt> deplExtItems = - cfyDepExList.stream().filter((Predicate<? super CloudifyDeploymentExt>) s->s.id.equals(srvc.id)). - collect(Collectors.toList()); + List<CloudifyDeploymentExt> deplExtItems = cfyDepExList.stream() + .filter( + (Predicate<? super CloudifyDeploymentExt>) s -> s.id.equals(srvc.id)) + .collect(Collectors.toList()); if (deplExtItems != null && !deplExtItems.isEmpty()) { srvc.lastExecution = deplExtItems.get(0).lastExecution; } } if (cfyDeplHelmList != null) { - List<CloudifyDeploymentHelm> deplHelmItems = - cfyDeplHelmList.stream().filter((Predicate<? super CloudifyDeploymentHelm>) s->s.id.equals(srvc.id)). - collect(Collectors.toList()); + List<CloudifyDeploymentHelm> deplHelmItems = cfyDeplHelmList.stream() + .filter( + (Predicate<? super CloudifyDeploymentHelm>) s -> s.id.equals(srvc.id)) + .collect(Collectors.toList()); if (deplHelmItems != null && !deplHelmItems.isEmpty()) { srvc.helmStatus = deplHelmItems.get(0).helmStatus; srvc.isHelm = deplHelmItems.get(0).isHelm; @@ -588,8 +590,8 @@ public class CloudifyController extends DashboardRestrictedBaseController { } else { for (CloudifyDeployment srvc : (List<CloudifyDeployment>) itemList) { String deplRef = srvc.id.split("_")[0].toLowerCase(); - if (comp_deploy_tab.containsKey(deplRef)) { - boolean enableDeploy = comp_deploy_tab.get(deplRef); + if (compDeployTab.containsKey(deplRef)) { + boolean enableDeploy = compDeployTab.get(deplRef); srvc.canDeploy = enableDeploy; } else { srvc.canDeploy = false; @@ -601,7 +603,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { srvc.canDeploy = true; } } - } + } RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); String outboundJson = objectMapper.writeValueAsString(model); return outboundJson; @@ -612,7 +614,7 @@ public class CloudifyController 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 * @param inputKey Input key to search for if using filters * @param inputValue Input value to search for if using filters * @return JSON with one page of objects; or an error. @@ -620,27 +622,42 @@ public class CloudifyController extends DashboardRestrictedBaseController { protected String getItemListForPageWrapper(HttpServletRequest request, CloudifyDataItem option, String sortBy, String searchBy) { String outboundJson = null; + RestResponseError result = null; try { User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + if (appUser == null || appUser.getLoginId() == null + || appUser.getLoginId().length() == 0) { throw new Exception("getItemListForPageWrapper: Failed to get application user"); + } int pageNum = getRequestPageNumber(request); int pageSize = getRequestPageSize(request); - outboundJson = getItemListForPage(request, appUser.getId(), option, pageNum, pageSize, + outboundJson = getItemListForPage(request, option, pageNum, pageSize, sortBy, searchBy); - } catch (Exception ex) { - 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!"); + } catch (HttpStatusCodeException ex) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, "Getting page of items failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception"); + result = + new RestResponseError(ex.getResponseBodyAsString()); + try { + outboundJson = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } + } catch (Exception ex) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, "Getting page of items failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception"); - RestResponseError result = null; - if (ex instanceof HttpStatusCodeException) - result = new RestResponseError(((HttpStatusCodeException) ex).getResponseBodyAsString()); - else - result = new RestResponseError("Failed to get " + option.name(), ex); + result = new RestResponseError("Failed to get " + option.name(), ex); try { outboundJson = objectMapper.writeValueAsString(result); } catch (JsonProcessingException jpe) { @@ -650,7 +667,6 @@ public class CloudifyController extends DashboardRestrictedBaseController { } return outboundJson; } - /** * Serves one page of deployments @@ -658,205 +674,201 @@ public class CloudifyController extends DashboardRestrictedBaseController { * @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,request.getParameter("sortBy"), request.getParameter("searchBy")); - postLogAudit(request); - return json; - } - - /** - * Gets the specified blueprint content for viewing. - * - * @param id - * Blueprint ID - * @param request - * HttpServletRequest - * @return Blueprint as YAML; or error. - * @throws Exception - * on serialization error - * - */ - @RequestMapping(value = { - BLUEPRINTS_PATH + "/{id:.+}" + "/archive" }, method = RequestMethod.GET, produces = "application/yaml") - @ResponseBody - public byte[] viewBlueprintContentById(@PathVariable("id") String id, @RequestParam(value = "tenant", required = true) String tenant, HttpServletRequest request) throws Exception { - preLogAudit(request); - byte[] result = null; - try { - result = cloudifyClient.viewBlueprint(tenant, 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 result; - //objectMapper.writeValueAsString(result); - } + @GetMapping( + value = {DEPLOYMENTS_PATH}, + produces = "application/json") + public String getDeploymentsByPage(HttpServletRequest request) { + preLogAudit(request); + String json = getItemListForPageWrapper(request, CloudifyDataItem.DEPLOYMENT, + request.getParameter(SORT_BY), request.getParameter(SEARCH_BY)); + postLogAudit(request); + return json; + } + + /** + * Gets the specified blueprint content for viewing. + * + * @param id + * Blueprint ID + * @param request + * HttpServletRequest + * @return Blueprint as YAML; or error. + * @throws Exception + * on serialization error + * + */ + @GetMapping( + value = {BLUEPRINTS_PATH + "/{id:.+}" + "/archive"}, + produces = "application/yaml") + public byte[] viewBlueprintContentById(@PathVariable("id") String id, + @RequestParam(value = "tenant", required = true) String tenant, HttpServletRequest request) + throws Exception { + preLogAudit(request); + byte[] result = null; + final String errStr = "View blueprint failed: " + id ; + final String errLogStr = "viewBlueprintContentById caught exception"; + try { + result = cloudifyClient.viewBlueprint(tenant, id); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + } finally { + postLogAudit(request); + } + return result; + } + + /** + * Serves the complete list of deployment IDs. + * + * @param request HttpServletRequest + * + * @return list of cloudify deployment IDs + */ + @GetMapping(value = {SERVICE_ID}, produces = "application/json") + public String getAllServiceNames(HttpServletRequest request) { + preLogAudit(request); + String json = null; + json = getItemListForPageWrapper(request, CloudifyDataItem.SERVICE_ID, + request.getParameter(SORT_BY), request.getParameter(SEARCH_BY)); + postLogAudit(request); + return json; + } + + /** + * Serves the count of deployment IDs. + * + * @param request HttpServletRequest + * + * @return list of cloudify deployment IDs + */ + @GetMapping( + value = {SERVICE_ID_COUNT}, + produces = "application/json") + public String getDepCount(HttpServletRequest request) { + preLogAudit(request); + String json = null; + json = getItemListForPageWrapper(request, CloudifyDataItem.SERVICE_ID_COUNT, + request.getParameter(SORT_BY), request.getParameter(SEARCH_BY)); + postLogAudit(request); + return json; + } - /** - * Serves the complete list of deployment IDs - * - * @param request HttpServletRequest - * - * @return list of cloudify deployment IDs - */ - @RequestMapping( - value = {SERVICE_ID}, - method = RequestMethod.GET, - produces = "application/json") - @ResponseBody - public String getAllServiceNames(HttpServletRequest request) { - preLogAudit(request); - String json = null; - json = getItemListForPageWrapper(request, CloudifyDataItem.SERVICE_ID, - request.getParameter("sortBy"), request.getParameter("searchBy")); - postLogAudit(request); - return json; - } - - /** - * Serves the count of deployment IDs - * - * @param request HttpServletRequest - * - * @return list of cloudify deployment IDs - */ - @RequestMapping( - value = {SERVICE_ID_COUNT}, - method = RequestMethod.GET, - produces = "application/json") - @ResponseBody - public String getDepCount(HttpServletRequest request) { - preLogAudit(request); - String json = null; - json = getItemListForPageWrapper(request, CloudifyDataItem.SERVICE_ID_COUNT, - request.getParameter("sortBy"), request.getParameter("searchBy")); - postLogAudit(request); - return json; - } - - /** - * Serves the count of plugins - * - * @param request HttpServletRequest - * - * @return count of cloudify plugins - * @throws JsonProcessingException - */ - @RequestMapping( - value = {PLUGIN_COUNT}, - method = RequestMethod.GET, - produces = "application/json") - @ResponseBody - public String getPluginCount(HttpServletRequest request) - throws JsonProcessingException { - preLogAudit(request); - ECTransportModel result = null; - try { - int totalItems = - (int) cloudifyClient.getPlugins().metadata.pagination.total; - RestResponsePage<List> model = - new RestResponsePage<>(totalItems, 1, null); - String outboundJson = objectMapper.writeValueAsString(model); - return outboundJson; - } 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 plugins failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getPlugins caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - return objectMapper.writeValueAsString(result); - } 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 plugins failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getPlugins caught exception"); - result = new RestResponseError("getSecret failed", t); - return objectMapper.writeValueAsString(result); - } finally { - postLogAudit(request); - } - } - /** - * gets the tenants list + * Serves the count of plugins. + * + * @param request HttpServletRequest + * + * @return count of cloudify plugins + * @throws JsonProcessingException + */ + @GetMapping( + value = {PLUGIN_COUNT}, + produces = "application/json") + public String getPluginCount(HttpServletRequest request) throws JsonProcessingException { + preLogAudit(request); + ECTransportModel result = null; + final String errStr = "Getting plugins failed!"; + final String errLogStr = "getPlugins caught exception"; + try { + int totalItems = (int) cloudifyClient.getPlugins().metadata.pagination.total; + RestResponsePage<List> model = new RestResponsePage<>(totalItems, 1, null); + return objectMapper.writeValueAsString(model); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + result = new RestResponseError(e.getResponseBodyAsString()); + return objectMapper.writeValueAsString(result); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + result = new RestResponseError("getSecret failed", t); + return objectMapper.writeValueAsString(result); + } finally { + postLogAudit(request); + } + } + + /** + * get the tenants list. * * @param request HttpServletRequest * @return List of CloudifyDeployment objects */ - @RequestMapping(value = { TENANTS_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping( + value = {TENANTS_PATH}, + produces = "application/json") public String getTenants(HttpServletRequest request) { preLogAudit(request); String json = getItemListForPageWrapper(request, CloudifyDataItem.TENANT, - request.getParameter("sortBy"), request.getParameter("searchBy")); + request.getParameter(SORT_BY), request.getParameter(SEARCH_BY)); postLogAudit(request); return json; } - + /** * Gets the specified blueprint metadata. * - * @param id Blueprint ID + * @param id Blueprint ID * @param request HttpServletRequest * @return Blueprint as JSON; or error. * @throws Exception on serialization error * */ - @RequestMapping(value = { BLUEPRINTS_PATH + "/{id:.+}" }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping( + value = {BLUEPRINTS_PATH + "/{id:.+}"}, + produces = "application/json") public String getBlueprintById(@PathVariable("id") String id, - @RequestParam(value = "tenant", required = true) String tenant, HttpServletRequest request) - throws Exception { + @RequestParam(value = "tenant", required = true) String tenant, HttpServletRequest request) + throws Exception { preLogAudit(request); ECTransportModel result = null; + final String errStr = "Getting blueprint failed: " + id ; + final String errLogStr = "getBlueprintById caught exception"; try { result = cloudifyClient.getBlueprint(id, 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 blueprint " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getBlueprintById caught exception"); + + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError(e.getResponseBodyAsString()); } catch (Exception 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 blueprint " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getBlueprintById caught exception"); + + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError("getBlueprintById failed", t); } finally { postLogAudit(request); @@ -867,39 +879,42 @@ public class CloudifyController extends DashboardRestrictedBaseController { /** * Deletes the specified blueprint. * - * @param id Blueprint ID - * @param request HttpServletRequest + * @param id Blueprint ID + * @param request HttpServletRequest * @param response HttpServletResponse * @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, - @RequestParam(value = "tenant", required = false) String tenant, - HttpServletRequest request, HttpServletResponse response) throws Exception { + @DeleteMapping( + value = {BLUEPRINTS_PATH + "/{id}"}, + produces = "application/json") + public String deleteBlueprint(@PathVariable("id") String id, + @RequestParam(value = "tenant", required = false) String tenant, HttpServletRequest request, + HttpServletResponse response) throws Exception { preLogAudit(request); String json = "{\"202\": \"OK\"}"; + final String errStr = "Deleting blueprint " + id + " failed!"; + final String errLogStr = "deleteBlueprint caught exception"; try { cloudifyClient.deleteBlueprint(id, tenant); response.setStatus(202); - } 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"); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } 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"); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); json = objectMapper .writeValueAsString(new RestResponseError("deleteBlueprint failed on ID " + id, t)); } finally { @@ -907,168 +922,174 @@ public class CloudifyController extends DashboardRestrictedBaseController { } return json; } - + /** * - * Deployment IDs for the given list of blueprint IDs + * Deployment IDs for the given list of blueprint IDs. * */ - @RequestMapping( - value = {"deployment_blueprint_map"}, - method = RequestMethod.POST, - produces = "application/json") - @ResponseBody - public String getDeploymentsForType(HttpServletRequest request, @RequestBody String[] typeList) - throws Exception { - List<ServiceTypeServiceMap> result = new ArrayList<ServiceTypeServiceMap>(); - for (String typeId : typeList) { - List<CloudifyDeployedTenant> deplForBpAggr = new ArrayList<CloudifyDeployedTenant>(); - List<CloudifyDeployedTenant> deplForBp = - cloudifyClient.getDeploymentForBlueprint("TID-"+typeId); - deplForBpAggr.addAll(deplForBp); - - ServiceQueryParams qryParams = - new ServiceQueryParams.Builder().typeId(typeId).build(); - ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); - Set<String> dep_ids = srvcRefs.items.stream().map(x -> ((ServiceRef)x).id).collect(Collectors.toSet()); - if (dep_ids.size() > 0) { - // lookup these dep_ids in cloudify for tenant mapping - for (String str: dep_ids) { - List<CloudifyDeployedTenant> deplForBpInv = - cloudifyClient.getDeploymentForBlueprint(str); - deplForBpAggr.addAll(deplForBpInv); - } - } - ServiceRefCfyList cfyDeplRefList = new ServiceRefCfyList(deplForBpAggr, deplForBpAggr.size()); - ServiceTypeServiceMap srvcMap = new ServiceTypeServiceMap(typeId, cfyDeplRefList); - result.add(srvcMap); - } - String resultStr = objectMapper.writeValueAsString(result); - return resultStr; - } + @PostMapping( + value = {"deployment_blueprint_map"}, + produces = "application/json") + public String getDeploymentsForType(HttpServletRequest request, @RequestBody String[] typeList) + throws Exception { + List<ServiceTypeServiceMap> result = new ArrayList<ServiceTypeServiceMap>(); + for (String typeId : typeList) { + List<CloudifyDeployedTenant> deplForBpAggr = new ArrayList<CloudifyDeployedTenant>(); + List<CloudifyDeployedTenant> deplForBp = + cloudifyClient.getDeploymentForBlueprint("TID-" + typeId); + deplForBpAggr.addAll(deplForBp); - @SuppressWarnings("unchecked") - @Scheduled(fixedDelay=3600000, initialDelay=180000) - public void cacheOwnerDeployMap() { - logger.debug(EELFLoggerDelegate.debugLogger, "cacheOwnerDeployMap begin"); - Map<String, List<CloudifyDeployedTenant>> deplPerOwner = - new HashMap<String, List<CloudifyDeployedTenant>>(); - new HashMap<String, List<ServiceTypeSummary>>(); - List<ServiceTypeSummary> bpNoDeplItems = - new ArrayList<ServiceTypeSummary>(); - List<ServiceTypeServiceMap> result = new ArrayList<ServiceTypeServiceMap>(); - List<CloudifyDeployedTenant> deplForBpAggr = - new ArrayList<CloudifyDeployedTenant>(); - String typeId = ""; - String owner = ""; - - ReadWriteLock lock = new ReentrantReadWriteLock(); - lock.readLock().lock(); - List<ServiceTypeSummary> bpItems = - (List<ServiceTypeSummary>) getCacheManager().getObject(SERVICE_TYPES); - lock.readLock().unlock(); - if (bpItems != null) { - for (ServiceTypeSummary item : bpItems) { - try { - typeId = item.getTypeId().get(); - owner = item.getOwner(); - List<CloudifyDeployedTenant> deplForBp = - cloudifyClient.getDeploymentForBlueprint("TID-"+typeId); - deplForBpAggr.clear(); - deplForBpAggr.addAll(deplForBp); - ServiceQueryParams qryParams = - new ServiceQueryParams.Builder().typeId(typeId).build(); - ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); - Set<String> dep_ids = srvcRefs.items.stream().map(x -> ((ServiceRef)x).id).collect(Collectors.toSet()); - if (dep_ids.size() > 0) { - for (String str: dep_ids) { - List<CloudifyDeployedTenant> deplForBpInv = - cloudifyClient.getDeploymentForBlueprint(str); - deplForBpAggr.addAll(deplForBpInv); - } - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "cacheOwnerDeployMap: " + e.getMessage()); - } finally { - if (deplForBpAggr.isEmpty()) { - bpNoDeplItems.add(item); - } - List<CloudifyDeployedTenant> iterBpIdDepl = - new ArrayList<CloudifyDeployedTenant>(); - iterBpIdDepl.addAll(deplForBpAggr); - ServiceRefCfyList cfyDeplRefList = new ServiceRefCfyList(iterBpIdDepl, iterBpIdDepl.size()); - ServiceTypeServiceMap srvcMap = new ServiceTypeServiceMap(typeId, cfyDeplRefList); - result.add(srvcMap); - - List<CloudifyDeployedTenant> iterDeplBpAggr = - new ArrayList<CloudifyDeployedTenant>(); - iterDeplBpAggr.addAll(deplForBpAggr); - if (deplPerOwner.containsKey(owner)) { - List<CloudifyDeployedTenant> currOwnerDepl = - deplPerOwner.get(owner); - iterDeplBpAggr.addAll(0, currOwnerDepl); - deplPerOwner.put(owner, iterDeplBpAggr); - } else { - deplPerOwner.putIfAbsent(owner, iterDeplBpAggr); - } - } - } - } + ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); + ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); + Set<String> depIds = + srvcRefs.items.stream().map(x -> ((ServiceRef) x).id).collect(Collectors.toSet()); + if (!depIds.isEmpty()) { + // lookup these dep_ids in cloudify for tenant mapping + for (String str : depIds) { + List<CloudifyDeployedTenant> deplForBpInv = + cloudifyClient.getDeploymentForBlueprint(str); + deplForBpAggr.addAll(deplForBpInv); + } + } + ServiceRefCfyList cfyDeplRefList = + new ServiceRefCfyList(deplForBpAggr, deplForBpAggr.size()); + ServiceTypeServiceMap srvcMap = new ServiceTypeServiceMap(typeId, cfyDeplRefList); + result.add(srvcMap); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Scheduled method to build and update application cache + * containing a collection of user to deployments mapping. + */ + @SuppressWarnings("unchecked") + @Scheduled(fixedDelay = 3600000, initialDelay = 180000) + public void cacheOwnerDeployMap() { + logger.debug(EELFLoggerDelegate.debugLogger, "cacheOwnerDeployMap begin"); + Map<String, List<CloudifyDeployedTenant>> deplPerOwner = + new HashMap<>(); + new HashMap<String, List<ServiceTypeSummary>>(); + List<ServiceTypeSummary> bpNoDeplItems = new ArrayList<>(); + List<ServiceTypeServiceMap> result = new ArrayList<>(); + List<CloudifyDeployedTenant> deplForBpAggr = new ArrayList<>(); + String typeId = ""; + String owner = ""; + + ReadWriteLock lock = new ReentrantReadWriteLock(); + lock.readLock().lock(); + List<ServiceTypeSummary> bpItems = + (List<ServiceTypeSummary>) getCacheManager().getObject(SERVICE_TYPES); + lock.readLock().unlock(); + if (bpItems != null) { + for (ServiceTypeSummary item : bpItems) { + try { + typeId = item.getTypeId().get(); + owner = item.getOwner(); + List<CloudifyDeployedTenant> deplForBp = + cloudifyClient.getDeploymentForBlueprint("TID-" + typeId); + deplForBpAggr.clear(); + deplForBpAggr.addAll(deplForBp); + ServiceQueryParams qryParams = + new ServiceQueryParams.Builder().typeId(typeId).build(); + ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); + Set<String> depIds = srvcRefs.items.stream().map(x -> (x).id) + .collect(Collectors.toSet()); + if (!depIds.isEmpty()) { + for (String str : depIds) { + List<CloudifyDeployedTenant> deplForBpInv = + cloudifyClient.getDeploymentForBlueprint(str); + deplForBpAggr.addAll(deplForBpInv); + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "cacheOwnerDeployMap: " + e.getMessage()); + } finally { + if (deplForBpAggr.isEmpty()) { + bpNoDeplItems.add(item); + } + List<CloudifyDeployedTenant> iterBpIdDepl = + new ArrayList<CloudifyDeployedTenant>(); + iterBpIdDepl.addAll(deplForBpAggr); + ServiceRefCfyList cfyDeplRefList = + new ServiceRefCfyList(iterBpIdDepl, iterBpIdDepl.size()); + ServiceTypeServiceMap srvcMap = + new ServiceTypeServiceMap(typeId, cfyDeplRefList); + result.add(srvcMap); + + List<CloudifyDeployedTenant> iterDeplBpAggr = + new ArrayList<>(); + iterDeplBpAggr.addAll(deplForBpAggr); + if (deplPerOwner.containsKey(owner)) { + List<CloudifyDeployedTenant> currOwnerDepl = deplPerOwner.get(owner); + iterDeplBpAggr.addAll(0, currOwnerDepl); + deplPerOwner.put(owner, iterDeplBpAggr); + } else { + deplPerOwner.putIfAbsent(owner, iterDeplBpAggr); + } + } + } + } + + lock.writeLock().lock(); + getCacheManager().putObject("bp_deploy_map", result); + getCacheManager().putObject("owner_deploy_map", deplPerOwner); + lock.writeLock().unlock(); + } - lock.writeLock().lock(); - getCacheManager().putObject("bp_deploy_map", result); - getCacheManager().putObject("owner_deploy_map", deplPerOwner); - lock.writeLock().unlock(); - } - /** * Gets the specified deployment. * - * @param id Deployment ID + * @param id Deployment ID * @param request HttpServletRequest * @return Deployment for the specified ID; error on failure. * @throws Exception On serialization failure * */ - @RequestMapping(value = { DEPLOYMENTS_PATH + "/{id:.+}" }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping( + value = {DEPLOYMENTS_PATH + "/{id:.+}"}, + produces = "application/json") public String getDeploymentById(@PathVariable("id") String id, - @RequestParam(value = "tenant", required = false) String tenant, HttpServletRequest request) - throws Exception { + @RequestParam(value = "tenant", required = false) String tenant, HttpServletRequest request) + throws Exception { preLogAudit(request); ECTransportModel result = null; + final String errStr = "Getting deployment " + id + " failed!"; + final String errLogStr = "getDeploymentById caught exception"; try { if (tenant != null && tenant.length() > 0) { result = cloudifyClient.getDeployment(id, tenant); } else { result = cloudifyClient.getDeployment(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", "Getting deployment " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); + } catch (HttpStatusCodeException e) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception 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 deployment " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError("getDeploymentById failed", t); } finally { postLogAudit(request); } return objectMapper.writeValueAsString(result); } - + /** - * Gets and serves one page of executions: + * Gets and serves one page of executions. * <OL> * <LI>Gets all deployments; OR uses the specified deployment ID if the query * parameter is present @@ -1079,35 +1100,35 @@ public class CloudifyController extends DashboardRestrictedBaseController { * to the executions with that status. * </OL> * - * @param request HttpServletRequest + * @param request HttpServletRequest * @param deployment_id Optional request parameter; if found, only executions - * for that deployment ID are returned. - * @param status Optional request parameter; if found, only executions - * with that status are returned. + * for that deployment ID are returned. + * @param status Optional request parameter; if found, only executions + * with that status are returned. * @return List of CloudifyExecution objects * @throws Exception on serialization failure */ @SuppressWarnings("unchecked") - @RequestMapping(value = { EXECUTIONS_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping( + value = {EXECUTIONS_PATH}, + produces = "application/json") public String getExecutionsByPage(HttpServletRequest request, - @RequestParam(value = "deployment_id", required = true) String deployment_id, + @RequestParam(value = "deployment_id", required = true) String deploymentId, @RequestParam(value = "status", required = false) String status, @RequestParam(value = "tenant", required = true) String tenant) throws Exception { preLogAudit(request); ECTransportModel result = null; + final String errStr = "Getting executions failed!"; + final String errLogStr = "getExecutionsByPage caught exception"; try { - if (tenant == null) { - throw new Exception("required tenant input missing"); - } List<CloudifyExecution> itemList = new ArrayList<CloudifyExecution>(); List<String> depIds = new ArrayList<>(); - if (deployment_id == null) { + if (deploymentId == null) { CloudifyDeploymentList depList = cloudifyClient.getDeployments(tenant, 100, 0); for (CloudifyDeployment cd : depList.items) depIds.add(cd.id); } else { - depIds.add(deployment_id); + depIds.add(deploymentId); } for (String depId : depIds) { CloudifyExecutionList exeList = cloudifyClient.getExecutions(depId, tenant); @@ -1118,30 +1139,32 @@ public class CloudifyController extends DashboardRestrictedBaseController { Iterator<CloudifyExecution> exeIter = itemList.iterator(); while (exeIter.hasNext()) { CloudifyExecution ce = exeIter.next(); - if (!status.equals(ce.status)) + if (!status.equals(ce.status)) { exeIter.remove(); + } } } - Collections.sort(itemList, executionComparator); - + itemList.sort((CloudifyExecution o1, CloudifyExecution o2) -> o1 + .created_at.compareTo(o2.created_at)); // Paginate final int pageNum = getRequestPageNumber(request); final int pageSize = getRequestPageSize(request); final int totalItems = itemList.size(); final int pageCount = (int) Math.ceil((double) totalItems / pageSize); // Shrink if needed - if (totalItems > pageSize) + if (totalItems > pageSize) { itemList = getPageOfList(pageNum, pageSize, itemList); + } result = new RestResponsePage<>(totalItems, pageCount, itemList); - } catch (Exception 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 executions failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionsByPage caught exception"); - result = new RestResponseError("getExecutionsByPage failed", t); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + result = new RestResponseError(errLogStr, t); } finally { postLogAudit(request); } @@ -1149,8 +1172,9 @@ public class CloudifyController extends DashboardRestrictedBaseController { } @SuppressWarnings("unchecked") - @RequestMapping(value = { EXECUTIONS_PATH + "/tenant" }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping( + value = {EXECUTIONS_PATH + "/tenant"}, + produces = "application/json") public String getExecutionsPerTenant(HttpServletRequest request, @RequestParam(value = "tenant", required = true) String tenant, @RequestParam(value = "status", required = false) String status) throws Exception { @@ -1159,34 +1183,38 @@ public class CloudifyController extends DashboardRestrictedBaseController { ReadWriteLock lock = new ReentrantReadWriteLock(); List<CloudifyTenant> cfyTenantList = null; List<CloudifyTenant> myTenantsList = null; + final String errStr = "Getting executions failed!"; + final String errLogStr = "getExecutionsByPage caught exception"; try { - List<CloudifyExecution> itemList = new ArrayList<CloudifyExecution>(); + List<CloudifyExecution> itemList = new ArrayList<>(); if (tenant == null) { // process all tenants that are relevant lock.readLock().lock(); - cfyTenantList = (List<CloudifyTenant>)getCacheManager().getObject(TENANTS_PATH); + cfyTenantList = (List<CloudifyTenant>) getCacheManager().getObject(TENANTS_PATH); lock.readLock().unlock(); if (cfyTenantList == null || cfyTenantList.isEmpty()) { - cfyTenantList = (List<CloudifyTenant>)cloudifyClient.getTenants().items; - } + cfyTenantList = cloudifyClient.getTenants().items; + } myTenantsList = cfyTenantList; - + for (CloudifyTenant tenItem : myTenantsList) { - CloudifyExecutionList exeList = + CloudifyExecutionList exeList = cloudifyClient.getExecutionsSummaryPerTenant(tenItem.name); // Filter down to specified status as needed if (status != null && !status.isEmpty()) { Iterator<CloudifyExecution> exeIter = exeList.items.iterator(); while (exeIter.hasNext()) { CloudifyExecution ce = exeIter.next(); - if (!status.equals(ce.status)) + if (!status.equals(ce.status)) { exeIter.remove(); + } } } itemList.addAll(exeList.items); } } else { - CloudifyExecutionList exeList = cloudifyClient.getExecutionsSummaryPerTenant(tenant); + CloudifyExecutionList exeList = + cloudifyClient.getExecutionsSummaryPerTenant(tenant); itemList.addAll(exeList.items); // Filter down to specified status as needed @@ -1194,31 +1222,31 @@ public class CloudifyController extends DashboardRestrictedBaseController { Iterator<CloudifyExecution> exeIter = itemList.iterator(); while (exeIter.hasNext()) { CloudifyExecution ce = exeIter.next(); - if (!status.equals(ce.status)) + if (!status.equals(ce.status)) { exeIter.remove(); + } } - } + } } - //Collections.sort(itemList, executionComparator); - // Paginate final int pageNum = getRequestPageNumber(request); final int pageSize = getRequestPageSize(request); final int totalItems = itemList.size(); final int pageCount = (int) Math.ceil((double) totalItems / pageSize); // Shrink if needed - if (totalItems > pageSize) + if (totalItems > pageSize) { itemList = getPageOfList(pageNum, pageSize, itemList); + } result = new RestResponsePage<>(totalItems, pageCount, itemList); - } catch (Exception 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 executions failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionsByPage caught exception"); - result = new RestResponseError("getExecutionsByPage failed", t); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + result = new RestResponseError(errLogStr, t); } finally { postLogAudit(request); } @@ -1226,14 +1254,18 @@ public class CloudifyController extends DashboardRestrictedBaseController { } @SuppressWarnings("unchecked") - @RequestMapping(value = { EXECUTIONS_PATH + "/{id:.+}"}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String queryExecution(@PathVariable("id") String id, @RequestParam(value = "tenant", required = true) - String tenant, HttpServletRequest request) throws Exception { + @GetMapping( + value = {EXECUTIONS_PATH + "/{id:.+}"}, + produces = "application/json") + public String queryExecution(@PathVariable("id") String id, + @RequestParam(value = "tenant", required = true) String tenant, HttpServletRequest request) + throws Exception { preLogAudit(request); ECTransportModel result = null; + final String errStr = "Getting executions failed!"; + final String errLogStr = "getExecutionsByPage caught exception"; try { - List<CloudifyExecution> itemList = new ArrayList<CloudifyExecution>(); + List<CloudifyExecution> itemList = new ArrayList<>(); CloudifyExecution cfyExecObj = cloudifyClient.getExecutionIdSummary(id, tenant); itemList.add(cfyExecObj); final int pageNum = getRequestPageNumber(request); @@ -1241,27 +1273,29 @@ public class CloudifyController extends DashboardRestrictedBaseController { final int totalItems = itemList.size(); final int pageCount = (int) Math.ceil((double) totalItems / pageSize); // Shrink if needed - if (totalItems > pageSize) + if (totalItems > pageSize) { itemList = getPageOfList(pageNum, pageSize, itemList); + } result = new RestResponsePage<>(totalItems, pageCount, itemList); - } catch (Exception 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 executions failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionsByPage caught exception"); - result = new RestResponseError("getExecutionsByPage failed", t); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + result = new RestResponseError(errLogStr, t); } finally { postLogAudit(request); } return objectMapper.writeValueAsString(result); - } - + } + @SuppressWarnings("unchecked") - @RequestMapping(value = { EXECUTIONS_PATH + "/active"}, method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping( + value = {EXECUTIONS_PATH + "/active"}, + produces = "application/json") public String getActiveExecutions(HttpServletRequest request) throws Exception { preLogAudit(request); ECTransportModel result = null; @@ -1269,22 +1303,23 @@ public class CloudifyController extends DashboardRestrictedBaseController { List<CloudifyTenant> cfyTenantList = null; List<CloudifyTenant> myTenantsList = null; String status = "started"; + final String errStr = "Getting executions failed!"; + final String errLogStr = "getExecutionsByPage caught exception"; try { - List<CloudifyExecution> itemList = new ArrayList<CloudifyExecution>(); + List<CloudifyExecution> itemList = new ArrayList<>(); // process all tenants that are relevant lock.readLock().lock(); - cfyTenantList = (List<CloudifyTenant>)getCacheManager().getObject(TENANTS_PATH); + cfyTenantList = (List<CloudifyTenant>) getCacheManager().getObject(TENANTS_PATH); lock.readLock().unlock(); if (cfyTenantList == null || cfyTenantList.isEmpty()) { - cfyTenantList = (List<CloudifyTenant>)cloudifyClient.getTenants().items; - } + cfyTenantList = cloudifyClient.getTenants().items; + } myTenantsList = cfyTenantList; - + for (CloudifyTenant tenItem : myTenantsList) { CloudifyExecutionList exeList = null; try { - exeList = - cloudifyClient.getExecutionsSummaryPerTenant(tenItem.name); + exeList = cloudifyClient.getExecutionsSummaryPerTenant(tenItem.name); } catch (Exception e) { continue; } @@ -1297,26 +1332,25 @@ public class CloudifyController extends DashboardRestrictedBaseController { } itemList.addAll(exeList.items); } - //Collections.sort(itemList, executionComparator); - // Paginate final int pageNum = getRequestPageNumber(request); final int pageSize = getRequestPageSize(request); final int totalItems = itemList.size(); final int pageCount = (int) Math.ceil((double) totalItems / pageSize); // Shrink if needed - if (totalItems > pageSize) + if (totalItems > pageSize) { itemList = getPageOfList(pageNum, pageSize, itemList); + } result = new RestResponsePage<>(totalItems, pageCount, itemList); - } catch (Exception 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 executions failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionsByPage caught exception"); - result = new RestResponseError("getExecutionsByPage failed", t); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + result = new RestResponseError(errLogStr, t); } finally { postLogAudit(request); } @@ -1328,27 +1362,27 @@ public class CloudifyController extends DashboardRestrictedBaseController { * * * @param execution_id Execution ID (request parameter) - * @param tenant tenant name (query parameter) - * @param request HttpServletRequest + * @param tenant tenant name (query parameter) + * @param request HttpServletRequest * @return CloudifyExecutionList * @throws Exception on serialization failure */ @SuppressWarnings("unchecked") - @RequestMapping(value = { EVENTS_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping( + value = {EVENTS_PATH}, + produces = "application/json") public String getExecutionEventsById( - @RequestParam(value = "execution_id", required = false) String execution_id, + @RequestParam(value = "execution_id", required = false) String executionId, @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; + final String errStr = "Getting executions failed for: " + executionId; + final String errLogStr = "getExecutionEventsById caught exception"; try { - if (tenant == null) { - throw new Exception("required tenant input missing"); - } - eventsList = cloudifyClient.getEventlogs(execution_id, tenant); + eventsList = cloudifyClient.getEventlogs(executionId, tenant); // Filter down to specified event type as needed List<CloudifyEvent> itemList = eventsList.items; if (!isLogEvent.isEmpty() && isLogEvent.equals("false")) { @@ -1360,33 +1394,35 @@ public class CloudifyController extends DashboardRestrictedBaseController { } } } - Collections.sort(itemList, eventComparator); + itemList.sort((CloudifyEvent o1, CloudifyEvent o2) -> o1 + .reported_timestamp.compareTo(o2.reported_timestamp)); Collections.reverse(itemList); final int pageNum = getRequestPageNumber(request); final int pageSize = getRequestPageSize(request); final int totalItems = itemList.size(); final int pageCount = (int) Math.ceil((double) totalItems / pageSize); // Shrink if needed - if (totalItems > pageSize) + if (totalItems > pageSize) { itemList = getPageOfList(pageNum, pageSize, itemList); + } result = new RestResponsePage<>(totalItems, pageCount, itemList); } 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 executions " + execution_id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionEventsById caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError(e.getResponseBodyAsString()); } catch (Exception 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 executions " + execution_id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError("getExecutionEventsById failed", t); } finally { postLogAudit(request); @@ -1397,19 +1433,23 @@ public class CloudifyController extends DashboardRestrictedBaseController { /** * Processes request to create an execution based on a deployment. * - * @param request HttpServletRequest + * @param request HttpServletRequest * @param execution Execution model * @return Information about the execution * @throws Exception on serialization failure */ - @RequestMapping(value = { EXECUTIONS_PATH }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String startExecution(HttpServletRequest request, @RequestBody CloudifyExecutionRequest execution) - throws Exception { + @PostMapping( + value = {EXECUTIONS_PATH}, + produces = "application/json") + public String startExecution(HttpServletRequest request, + @RequestBody CloudifyExecutionRequest execution) throws Exception { preLogAudit(request); ECTransportModel result = null; + final String errStr = "Starting execution failed!"; + final String errLogStr = "startExecution caught exception"; try { - if (!(execution.workflow_id.equals("status") || execution.workflow_id.equals("execute_operation")) + if (!(execution.workflow_id.equals("status") + || execution.workflow_id.equals("execute_operation")) && !execution.getParameters().containsKey("node_instance_id")) { // get the node instance ID for the deployment String nodeInstId = ""; @@ -1423,31 +1463,31 @@ public class CloudifyController extends DashboardRestrictedBaseController { execution.setParameters(inParms); } if (execution.workflow_id.equals("upgrade")) { - String repo_user = - cloudifyClient.getSecret("controller_helm_user", execution.getTenant()).value; - String repo_user_password = - cloudifyClient.getSecret("controller_helm_password", execution.getTenant()).value; - execution.getParameters().put("repo_user", repo_user); - execution.getParameters().put("repo_user_password", repo_user_password); + String repoUser = + cloudifyClient.getSecret("controller_helm_user", execution.getTenant()).value; + String repoUserPassword = cloudifyClient.getSecret("controller_helm_password", + execution.getTenant()).value; + execution.getParameters().put("repo_user", repoUser); + execution.getParameters().put("repo_user_password", repoUserPassword); } result = cloudifyClient.startExecution(execution); } 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"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception 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"); + } catch (Exception t) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError("startExecution failed", t); } finally { postLogAudit(request); @@ -1458,140 +1498,145 @@ public class CloudifyController extends DashboardRestrictedBaseController { /** * Cancels an execution. * - * @param id Execution ID + * @param id Execution ID * @param deploymentId Deployment ID (not clear why this is needed) - * @param action Action to perform (not clear why this is needed) - * @param request HttpServletRequest - * @param response HttpServletRequest + * @param action Action to perform (not clear why this is needed) + * @param request HttpServletRequest + * @param response HttpServletRequest * @return Passes thru HTTP status code from remote endpoint; no body on success * @throws Exception on serialization failure */ - @RequestMapping(value = { EXECUTIONS_PATH + "/{id}" }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody + @PostMapping( + value = {EXECUTIONS_PATH + "/{id}"}, + produces = "application/json") public String cancelExecution(@RequestHeader HttpHeaders headers, @PathVariable("id") String id, - @RequestBody Map<String, String> parameters, HttpServletRequest request, HttpServletResponse response) - throws Exception { + @RequestBody Map<String, String> parameters, HttpServletRequest request, + HttpServletResponse response) throws Exception { preLogAudit(request); ECTransportModel result = null; List<String> tenant = null; + final String errStr = "Cancelling execution failed: " + id; + final String errLogStr = "cancelExecution caught exception"; try { tenant = headers.get("tenant"); result = cloudifyClient.cancelExecution(id, parameters, tenant.get(0)); } 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", "Cancelling execution " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError(e.getResponseBodyAsString()); } catch (Exception 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", "Cancelling execution " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError("cancelExecution failed on ID " + id, t); } finally { postLogAudit(request); } - if (result == null) + if (result == null) { return null; - else + } + else { return objectMapper.writeValueAsString(result); + } } /** * Gets the specified node-instances details * - * @query param deployment deployment ID - * @query param tenant tenant name + * @query param deployment deployment ID + * @query param tenant tenant name * @param request HttpServletRequest * @return node instances as a string; or error. * @throws Exception on serialization error * */ - @RequestMapping(value = {"node-instances-data"}, - method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping( + value = {"node-instances-data"}, + produces = "application/json") public String getNodeInstanceDetails( - @RequestParam(value = "deployment", required = true) String deployment, - @RequestParam(value = "tenant", required = true) String tenant, - HttpServletRequest request) throws Exception { + @RequestParam(value = "deployment", required = true) String deployment, + @RequestParam(value = "tenant", required = true) String tenant, HttpServletRequest request) + throws Exception { preLogAudit(request); ECTransportModel result = null; + final String errStr = "Getting node-instance failed for deploymentId: " + deployment; + final String errLogStr = "getNodeInstance caught exception"; try { result = cloudifyClient.getNodeInstanceDetails(deployment, 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 node-instance with deploymentId " + deployment - + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getNodeInstance caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError(e.getResponseBodyAsString()); } catch (Exception 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 node-instance with deploymentId " + deployment - + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getNodeInstance caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError("getNodeInstance failed", t); } finally { postLogAudit(request); } return objectMapper.writeValueAsString(result); } - + /** * Gets the specified node-instances for viewing. * - * @param id deployment ID + * @param id deployment ID * @param request HttpServletRequest * @return node instances as a string; or error. * @throws Exception on serialization error * */ - @RequestMapping(value = { NODE_INSTANCES_PATH - + "/{deploymentId:.+}" }, method = RequestMethod.GET, produces = "application/yaml") - @ResponseBody + @GetMapping( + value = {NODE_INSTANCES_PATH + "/{deploymentId:.+}"}, + produces = "application/yaml") public String getNodeInstances(@PathVariable("deploymentId") String deploymentId, - @RequestParam(value = "tenant", required = true) String tenant, - HttpServletRequest request) throws Exception { + @RequestParam(value = "tenant", required = true) String tenant, HttpServletRequest request) + throws Exception { preLogAudit(request); ECTransportModel result = null; + final String errStr = "Getting node-instance-id failed for deploymentId: " + deploymentId; + final String errLogStr = "getNodeInstanceId caught exception"; try { if (tenant == null) { throw new Exception("required tenant input missing"); } result = cloudifyClient.getNodeInstances(deploymentId, 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 node-instance-id with deploymentId " + deploymentId - + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getNodeInstanceId caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError(e.getResponseBodyAsString()); } catch (Exception 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 node-instance-id with deploymentId " + deploymentId - + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getNodeInstanceId caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CFY_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CFY_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError("getNodeInstanceId failed", t); } finally { postLogAudit(request); @@ -1602,25 +1647,22 @@ public class CloudifyController extends DashboardRestrictedBaseController { /** * Gets the specified node-instance-id content for viewing. * - * @param id deployment ID - * @param id node ID + * @param id deployment ID + * @param id node ID * @param request HttpServletRequest * @return Blueprint as YAML; or error. * @throws Exception on serialization error * */ - @RequestMapping(value = { NODE_INSTANCES_PATH - + "/{deploymentId:.+}/{nodeId}" }, method = RequestMethod.GET, produces = "application/yaml") - @ResponseBody + @GetMapping( + value = {NODE_INSTANCES_PATH + "/{deploymentId:.+}/{nodeId}"}, + produces = "application/yaml") public String getNodeInstanceId(@PathVariable("deploymentId") String deploymentId, - @RequestParam(value = "tenant", required = true) String tenant, @PathVariable("nodeId") String nodeId, - HttpServletRequest request) throws Exception { + @RequestParam(value = "tenant", required = true) String tenant, + @PathVariable("nodeId") String nodeId, HttpServletRequest request) throws Exception { preLogAudit(request); ECTransportModel result = null; try { - 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"); @@ -1628,8 +1670,8 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("TargetServiceName", "Cloudify Manager"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting node-instance-id with deploymentId " + deploymentId + " and nodeId " - + nodeId + " failed!"); + MDC.put("ErrorDescription", "Getting node-instance-id with deploymentId " + deploymentId + + " and nodeId " + nodeId + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getNodeInstanceId caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); } catch (Exception t) { @@ -1638,8 +1680,8 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("TargetServiceName", "Cloudify Manager"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting node-instance-id with deploymentId " + deploymentId + " and nodeId " - + nodeId + " failed!"); + MDC.put("ErrorDescription", "Getting node-instance-id with deploymentId " + deploymentId + + " and nodeId " + nodeId + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getNodeInstanceId caught exception"); result = new RestResponseError("getNodeInstanceId failed", t); } finally { @@ -1648,17 +1690,15 @@ public class CloudifyController extends DashboardRestrictedBaseController { return objectMapper.writeValueAsString(result); } - @RequestMapping(value = { - DEPLOYMENTS_PATH + "/{deploymentId:.+}/revisions" }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping( + value = {DEPLOYMENTS_PATH + "/{deploymentId:.+}/revisions"}, + produces = "application/json") public String getDeploymentRevisions(@PathVariable("deploymentId") String deploymentId, - @RequestParam(value = "tenant") String tenant, HttpServletRequest request) throws Exception { + @RequestParam(value = "tenant") String tenant, HttpServletRequest request) + throws Exception { preLogAudit(request); ECTransportModel result = null; try { - if (tenant == null) { - throw new Exception("required tenant input missing"); - } result = cloudifyClient.getNodeInstanceVersion(deploymentId, tenant); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -1666,8 +1706,10 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("TargetServiceName", "Cloudify Manager"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + MDC.put("ErrorDescription", + "Getting executions for deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, + "getExecutionByIdAndDeploymentId caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -1675,8 +1717,10 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("TargetServiceName", "Cloudify Manager"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); + MDC.put("ErrorDescription", + "Getting executions for deployment " + deploymentId + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, + "getExecutionByIdAndDeploymentId caught exception"); result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); } finally { postLogAudit(request); @@ -1689,18 +1733,18 @@ public class CloudifyController extends DashboardRestrictedBaseController { * * * @param request - * HttpServletRequest + * HttpServletRequest * @return list of CloudifyPlugin * @throws Exception - * on serialization failure + * on serialization failure */ @SuppressWarnings("unchecked") - @RequestMapping(value = { PLUGINS_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getPlugins( - HttpServletRequest request) throws Exception { + @GetMapping( + value = {PLUGINS_PATH}, + produces = "application/json") + public String getPlugins(HttpServletRequest request) throws Exception { preLogAudit(request); - ECTransportModel result = null; + ECTransportModel result = null; try { List<CloudifyPlugin> resultsArr = cloudifyClient.getPlugins().items; return objectMapper.writeValueAsString(resultsArr); @@ -1714,7 +1758,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { logger.error(EELFLoggerDelegate.errorLogger, "getPlugins caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); return objectMapper.writeValueAsString(result); - } catch (Throwable t) { + } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); @@ -1730,22 +1774,21 @@ public class CloudifyController extends DashboardRestrictedBaseController { } public void preLogAudit(HttpServletRequest request) { - begin = new Date(); + Date begin = new Date(); 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) { - end = new Date(); + Date end = new Date(); MDC.put("AlertSeverity", "0"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); 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()))); 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/ConsulController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ConsulController.java index 25ab3fd..6855793 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 @@ -2,28 +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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.controller; import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; import java.util.Date; import java.util.List; @@ -32,9 +30,6 @@ import javax.servlet.http.HttpServletRequest; 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.RestResponseSuccess; -import org.onap.ccsdk.dashboard.model.consul.ConsulHealthServiceRegistration; -import org.onap.ccsdk.dashboard.model.consul.ConsulHealthServiceRegistration.EndpointCheck; import org.onap.ccsdk.dashboard.model.consul.ConsulNodeInfo; import org.onap.ccsdk.dashboard.model.consul.ConsulServiceHealth; import org.onap.ccsdk.dashboard.model.consul.ConsulServiceInfo; @@ -45,14 +40,13 @@ 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.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.core.JsonProcessingException; @@ -61,7 +55,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; * centers. Methods serve Ajax requests made by Angular scripts on pages that * show content. */ -@Controller +@RestController @RequestMapping("/healthservices") public class ConsulController extends DashboardRestrictedBaseController { @@ -77,46 +71,24 @@ public class ConsulController extends DashboardRestrictedBaseController { SERVICE_INFO, SERVICE_HEALTH, NODES, DATACENTERS; } - private static Date begin, end; private static final String NODES_PATH = "/nodes"; private static final String SERVICES_PATH = "/services"; - - /** - * Supports sorting results by node name - */ - private static Comparator<ConsulNodeInfo> nodeHealthComparator = new Comparator<ConsulNodeInfo>() { - @Override - public int compare(ConsulNodeInfo o1, ConsulNodeInfo o2) { - return o1.node.compareTo(o2.node); - } - }; - - /** - * Supports sorting results by service name - */ - private static Comparator<ConsulServiceHealth> serviceHealthComparator = new Comparator<ConsulServiceHealth>() { - @Override - public int compare(ConsulServiceHealth o1, ConsulServiceHealth o2) { - return o1.serviceName.compareTo(o2.serviceName); - } - }; - - /** - * Supports sorting results by service name - */ - private static Comparator<ConsulServiceInfo> serviceInfoComparator = new Comparator<ConsulServiceInfo>() { - @Override - public int compare(ConsulServiceInfo o1, ConsulServiceInfo o2) { - return o1.name.compareTo(o2.name); - } - }; + private static final String TARGET_ENTITY_KEY = "TargetEntity"; + private static final String TARGET_SERVICE_KEY = "TargetServiceName"; + private static final String CNSL_SVC_ENTITY = "Consul Service"; + private static final String CNSL_TARGET_SERVICE = "Consul API"; + private static final String ERROR_RESPONSE = "ERROR"; + private static final String ERROR_CODE_KEY = "ErrorCode"; + private static final String ERROR_CODE = "300"; + private static final String ERROR_CATEGORY_KEY = "ErrorCategory"; + private static final String ERROR_DESCRIPTION_KEY = "ErrorDescription"; /** * Gets one page of objects and supporting information via the REST client. On * success, returns a page of objects as String. * - * @param option Specifies which item type to get - * @param pageNum Page number of results + * @param option Specifies which item 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. @@ -125,22 +97,25 @@ public class ConsulController extends DashboardRestrictedBaseController { private String getItemListForPage(long userId, ConsulDataItem option, int pageNum, int pageSize, String dc) throws Exception { List itemList = null; + final String errStr = "Getting page of items failed!"; + final String errLogStr = "getItemListForPage caught exception"; switch (option) { case NODES: itemList = consulClient.getNodes(dc); - Collections.sort(itemList, nodeHealthComparator); + ((List<ConsulNodeInfo>) itemList) + .sort((ConsulNodeInfo o1, ConsulNodeInfo o2) -> o1.node.compareTo(o2.node)); 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"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CNSL_SVC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CNSL_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); throw new Exception( "getItemListForPage failed: unimplemented case: " + option.name()); } @@ -159,27 +134,32 @@ public class ConsulController 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, String dc, ConsulDataItem option) { + protected String getItemListForPageWrapper(HttpServletRequest request, String dc, + ConsulDataItem option) { String outboundJson = null; + final String errStr = "Getting page of items failed!"; + final String errLogStr = "getItemListForPageWrapper caught exception"; try { User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + if (appUser == null || appUser.getLoginId() == null + || appUser.getLoginId().length() == 0) { throw new Exception("getItemListForPageWrapper: Failed to get application user"); + } int pageNum = getRequestPageNumber(request); int pageSize = getRequestPageSize(request); outboundJson = getItemListForPage(appUser.getId(), option, pageNum, pageSize, dc); } catch (Exception ex) { // Remote service failed; build descriptive error message - 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, "getItemListForPageWrapper caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CNSL_SVC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CNSL_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); RestResponseError result = new RestResponseError("Failed to get " + option.name(), ex); try { outboundJson = objectMapper.writeValueAsString(result); @@ -194,28 +174,28 @@ public class ConsulController extends DashboardRestrictedBaseController { /** * Serves service health details - not paginated. * - * @param request HttpServletRequest + * @param request HttpServletRequest * @param serviceId Service ID * @return List of ConsulServiceHealth objects as JSON * @throws Exception if serialization fails */ - @RequestMapping(value = { - SERVICES_PATH + "/{serviceId}" }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping(value = {SERVICES_PATH + "/{serviceId}"}, produces = "application/json") public String getServiceHealthDetails(HttpServletRequest request, @RequestParam String dc, - @PathVariable String serviceId) throws Exception { + @PathVariable String serviceId) throws Exception { preLogAudit(request); Object result = null; + final String errStr = "Getting service health details failed for: " + serviceId; + final String errLogStr = "getServiceHealthDetails caught exception"; try { result = consulClient.getServiceHealth(dc, serviceId); } catch (Exception t) { - 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 service health details for " + serviceId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getServiceHealthDetails caught exception"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CNSL_SVC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CNSL_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); result = new RestResponseError("getServiceHealthDetails failed", t); } finally { postLogAudit(request); @@ -227,17 +207,16 @@ public class ConsulController extends DashboardRestrictedBaseController { * Serves one page of service health information by getting all service names, * then iterating over them to get the health of each service. * - * ECOMP-C does NOT provide an API to get the health of all services in one - * request. + * API to get the health of all services in one request is not available. * * @param request HttpServletRequest * @return List of ConsulServiceHealth objects, as JSON * @throws Exception on serialization exception */ @SuppressWarnings("unchecked") - @RequestMapping(value = { "/serviceshealth" }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getServicesHealth(HttpServletRequest request, @RequestParam String dc) throws Exception { + @GetMapping(value = {"/serviceshealth"}, produces = "application/json") + public String getServicesHealth(HttpServletRequest request, @RequestParam String dc) + throws Exception { preLogAudit(request); ECTransportModel result = null; try { @@ -247,23 +226,25 @@ public class ConsulController extends DashboardRestrictedBaseController { List<ConsulServiceHealth> csh = consulClient.getServiceHealth(dc, csi.name); itemList.addAll(csh); } - Collections.sort(itemList, serviceHealthComparator); + itemList.sort((ConsulServiceHealth o1, ConsulServiceHealth o2) -> o1.serviceName + .compareTo(o2.serviceName)); // Paginate final int pageNum = getRequestPageNumber(request); final int pageSize = getRequestPageSize(request); final int totalItems = itemList.size(); final int pageCount = (int) Math.ceil((double) totalItems / pageSize); // Shrink if needed - if (totalItems > pageSize) + if (totalItems > pageSize) { itemList = getPageOfList(pageNum, pageSize, itemList); + } result = new RestResponsePage<>(totalItems, pageCount, itemList); } catch (Exception t) { - 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 services health failed!"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CNSL_SVC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CNSL_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, "Getting services health failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getServicesHealth caught exception"); result = new RestResponseError("getServicesHealth failed", t); } finally { @@ -278,8 +259,7 @@ public class ConsulController extends DashboardRestrictedBaseController { * @param request HttpServletRequest * @return List of ConsulNodeInfo objects, as JSON */ - @RequestMapping(value = { NODES_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping(value = {NODES_PATH}, produces = "application/json") public String getNodesInfo(HttpServletRequest request, @RequestParam String dc) { preLogAudit(request); String json = getItemListForPageWrapper(request, dc, ConsulDataItem.NODES); @@ -290,26 +270,26 @@ public class ConsulController extends DashboardRestrictedBaseController { /** * Serves node services health details - not paginated. * - * @param request HttpServletRequest + * @param request HttpServletRequest * @param nodeName Node name * @return List of ConsulServiceHealth objects as JSON * @throws Exception if serialization fails */ - @RequestMapping(value = { NODES_PATH + "/{nodeName}" }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping(value = {NODES_PATH + "/{nodeName}"}, produces = "application/json") public String getNodeServicesHealth(HttpServletRequest request, @RequestParam String dc, - @PathVariable String nodeName) throws Exception { + @PathVariable String nodeName) throws Exception { preLogAudit(request); Object result = null; try { result = consulClient.getNodeServicesHealth(dc, nodeName); } catch (Exception t) { - 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 node services health for " + nodeName + " failed!"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, CNSL_SVC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CNSL_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_RESPONSE); + MDC.put(ERROR_DESCRIPTION_KEY, + "Getting node services health for " + nodeName + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "getNodeServicesHealth caught exception"); result = new RestResponseError("getNodeServicesHealth failed", t); } finally { @@ -324,8 +304,9 @@ public class ConsulController extends DashboardRestrictedBaseController { * @param request HttpServletRequest * @return List of ConsulHealthStatus objects */ - @RequestMapping(value = { "/datacenters" }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody + @GetMapping( + value = {"/datacenters"}, + produces = "application/json") public String getDatacentersHealth(HttpServletRequest request) { preLogAudit(request); String json = getItemListForPageWrapper(request, null, ConsulDataItem.DATACENTERS); @@ -334,22 +315,21 @@ public class ConsulController extends DashboardRestrictedBaseController { } public void preLogAudit(HttpServletRequest request) { - begin = new Date(); + Date begin = new Date(); 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) { - end = new Date(); + Date end = new Date(); MDC.put("AlertSeverity", "0"); - MDC.put("TargetEntity", "Consul"); - MDC.put("TargetServiceName", "Consul"); + MDC.put(TARGET_ENTITY_KEY, CNSL_SVC_ENTITY); + MDC.put(TARGET_SERVICE_KEY, CNSL_TARGET_SERVICE); 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()))); 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/DashboardHomeController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardHomeController.java index 263c3d0..b647ec3 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 @@ -17,8 +17,8 @@ * 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.util.Date; @@ -54,9 +54,8 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { */ private final ObjectMapper mapper; - private static Date begin, end; private static final String APP_LABEL = "app-label"; - + /** * Never forget that Spring autowires fields AFTER the constructor is called. */ @@ -68,7 +67,7 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { /** * @return View name key, which is resolved to a file using an Apache tiles - * "definitions.xml" file. + * "definitions.xml" file. */ @RequestMapping(value = {"/ecd"}, method = RequestMethod.GET) public ModelAndView dbcDefaultController() { @@ -83,7 +82,7 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { } /** - * Get the application label - name + environment + * Get the application label - name + environment. * */ @RequestMapping(value = {APP_LABEL}, method = RequestMethod.GET, produces = "application/json") @@ -92,22 +91,22 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { return mapper.writeValueAsString( DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_IN_ENV, "NA")); } - + public void preLogAudit(HttpServletRequest request) { - begin = new Date(); + Date begin = new Date(); MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); } public void postLogAudit(HttpServletRequest request) { - end = new Date(); + Date end = new Date(); MDC.put("AlertSeverity", "0"); MDC.put("TargetEntity", "DashboardHomeController"); MDC.put("TargetServiceName", "DashboardHomeController"); 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/DashboardRestrictedBaseController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/DashboardRestrictedBaseController.java index cc1e9d8..1bb6a03 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 @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.controller; import java.text.DateFormat; @@ -41,27 +41,28 @@ import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; public class DashboardRestrictedBaseController extends RestrictedBaseController { /** - * Application name + * Application name. */ protected static final String APP_NAME = "ecd-app"; /** - * EELF-approved format + * EELF-approved format. */ - protected static final DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + protected static final DateFormat logDateFormat = + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); /** - * Query parameter for desired page number + * Query parameter for desired page number. */ protected static final String PAGE_NUM_QUERY_PARAM = "pageNum"; /** - * Query parameter for desired items per page + * Query parameter for desired items per page. */ protected static final String PAGE_SIZE_QUERY_PARAM = "viewPerPage"; /** - * For general use in these methods and subclasses + * For general use in these methods and subclasses. */ protected final ObjectMapper objectMapper = new ObjectMapper(); @@ -71,7 +72,6 @@ public class DashboardRestrictedBaseController extends RestrictedBaseController @Autowired protected DashboardProperties appProperties; - /** * Hello Spring, here's your no-arg constructor. */ @@ -98,13 +98,14 @@ public class DashboardRestrictedBaseController extends RestrictedBaseController * * @param request HttpServletRequest * @return Value of query parameter {@link #PAGE_NUM_QUERY_PARAM}; 1 if not - * found. + * found. */ protected int getRequestPageNumber(HttpServletRequest request) { int pageNum = 1; String param = request.getParameter(PAGE_NUM_QUERY_PARAM); - if (param != null) + if (param != null) { pageNum = Integer.parseInt(param); + } return pageNum; } @@ -115,30 +116,34 @@ public class DashboardRestrictedBaseController extends RestrictedBaseController * * @param request HttpServletRequest * @return Value of query parameter {@link #PAGE_SIZE_QUERY_PARAM}; 50 if not - * found. + * found. */ protected int getRequestPageSize(HttpServletRequest request) { int pageSize = 50; String param = request.getParameter(PAGE_SIZE_QUERY_PARAM); - if (param != null) + if (param != null) { pageSize = Integer.parseInt(param); + } return pageSize; } /** * Gets the items for the specified page from the specified list. * - * @param pageNum Page number requested by user, indexed from 1 + * @param pageNum Page number requested by user, indexed from 1 * @param pageSize Number of items per page * @param itemList List of items to adjust * @return List of items; empty list if from==to */ @SuppressWarnings("rawtypes") - protected static List getPageOfList(final int pageNum, final int pageSize, final List itemList) { + protected static List getPageOfList(final int pageNum, final int pageSize, + final List itemList) { int firstIndexOnThisPage = pageSize * (pageNum - 1); int firstIndexOnNextPage = pageSize * pageNum; - int fromIndex = firstIndexOnThisPage < itemList.size() ? firstIndexOnThisPage : itemList.size(); - int toIndex = firstIndexOnNextPage < itemList.size() ? firstIndexOnNextPage : itemList.size(); + int fromIndex = + firstIndexOnThisPage < itemList.size() ? firstIndexOnThisPage : itemList.size(); + int toIndex = + firstIndexOnNextPage < itemList.size() ? firstIndexOnNextPage : itemList.size(); return itemList.subList(fromIndex, toIndex); } } 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 d98c404..f716f46 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 @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.controller; import java.util.Date; @@ -42,160 +42,124 @@ 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.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; /** * Controller for Deployment Handler features: get/put/delete deployments * Methods serve Ajax requests made by Angular scripts on pages that show * content. */ -@Controller +@RestController @RequestMapping("/deploymenthandler") public class DeploymentHandlerController extends DashboardRestrictedBaseController { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DeploymentHandlerController.class); - + @Autowired DeploymentHandlerClient deploymentHandlerClient; - - private static final String DEPLOYMENTS_PATH = "dcae-deployments"; - private static Date begin, end; + private static final String DEPLOYMENTS_PATH = "dcae-deployments"; + private static final String TARGET_ENTITY_KEY = "TargetEntity"; + private static final String TARGET_SERVICE_KEY = "TargetServiceName"; + private static final String DPLH_DEP_ENTITY = "DCAE Deployment"; + private static final String DPLH_TARGET_SERVICE = "DCAE Deployment Handler"; + private static final String ERROR_RESPONSE = "ERROR"; + private static final String ERROR_CODE_KEY = "ErrorCode"; + private static final String ERROR_CODE = "300"; + private static final String ERROR_CATEGORY_KEY = "ErrorCategory"; + private static final String ERROR_CATEGORY = "ERROR"; + private static final String ERROR_DESCRIPTION_KEY = "ErrorDescription"; - @SuppressWarnings("unchecked") - @RequestMapping(value = { - DEPLOYMENTS_PATH + "/{deploymentId:.+}" }, method = RequestMethod.PUT, produces = "application/json") - @ResponseBody + @PutMapping( + value = {DEPLOYMENTS_PATH + "/{deploymentId:.+}"}, + produces = "application/json") public String putDeployment(HttpServletRequest request, - @RequestBody DeploymentRequestObject deploymentRequestObject) throws Exception { + @RequestBody DeploymentRequestObject deploymentRequestObject) throws Exception { preLogAudit(request); String json = null; + final String errStr = "Deployment failed!"; + final String errLogStr = "putDeployment caught exception: "; try { if (deploymentRequestObject.getMethod().equals("create")) { json = objectMapper.writeValueAsString(deploymentHandlerClient.putDeployment( - deploymentRequestObject.getDeploymentId(), deploymentRequestObject.getTenant(), - new DeploymentRequest(deploymentRequestObject.getServiceTypeId(), - deploymentRequestObject.getInputs()), request)); - } - } catch (BadRequestException e) { - 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! Bad Request"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("Bad Request " + e.getMessage())); - } catch (ServiceAlreadyExistsException e) { - 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! Service already exists"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("Service already exists " + e.getMessage())); - } catch (ServerErrorException e) { - 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! Server Error"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("Server Error " + e.getMessage())); - } catch (DownstreamException e) { - 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! Downstream Exception"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); - json = objectMapper.writeValueAsString( - new RestResponseError("Downstream Exception " + e.getMessage())); + deploymentRequestObject.getDeploymentId(), deploymentRequestObject.getTenant(), + new DeploymentRequest(deploymentRequestObject.getServiceTypeId(), + deploymentRequestObject.getInputs()), + request)); + } + } catch (BadRequestException|ServiceAlreadyExistsException|ServerErrorException|DownstreamException e) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, DPLH_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, DPLH_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr + e.getMessage()); + json = objectMapper + .writeValueAsString(new RestResponseError("Error: " + e.getMessage())); } catch (Exception t) { - 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 = objectMapper.writeValueAsString(new RestResponseError("putDeployment failed", t)); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, DPLH_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, DPLH_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + json = + objectMapper.writeValueAsString(new RestResponseError("putDeployment failed", t)); } finally { postLogAudit(request); } return json; } - @RequestMapping(value = { - DEPLOYMENTS_PATH + "/{deploymentId:.+}" }, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String deleteDeployment(@PathVariable("deploymentId") String deploymentId, HttpServletRequest request, - @RequestParam("tenant") String tenant, HttpServletResponse response) throws Exception { + @DeleteMapping( + value = {DEPLOYMENTS_PATH + "/{deploymentId:.+}"}, + produces = "application/json") + public String deleteDeployment(@PathVariable("deploymentId") String deploymentId, + HttpServletRequest request, @RequestParam("tenant") String tenant, + HttpServletResponse response) throws Exception { preLogAudit(request); String json = null; StringBuffer status = new StringBuffer(); + final String errStr = "Deleting deployment " + deploymentId + " failed!"; + final String errLogStr = "deleteDeployment caught exception"; try { deploymentHandlerClient.deleteDeployment(deploymentId, tenant, request); String self = request.getRequestURL().toString().split("\\?")[0]; status.append(self).append("/executions?tenant=").append(tenant); DeploymentResource deplRsrc = new DeploymentResource(deploymentId, - new DeploymentResourceLinks(self, "", status.toString())); + new DeploymentResourceLinks(self, "", status.toString())); JSONObject statObj = new JSONObject(deplRsrc); json = statObj.toString(); - } catch (BadRequestException e) { - 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 = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (ServerErrorException e) { - 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 = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (DownstreamException e) { - 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 = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (DeploymentNotFoundException e) { - 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"); + } catch (BadRequestException|ServerErrorException|DownstreamException|DeploymentNotFoundException e) { + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, DPLH_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, DPLH_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); } catch (Exception t) { - 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 = objectMapper.writeValueAsString(new RestResponseError("deleteDeployment failed", t)); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, DPLH_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, DPLH_TARGET_SERVICE); + MDC.put(ERROR_CODE_KEY, ERROR_CODE); + MDC.put(ERROR_CATEGORY_KEY, ERROR_CATEGORY); + MDC.put(ERROR_DESCRIPTION_KEY, errStr); + logger.error(EELFLoggerDelegate.errorLogger, errLogStr); + json = objectMapper + .writeValueAsString(new RestResponseError("deleteDeployment failed", t)); } finally { postLogAudit(request); } @@ -203,7 +167,7 @@ public class DeploymentHandlerController extends DashboardRestrictedBaseControll } public void preLogAudit(HttpServletRequest request) { - begin = new Date(); + Date begin = new Date(); MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); MDC.put(SystemProperties.STATUS_CODE, "COMPLETE"); @@ -211,14 +175,15 @@ public class DeploymentHandlerController extends DashboardRestrictedBaseControll } public void postLogAudit(HttpServletRequest request) { - end = new Date(); + Date end = new Date(); MDC.put("AlertSeverity", "0"); - MDC.put("TargetEntity", "Deployment Handler"); - MDC.put("TargetServiceName", "Deployment Handler"); + MDC.put(SystemProperties.STATUS_CODE, ERROR_RESPONSE); + MDC.put(TARGET_ENTITY_KEY, DPLH_DEP_ENTITY); + MDC.put(TARGET_SERVICE_KEY, DPLH_TARGET_SERVICE); 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()))); 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/ECDSingleSignOnController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnController.java index ad671ad..aed6810 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 @@ -2,44 +2,24 @@ * =============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; - -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property + * 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 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ================================================================================ - */ + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.ccsdk.dashboard.controller; import java.net.URLDecoder; import java.net.URLEncoder; @@ -90,7 +70,8 @@ import org.springframework.web.util.WebUtils; */ public class ECDSingleSignOnController extends UnRestrictedBaseController { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ECDSingleSignOnController.class); + private EELFLoggerDelegate logger = + EELFLoggerDelegate.getLogger(ECDSingleSignOnController.class); @Autowired private LoginService loginService; @@ -103,25 +84,26 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { @Autowired private DataAccessService dataAccessService; - - private String viewName; + + //private String viewName; private String welcomeView; - @RequestMapping(value = { "signup.htm" }, method = RequestMethod.GET) + @RequestMapping(value = {"signup.htm"}, method = RequestMethod.GET) public ModelAndView externalLogin() { Map<String, Object> model = new HashMap<>(); return new ModelAndView("signup", "model", model); } - + /** - * User sign up handler + * User sign up handler. * * @param request * @return - * @throws Exception + * @throws Exception */ - @RequestMapping(value = { "/signup" }, method = RequestMethod.POST) - public ModelAndView userSignup(HttpServletRequest request, HttpServletResponse response) throws Exception { + @RequestMapping(value = {"/signup"}, method = RequestMethod.POST) + public ModelAndView userSignup(HttpServletRequest request, HttpServletResponse response) + throws Exception { LoginBean commandBean = new LoginBean(); String loginId = request.getParameter("loginId"); String password = request.getParameter("password"); @@ -130,15 +112,16 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { Map<String, String> model = new HashMap<>(); model.put("error", loginErrorMessage); return new ModelAndView("signup", "model", model); - } + } commandBean.setLoginId(loginId); commandBean.setLoginPwd(password); commandBean.setUserid(loginId); commandBean = loginService.findUser(commandBean, - (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), new HashMap()); + (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), + new HashMap()); if (commandBean.getUser() == null) { - // add new user + // add new user User user = new User(); user.setLoginId(loginId); user.setLoginPwd(password); @@ -155,41 +138,47 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { user.setPseudoRoles(new TreeSet<Role>()); try { dataAccessService.saveDomainObject(user, additionalParams); - role = (Role) dataAccessService.getDomainObject(Role.class, - Long.valueOf(SystemProperties.getProperty(SystemProperties.POST_DEFAULT_ROLE_ID)), + role = + (Role) dataAccessService.getDomainObject(Role.class, + Long.valueOf( + SystemProperties.getProperty(SystemProperties.POST_DEFAULT_ROLE_ID)), null); - if(role.getId() == null){ - logger.error(EELFLoggerDelegate.errorLogger, - "process failed: No Role Exsists in DB with requested RoleId :"+ Long.valueOf(SystemProperties.getProperty(SystemProperties.POST_DEFAULT_ROLE_ID))); - throw new Exception("user cannot be added"); + if (role.getId() == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "process failed: No Role Exsists in DB with requested RoleId :" + + Long.valueOf(SystemProperties + .getProperty(SystemProperties.POST_DEFAULT_ROLE_ID))); + throw new Exception("user cannot be added"); } user.addRole(role); - //saveUserExtension(user); dataAccessService.saveDomainObject(user, additionalParams); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "saveDomainObject failed on user " + user.getLoginId(), e); - String loginErrorMessage = (e.getMessage() != null) ? e.getMessage() - : "login.error.external.invalid - saveDomainObject failed on user " + user.getLoginId(); - Map<String, String> model = new HashMap<>(); - model.put("error", loginErrorMessage); - return new ModelAndView("signup", "model", model); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "saveDomainObject failed on user " + user.getLoginId(), e); + String loginErrorMessage = (e.getMessage() != null) ? e.getMessage() + : "login.error.external.invalid - saveDomainObject failed on user " + + user.getLoginId(); + Map<String, String> model = new HashMap<>(); + model.put("error", loginErrorMessage); + return new ModelAndView("signup", "model", model); } } Map<String, Object> model = new HashMap<>(); return new ModelAndView("login_external", "model", model); } - + /** * Handles requests directed to the single sign-on page by the session timeout * interceptor. * - * @param request HttpServletRequest + * @param request HttpServletRequest * @param response HttpServletResponse * @return Redirect to an appropriate address * @throws Exception On any failure */ - @RequestMapping(value = { "/single_signon.htm" }, method = RequestMethod.GET) - public ModelAndView singleSignOnLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + @RequestMapping(value = {"/single_signon.htm"}, method = RequestMethod.GET) + public ModelAndView singleSignOnLogin(HttpServletRequest request, HttpServletResponse response) + throws Exception { Map<String, String> model = new HashMap<String, String>(); HashMap<String, String> additionalParamsMap = new HashMap<String, String>(); @@ -205,45 +194,52 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { User user = UserUtils.getUserSession(request); if (session == null || user == null) { - final String authMech = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM); + final String authMech = + SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM); String userId = loginStrategy.getUserId(request); commandBean.setUserid(userId); commandBean = getLoginService().findUser(commandBean, - (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), - additionalParamsMap); + (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), + additionalParamsMap); if (commandBean.getUser() == null) { String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) - ? commandBean.getLoginErrorMessage() - : SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_NOT_FOUND; - model.put(LoginStrategy.ERROR_MESSAGE_KEY, SystemProperties.getProperty(loginErrorMessage)); - final String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL) + ? commandBean.getLoginErrorMessage() + : SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_NOT_FOUND; + model.put(LoginStrategy.ERROR_MESSAGE_KEY, + SystemProperties.getProperty(loginErrorMessage)); + final String redirectUrl = + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL) + "?noUserError=Yes"; - logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: user is null, redirect URL is {}", - redirectUrl); + logger.debug(EELFLoggerDelegate.debugLogger, + "singleSignOnLogin: user is null, redirect URL is {}", redirectUrl); return new ModelAndView("redirect:" + redirectUrl); } else { // store the user's information in the session String loginMethod; if (null == authMech || "".equals(authMech) || "BOTH".equals(authMech)) { - loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_CSP); + loginMethod = + SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_CSP); } else if ("CSP".equals(authMech)) { - loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_CSP); + loginMethod = + SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_CSP); } else { - loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_WEB_JUNCTION); + loginMethod = SystemProperties + .getProperty(SystemProperties.LOGIN_METHOD_WEB_JUNCTION); } UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), - commandBean.getBusinessDirectMenu(), loginMethod, roleService.getRoleFunctions(userId)); + commandBean.getBusinessDirectMenu(), loginMethod, + roleService.getRoleFunctions(userId)); initateSessionMgtHandler(request); logger.debug(EELFLoggerDelegate.debugLogger, - "singleSignOnLogin: create new user session for expired user {}; user {} exists in the system", - userId, commandBean.getUser().getOrgUserId()); + "singleSignOnLogin: create new user session for expired user {}; user {} exists in the system", + userId, commandBean.getUser().getOrgUserId()); return new ModelAndView("redirect:" + forwardURL); } } // user is null or session is null else { // both user and session are non-null. - logger.info(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: redirecting to the forwardURL {}", - forwardURL); + logger.info(EELFLoggerDelegate.debugLogger, + "singleSignOnLogin: redirecting to the forwardURL {}", forwardURL); return new ModelAndView("redirect:" + forwardURL); } } else { @@ -267,7 +263,8 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { String appUrl = SystemProperties.getProperty(SystemProperties.APP_BASE_URL); returnToAppUrl = appUrl + (appUrl.endsWith("/") ? "" : "/") + forwardURL; logger.debug(EELFLoggerDelegate.debugLogger, - "singleSignOnLogin: using app base URL {} and redirectURL {}", appUrl, returnToAppUrl); + "singleSignOnLogin: using app base URL {} and redirectURL {}", appUrl, + returnToAppUrl); } else { /** * Be backward compatible with applications that don't need this feature. This @@ -275,20 +272,22 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { * always find the specified token. */ returnToAppUrl = ((HttpServletRequest) request).getRequestURL().toString() - .replace("single_signon.htm", forwardURL); - logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: computed redirectURL {}", - returnToAppUrl); + .replace("single_signon.htm", forwardURL); + logger.debug(EELFLoggerDelegate.debugLogger, + "singleSignOnLogin: computed redirectURL {}", returnToAppUrl); } final String encodedReturnToAppUrl = URLEncoder.encode(returnToAppUrl, "UTF-8"); // Also send the application's UEB key so Portal can block URL // reflection attacks. - final String uebAppKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); - final String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); + final String uebAppKey = + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); + final String url = + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); final String portalUrl = url.substring(0, url.lastIndexOf('/')) + "/process_csp"; - final String redirectUrl = portalUrl + "?uebAppKey=" + uebAppKey + "&redirectUrl=" - + encodedReturnToAppUrl; - logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: portal-bound redirect URL is {}", - redirectUrl); + final String redirectUrl = + portalUrl + "?uebAppKey=" + uebAppKey + "&redirectUrl=" + encodedReturnToAppUrl; + logger.debug(EELFLoggerDelegate.debugLogger, + "singleSignOnLogin: portal-bound redirect URL is {}", redirectUrl); return new ModelAndView("redirect:" + redirectUrl); } // portal is available @@ -303,7 +302,7 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { } } - @RequestMapping(value = { "logout.htm" }, method = RequestMethod.GET) + @RequestMapping(value = {"logout.htm"}, method = RequestMethod.GET) public ModelAndView appLogout(HttpServletRequest request) { try { request.getSession().invalidate(); @@ -320,7 +319,8 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { * @return True if the portal answers, otherwise false. */ private boolean isPortalAvailable() { - HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(); + HttpComponentsClientHttpRequestFactory httpRequestFactory = + new HttpComponentsClientHttpRequestFactory(); final int oneSecond = 1000; httpRequestFactory.setConnectionRequestTimeout(oneSecond); httpRequestFactory.setConnectTimeout(oneSecond); @@ -328,7 +328,8 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { RestTemplate restTemplate = new RestTemplate(httpRequestFactory); boolean avail = true; try { - final String portalUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); + final String portalUrl = + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); String s = restTemplate.getForObject(portalUrl, String.class); logger.trace("isPortalAvailable got response {}", s); } catch (RestClientException ex) { @@ -344,7 +345,8 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { protected void initateSessionMgtHandler(HttpServletRequest request) { String portalJSessionId = getPortalJSessionId(request); String jSessionId = getJessionId(request); - PortalTimeoutHandler.sessionCreated(portalJSessionId, jSessionId, AppUtils.getSession(request)); + PortalTimeoutHandler.sessionCreated(portalJSessionId, jSessionId, + AppUtils.getSession(request)); } public boolean isLoginCookieExist(HttpServletRequest request) { 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 f8fd19e..653930d 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ package org.onap.ccsdk.dashboard.controller; @@ -25,7 +24,6 @@ package org.onap.ccsdk.dashboard.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.http.HttpStatus; import org.onap.ccsdk.dashboard.model.HealthStatus; import org.onap.ccsdk.dashboard.rest.CloudifyClient; import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; @@ -33,8 +31,6 @@ import org.onap.ccsdk.dashboard.rest.InventoryClient; import org.onap.portalsdk.core.controller.FusionBaseController; import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @@ -51,25 +47,23 @@ public class HealthCheckController extends FusionBaseController { @Autowired InventoryClient inventoryClient; - + @Autowired DeploymentHandlerClient deploymentHandlerClient; - + @Autowired CloudifyClient cfyClient; - + /** - * Application name + * Application name. */ protected static final String APP_NAME = "ecd-app"; private static final String APP_HEALTH_CHECK_PATH = "/health"; - private static final String APP_SRVC_HEALTH_CHECK_PATH = "/health-info"; - protected final ObjectMapper objectMapper = new ObjectMapper(); /** - * application health by simply responding with a JSON object indicating status + * application health by simply responding with a JSON object indicating status. * * @param request HttpServletRequest * @return HealthStatus object always 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 3877dfc..737eb2c 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 @@ -22,7 +22,6 @@ package org.onap.ccsdk.dashboard.controller; -import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; @@ -71,7 +70,10 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -99,12 +101,11 @@ public class InventoryController extends DashboardRestrictedBaseController { CloudifyClient cloudifyClient; @Autowired ConsulClient consulClient; - + /** - * For caching data + * For caching data */ private AbstractCacheManager cacheManager; - @Autowired public void setCacheManager(AbstractCacheManager cacheManager) { @@ -114,7 +115,7 @@ public class InventoryController extends DashboardRestrictedBaseController { public AbstractCacheManager getCacheManager() { return cacheManager; } - + /** * Enum for selecting an item type. */ @@ -122,7 +123,6 @@ public class InventoryController extends DashboardRestrictedBaseController { SERVICE_TYPES, SERVICE_TYPE_NAME, OWNER, SERVICE_TYPE_ID; } - private static Date begin, end; private static final String OWNERS = "owners"; private static final String SERVICE_TYPES_PATH = "dcae-service-types"; private static final String SERVICE_TYPE_NAME = "service-type-list"; @@ -145,17 +145,17 @@ public class InventoryController extends DashboardRestrictedBaseController { 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> compDeployTab = (HashMap<String, Boolean>) session.getAttribute("comp_access"); String roleLevel = (String) session.getAttribute("role_level"); String roleAuth = (String) session.getAttribute("auth_role"); String user = UserUtils.getUserSession(request).getLoginId(); - + if (roleLevel == null) { roleLevel = "dev"; } - if (comp_deploy_tab == null) { - comp_deploy_tab = new HashMap<String, Boolean>(); + if (compDeployTab == null) { + compDeployTab = new HashMap<String, Boolean>(); } if (roleAuth == null) { roleAuth = "READ"; @@ -170,8 +170,8 @@ public class InventoryController extends DashboardRestrictedBaseController { int totalItems = 0; lock.readLock().lock(); - List<ServiceTypeSummary> bpList = - (List<ServiceTypeSummary>)getCacheManager().getObject(SERVICE_TYPES_PATH); + List<ServiceTypeSummary> bpList = + (List<ServiceTypeSummary>) getCacheManager().getObject(SERVICE_TYPES_PATH); lock.readLock().unlock(); if (bpList == null) { bpList = inventoryClient.getServiceTypes().collect(Collectors.toList()); @@ -184,57 +184,59 @@ public class InventoryController extends DashboardRestrictedBaseController { String containsFilterStr = ""; // apply user search filters if (searchBy != null && !searchBy.isEmpty()) { - // parse the search filters string - // look for service name patterns - List<String> searchFilters = - new ArrayList<String>(Arrays.asList(searchBy.split(";"))); - if (searchFilters.stream().anyMatch(s->s.startsWith("contains"))) { - List<String> containsList = searchFilters.stream().filter(s->s.startsWith("contains")). - collect(Collectors.toList()); + // parse the search filters string + // look for service name patterns + List<String> searchFilters = new ArrayList<String>(Arrays.asList(searchBy.split(";"))); + if (searchFilters.stream().anyMatch(s -> s.startsWith("contains"))) { + List<String> containsList = searchFilters.stream() + .filter(s -> s.startsWith("contains")).collect(Collectors.toList()); containsFilterStr = containsList.get(0).split(":")[1]; } - if (searchFilters.stream().anyMatch(s->s.startsWith("serviceRef"))) { - List<String> svcRefsList = searchFilters.stream().filter(s->s.startsWith("serviceRef")). - collect(Collectors.toList()); + if (searchFilters.stream().anyMatch(s -> s.startsWith("serviceRef"))) { + List<String> svcRefsList = searchFilters.stream() + .filter(s -> s.startsWith("serviceRef")).collect(Collectors.toList()); svcRefFilterStr = svcRefsList.get(0).split(":")[1]; } - if (searchFilters.stream().anyMatch(s->s.startsWith("app"))) { - List<String> appsList = searchFilters.stream().filter(s->s.startsWith("app")). - collect(Collectors.toList()); + if (searchFilters.stream().anyMatch(s -> s.startsWith("app"))) { + List<String> appsList = searchFilters.stream().filter(s -> s.startsWith("app")) + .collect(Collectors.toList()); appFilterStr = appsList.get(0).split(":")[1]; } - if (searchFilters.stream().anyMatch(s->s.startsWith("comp"))) { - List<String> compList = searchFilters.stream().filter(s->s.startsWith("comp")). - collect(Collectors.toList()); + if (searchFilters.stream().anyMatch(s -> s.startsWith("comp"))) { + List<String> compList = searchFilters.stream().filter(s -> s.startsWith("comp")) + .collect(Collectors.toList()); compFilterStr = compList.get(0).split(":")[1]; } - if (searchFilters.stream().anyMatch(s->s.startsWith("owner"))) { - List<String> ownerList = searchFilters.stream().filter(s->s.startsWith("owner")). - collect(Collectors.toList()); + if (searchFilters.stream().anyMatch(s -> s.startsWith("owner"))) { + List<String> ownerList = searchFilters.stream().filter(s -> s.startsWith("owner")) + .collect(Collectors.toList()); ownerFilterStr = ownerList.get(0).split(":")[1]; } if (!ownerFilterStr.isEmpty()) { List<ServiceTypeSummary> ownerBpList = new ArrayList<ServiceTypeSummary>(); - lock.readLock().lock(); + lock.readLock().lock(); Map<String, List<ServiceTypeSummary>> bpPerOwner = - (Map<String, List<ServiceTypeSummary>>) getCacheManager().getObject("owner_bp_map"); + (Map<String, List<ServiceTypeSummary>>) getCacheManager() + .getObject("owner_bp_map"); lock.readLock().unlock(); - List<String> ownerFilterList = - new ArrayList<String>(Arrays.asList(ownerFilterStr.split(","))); - + List<String> ownerFilterList = + new ArrayList<String>(Arrays.asList(ownerFilterStr.split(","))); + if (ownerFilterList.size() == 1 && ownerFilterList.get(0).equals("undefined")) { ownerFilterList.clear(); ownerFilterList.add(user); } - + if (bpPerOwner != null) { - Stream<Map.Entry<String, List<ServiceTypeSummary>>> bpOwnerEntriesStream = - bpPerOwner.entrySet().stream(); + Stream<Map.Entry<String, List<ServiceTypeSummary>>> bpOwnerEntriesStream = + bpPerOwner.entrySet().stream(); - Set<Map.Entry<String, List<ServiceTypeSummary>>> bpOwnerSet = - bpOwnerEntriesStream.filter(m -> ownerFilterList.stream(). - anyMatch(ownFilter -> m.getKey().equalsIgnoreCase(ownFilter))).collect(Collectors.toSet()); + Set<Map.Entry<String, List<ServiceTypeSummary>>> bpOwnerSet = + bpOwnerEntriesStream + .filter(m -> ownerFilterList.stream() + .anyMatch(ownFilter -> m.getKey().equalsIgnoreCase(ownFilter))) + .collect(Collectors.toSet()); bpOwnerSet.stream().forEach(e -> ownerBpList.addAll(e.getValue())); bpItemList = ownerBpList; } @@ -252,32 +254,33 @@ public class InventoryController extends DashboardRestrictedBaseController { if (roleLevel.equals("app")) { @SuppressWarnings("unchecked") List<String> myApps = new ArrayList(userApps); - bpItemList = (List<ServiceTypeSummary>)bpItemList.stream().filter(s -> myApps.stream() - .anyMatch(appFilter -> (((ServiceTypeSummary)s).getComponent() != null && - ((ServiceTypeSummary)s).getComponent().equalsIgnoreCase(appFilter)))) - .collect(Collectors.<ServiceTypeSummary>toList()); + bpItemList = (List<ServiceTypeSummary>) bpItemList.stream() + .filter(s -> myApps.stream() + .anyMatch(appFilter -> (((ServiceTypeSummary) s).getComponent() != null + && ((ServiceTypeSummary) s).getComponent().equalsIgnoreCase(appFilter)))) + .collect(Collectors.<ServiceTypeSummary>toList()); } else if (roleLevel.equals("app_dev")) { Predicate<ServiceTypeSummary> appFilter = - p -> p.getComponent() != null && !p.getComponent().equalsIgnoreCase("dcae") + p -> p.getComponent() != null && !p.getComponent().equalsIgnoreCase("dcae") && !p.getComponent().equalsIgnoreCase("d2a"); - bpItemList = (List<ServiceTypeSummary>)bpItemList.stream().filter(appFilter). - collect(Collectors.toList()); - } - + bpItemList = (List<ServiceTypeSummary>) bpItemList.stream().filter(appFilter) + .collect(Collectors.toList()); + } + switch (option) { case OWNER: - Set<String> ownersList = - (Set) bpItemList.stream().map(x -> ((ServiceTypeSummary)x).getOwner()).collect(Collectors.toSet()); + Set<String> ownersList = (Set) bpItemList.stream() + .map(x -> ((ServiceTypeSummary) x).getOwner()).collect(Collectors.toSet()); return objectMapper.writeValueAsString(ownersList); case SERVICE_TYPE_ID: itemList = bpItemList; totalItems = itemList.size(); RestResponsePage<List> model = new RestResponsePage<>(totalItems, 1, itemList); String outboundJson = objectMapper.writeValueAsString(model); - return outboundJson; - case SERVICE_TYPE_NAME: - Set<String> svcTypeList = - (Set) bpItemList.stream().map(x -> ((ServiceTypeSummary)x).getTypeName()).collect(Collectors.toSet()); + return outboundJson; + case SERVICE_TYPE_NAME: + Set<String> svcTypeList = (Set) bpItemList.stream() + .map(x -> ((ServiceTypeSummary) x).getTypeName()).collect(Collectors.toSet()); itemList = new ArrayList<String>(); itemList.addAll(svcTypeList); break; @@ -286,73 +289,84 @@ public class InventoryController extends DashboardRestrictedBaseController { itemList = bpItemList; String outFilter = request.getParameter("_include"); if (outFilter != null) { - List<String> svcSummaryList = - (List) itemList.stream().map(x -> extractBpSummary((ServiceTypeSummary)x)).collect(Collectors.toList()); + List<String> svcSummaryList = + (List) itemList.stream().map(x -> extractBpSummary((ServiceTypeSummary) x)) + .collect(Collectors.toList()); return objectMapper.writeValueAsString(svcSummaryList); } // apply user search filters if (searchBy != null && !searchBy.isEmpty()) { if (!svcRefFilterStr.isEmpty()) { - List<String> svcFilterList = - new ArrayList<String>(Arrays.asList(svcRefFilterStr.split(","))); + List<String> svcFilterList = + new ArrayList<>(Arrays.asList(svcRefFilterStr.split(","))); if (!svcFilterList.isEmpty()) { - itemList = (List) itemList.stream().filter(s -> svcFilterList.stream() - .anyMatch(svcFilter -> ((ServiceTypeSummary) s).getTypeName().toLowerCase().contains(svcFilter.toLowerCase()))) + itemList = (List) itemList.stream() + .filter(s -> svcFilterList.stream() + .anyMatch(svcFilter -> ((ServiceTypeSummary) s).getTypeName() + .toLowerCase().contains(svcFilter.toLowerCase()))) .collect(Collectors.toList()); } - } + } if (!appFilterStr.isEmpty()) { - List<String> appFilterList = - new ArrayList<String>(Arrays.asList(appFilterStr.split(","))); + List<String> appFilterList = + new ArrayList<>(Arrays.asList(appFilterStr.split(","))); Predicate<ServiceTypeSummary> srvcAppFilter = p -> p.getApplication() != null; - Stream<ServiceTypeSummary> svcStream = itemList.stream(); + Stream<ServiceTypeSummary> svcStream = itemList.stream(); - itemList = svcStream.filter( srvcAppFilter.and( - s -> appFilterList.stream() - .anyMatch(appFilter ->((ServiceTypeSummary) s).getApplication().equalsIgnoreCase(appFilter)))) - .collect(Collectors.toList()); - } + itemList = + svcStream + .filter(srvcAppFilter.and(s -> appFilterList.stream() + .anyMatch(appFilter -> ((ServiceTypeSummary) s).getApplication() + .equalsIgnoreCase(appFilter)))) + .collect(Collectors.toList()); + } if (!compFilterStr.isEmpty()) { - List<String> compFilterList = - new ArrayList<String>(Arrays.asList(compFilterStr.split(","))); + List<String> compFilterList = + new ArrayList<>(Arrays.asList(compFilterStr.split(","))); Predicate<ServiceTypeSummary> srvcCompFilter = p -> p.getComponent() != null; - Stream<ServiceTypeSummary> svcStream = itemList.stream(); - itemList = svcStream.filter( srvcCompFilter.and( - s -> compFilterList.stream() - .anyMatch(compFilter ->((ServiceTypeSummary) s).getComponent().equalsIgnoreCase(compFilter)))) - .collect(Collectors.toList()); + Stream<ServiceTypeSummary> svcStream = itemList.stream(); + itemList = svcStream + .filter(srvcCompFilter.and(s -> compFilterList.stream().anyMatch( + compFilter -> (s).getComponent().equalsIgnoreCase(compFilter)))) + .collect(Collectors.toList()); } if (!containsFilterStr.isEmpty()) { final String simpleSrch = containsFilterStr.split(",")[0]; itemList = (List<ServiceTypeSummary>) itemList.stream() - .filter(s -> ((ServiceTypeSummary) s).contains(simpleSrch)).collect(Collectors.toList()); + .filter(s -> ((ServiceTypeSummary) s).contains(simpleSrch)) + .collect(Collectors.toList()); } - } + } if (sortBy != null) { if (sortBy.equals("owner")) { - ((List<ServiceTypeSummary>)itemList).sort( - (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getOwner().compareTo(o2.getOwner())); + ((List<ServiceTypeSummary>) itemList).sort((ServiceTypeSummary o1, + ServiceTypeSummary o2) -> o1.getOwner().compareTo(o2.getOwner())); } else if (sortBy.equals("typeId")) { - ((List<ServiceTypeSummary>)itemList).sort( - (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getTypeId().get().compareTo(o2.getTypeId().get())); + ((List<ServiceTypeSummary>) itemList) + .sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getTypeId() + .get().compareTo(o2.getTypeId().get())); } else if (sortBy.equals("typeName")) { - ((List<ServiceTypeSummary>)itemList).sort( - (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getTypeName().compareTo(o2.getTypeName())); + ((List<ServiceTypeSummary>) itemList).sort((ServiceTypeSummary o1, + ServiceTypeSummary o2) -> o1.getTypeName().compareTo(o2.getTypeName())); } else if (sortBy.equals("typeVersion")) { - ((List<ServiceTypeSummary>)itemList).sort( - (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getTypeVersion().compareTo(o2.getTypeVersion())); + ((List<ServiceTypeSummary>) itemList) + .sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1 + .getTypeVersion().compareTo(o2.getTypeVersion())); } else if (sortBy.equals("created")) { - ((List<ServiceTypeSummary>)itemList).sort( - (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getCreated().get().compareTo(o2.getCreated().get())); + ((List<ServiceTypeSummary>) itemList) + .sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getCreated() + .get().compareTo(o2.getCreated().get())); } else if (sortBy.equals("application")) { - ((List<ServiceTypeSummary>)itemList).sort( - (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getApplication().compareTo(o2.getApplication())); + ((List<ServiceTypeSummary>) itemList) + .sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1 + .getApplication().compareTo(o2.getApplication())); } else if (sortBy.equals("component")) { - ((List<ServiceTypeSummary>)itemList).sort( - (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getComponent().compareTo(o2.getComponent())); + ((List<ServiceTypeSummary>) itemList) + .sort((ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1 + .getComponent().compareTo(o2.getComponent())); } } break; @@ -373,11 +387,11 @@ public class InventoryController extends DashboardRestrictedBaseController { final int pageCount = (int) Math.ceil((double) totalItems / pageSize); if (totalItems > pageSize && option.equals(InventoryDataItem.SERVICE_TYPES)) { itemList = getPageOfList(pageNum, pageSize, itemList); - } + } if (option.equals(InventoryDataItem.SERVICE_TYPES)) { if (!roleLevel.equals("ops")) { if (roleLevel.equals("dev") || roleLevel.equals("app_dev")) { - boolean deployFlag = roleAuth.equals("WRITE") ? true : false; + boolean deployFlag = roleAuth.equals("WRITE"); for (ServiceTypeSummary bp : (List<ServiceTypeSummary>) itemList) { bp.setCanDeploy(Optional.of(deployFlag)); } @@ -392,8 +406,8 @@ public class InventoryController extends DashboardRestrictedBaseController { bpComp = bp.getOwner().split(":")[0].toLowerCase(); } } - if (comp_deploy_tab.containsKey(bpComp)) { - boolean enableDeploy = comp_deploy_tab.get(bpComp); + if (compDeployTab.containsKey(bpComp)) { + boolean enableDeploy = compDeployTab.get(bpComp); logger.debug(">>>> enable deploy button: " + enableDeploy); bp.setCanDeploy(Optional.of(enableDeploy)); } else { @@ -408,49 +422,53 @@ public class InventoryController extends DashboardRestrictedBaseController { } // add the deployments mapping to the list lock.readLock().lock(); - List<ServiceTypeServiceMap> cache_bp_map_arr = + List<ServiceTypeServiceMap> cacheBpMapArr = (List<ServiceTypeServiceMap>) getCacheManager().getObject("bp_deploy_map"); lock.readLock().unlock(); - if (cache_bp_map_arr != null) { - for (ServiceTypeSummary bpSum: (List<ServiceTypeSummary>)itemList) { + if (cacheBpMapArr != null) { + for (ServiceTypeSummary bpSum : (List<ServiceTypeSummary>) itemList) { // correlate the cached data for deployments - List<ServiceTypeServiceMap> bp_depl_list = - cache_bp_map_arr.stream().filter( - (Predicate<? super ServiceTypeServiceMap>) - s->s.getServiceTypeId().equals(bpSum.getTypeId().get())). - collect(Collectors.toList()); - if (bp_depl_list != null && !bp_depl_list.isEmpty()) { - bpSum.setDeployments((ServiceRefCfyList)bp_depl_list.get(0).getServiceRefList()); - } + List<ServiceTypeServiceMap> bp_depl_list = cacheBpMapArr + .stream().filter((Predicate<? super ServiceTypeServiceMap>) s -> s + .getServiceTypeId().equals(bpSum.getTypeId().get())) + .collect(Collectors.toList()); + if (bp_depl_list != null && !bp_depl_list.isEmpty()) { + bpSum.setDeployments( + (ServiceRefCfyList) bp_depl_list.get(0).getServiceRefList()); + } } } } RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); - String outboundJson = objectMapper.writeValueAsString(model); - return outboundJson; + return objectMapper.writeValueAsString(model); } - + + /** + * scheduled method to build and update application cache + * store containing a collection of user to blueprints list mapping. + */ @SuppressWarnings("unchecked") - @Scheduled(fixedDelay=600000, initialDelay=150000) + @Scheduled(fixedDelay = 600000, initialDelay = 150000) public void cacheOwnerToBpMap() { ReadWriteLock lock = new ReentrantReadWriteLock(); lock.readLock().lock(); - List<ServiceTypeSummary> bpList = - (List<ServiceTypeSummary>)getCacheManager().getObject(SERVICE_TYPES_PATH); + List<ServiceTypeSummary> bpList = + (List<ServiceTypeSummary>) getCacheManager().getObject(SERVICE_TYPES_PATH); lock.readLock().unlock(); if (bpList != null) { - Map<String, List<ServiceTypeSummary>> bpPerOwner = bpList.stream() - .collect(Collectors.groupingBy(bp -> bp.getOwner())); - + Map<String, List<ServiceTypeSummary>> bpPerOwner = + bpList.stream().collect(Collectors.groupingBy(bp -> bp.getOwner())); + lock.writeLock().lock(); getCacheManager().putObject("owner_bp_map", bpPerOwner); lock.writeLock().unlock(); } } - + private BlueprintResponse extractBpSummary(ServiceTypeSummary bp) { return new BlueprintResponse(bp.getTypeName(), bp.getTypeVersion(), bp.getTypeId().get()); } + /** * Gets one page of the specified items. This method traps exceptions and * constructs an appropriate JSON block to report errors. @@ -478,11 +496,12 @@ public class InventoryController extends DashboardRestrictedBaseController { logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception"); RestResponseError result = null; - if (ex instanceof HttpStatusCodeException) + if (ex instanceof HttpStatusCodeException) { result = new RestResponseError(((HttpStatusCodeException) ex).getResponseBodyAsString()); - else + } else { result = new RestResponseError("Failed to get " + option.name(), ex); + } try { outboundJson = objectMapper.writeValueAsString(result); } catch (JsonProcessingException jpe) { @@ -501,11 +520,7 @@ public class InventoryController extends DashboardRestrictedBaseController { * @param request HttpServletRequest * @return List of ServiceTypes objects */ - @RequestMapping( - value = {OWNERS}, - method = RequestMethod.GET, - produces = "application/json") - @ResponseBody + @GetMapping(value = {OWNERS}, produces = "application/json") public String getOwnersByPage(HttpServletRequest request) { preLogAudit(request); String json = getItemListForPageWrapper(request, InventoryDataItem.OWNER, @@ -513,9 +528,9 @@ public class InventoryController extends DashboardRestrictedBaseController { postLogAudit(request); return json; } - + /** - * Serves one page of service types + * Serves one page of service types. * * @param request HttpServletRequest * @return List of ServiceTypes objects @@ -534,13 +549,10 @@ public class InventoryController extends DashboardRestrictedBaseController { } /** - * Query Service objects matching a service type ID + * Query Service objects matching a service type ID. * */ - @RequestMapping( - value = {DEP_IDS_FOR_TYPE}, - method = RequestMethod.POST, - produces = "application/json") + @PostMapping(value = {DEP_IDS_FOR_TYPE}, produces = "application/json") public String getServicesForType(HttpServletRequest request, @RequestBody String[] typeList) throws Exception { preLogAudit(request); @@ -554,50 +566,40 @@ public class InventoryController extends DashboardRestrictedBaseController { return objectMapper.writeValueAsString(result); } - /** - * Serves the complete list of service type names + * Serves the complete list of service type names. * * @param request HttpServletRequest * * @return list of service type names */ - @RequestMapping( - value = {SERVICE_TYPE_NAME}, - method = RequestMethod.GET, - produces = "application/json") + @GetMapping(value = {SERVICE_TYPE_NAME}, produces = "application/json") @ResponseBody @Cacheable public String getAllServiceTypeNames(HttpServletRequest request) { - // preLogAudit(request); String json = null; json = getItemListForPageWrapper(request, InventoryDataItem.SERVICE_TYPE_NAME, request.getParameter("sortBy"), request.getParameter("searchBy")); postLogAudit(request); return json; - } - + } + /** - * Serves the aggregate count of service types + * Serves the aggregate count of service types. * * @param request HttpServletRequest * * @return count of service types */ - @RequestMapping( - value = {SERVICE_TYPE_ID}, - method = RequestMethod.GET, - produces = "application/json") - @ResponseBody - @Cacheable + @GetMapping(value = {SERVICE_TYPE_ID}, produces = "application/json") public String getAllServiceTypeIds(HttpServletRequest request) { String json = null; json = getItemListForPageWrapper(request, InventoryDataItem.SERVICE_TYPE_ID, request.getParameter("sortBy"), request.getParameter("searchBy")); postLogAudit(request); return json; - } - + } + /** * Gets the specified blueprint content for viewing. * @@ -607,11 +609,9 @@ public class InventoryController extends DashboardRestrictedBaseController { * @throws Exception on serialization error * */ - @RequestMapping( + @GetMapping( 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 { preLogAudit(request); @@ -655,33 +655,29 @@ public class InventoryController extends DashboardRestrictedBaseController { * @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") - @ResponseBody + @DeleteMapping(value = {SERVICE_TYPES_PATH + "/{typeId:.+}"}, produces = "application/json") public String deleteServiceType(@PathVariable("typeId") String typeId, - HttpServletRequest request, - HttpServletResponse response) throws Exception { + HttpServletRequest request, HttpServletResponse response) throws Exception { preLogAudit(request); String json = "{\"204\": \"Blueprint deleted\"}"; boolean allow = true; try { // check if these dep_ids exist in cloudify - List<CloudifyDeployedTenant> deplForBp = - cloudifyClient.getDeploymentForBlueprint("TID-"+typeId); - if (deplForBp.size() > 0 ) { + List<CloudifyDeployedTenant> deplForBp = + cloudifyClient.getDeploymentForBlueprint("TID-" + typeId); + if (!deplForBp.isEmpty()) { allow = false; - } else { - ServiceQueryParams qryParams = + } else { + ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); - Set<String> dep_ids = srvcRefs.items.stream().map(x -> ((ServiceRef)x).id).collect(Collectors.toSet()); - if (dep_ids.size() > 0) { + Set<String> depIds = srvcRefs.items.stream().map(x -> ((ServiceRef) x).id) + .collect(Collectors.toSet()); + if (!depIds.isEmpty()) { // now check again if these dep_ids still exist in cloudify List<String> allDepNames = cloudifyClient.getDeploymentNamesWithFilter(request); - for (String str: dep_ids) { - if (allDepNames.stream().anyMatch(s->s.equalsIgnoreCase(str))) { + for (String str : depIds) { + if (allDepNames.stream().anyMatch(s -> s.equalsIgnoreCase(str))) { allow = false; break; } @@ -692,13 +688,6 @@ public class InventoryController extends DashboardRestrictedBaseController { response.setStatus(HttpStatus.SC_BAD_REQUEST); json = objectMapper.writeValueAsString( new RestResponseError("Deployments exist for this blueprint")); - /* - PrintWriter out = response.getWriter(); - response.setContentType("application/json"); - response.setCharacterEncoding("UTF-8"); - out.print(json); - out.flush(); - */ return json; } else { inventoryClient.deleteServiceType(typeId); @@ -737,18 +726,14 @@ public class InventoryController extends DashboardRestrictedBaseController { * @return Blueprint as uploaded; or error. * @throws Exception on serialization error */ - @RequestMapping( - value = {SERVICE_TYPES_PATH + "/update"}, - method = RequestMethod.POST, - produces = "application/json") - @ResponseBody + @PostMapping(value = {SERVICE_TYPES_PATH + "/update"}, produces = "application/json") 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()); + Blueprint.parse(serviceType.getBlueprintTemplate()); inventoryClient.addServiceType(serviceType); } catch (BlueprintParseException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -797,11 +782,7 @@ public class InventoryController extends DashboardRestrictedBaseController { * @return Blueprint as uploaded; or error. * @throws Exception on serialization error */ - @RequestMapping( - value = {SERVICE_TYPES_PATH + "/upload"}, - method = RequestMethod.POST, - produces = "application/json") - @ResponseBody + @PostMapping(value = {SERVICE_TYPES_PATH + "/upload"}, produces = "application/json") public String uploadServiceTypeBlueprint(HttpServletRequest request, @RequestBody ServiceTypeRequest serviceTypeRequest) throws Exception { preLogAudit(request); @@ -850,21 +831,19 @@ public class InventoryController extends DashboardRestrictedBaseController { } public void preLogAudit(HttpServletRequest request) { - begin = new Date(); + Date begin = new Date(); 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) { - end = new Date(); + Date end = new Date(); MDC.put("AlertSeverity", "0"); MDC.put("TargetEntity", "DCAE Inventory"); MDC.put("TargetServiceName", "DCAE Inventory"); 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()))); 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/exceptions/BadRequestException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/BadRequestException.java index f06c3a1..4c706ac 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/BadRequestException.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/BadRequestException.java @@ -17,16 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ package org.onap.ccsdk.dashboard.exceptions; public class BadRequestException extends Exception { - /** - * - */ + private static final long serialVersionUID = -8654510668910559419L; public BadRequestException(String message) { diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DashboardControllerException.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DashboardControllerException.java index de89257..be0e5c3 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DashboardControllerException.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/exceptions/DashboardControllerException.java @@ -17,8 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ + package org.onap.ccsdk.dashboard.exceptions; /** diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponsePage.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponsePage.java index 39a04ed..c473d58 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponsePage.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponsePage.java @@ -17,8 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model; /** diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponseSuccess.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponseSuccess.java index 4db65f1..5854433 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponseSuccess.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/RestResponseSuccess.java @@ -17,8 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model; /** diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyBlueprint.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyBlueprint.java index bdb920d..1874556 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyBlueprint.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyBlueprint.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.Map; @@ -34,30 +34,31 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ public final class CloudifyBlueprint extends ECTransportModel { - /** A unique identifier for the blueprint. */ - public final String id; - /** The blueprint’s main file name. */ - public final String main_file_name; - /** The blueprint’s description. */ - public final String description; - /** The time the blueprint was uploaded to the manager. */ - public final String created_at; - /** The last time the blueprint was updated. */ - public final String updated_at; - /** The parsed result of the blueprint. */ - public final Map<String, Object> plan; - - @JsonCreator - public CloudifyBlueprint(@JsonProperty("main_file_name") String main_file_name, - @JsonProperty("description") String description, @JsonProperty("created_at") String created_at, - @JsonProperty("updated_at") String updated_at, @JsonProperty("id") String id, - @JsonProperty("plan") Map<String, Object> plan) { - this.main_file_name = main_file_name; - this.description = description; - this.created_at = created_at; - this.updated_at = updated_at; - this.id = id; - this.plan = plan; - } + /** A unique identifier for the blueprint. */ + public final String id; + /** The blueprint’s main file name. */ + public final String main_file_name; + /** The blueprint’s description. */ + public final String description; + /** The time the blueprint was uploaded to the manager. */ + public final String created_at; + /** The last time the blueprint was updated. */ + public final String updated_at; + /** The parsed result of the blueprint. */ + public final Map<String, Object> plan; + + @JsonCreator + public CloudifyBlueprint(@JsonProperty("main_file_name") String main_file_name, + @JsonProperty("description") String description, + @JsonProperty("created_at") String created_at, + @JsonProperty("updated_at") String updated_at, @JsonProperty("id") String id, + @JsonProperty("plan") Map<String, Object> plan) { + this.main_file_name = main_file_name; + this.description = description; + this.created_at = created_at; + this.updated_at = updated_at; + this.id = id; + this.plan = plan; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyBlueprintList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyBlueprintList.java index faee797..33d7142 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyBlueprintList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyBlueprintList.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; @@ -29,36 +29,38 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyBlueprintList extends ECTransportModel { - - public final List<CloudifyBlueprint> items; - public final Metadata metadata; + + public final List<CloudifyBlueprint> items; + public final Metadata metadata; @JsonCreator - public CloudifyBlueprintList(@JsonProperty("items") List<CloudifyBlueprint> items, @JsonProperty("metadata") Metadata metadata){ - this.items = items; - this.metadata = metadata; - } - - public static final class Metadata { - public final Pagination pagination; + public CloudifyBlueprintList(@JsonProperty("items") List<CloudifyBlueprint> items, + @JsonProperty("metadata") Metadata metadata) { + this.items = items; + this.metadata = metadata; + } + + public static final class Metadata { + public final Pagination pagination; @JsonCreator - public Metadata(@JsonProperty("pagination") Pagination pagination){ + public Metadata(@JsonProperty("pagination") Pagination pagination) { this.pagination = pagination; } - - public static final class Pagination { - public final long total; - public final long offset; - public final long size; + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; @JsonCreator - public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ - this.total = total; - this.offset = offset; - this.size = size; - } - } - } - + public Pagination(@JsonProperty("total") long total, + @JsonProperty("offset") long offset, @JsonProperty("size") long size) { + this.total = total; + this.offset = offset; + this.size = size; + } + } + } + } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployedTenant.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployedTenant.java index a895dd0..a5052bc 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployedTenant.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployedTenant.java @@ -2,25 +2,24 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model.cloudify; +package org.onap.ccsdk.dashboard.model.cloudify; import org.onap.ccsdk.dashboard.model.ECTransportModel; @@ -28,26 +27,28 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyDeployedTenant extends ECTransportModel { - - /** A unique identifier for the deployment. */ - public final String id; - /** tenant where the deployment was done */ - public final String tenant_name; - public final String created_at; + + /** A unique identifier for the deployment. */ + public final String id; + /** tenant where the deployment was done */ + public final String tenant_name; + public final String created_at; public final String updated_at; - - @JsonCreator - public CloudifyDeployedTenant(@JsonProperty("id") String id, - @JsonProperty("tenant_name") String tenant_name, - @JsonProperty("created_at") String created_at, - @JsonProperty("updated_at") String updated_at) { - this.id = id; - this.tenant_name = tenant_name; - this.created_at = created_at; - this.updated_at = updated_at; - } - - /* (non-Javadoc) + + @JsonCreator + public CloudifyDeployedTenant(@JsonProperty("id") String id, + @JsonProperty("tenant_name") String tenant_name, + @JsonProperty("created_at") String created_at, + @JsonProperty("updated_at") String updated_at) { + this.id = id; + this.tenant_name = tenant_name; + this.created_at = created_at; + this.updated_at = updated_at; + } + + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ @Override @@ -61,17 +62,22 @@ public class CloudifyDeployedTenant extends ECTransportModel { return result; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } CloudifyDeployedTenant other = (CloudifyDeployedTenant) obj; if (created_at == null) { if (other.created_at != null) @@ -79,20 +85,26 @@ public class CloudifyDeployedTenant extends ECTransportModel { } else if (!created_at.equals(other.created_at)) return false; if (id == null) { - if (other.id != null) + if (other.id != null) { return false; - } else if (!id.equals(other.id)) + } + } else if (!id.equals(other.id)) { return false; + } if (tenant_name == null) { - if (other.tenant_name != null) + if (other.tenant_name != null) { return false; - } else if (!tenant_name.equals(other.tenant_name)) + } + } else if (!tenant_name.equals(other.tenant_name)) { return false; + } if (updated_at == null) { - if (other.updated_at != null) + if (other.updated_at != null) { return false; - } else if (!updated_at.equals(other.updated_at)) + } + } else if (!updated_at.equals(other.updated_at)) { return false; + } return true; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployedTenantList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployedTenantList.java index 96a91b6..0b1cc66 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployedTenantList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployedTenantList.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; @@ -29,34 +29,36 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyDeployedTenantList extends ECTransportModel { - public final List<CloudifyDeployedTenant> items; - public final Metadata metadata; + public final List<CloudifyDeployedTenant> items; + public final Metadata metadata; @JsonCreator - public CloudifyDeployedTenantList(@JsonProperty("items") List<CloudifyDeployedTenant> items, @JsonProperty("metadata") Metadata metadata){ - this.items = items; - this.metadata = metadata; - } + public CloudifyDeployedTenantList(@JsonProperty("items") List<CloudifyDeployedTenant> items, + @JsonProperty("metadata") Metadata metadata) { + this.items = items; + this.metadata = metadata; + } - public static final class Metadata { - public final Pagination pagination; + public static final class Metadata { + public final Pagination pagination; @JsonCreator - public Metadata(@JsonProperty("pagination") Pagination pagination){ + public Metadata(@JsonProperty("pagination") Pagination pagination) { this.pagination = pagination; } - - public static final class Pagination { - public final long total; - public final long offset; - public final long size; + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; @JsonCreator - public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ - this.total = total; - this.offset = offset; - this.size = size; - } - } - } + public Pagination(@JsonProperty("total") long total, + @JsonProperty("offset") long offset, @JsonProperty("size") long size) { + this.total = total; + this.offset = offset; + this.size = size; + } + } + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployment.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployment.java index 94ccf7d..f4d87bf 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployment.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployment.java @@ -2,28 +2,27 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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========================================================= * - *******************************************************************************/ + *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; import java.util.Map; -import java.util.Optional; - import org.onap.ccsdk.dashboard.model.ECTransportModel; import com.fasterxml.jackson.annotation.JsonCreator; @@ -35,42 +34,42 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ public final class CloudifyDeployment extends ECTransportModel { - /** A unique identifier for the deployment. */ - public final String id; - public final String description; - /** The id of the blueprint the deployment is based on. */ - public final String blueprint_id; - /** The time when the deployment was created. */ - public final String created_at; - /** The time the deployment was last updated at. */ - public final String updated_at; - /** - * A dictionary containing key value pairs which represents a deployment - * input and its provided value. - */ - public final Map<String, Object> inputs; - /** A dictionary containing policies of a deployment. */ - public final Map<String, Object> policy_types; - /** A dictionary containing policy triggers of a deployment. */ - public final Map<String, Object> policy_triggers; - /** A dictionary containing an outputs definition of a deployment. */ - public final Map<String, Object> outputs; - /** A dictionary containing the groups definition of deployment. */ - public final Map<String, Object> groups; - - public final Map<String, Object> scaling_groups; - /** A list of workflows that can be executed on a deployment. */ - public final List<Workflow> workflows; - - public final String tenant_name; - + /** A unique identifier for the deployment. */ + public final String id; + public final String description; + /** The id of the blueprint the deployment is based on. */ + public final String blueprint_id; + /** The time when the deployment was created. */ + public final String created_at; + /** The time the deployment was last updated at. */ + public final String updated_at; + /** + * A dictionary containing key value pairs which represents a deployment + * input and its provided value. + */ + public final Map<String, Object> inputs; + /** A dictionary containing policies of a deployment. */ + public final Map<String, Object> policy_types; + /** A dictionary containing policy triggers of a deployment. */ + public final Map<String, Object> policy_triggers; + /** A dictionary containing an outputs definition of a deployment. */ + public final Map<String, Object> outputs; + /** A dictionary containing the groups definition of deployment. */ + public final Map<String, Object> groups; + + public final Map<String, Object> scaling_groups; + /** A list of workflows that can be executed on a deployment. */ + public final List<Workflow> workflows; + + public final String tenant_name; + /** internal role based setting */ public boolean canDeploy; - + /** latest execution object */ public CloudifyExecution lastExecution; /** install execution workflow status */ - //public String installStatus; + // public String installStatus; /** true if helm plugin is used */ public Boolean isHelm; /** true if helm status is enabled */ @@ -80,106 +79,115 @@ public final class CloudifyDeployment extends ECTransportModel { /** blueprint owner */ public String owner; - @JsonCreator - public CloudifyDeployment(@JsonProperty("description") String description, - @JsonProperty("blueprint_id") String blueprint_id, @JsonProperty("created_at") String created_at, - @JsonProperty("updated_at") String updated_at, @JsonProperty("id") String id, - @JsonProperty("inputs") Map<String, Object> inputs, @JsonProperty("policy_types") Map<String, Object> policy_types, - @JsonProperty("policy_triggers") Map<String, Object> policy_triggers, - @JsonProperty("outputs") Map<String, Object> outputs, @JsonProperty("groups") Map<String, Object> groups, - @JsonProperty("scaling_groups") Map<String, Object> scaling_groups, - @JsonProperty("workflows") List<Workflow> workflows, @JsonProperty("tenant_name") String tenant_name) { - this.description = description; - this.blueprint_id = blueprint_id; - this.created_at = created_at; - this.updated_at = updated_at; - this.id = id; - this.inputs = inputs; - this.policy_types = policy_types; - this.policy_triggers = policy_triggers; - this.outputs = outputs; - this.groups = groups; - this.scaling_groups = scaling_groups; - this.workflows = workflows; - this.tenant_name = tenant_name; - } - - public static final class Inputs { - public final String openstack_auth_url; - public final String external_network_name; - public final String openstack_username; - public final String instance_image; - public final String keypair_name; - public final String instance_name; - public final String keypair_private_key_path; - public final String openstack_tenant_name; - public final String subnet_name; - public final String openstack_region; - public final String openstack_password; - public final String ssh_username; - public final String instance_flavor; - public final String network_name; - - @JsonCreator - public Inputs(@JsonProperty("openstack_auth_url") String openstack_auth_url, - @JsonProperty("external_network_name") String external_network_name, - @JsonProperty("openstack_username") String openstack_username, - @JsonProperty("instance_image") String instance_image, - @JsonProperty("keypair_name") String keypair_name, @JsonProperty("instance_name") String instance_name, - @JsonProperty("keypair_private_key_path") String keypair_private_key_path, - @JsonProperty("openstack_tenant_name") String openstack_tenant_name, - @JsonProperty("subnet_name") String subnet_name, - @JsonProperty("openstack_region") String openstack_region, - @JsonProperty("openstack_password") String openstack_password, - @JsonProperty("ssh_username") String ssh_username, - @JsonProperty("instance_flavor") String instance_flavor, - @JsonProperty("network_name") String network_name) { - - this.openstack_auth_url = openstack_auth_url; - this.external_network_name = external_network_name; - this.openstack_username = openstack_username; - this.instance_image = instance_image; - this.keypair_name = keypair_name; - this.instance_name = instance_name; - this.keypair_private_key_path = keypair_private_key_path; - this.openstack_tenant_name = openstack_tenant_name; - this.subnet_name = subnet_name; - this.openstack_region = openstack_region; - this.openstack_password = openstack_password; - this.ssh_username = ssh_username; - this.instance_flavor = instance_flavor; - this.network_name = network_name; - } - } - - public static final class Workflow { - public final String name; - public final String created_at; - public final Map<String,Parameter> parameters; - - @JsonCreator - public Workflow(@JsonProperty("name") String name, @JsonProperty("created_at") String created_at, - @JsonProperty("parameters") Map<String,Parameter> parameters) { - this.name = name; - this.created_at = created_at; - this.parameters = parameters; - } - } - - public static final class Parameter { - - @JsonProperty("default") - public final Object xdefault; - public final String description; - - @JsonCreator - public Parameter(@JsonProperty("default") Object xdefault, @JsonProperty("description") String description) { - this.xdefault = xdefault; - this.description = description; - } - } - - /* (non-Javadoc) + @JsonCreator + public CloudifyDeployment(@JsonProperty("description") String description, + @JsonProperty("blueprint_id") String blueprint_id, + @JsonProperty("created_at") String created_at, + @JsonProperty("updated_at") String updated_at, @JsonProperty("id") String id, + @JsonProperty("inputs") Map<String, Object> inputs, + @JsonProperty("policy_types") Map<String, Object> policy_types, + @JsonProperty("policy_triggers") Map<String, Object> policy_triggers, + @JsonProperty("outputs") Map<String, Object> outputs, + @JsonProperty("groups") Map<String, Object> groups, + @JsonProperty("scaling_groups") Map<String, Object> scaling_groups, + @JsonProperty("workflows") List<Workflow> workflows, + @JsonProperty("tenant_name") String tenant_name) { + this.description = description; + this.blueprint_id = blueprint_id; + this.created_at = created_at; + this.updated_at = updated_at; + this.id = id; + this.inputs = inputs; + this.policy_types = policy_types; + this.policy_triggers = policy_triggers; + this.outputs = outputs; + this.groups = groups; + this.scaling_groups = scaling_groups; + this.workflows = workflows; + this.tenant_name = tenant_name; + } + + public static final class Inputs { + public final String openstack_auth_url; + public final String external_network_name; + public final String openstack_username; + public final String instance_image; + public final String keypair_name; + public final String instance_name; + public final String keypair_private_key_path; + public final String openstack_tenant_name; + public final String subnet_name; + public final String openstack_region; + public final String openstack_password; + public final String ssh_username; + public final String instance_flavor; + public final String network_name; + + @JsonCreator + public Inputs(@JsonProperty("openstack_auth_url") String openstack_auth_url, + @JsonProperty("external_network_name") String external_network_name, + @JsonProperty("openstack_username") String openstack_username, + @JsonProperty("instance_image") String instance_image, + @JsonProperty("keypair_name") String keypair_name, + @JsonProperty("instance_name") String instance_name, + @JsonProperty("keypair_private_key_path") String keypair_private_key_path, + @JsonProperty("openstack_tenant_name") String openstack_tenant_name, + @JsonProperty("subnet_name") String subnet_name, + @JsonProperty("openstack_region") String openstack_region, + @JsonProperty("openstack_password") String openstack_password, + @JsonProperty("ssh_username") String ssh_username, + @JsonProperty("instance_flavor") String instance_flavor, + @JsonProperty("network_name") String network_name) { + + this.openstack_auth_url = openstack_auth_url; + this.external_network_name = external_network_name; + this.openstack_username = openstack_username; + this.instance_image = instance_image; + this.keypair_name = keypair_name; + this.instance_name = instance_name; + this.keypair_private_key_path = keypair_private_key_path; + this.openstack_tenant_name = openstack_tenant_name; + this.subnet_name = subnet_name; + this.openstack_region = openstack_region; + this.openstack_password = openstack_password; + this.ssh_username = ssh_username; + this.instance_flavor = instance_flavor; + this.network_name = network_name; + } + } + + public static final class Workflow { + public final String name; + public final String created_at; + public final Map<String, Parameter> parameters; + + @JsonCreator + public Workflow(@JsonProperty("name") String name, + @JsonProperty("created_at") String created_at, + @JsonProperty("parameters") Map<String, Parameter> parameters) { + this.name = name; + this.created_at = created_at; + this.parameters = parameters; + } + } + + public static final class Parameter { + + @JsonProperty("default") + public final Object xdefault; + public final String description; + + @JsonCreator + public Parameter(@JsonProperty("default") Object xdefault, + @JsonProperty("description") String description) { + this.xdefault = xdefault; + this.description = description; + } + } + + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ @Override @@ -191,28 +199,37 @@ public final class CloudifyDeployment extends ECTransportModel { return result; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } CloudifyDeployment other = (CloudifyDeployment) obj; if (id == null) { - if (other.id != null) + if (other.id != null) { return false; - } else if (!id.equals(other.id)) + } + } else if (!id.equals(other.id)) { return false; + } if (tenant_name == null) { - if (other.tenant_name != null) + if (other.tenant_name != null) { return false; - } else if (!tenant_name.equals(other.tenant_name)) + } + } else if (!tenant_name.equals(other.tenant_name)) { return false; + } return true; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentExt.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentExt.java index 3f906d1..caddb37 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentExt.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentExt.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import org.onap.ccsdk.dashboard.model.ECTransportModel; @@ -36,7 +36,7 @@ public class CloudifyDeploymentExt extends ECTransportModel { public Boolean isHelm; /** true if helm status is enabled */ public Boolean helmStatus; - + public CloudifyDeploymentExt(String id, String bp_id, String tenant) { super(); this.id = id; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentHelm.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentHelm.java index 9e4d122..57a7cac 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentHelm.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentHelm.java @@ -2,22 +2,21 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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. *******************************************************************************/ package org.onap.ccsdk.dashboard.model.cloudify; @@ -30,13 +29,12 @@ public class CloudifyDeploymentHelm { public Boolean isHelm; /** true if helm status is enabled */ public Boolean helmStatus; - + public CloudifyDeploymentHelm(String id, Boolean isHelm, Boolean helmStatus) { super(); this.id = id; this.isHelm = isHelm; this.helmStatus = helmStatus; } - - + } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentList.java index 4f83648..65f8c26 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentList.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; @@ -29,36 +29,38 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyDeploymentList extends ECTransportModel { - - public final List<CloudifyDeployment> items; - public final Metadata metadata; + + public final List<CloudifyDeployment> items; + public final Metadata metadata; @JsonCreator - public CloudifyDeploymentList(@JsonProperty("items") List<CloudifyDeployment> items, @JsonProperty("metadata") Metadata metadata){ - this.items = items; - this.metadata = metadata; - } + public CloudifyDeploymentList(@JsonProperty("items") List<CloudifyDeployment> items, + @JsonProperty("metadata") Metadata metadata) { + this.items = items; + this.metadata = metadata; + } - public static final class Metadata { - public final Pagination pagination; + public static final class Metadata { + public final Pagination pagination; @JsonCreator - public Metadata(@JsonProperty("pagination") Pagination pagination){ + public Metadata(@JsonProperty("pagination") Pagination pagination) { this.pagination = pagination; } - - public static final class Pagination { - public final long total; - public final long offset; - public final long size; + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; @JsonCreator - public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ - this.total = total; - this.offset = offset; - this.size = size; - } - } - } - + public Pagination(@JsonProperty("total") long total, + @JsonProperty("offset") long offset, @JsonProperty("size") long size) { + this.total = total; + this.offset = offset; + this.size = size; + } + } + } + } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyErrorCause.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyErrorCause.java index 8f6599c..69aa083 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyErrorCause.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyErrorCause.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import org.onap.ccsdk.dashboard.model.ECTransportModel; @@ -28,28 +28,27 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyErrorCause extends ECTransportModel { - /** Error message */ - public final String message; - - /** Stack trace at the point where the exception was raised */ - public final String traceback; - - /** Exception type */ - public final String type; - - @JsonCreator - public CloudifyErrorCause( - @JsonProperty("message") String message, - @JsonProperty("traceback") String traceback, - @JsonProperty("type") String type) { - - this.message = message; - this.traceback = traceback; - this.type = type; - } - - @Override - public String toString() { - return "CloudifyErrorCause [message=" + message + ", traceback=" + traceback + ", type=" + type + "]"; - } + /** Error message */ + public final String message; + + /** Stack trace at the point where the exception was raised */ + public final String traceback; + + /** Exception type */ + public final String type; + + @JsonCreator + public CloudifyErrorCause(@JsonProperty("message") String message, + @JsonProperty("traceback") String traceback, @JsonProperty("type") String type) { + + this.message = message; + this.traceback = traceback; + this.type = type; + } + + @Override + public String toString() { + return "CloudifyErrorCause [message=" + message + ", traceback=" + traceback + ", type=" + + type + "]"; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyEvent.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyEvent.java index a6593ab..5cc95ee 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyEvent.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyEvent.java @@ -2,22 +2,23 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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========================================================= * *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.LinkedList; @@ -30,69 +31,65 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyEvent extends ECTransportModel { - /** The id of the blueprint the execution is in the context of. */ - public final String blueprint_id; - /** The id of the deployment the execution is in the context of. */ - public final String deployment_id; - /** List of errors that happened while executing a given task */ - public final List<CloudifyErrorCause> error_causes; - /** The executions status. */ - public final String event_type; - /** The time the execution was queued at. */ - public final String execution_id; - /** log level */ - public final String level; - /** logger id */ - public final String logger; - /** message text */ - public final String message; - /** node instance id */ - public final String node_instance_id; - /** node name */ - public final String node_name; - /** Operation path */ - public final String operation; - /** time at which the event occurred on the executing machine */ - public final String reported_timestamp; - /** time at which the event was logged on the management machine */ - public final String timestamp; - /** resource is a cloudify_event or a cloudify_log */ - public final String type; - /** The id/name of the workflow the execution is of. */ - public final String workflow_id; + /** The id of the blueprint the execution is in the context of. */ + public final String blueprint_id; + /** The id of the deployment the execution is in the context of. */ + public final String deployment_id; + /** List of errors that happened while executing a given task */ + public final List<CloudifyErrorCause> error_causes; + /** The executions status. */ + public final String event_type; + /** The time the execution was queued at. */ + public final String execution_id; + /** log level */ + public final String level; + /** logger id */ + public final String logger; + /** message text */ + public final String message; + /** node instance id */ + public final String node_instance_id; + /** node name */ + public final String node_name; + /** Operation path */ + public final String operation; + /** time at which the event occurred on the executing machine */ + public final String reported_timestamp; + /** time at which the event was logged on the management machine */ + public final String timestamp; + /** resource is a cloudify_event or a cloudify_log */ + public final String type; + /** The id/name of the workflow the execution is of. */ + public final String workflow_id; - @JsonCreator - public CloudifyEvent( - @JsonProperty("blueprint_id") String blueprint_id, - @JsonProperty("deployment_id") String deployment_id, - @JsonProperty("error_causes") List<CloudifyErrorCause> error_causes, - @JsonProperty("event_type") String event_type, - @JsonProperty("execution_id") String execution_id, - @JsonProperty("level") String level, - @JsonProperty("logger") String logger, - @JsonProperty("message") String message, - @JsonProperty("node_instance_id") String node_instance_id, - @JsonProperty("node_name") String node_name, - @JsonProperty("operation") String operation, - @JsonProperty("reported_timestamp") String reported_timestamp, - @JsonProperty("timestamp") String timestamp, - @JsonProperty("type") String type, - @JsonProperty("workflow_id") String workflow_id) { + @JsonCreator + public CloudifyEvent(@JsonProperty("blueprint_id") String blueprint_id, + @JsonProperty("deployment_id") String deployment_id, + @JsonProperty("error_causes") List<CloudifyErrorCause> error_causes, + @JsonProperty("event_type") String event_type, + @JsonProperty("execution_id") String execution_id, @JsonProperty("level") String level, + @JsonProperty("logger") String logger, @JsonProperty("message") String message, + @JsonProperty("node_instance_id") String node_instance_id, + @JsonProperty("node_name") String node_name, @JsonProperty("operation") String operation, + @JsonProperty("reported_timestamp") String reported_timestamp, + @JsonProperty("timestamp") String timestamp, @JsonProperty("type") String type, + @JsonProperty("workflow_id") String workflow_id) { - this.blueprint_id = blueprint_id; - this.deployment_id = deployment_id; - this.error_causes = (error_causes == null) ? new LinkedList<CloudifyErrorCause> () : error_causes; - this.event_type = event_type; - this.execution_id = execution_id; - this.level = level; - this.logger = logger; - this.message = message; - this.node_instance_id = node_instance_id; - this.node_name = node_name; - this.operation = operation; - this.reported_timestamp = reported_timestamp; - this.timestamp = timestamp; - this.type = type; - this.workflow_id = workflow_id; - } + this.blueprint_id = blueprint_id; + this.deployment_id = deployment_id; + this.error_causes = + (error_causes == null) ? new LinkedList<CloudifyErrorCause>() : error_causes; + this.event_type = event_type; + this.execution_id = execution_id; + this.level = level; + this.logger = logger; + this.message = message; + this.node_instance_id = node_instance_id; + this.node_name = node_name; + this.operation = operation; + this.reported_timestamp = reported_timestamp; + this.timestamp = timestamp; + this.type = type; + this.workflow_id = workflow_id; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyEventList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyEventList.java index dc0052b..58ea962 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyEventList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyEventList.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; @@ -30,34 +30,36 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyEventList extends ECTransportModel { - public final List<CloudifyEvent> items; - public final Metadata metadata; + public final List<CloudifyEvent> items; + public final Metadata metadata; @JsonCreator - public CloudifyEventList(@JsonProperty("items") List<CloudifyEvent> items, @JsonProperty("metadata") Metadata metadata){ - this.items = items; - this.metadata = metadata; - } + public CloudifyEventList(@JsonProperty("items") List<CloudifyEvent> items, + @JsonProperty("metadata") Metadata metadata) { + this.items = items; + this.metadata = metadata; + } - public static final class Metadata { - public final Pagination pagination; + public static final class Metadata { + public final Pagination pagination; @JsonCreator - public Metadata(@JsonProperty("pagination") Pagination pagination){ + public Metadata(@JsonProperty("pagination") Pagination pagination) { this.pagination = pagination; } - - public static final class Pagination { - public final long total; - public final long offset; - public final long size; + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; @JsonCreator - public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ - this.total = total; - this.offset = offset; - this.size = size; - } - } - } + public Pagination(@JsonProperty("total") long total, + @JsonProperty("offset") long offset, @JsonProperty("size") long size) { + this.total = total; + this.offset = offset; + this.size = size; + } + } + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecution.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecution.java index 366a43d..647931f 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecution.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecution.java @@ -2,22 +2,23 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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========================================================= * *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.Map; @@ -33,52 +34,50 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ public final class CloudifyExecution extends ECTransportModel { - /** A unique identifier for the execution. */ - public final String id; - /** The executions status. */ - public final String status; - /** The time the execution was queued at. */ - public final String created_at; - /** The time the execution ended in successful, failed or cancelled state */ - public final String ended_at; - /** The id/name of the workflow the execution is of. */ - public final String workflow_id; - /** true if the execution is of a system workflow. */ - public final Boolean is_system_workflow; - /** The id of the blueprint the execution is in the context of. */ - public final String blueprint_id; - /** The id of the deployment the execution is in the context of. */ - public final String deployment_id; - /** The tenant used to deploy */ - public final String tenant_name; - /** The execution’s error message on execution failure. */ - public final String error; - /** A dict of the workflow parameters passed when starting the execution. */ - public final Map<String, Object> parameters; + /** A unique identifier for the execution. */ + public final String id; + /** The executions status. */ + public final String status; + /** The time the execution was queued at. */ + public final String created_at; + /** The time the execution ended in successful, failed or cancelled state */ + public final String ended_at; + /** The id/name of the workflow the execution is of. */ + public final String workflow_id; + /** true if the execution is of a system workflow. */ + public final Boolean is_system_workflow; + /** The id of the blueprint the execution is in the context of. */ + public final String blueprint_id; + /** The id of the deployment the execution is in the context of. */ + public final String deployment_id; + /** The tenant used to deploy */ + public final String tenant_name; + /** The execution’s error message on execution failure. */ + public final String error; + /** A dict of the workflow parameters passed when starting the execution. */ + public final Map<String, Object> parameters; - @JsonCreator - public CloudifyExecution(@JsonProperty("status") String status, - @JsonProperty("created_at") String created_at, - @JsonProperty("ended_at") String ended_at, - @JsonProperty("workflow_id") String workflow_id, - @JsonProperty("is_system_workflow") Boolean is_system_workflow, - @JsonProperty("blueprint_id") String blueprint_id, - @JsonProperty("deployment_id") String deployment_id, - @JsonProperty("tenant_name") String tenant_name, - @JsonProperty("error") String error, @JsonProperty("id") String id, - @JsonProperty("parameters") Map<String, Object> parameters) { + @JsonCreator + public CloudifyExecution(@JsonProperty("status") String status, + @JsonProperty("created_at") String created_at, @JsonProperty("ended_at") String ended_at, + @JsonProperty("workflow_id") String workflow_id, + @JsonProperty("is_system_workflow") Boolean is_system_workflow, + @JsonProperty("blueprint_id") String blueprint_id, + @JsonProperty("deployment_id") String deployment_id, + @JsonProperty("tenant_name") String tenant_name, @JsonProperty("error") String error, + @JsonProperty("id") String id, @JsonProperty("parameters") Map<String, Object> parameters) { - this.status = status; - this.created_at = created_at; - this.ended_at = ended_at; - this.workflow_id = workflow_id; - this.is_system_workflow = is_system_workflow; - this.blueprint_id = blueprint_id; - this.deployment_id = deployment_id; - this.tenant_name = tenant_name; - this.error = error; - this.id = id; - this.parameters = parameters; - } + this.status = status; + this.created_at = created_at; + this.ended_at = ended_at; + this.workflow_id = workflow_id; + this.is_system_workflow = is_system_workflow; + this.blueprint_id = blueprint_id; + this.deployment_id = deployment_id; + this.tenant_name = tenant_name; + this.error = error; + this.id = id; + this.parameters = parameters; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecutionList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecutionList.java index 9592179..f7e9b36 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecutionList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecutionList.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; @@ -29,36 +29,38 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyExecutionList extends ECTransportModel { - - public final List<CloudifyExecution> items; - public final Metadata metadata; + + public final List<CloudifyExecution> items; + public final Metadata metadata; @JsonCreator - public CloudifyExecutionList(@JsonProperty("items") List<CloudifyExecution> items, @JsonProperty("metadata") Metadata metadata){ - this.items = items; - this.metadata = metadata; - } + public CloudifyExecutionList(@JsonProperty("items") List<CloudifyExecution> items, + @JsonProperty("metadata") Metadata metadata) { + this.items = items; + this.metadata = metadata; + } - public static final class Metadata { - public final Pagination pagination; + public static final class Metadata { + public final Pagination pagination; @JsonCreator - public Metadata(@JsonProperty("pagination") Pagination pagination){ + public Metadata(@JsonProperty("pagination") Pagination pagination) { this.pagination = pagination; } - - public static final class Pagination { - public final long total; - public final long offset; - public final long size; + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; @JsonCreator - public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ - this.total = total; - this.offset = offset; - this.size = size; - } - } - } - + public Pagination(@JsonProperty("total") long total, + @JsonProperty("offset") long offset, @JsonProperty("size") long size) { + this.total = total; + this.offset = offset; + this.size = size; + } + } + } + } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecutionRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecutionRequest.java index 41b034c..8b6b68c 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecutionRequest.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecutionRequest.java @@ -2,22 +2,23 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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========================================================= * *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.Map; @@ -29,77 +30,76 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyExecutionRequest extends ECTransportModel { - /** A unique identifier for the deployment. */ - public String deployment_id; - /** A unique identifier for the workflow */ - public String workflow_id; - public Boolean allow_custom_parameters; - public Boolean force; - public String tenant; - /** Parameters: retrieve using the GET /deployments */ - public Map<String, Object> parameters; - - public String getDeployment_id() { - return deployment_id; - } - - public String getWorkflow_id() { - return workflow_id; - } - - public Boolean getAllow_custom_parameters() { - return allow_custom_parameters; - } - - public Boolean getForce() { - return force; - } - - public String getTenant() { - return tenant; - } - - public Map<String, Object> getParameters() { - return parameters; - } - - public void setDeployment_id(String deployment_id) { - this.deployment_id = deployment_id; - } - - public void setWorkflow_id(String workflow_id) { - this.workflow_id = workflow_id; - } - - public void setAllow_custom_parameters(Boolean allow_custom_parameters) { - this.allow_custom_parameters = allow_custom_parameters; - } - - public void setForce(Boolean force) { - this.force = force; - } - - public void setTenant(String tenant) { - this.tenant = tenant; - } - - public void setParameters(Map<String, Object> parameters) { - this.parameters = parameters; - } - - @JsonCreator - public CloudifyExecutionRequest(@JsonProperty("deployment_id") String deployment_id, - @JsonProperty("workflow_id") String workflow_id, - @JsonProperty("allow_custom_parameters") Boolean allowCustomParameters, - @JsonProperty("force") Boolean force, - @JsonProperty("tenant") String tenant, - @JsonProperty("parameters") Map<String, Object> parameters) { - this.deployment_id = deployment_id; - this.workflow_id = workflow_id; - this.allow_custom_parameters = allowCustomParameters; - this.force = force; - this.tenant = tenant; - this.parameters = parameters; - } + /** A unique identifier for the deployment. */ + public String deployment_id; + /** A unique identifier for the workflow */ + public String workflow_id; + public Boolean allow_custom_parameters; + public Boolean force; + public String tenant; + /** Parameters: retrieve using the GET /deployments */ + public Map<String, Object> parameters; + + public String getDeployment_id() { + return deployment_id; + } + + public String getWorkflow_id() { + return workflow_id; + } + + public Boolean getAllow_custom_parameters() { + return allow_custom_parameters; + } + + public Boolean getForce() { + return force; + } + + public String getTenant() { + return tenant; + } + + public Map<String, Object> getParameters() { + return parameters; + } + + public void setDeployment_id(String deployment_id) { + this.deployment_id = deployment_id; + } + + public void setWorkflow_id(String workflow_id) { + this.workflow_id = workflow_id; + } + + public void setAllow_custom_parameters(Boolean allow_custom_parameters) { + this.allow_custom_parameters = allow_custom_parameters; + } + + public void setForce(Boolean force) { + this.force = force; + } + + public void setTenant(String tenant) { + this.tenant = tenant; + } + + public void setParameters(Map<String, Object> parameters) { + this.parameters = parameters; + } + + @JsonCreator + public CloudifyExecutionRequest(@JsonProperty("deployment_id") String deployment_id, + @JsonProperty("workflow_id") String workflow_id, + @JsonProperty("allow_custom_parameters") Boolean allowCustomParameters, + @JsonProperty("force") Boolean force, @JsonProperty("tenant") String tenant, + @JsonProperty("parameters") Map<String, Object> parameters) { + this.deployment_id = deployment_id; + this.workflow_id = workflow_id; + this.allow_custom_parameters = allowCustomParameters; + this.force = force; + this.tenant = tenant; + this.parameters = parameters; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeId.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeId.java index da517b1..f9ae268 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeId.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeId.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import org.onap.ccsdk.dashboard.model.ECTransportModel; @@ -27,12 +27,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyNodeId extends ECTransportModel { - /** The id of the node */ - public final String id; - - @JsonCreator - public CloudifyNodeId(@JsonProperty("id") String id) { - this.id = id; - } + /** The id of the node */ + public final String id; + + @JsonCreator + public CloudifyNodeId(@JsonProperty("id") String id) { + this.id = id; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeIdList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeIdList.java index 53bde24..05d3dc8 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeIdList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeIdList.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; @@ -28,34 +28,36 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyNodeIdList { - public final List<CloudifyNodeId> items; - public final Metadata metadata; + public final List<CloudifyNodeId> items; + public final Metadata metadata; @JsonCreator - public CloudifyNodeIdList(@JsonProperty("items") List<CloudifyNodeId> items, @JsonProperty("metadata") Metadata metadata){ - this.items = items; - this.metadata = metadata; - } - - public static final class Metadata { - public final Pagination pagination; + public CloudifyNodeIdList(@JsonProperty("items") List<CloudifyNodeId> items, + @JsonProperty("metadata") Metadata metadata) { + this.items = items; + this.metadata = metadata; + } + + public static final class Metadata { + public final Pagination pagination; @JsonCreator - public Metadata(@JsonProperty("pagination") Pagination pagination){ + public Metadata(@JsonProperty("pagination") Pagination pagination) { this.pagination = pagination; } - - public static final class Pagination { - public final long total; - public final long offset; - public final long size; + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; @JsonCreator - public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ - this.total = total; - this.offset = offset; - this.size = size; - } - } - } + public Pagination(@JsonProperty("total") long total, + @JsonProperty("offset") long offset, @JsonProperty("size") long size) { + this.total = total; + this.offset = offset; + this.size = size; + } + } + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstance.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstance.java index 2b17e77..d7884c0 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstance.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstance.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.Map; @@ -30,16 +30,16 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyNodeInstance extends ECTransportModel { - /** The id of the node instance. */ - public final String id; - - /** The runtime properties of the node instance. */ - public final Map<String, Object> runtime_properties; - - @JsonCreator - public CloudifyNodeInstance(@JsonProperty("id") String id, - @JsonProperty("runtime_properties") Map<String, Object> runtime_properties) { - this.id = id; - this.runtime_properties = runtime_properties; - } + /** The id of the node instance. */ + public final String id; + + /** The runtime properties of the node instance. */ + public final Map<String, Object> runtime_properties; + + @JsonCreator + public CloudifyNodeInstance(@JsonProperty("id") String id, + @JsonProperty("runtime_properties") Map<String, Object> runtime_properties) { + this.id = id; + this.runtime_properties = runtime_properties; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceId.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceId.java index 1775b65..b8a0fc0 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceId.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceId.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import org.onap.ccsdk.dashboard.model.ECTransportModel; @@ -32,12 +32,12 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ public final class CloudifyNodeInstanceId extends ECTransportModel { - /** The id of the node instance. */ - public final String id; - - @JsonCreator - public CloudifyNodeInstanceId(@JsonProperty("id") String id) { - this.id = id; - } + /** The id of the node instance. */ + public final String id; + + @JsonCreator + public CloudifyNodeInstanceId(@JsonProperty("id") String id) { + this.id = id; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceIdList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceIdList.java index 1909bf6..6c1bced 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceIdList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceIdList.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; @@ -29,36 +29,38 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyNodeInstanceIdList extends ECTransportModel { - - public final List<CloudifyNodeInstanceId> items; - public final Metadata metadata; + + public final List<CloudifyNodeInstanceId> items; + public final Metadata metadata; @JsonCreator - public CloudifyNodeInstanceIdList(@JsonProperty("items") List<CloudifyNodeInstanceId> items, @JsonProperty("metadata") Metadata metadata){ - this.items = items; - this.metadata = metadata; - } - - public static final class Metadata { - public final Pagination pagination; + public CloudifyNodeInstanceIdList(@JsonProperty("items") List<CloudifyNodeInstanceId> items, + @JsonProperty("metadata") Metadata metadata) { + this.items = items; + this.metadata = metadata; + } + + public static final class Metadata { + public final Pagination pagination; @JsonCreator - public Metadata(@JsonProperty("pagination") Pagination pagination){ + public Metadata(@JsonProperty("pagination") Pagination pagination) { this.pagination = pagination; } - - public static final class Pagination { - public final long total; - public final long offset; - public final long size; + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; @JsonCreator - public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ - this.total = total; - this.offset = offset; - this.size = size; - } - } - } - + public Pagination(@JsonProperty("total") long total, + @JsonProperty("offset") long offset, @JsonProperty("size") long size) { + this.total = total; + this.offset = offset; + this.size = size; + } + } + } + } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceList.java index adf005c..00992b6 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceList.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; @@ -30,34 +30,36 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyNodeInstanceList extends ECTransportModel { - public final List<CloudifyNodeInstance> items; - public final Metadata metadata; + public final List<CloudifyNodeInstance> items; + public final Metadata metadata; @JsonCreator - public CloudifyNodeInstanceList(@JsonProperty("items") List<CloudifyNodeInstance> items, @JsonProperty("metadata") Metadata metadata){ - this.items = items; - this.metadata = metadata; - } - - public static final class Metadata { - public final Pagination pagination; + public CloudifyNodeInstanceList(@JsonProperty("items") List<CloudifyNodeInstance> items, + @JsonProperty("metadata") Metadata metadata) { + this.items = items; + this.metadata = metadata; + } + + public static final class Metadata { + public final Pagination pagination; @JsonCreator - public Metadata(@JsonProperty("pagination") Pagination pagination){ + public Metadata(@JsonProperty("pagination") Pagination pagination) { this.pagination = pagination; } - - public static final class Pagination { - public final long total; - public final long offset; - public final long size; + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; @JsonCreator - public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ - this.total = total; - this.offset = offset; - this.size = size; - } - } - } + public Pagination(@JsonProperty("total") long total, + @JsonProperty("offset") long offset, @JsonProperty("size") long size) { + this.total = total; + this.offset = offset; + this.size = size; + } + } + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyPlugin.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyPlugin.java index c79126c..74f3576 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyPlugin.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyPlugin.java @@ -2,53 +2,46 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyPlugin { -/* - * "uploaded_at": "2020-04-29T14:46:59.628Z", - "package_version": "1.7.2", - "package_name": "k8splugin", - "distribution": "centos", - "supported_platform": "linux_x86_64", - */ + public final String package_name; - + public final String package_version; - + public final String supported_platform; - + public final String distribution; - + public final String uploaded_at; - + @JsonCreator - public CloudifyPlugin( - @JsonProperty("package_name") String package_name, - @JsonProperty("package_version") String package_version, - @JsonProperty("supported_platform") String supported_platform, - @JsonProperty("distribution") String distribution, - @JsonProperty("uploaded_at") String uploaded_at) { + public CloudifyPlugin(@JsonProperty("package_name") String package_name, + @JsonProperty("package_version") String package_version, + @JsonProperty("supported_platform") String supported_platform, + @JsonProperty("distribution") String distribution, + @JsonProperty("uploaded_at") String uploaded_at) { this.package_name = package_name; this.package_version = package_version; this.supported_platform = supported_platform; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyPluginList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyPluginList.java index 8930fd4..2bfeba2 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyPluginList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyPluginList.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; @@ -33,7 +33,8 @@ public class CloudifyPluginList extends ECTransportModel { public final Metadata metadata; @JsonCreator - public CloudifyPluginList(@JsonProperty("items") List<CloudifyPlugin> items, @JsonProperty("metadata") Metadata metadata){ + public CloudifyPluginList(@JsonProperty("items") List<CloudifyPlugin> items, + @JsonProperty("metadata") Metadata metadata) { this.items = items; this.metadata = metadata; } @@ -42,17 +43,18 @@ public class CloudifyPluginList extends ECTransportModel { public final Pagination pagination; @JsonCreator - public Metadata(@JsonProperty("pagination") Pagination pagination){ + public Metadata(@JsonProperty("pagination") Pagination pagination) { this.pagination = pagination; } - + public static final class Pagination { public final long total; public final long offset; public final long size; @JsonCreator - public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ + public Pagination(@JsonProperty("total") long total, + @JsonProperty("offset") long offset, @JsonProperty("size") long size) { this.total = total; this.offset = offset; this.size = size; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifySecret.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifySecret.java index d087ce3..eeff3ad 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifySecret.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifySecret.java @@ -2,22 +2,23 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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========================================================= * *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import org.onap.ccsdk.dashboard.model.ECTransportModel; @@ -27,44 +28,41 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifySecret extends ECTransportModel { - /** The time when the secret was created */ - public final String created_at; - /** The secret’s key, unique per tenant */ - public final String key; + /** The time when the secret was created */ + public final String created_at; + /** The secret’s key, unique per tenant */ + public final String key; /** The time the secret was last updated at */ - public final String updated_at; - /** The secret’s value */ - public final String value; - /** Defines who can see the secret. Can be private, tenant or global*/ - public final String visibility; - /** Determines who can see the value of the secret. */ - public final String is_hidden_value; + public final String updated_at; + /** The secret’s value */ + public final String value; + /** Defines who can see the secret. Can be private, tenant or global */ + public final String visibility; + /** Determines who can see the value of the secret. */ + public final String is_hidden_value; + + public final String tenant_name; + + public final String resource_availability; - public final String tenant_name; - - public final String resource_availability; - - @JsonCreator - public CloudifySecret( - @JsonProperty("created_at") String created_at, - @JsonProperty("key") String key, - @JsonProperty("updated_at") String updated_at, - @JsonProperty("value") String value, - @JsonProperty("visibility") String visibility, - @JsonProperty("is_hidden_value") String is_hidden_value, - @JsonProperty("tenant_name") String tenant_name, - @JsonProperty("resource_availability") String resource_availability) { - this.created_at = created_at; - this.key = key; - this.updated_at = updated_at; - this.value = value; - this.visibility = visibility; - this.is_hidden_value = is_hidden_value; - this.tenant_name = tenant_name; - this.resource_availability = resource_availability; - } - - /** + @JsonCreator + public CloudifySecret(@JsonProperty("created_at") String created_at, + @JsonProperty("key") String key, @JsonProperty("updated_at") String updated_at, + @JsonProperty("value") String value, @JsonProperty("visibility") String visibility, + @JsonProperty("is_hidden_value") String is_hidden_value, + @JsonProperty("tenant_name") String tenant_name, + @JsonProperty("resource_availability") String resource_availability) { + this.created_at = created_at; + this.key = key; + this.updated_at = updated_at; + this.value = value; + this.visibility = visibility; + this.is_hidden_value = is_hidden_value; + this.tenant_name = tenant_name; + this.resource_availability = resource_availability; + } + + /** * @return the key */ public String getKey() { diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyTenant.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyTenant.java index 53f5149..078cd5b 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyTenant.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyTenant.java @@ -2,25 +2,24 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * ============LICENSE_END========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model.cloudify; +package org.onap.ccsdk.dashboard.model.cloudify; import org.onap.ccsdk.dashboard.model.ECTransportModel; @@ -29,19 +28,18 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyTenant extends ECTransportModel { - /** A unique identifier for the tenant */ - public final String id; - /** The tenant's name. */ - public final String name; - /** tenant display name */ - public String dName; - - @JsonCreator - public CloudifyTenant(@JsonProperty("name") String name, - @JsonProperty("dName") String dName, - @JsonProperty("id") String id) { - this.name = name; - this.dName = dName; - this.id = id; - } + /** A unique identifier for the tenant */ + public final String id; + /** The tenant's name. */ + public final String name; + /** tenant display name */ + public String dName; + + @JsonCreator + public CloudifyTenant(@JsonProperty("name") String name, @JsonProperty("dName") String dName, + @JsonProperty("id") String id) { + this.name = name; + this.dName = dName; + this.id = id; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyTenantList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyTenantList.java index 4610b9e..532d64b 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyTenantList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyTenantList.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; @@ -29,34 +29,36 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class CloudifyTenantList extends ECTransportModel { - public final List<CloudifyTenant> items; - public final Metadata metadata; + public final List<CloudifyTenant> items; + public final Metadata metadata; @JsonCreator - public CloudifyTenantList(@JsonProperty("items") List<CloudifyTenant> items, @JsonProperty("metadata") Metadata metadata){ - this.items = items; - this.metadata = metadata; - } - - public static final class Metadata { - public final Pagination pagination; + public CloudifyTenantList(@JsonProperty("items") List<CloudifyTenant> items, + @JsonProperty("metadata") Metadata metadata) { + this.items = items; + this.metadata = metadata; + } + + public static final class Metadata { + public final Pagination pagination; @JsonCreator - public Metadata(@JsonProperty("pagination") Pagination pagination){ + public Metadata(@JsonProperty("pagination") Pagination pagination) { this.pagination = pagination; } - - public static final class Pagination { - public final long total; - public final long offset; - public final long size; + + public static final class Pagination { + public final long total; + public final long offset; + public final long size; @JsonCreator - public Pagination(@JsonProperty("total") long total, @JsonProperty("offset") long offset, @JsonProperty("size") long size){ - this.total = total; - this.offset = offset; - this.size = size; - } - } - } + public Pagination(@JsonProperty("total") long total, + @JsonProperty("offset") long offset, @JsonProperty("size") long size) { + this.total = total; + this.offset = offset; + this.size = size; + } + } + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/ServiceRefCfyList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/ServiceRefCfyList.java index 10c9bea..53c9faf 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/ServiceRefCfyList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/ServiceRefCfyList.java @@ -2,23 +2,23 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.cloudify; import java.util.Collection; @@ -40,8 +40,7 @@ public class ServiceRefCfyList { } @JsonCreator - public ServiceRefCfyList( - @JsonProperty("items") Collection<CloudifyDeployedTenant> items, + public ServiceRefCfyList(@JsonProperty("items") Collection<CloudifyDeployedTenant> items, @JsonProperty("totalCount") Integer totalCount) { this.items = items; this.totalCount = totalCount; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulDatacenter.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulDatacenter.java index e95cdb1..ca26f96 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulDatacenter.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulDatacenter.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.consul; import org.onap.ccsdk.dashboard.model.ECTransportModel; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulDeploymentHealth.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulDeploymentHealth.java index 6837b8d..6338ab6 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulDeploymentHealth.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulDeploymentHealth.java @@ -2,33 +2,34 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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========================================================= * *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.consul; public class ConsulDeploymentHealth { - + private final String node; private final String checkID; private final String name; private final String status; private final String serviceID; private final String serviceName; - + private ConsulDeploymentHealth(String node, String checkID, String name, String status, String serviceID, String serviceName) { this.node = node; @@ -38,7 +39,7 @@ public class ConsulDeploymentHealth { this.serviceID = serviceID; this.serviceName = serviceName; } - + public String getNode() { return node; } @@ -70,7 +71,7 @@ public class ConsulDeploymentHealth { private final String status; private final String serviceID; private final String serviceName; - + public Builder(ConsulServiceHealth input) { this.node = input.node; this.checkID = input.checkID; @@ -79,9 +80,9 @@ public class ConsulDeploymentHealth { this.serviceID = input.serviceID; this.serviceName = input.serviceName; } - + public ConsulDeploymentHealth build() { - return new ConsulDeploymentHealth(node, checkID, name,status, serviceID, serviceName); + return new ConsulDeploymentHealth(node, checkID, name, status, serviceID, serviceName); } public String getNode() { diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulHealthServiceRegistration.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulHealthServiceRegistration.java deleted file mode 100644 index 76f9491..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulHealthServiceRegistration.java +++ /dev/null @@ -1,118 +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.model.consul; - -import java.util.List; - -import org.onap.ccsdk.dashboard.model.ECTransportModel; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Model for message POST-ed to controller to (de)register a node or service - * with the Consul health service. The ID is optional; the name is required. - * - * <pre> -{ - "services": [ - { - "id": "<service_id>", - "name": "<service_name>", - "address": "<service_address>", - "port": "<service_port>", - "tags": [ - ], - "checks": [ - { - "endpoint": "<http url for status>", - "interval": "<frequency to check health> e.g., 10s|10m", - "description": "<human readable description of the check", - "name":"<name of the check> - }, - { - "endpoint": "<http url for status>", - "interval": "<frequency to check health> e.g. 10s|10m", - "description": "<human readable description of the check", - "name":"<name of the check> - }, - ] - } - ] -}* - * </pre> - */ -public final class ConsulHealthServiceRegistration extends ECTransportModel { - - public final List<ConsulServiceRegistration> services; - - @JsonCreator - public ConsulHealthServiceRegistration(@JsonProperty("services") List<ConsulServiceRegistration> services) { - this.services = services; - } - - public static final class ConsulServiceRegistration { - - public final String id; - public final String name; - public final String address; - public final String port; - public final List<String> tags; - public final List<EndpointCheck> checks; - - @JsonCreator - public ConsulServiceRegistration(@JsonProperty("id") String id, // - @JsonProperty("name") String name, // - @JsonProperty("address") String address, // - @JsonProperty("port") String port, // - @JsonProperty("tags") List<String> tags, // - @JsonProperty("checks") List<EndpointCheck> checks) { - this.id = id; - this.name = name; - this.address = address; - this.port = port; - this.tags = tags; - this.checks = checks; - } - - } - - public static final class EndpointCheck { - - public final String endpoint; - public final String interval; - public final String description; - public final String name; - - @JsonCreator - public EndpointCheck(@JsonProperty("endpoint") String endpoint, // - @JsonProperty("interval") String interval, // - @JsonProperty("description") String description, // - @JsonProperty("name") String name) { - this.endpoint = endpoint; - this.interval = interval; - this.description = description; - this.name = name; - } - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulNodeInfo.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulNodeInfo.java index 3cbf3e0..b043151 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulNodeInfo.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulNodeInfo.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.consul; import java.util.Map; @@ -34,13 +34,13 @@ import com.fasterxml.jackson.annotation.JsonProperty; * * <pre> { - "ID":"a2788806-6e2e-423e-8ee7-6cad6f3d3de6", - "Node":"cjlvmcnsl00", - "Address":"10.170.8.13", - "TaggedAddresses":{"lan":"10.170.8.13","wan":"10.170.8.13"}, - "Meta":{}, - "CreateIndex":6, - "ModifyIndex":179808 + "ID":"a2788806-6e2e-423e-8ee7-6cad6f3d3de6", + "Node":"cjlvmcnsl00", + "Address":"10.170.8.13", + "TaggedAddresses":{"lan":"10.170.8.13","wan":"10.170.8.13"}, + "Meta":{}, + "CreateIndex":6, + "ModifyIndex":179808 } * </pre> */ @@ -56,10 +56,11 @@ public final class ConsulNodeInfo extends ECTransportModel { @JsonCreator public ConsulNodeInfo(@JsonProperty("ID") String id, @JsonProperty("Node") String node, - @JsonProperty("Address") String address, - @JsonProperty("TaggedAddresses") Map<String, Object> taggedAddresses, - @JsonProperty("Meta") Map<String, Object> meta, @JsonProperty("CreateIndex") int createIndex, - @JsonProperty("ModifyIndex") int modifyIndex) { + @JsonProperty("Address") String address, + @JsonProperty("TaggedAddresses") Map<String, Object> taggedAddresses, + @JsonProperty("Meta") Map<String, Object> meta, + @JsonProperty("CreateIndex") int createIndex, + @JsonProperty("ModifyIndex") int modifyIndex) { this.id = id; this.node = node; this.address = address; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceCatalogItem.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceCatalogItem.java index a5bfc3d..65a35cb 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceCatalogItem.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceCatalogItem.java @@ -2,19 +2,19 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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========================================================= * *******************************************************************************/ @@ -33,9 +33,11 @@ public class ConsulServiceCatalogItem { public final String servicePort; @JsonCreator - public ConsulServiceCatalogItem(@JsonProperty("Node") String node, @JsonProperty("Address") String address, - @JsonProperty("Datacenter") String datacenter, @JsonProperty("ServiceName") String serviceName, - @JsonProperty("ServiceAddress") String serviceAddress, @JsonProperty("ServicePort") String servicePort ) { + public ConsulServiceCatalogItem(@JsonProperty("Node") String node, + @JsonProperty("Address") String address, @JsonProperty("Datacenter") String datacenter, + @JsonProperty("ServiceName") String serviceName, + @JsonProperty("ServiceAddress") String serviceAddress, + @JsonProperty("ServicePort") String servicePort) { this.node = node; this.address = address; this.datacenter = datacenter; @@ -67,5 +69,5 @@ public class ConsulServiceCatalogItem { public String getServicePort() { return servicePort; } - + } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceHealth.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceHealth.java index 1c0cb35..2df00ca 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceHealth.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceHealth.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.consul; import org.onap.ccsdk.dashboard.model.ECTransportModel; @@ -61,11 +61,14 @@ public final class ConsulServiceHealth extends ECTransportModel { public final int modifyIndex; @JsonCreator - public ConsulServiceHealth(@JsonProperty("Node") String node, @JsonProperty("CheckID") String checkID, - @JsonProperty("Name") String name, @JsonProperty("Status") String status, - @JsonProperty("Notes") String notes, @JsonProperty("Output") String output, - @JsonProperty("ServiceID") String serviceID, @JsonProperty("ServiceName") String serviceName, - @JsonProperty("ServiceTags") String[] serviceTags, @JsonProperty("CreateIndex") int createIndex, @JsonProperty("ModifyIndex") int modifyIndex) { + public ConsulServiceHealth(@JsonProperty("Node") String node, + @JsonProperty("CheckID") String checkID, @JsonProperty("Name") String name, + @JsonProperty("Status") String status, @JsonProperty("Notes") String notes, + @JsonProperty("Output") String output, @JsonProperty("ServiceID") String serviceID, + @JsonProperty("ServiceName") String serviceName, + @JsonProperty("ServiceTags") String[] serviceTags, + @JsonProperty("CreateIndex") int createIndex, + @JsonProperty("ModifyIndex") int modifyIndex) { this.node = node; this.checkID = checkID; this.name = name; @@ -79,23 +82,25 @@ public final class ConsulServiceHealth extends ECTransportModel { this.modifyIndex = modifyIndex; ConstructTenant(); } - + /* * Search the service tags to find and * construct cfy tenant */ private void ConstructTenant() { - String tenantString = ""; - for (String tag : serviceTags) { - if (tag.contains("cfytenantname=")) { - tenantString = tag; - break; - } - } - if (!tenantString.equals("")) - tenant = tenantString.substring(tenantString.indexOf("=") + 1); - else - tenant = ""; + String tenantString = ""; + for (String tag : serviceTags) { + if (tag.contains("cfytenantname=")) { + tenantString = tag; + break; + } + } + if (!tenantString.equals("")) { + tenant = tenantString.substring(tenantString.indexOf("=") + 1); + } + else { + tenant = ""; + } } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceHealthHistory.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceHealthHistory.java deleted file mode 100644 index a3f0cf9..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceHealthHistory.java +++ /dev/null @@ -1,56 +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.model.consul; - -import org.onap.ccsdk.dashboard.model.ECTransportModel; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Model for message returned by Consul about health of a service observed at - * some point in time. - * - * <pre> - { - "Status": "critical", - "Output": "\"Get http://135.91.205.200:8080: dial tcp 135.91.205.200:8080: getsockopt: connection refused\"", - "Date": "2017-06-01 15:31:58.00-0000" - } - * </pre> - * - */ -public final class ConsulServiceHealthHistory extends ECTransportModel { - - public final String status; - public final String output; - public final String date; - - @JsonCreator - public ConsulServiceHealthHistory(@JsonProperty("Status") String status, @JsonProperty("Output") String output, - @JsonProperty("Date") String date) { - this.status = status; - this.output = output; - this.date = date; - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceInfo.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceInfo.java index 7f34bdb..e03688a 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceInfo.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceInfo.java @@ -2,22 +2,21 @@ * =============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. *******************************************************************************/ package org.onap.ccsdk.dashboard.model.consul; @@ -38,7 +37,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * * <pre> { - "pgaasServer1":["135.91.224.136"] + "pgaasServer1":["135.91.224.136"] } * </pre> */ @@ -48,7 +47,8 @@ public final class ConsulServiceInfo extends ECTransportModel { public final List<String> addresses; @JsonCreator - public ConsulServiceInfo(@JsonProperty("name") String name, @JsonProperty("addresses") List<String> addresses) { + public ConsulServiceInfo(@JsonProperty("name") String name, + @JsonProperty("addresses") List<String> addresses) { this.name = name; this.addresses = addresses; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentErrorResponse.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentErrorResponse.java index 844c066..088c935 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentErrorResponse.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentErrorResponse.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.deploymenthandler; import java.util.Collection; @@ -39,8 +39,9 @@ public class DeploymentErrorResponse { private final Optional<Collection<String>> stack; @JsonCreator - public DeploymentErrorResponse(@JsonProperty("status") int status, @JsonProperty("message") String message, - @JsonProperty("stack") Optional<Collection<String>> stack) { + public DeploymentErrorResponse(@JsonProperty("status") int status, + @JsonProperty("message") String message, + @JsonProperty("stack") Optional<Collection<String>> stack) { this.status = status; this.message = message; this.stack = stack; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentInput.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentInput.java index 33dfb6a..76f3624 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentInput.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentInput.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.deploymenthandler; import java.util.Collection; @@ -35,20 +35,20 @@ import com.fasterxml.jackson.annotation.JsonProperty; * * <pre> { - "component" : "comp", - "deploymentTag" : "tag", - "blueprintName" : "name", - "blueprintVersion" : "version", - "blueprintId" : "bp_id", - "inputs" : - { - "input1" : "parameter1", - "input2" : "parameter2", - ... - "inputn" : "parametern" - }, - "tenant" : "tenant_name" - } + "component" : "comp", + "deploymentTag" : "tag", + "blueprintName" : "name", + "blueprintVersion" : "version", + "blueprintId" : "bp_id", + "inputs" : + { + "input1" : "parameter1", + "input2" : "parameter2", + ... + "inputn" : "parametern" + }, + "tenant" : "tenant_name" + } * </pre> * * THIS OBJECT INCLUDES THE DEPLOYMENTID CREATED BY THE USER! @@ -80,31 +80,31 @@ public class DeploymentInput { private final Map<String, Object> inputs; private final Collection<String> reinstall_list; - + private final boolean skip_install; - + private final boolean skip_uninstall; - + private final boolean skip_reinstall; private final boolean force; - + private final boolean ignore_failure; - + private final boolean install_first; - + @JsonCreator - public DeploymentInput(@JsonProperty("component") String component, @JsonProperty("tag") String tag, - @JsonProperty("blueprintName") String blueprintName, - @JsonProperty("blueprintVersion") Integer blueprintVersion, @JsonProperty("blueprintId") String blueprintId, - @JsonProperty("inputs") Map<String, Object> inputs, @JsonProperty("tenant") String tenant, - @JsonProperty("reinstall_list") Collection<String> reinstallList, - @JsonProperty("skip_install") boolean skipInstall, - @JsonProperty("skip_uninstall") boolean skipUninstall, - @JsonProperty("skip_reinstall") boolean skipReinstall, - @JsonProperty("force") boolean force, - @JsonProperty("ignore_failure") boolean ignoreFailure, - @JsonProperty("install_first") boolean installFirst) { + public DeploymentInput(@JsonProperty("component") String component, + @JsonProperty("tag") String tag, @JsonProperty("blueprintName") String blueprintName, + @JsonProperty("blueprintVersion") Integer blueprintVersion, + @JsonProperty("blueprintId") String blueprintId, + @JsonProperty("inputs") Map<String, Object> inputs, @JsonProperty("tenant") String tenant, + @JsonProperty("reinstall_list") Collection<String> reinstallList, + @JsonProperty("skip_install") boolean skipInstall, + @JsonProperty("skip_uninstall") boolean skipUninstall, + @JsonProperty("skip_reinstall") boolean skipReinstall, @JsonProperty("force") boolean force, + @JsonProperty("ignore_failure") boolean ignoreFailure, + @JsonProperty("install_first") boolean installFirst) { this.component = component; this.tag = tag; this.blueprintName = blueprintName; @@ -148,7 +148,7 @@ public class DeploymentInput { public Optional<String> getBlueprintId() { return blueprintId; } - + public Collection<String> getReinstall_list() { return reinstall_list; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentLink.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentLink.java index ba0604d..918c32d 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentLink.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentLink.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.deploymenthandler; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequest.java index 94bb064..933a312 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequest.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequest.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.deploymenthandler; import java.util.Map; @@ -57,10 +57,10 @@ public class DeploymentRequest { * deployed. */ private final Map<String, Object> inputs; - + @JsonCreator public DeploymentRequest(@JsonProperty("serviceTypeId") String serviceTypeId, - @JsonProperty("inputs") Map<String, Object> inputs ) { + @JsonProperty("inputs") Map<String, Object> inputs) { this.serviceTypeId = serviceTypeId; this.inputs = inputs; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequestObject.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequestObject.java index 0bb6f74..af468a8 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequestObject.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentRequestObject.java @@ -2,31 +2,28 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.deploymenthandler; -import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.Map; -import java.util.Optional; - import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -35,17 +32,17 @@ import com.fasterxml.jackson.annotation.JsonProperty; * Deployment Handler API: * * <pre> - { - "serviceTypeId" : "serviceTypeId", - "type" : "install/update", - "inputs" : - { - "input1" : "parameter1" - "input2" : "parameter2" - ... - "inputn" : "parametern" - } - } + { + "serviceTypeId" : "serviceTypeId", + "type" : "install/update", + "inputs" : + { + "input1" : "parameter1" + "input2" : "parameter2" + ... + "inputn" : "parametern" + } + } * </pre> * * THIS OBJECT INCLUDES THE DEPLOYMENTID CREATED BY THE USER! @@ -74,30 +71,30 @@ public class DeploymentRequestObject { private final Map<String, Object> inputs; private final Collection<String> reinstall_list; - + private final boolean skip_install; - + private final boolean skip_uninstall; - + private final boolean skip_reinstall; private final boolean force; - + private final boolean ignore_failure; - + private final boolean install_first; - + @JsonCreator public DeploymentRequestObject(@JsonProperty("deploymentId") String deploymentId, - @JsonProperty("serviceTypeId") String serviceTypeId, @JsonProperty("inputs") Map<String, Object> inputs, - @JsonProperty("tenant") String tenant, @JsonProperty("method") String method, - @JsonProperty("reinstall_list") Collection<String> reinstallList, - @JsonProperty("skip_install") boolean skipInstall, - @JsonProperty("skip_uninstall") boolean skipUninstall, - @JsonProperty("skip_reinstall") boolean skipReinstall, - @JsonProperty("force") boolean force, - @JsonProperty("ignore_failure") boolean ignoreFailure, - @JsonProperty("install_first") boolean installFirst) { + @JsonProperty("serviceTypeId") String serviceTypeId, + @JsonProperty("inputs") Map<String, Object> inputs, @JsonProperty("tenant") String tenant, + @JsonProperty("method") String method, + @JsonProperty("reinstall_list") Collection<String> reinstallList, + @JsonProperty("skip_install") boolean skipInstall, + @JsonProperty("skip_uninstall") boolean skipUninstall, + @JsonProperty("skip_reinstall") boolean skipReinstall, @JsonProperty("force") boolean force, + @JsonProperty("ignore_failure") boolean ignoreFailure, + @JsonProperty("install_first") boolean installFirst) { this.deploymentId = deploymentId; this.serviceTypeId = serviceTypeId; this.inputs = inputs; @@ -112,7 +109,7 @@ public class DeploymentRequestObject { this.install_first = installFirst; } - public DeploymentRequestObject(String deploymentId, String serviceTypeId, String method, + public DeploymentRequestObject(String deploymentId, String serviceTypeId, String method, Map<String, Object> inputs, String tenant) { super(); this.deploymentId = deploymentId; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResource.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResource.java index 2c43f8a..7847c22 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResource.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResource.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.deploymenthandler; import com.fasterxml.jackson.annotation.JsonCreator; @@ -41,7 +41,7 @@ public class DeploymentResource { @JsonCreator public DeploymentResource(@JsonProperty("deployment_id") String deploymentId, - @JsonProperty("links") DeploymentResourceLinks links) { + @JsonProperty("links") DeploymentResourceLinks links) { this.deploymentId = deploymentId; this.links = links; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResourceLinks.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResourceLinks.java index 6d9644c..3884013 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResourceLinks.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResourceLinks.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.deploymenthandler; import com.fasterxml.jackson.annotation.JsonCreator; @@ -38,8 +38,8 @@ public class DeploymentResourceLinks { private final String status; @JsonCreator - public DeploymentResourceLinks(@JsonProperty("self") String self, @JsonProperty("outcome") String outcome, - @JsonProperty("status") String status) { + public DeploymentResourceLinks(@JsonProperty("self") String self, + @JsonProperty("outcome") String outcome, @JsonProperty("status") String status) { this.self = self; this.outcome = outcome; this.status = status; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponse.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponse.java index 83c1989..84bb414 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponse.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponse.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.deploymenthandler; import com.fasterxml.jackson.annotation.JsonCreator; @@ -38,7 +38,7 @@ public class DeploymentResponse { @JsonCreator public DeploymentResponse(@JsonProperty("requestId") String requestId, - @JsonProperty("links") DeploymentResponseLinks links) { + @JsonProperty("links") DeploymentResponseLinks links) { this.requestId = requestId; this.links = links; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponseLinks.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponseLinks.java index 68833cb..489d015 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponseLinks.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentResponseLinks.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.deploymenthandler; import com.fasterxml.jackson.annotation.JsonCreator; @@ -40,7 +40,8 @@ public class DeploymentResponseLinks { private final String status; @JsonCreator - public DeploymentResponseLinks(@JsonProperty("self") String self, @JsonProperty("status") String status) { + public DeploymentResponseLinks(@JsonProperty("self") String self, + @JsonProperty("status") String status) { this.self = self; this.status = status; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentsListResponse.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentsListResponse.java index 13dcc4b..05f2723 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentsListResponse.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/DeploymentsListResponse.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.model.deploymenthandler; import java.util.Collection; @@ -42,7 +42,7 @@ public class DeploymentsListResponse { @JsonCreator public DeploymentsListResponse(@JsonProperty("requestId") String requestId, - @JsonProperty("deployments") Collection<DeploymentLink> deployments) { + @JsonProperty("deployments") Collection<DeploymentLink> deployments) { this.requestId = requestId; this.deployments = deployments; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ApiResponseMessage.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ApiResponseMessage.java index 1cb0a51..ff5a15a 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ApiResponseMessage.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ApiResponseMessage.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.model.inventory; @@ -35,7 +35,7 @@ public class ApiResponseMessage { @JsonCreator public ApiResponseMessage(@JsonProperty("code") Integer code, @JsonProperty("type") String type, - @JsonProperty("message") String message) { + @JsonProperty("message") String message) { this.code = code; this.type = type; this.message = message; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Blueprint.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Blueprint.java index 184e0fb..4740113 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Blueprint.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Blueprint.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.model.inventory; @@ -32,7 +32,6 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; @JsonIgnoreProperties(ignoreUnknown = true) @@ -40,7 +39,6 @@ public class Blueprint { private static final ObjectMapper YAML_MAPPER = new ObjectMapper(new YAMLFactory()); - static { YAML_MAPPER.registerModule(new Jdk8Module()); } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintInput.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintInput.java index 972c86b..c708098 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintInput.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintInput.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.model.inventory; @@ -55,8 +55,9 @@ public class BlueprintInput { } @JsonCreator - public BlueprintInput(@JsonProperty("type") String type, @JsonProperty("default") Object defaultValue, - @JsonProperty("description") String description) { + public BlueprintInput(@JsonProperty("type") String type, + @JsonProperty("default") Object defaultValue, + @JsonProperty("description") String description) { // Case where there is no default and no type --> Type should be ANY if (defaultValue == null && type == null) { @@ -77,27 +78,33 @@ public class BlueprintInput { // Cases where there is a default and a type else { switch (BlueprintInput.Type.valueOf(type.toString().toUpperCase())) { - case ANY: - throw new IllegalArgumentException("Cannot specify type ANY (leave blank instead to get ANY type)"); - case BOOLEAN: - if (defaultValue != null && !(defaultValue instanceof Boolean)) - throw new IllegalArgumentException("default value does not match specified type"); - this.type = BlueprintInput.Type.BOOLEAN; - break; - case INTEGER: - if (defaultValue != null && !(defaultValue instanceof Integer)) - throw new IllegalArgumentException("default value does not match specified type"); - this.type = BlueprintInput.Type.INTEGER; - break; - case STRING: - if (defaultValue != null && !(defaultValue instanceof String)) - throw new IllegalArgumentException("default value does not match specified type"); - - this.type = BlueprintInput.Type.STRING; - break; - default: - this.type = Type.ANY; - break; + case ANY: + throw new IllegalArgumentException( + "Cannot specify type ANY (leave blank instead to get ANY type)"); + case BOOLEAN: + if (defaultValue != null && !(defaultValue instanceof Boolean)) { + throw new IllegalArgumentException( + "default value does not match specified type"); + } + this.type = BlueprintInput.Type.BOOLEAN; + break; + case INTEGER: + if (defaultValue != null && !(defaultValue instanceof Integer)) { + throw new IllegalArgumentException( + "default value does not match specified type"); + } + this.type = BlueprintInput.Type.INTEGER; + break; + case STRING: + if (defaultValue != null && !(defaultValue instanceof String)) { + throw new IllegalArgumentException( + "default value does not match specified type"); + } + this.type = BlueprintInput.Type.STRING; + break; + default: + this.type = Type.ANY; + break; } } @@ -135,7 +142,8 @@ public class BlueprintInput { final BlueprintInput obj = (BlueprintInput) o; return obj.getDefaultValue().equals(getDefaultValue()) - && obj.getDescriptionValue().equals(getDescriptionValue()) && obj.getType().equals(getType()); + && obj.getDescriptionValue().equals(getDescriptionValue()) + && obj.getType().equals(getType()); } return false; @@ -143,6 +151,7 @@ public class BlueprintInput { @Override public String toString() { - return "{" + "type: " + getType() + ",default: " + getDefault() + ",description: " + getDescription() + "}"; + return "{" + "type: " + getType() + ",default: " + getDefault() + ",description: " + + getDescription() + "}"; } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintResponse.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintResponse.java index 7c09ea6..39e7956 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintResponse.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/BlueprintResponse.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.model.inventory; @@ -40,7 +40,7 @@ public class BlueprintResponse { @JsonCreator public BlueprintResponse(@JsonProperty("typeName") String typeName, - @JsonProperty("typeVersion") Integer typeVersion, @JsonProperty("typeId") String typeId) { + @JsonProperty("typeVersion") Integer typeVersion, @JsonProperty("typeId") String typeId) { this.typeName = typeName; this.typeVersion = typeVersion; @@ -73,6 +73,7 @@ public class BlueprintResponse { @Override public String toString() { - return "BlueprintResponse [typeName=" + typeName + ", typeVersion=" + typeVersion + ", typeId=" + typeId + "]"; + return "BlueprintResponse [typeName=" + typeName + ", typeVersion=" + typeVersion + + ", typeId=" + typeId + "]"; } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/InventoryProperty.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/InventoryProperty.java index 4f0bf8e..627f417 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/InventoryProperty.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/InventoryProperty.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.model.inventory; @@ -34,8 +34,9 @@ public class InventoryProperty { public Link dcaeServiceQueryLink; @JsonCreator - public InventoryProperty(@JsonProperty("count") Integer count, @JsonProperty("propertyValue") String propertyValue, - @JsonProperty("dcaeServiceQueryLink") Link dcaeServiceQueryLink) { + public InventoryProperty(@JsonProperty("count") Integer count, + @JsonProperty("propertyValue") String propertyValue, + @JsonProperty("dcaeServiceQueryLink") Link dcaeServiceQueryLink) { this.count = count; this.propertyValue = propertyValue; this.dcaeServiceQueryLink = dcaeServiceQueryLink; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Link.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Link.java index 986e574..155982c 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Link.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Link.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.model.inventory; @@ -41,10 +41,11 @@ public class Link { public String type; @JsonCreator - public Link(@JsonProperty("title") String title, @JsonProperty("href") String href, @JsonProperty("rel") String rel, - @JsonProperty("uri") String uri, @JsonProperty("uriBuilder") UriBuilder uriBuilder, - @JsonProperty("rels") Collection<String> rels, @JsonProperty("params") Map<String, String> params, - @JsonProperty("type") String type) { + public Link(@JsonProperty("title") String title, @JsonProperty("href") String href, + @JsonProperty("rel") String rel, @JsonProperty("uri") String uri, + @JsonProperty("uriBuilder") UriBuilder uriBuilder, + @JsonProperty("rels") Collection<String> rels, + @JsonProperty("params") Map<String, String> params, @JsonProperty("type") String type) { this.title = title; this.href = href; this.rel = rel; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Service.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Service.java index dc1daa7..7791a21 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Service.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Service.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.model.inventory; @@ -65,14 +65,15 @@ public class Service { public Boolean helmStatus; /** Consul service health status */ private String healthStatus; - + @JsonCreator - public Service(@JsonProperty("serviceId") String serviceId, @JsonProperty("selfLink") Link selfLink, - @JsonProperty("created") String created, @JsonProperty("modified") String modified, - @JsonProperty("typeLink") Link typeLink, @JsonProperty("vnfId") String vnfId, - @JsonProperty("vnfLink") Link vnfLink, @JsonProperty("vnfType") String vnfType, - @JsonProperty("vnfLocation") String vnfLocation, @JsonProperty("deploymentRef") String deploymentRef, - @JsonProperty("components") Collection<ServiceComponent> components) { + public Service(@JsonProperty("serviceId") String serviceId, + @JsonProperty("selfLink") Link selfLink, @JsonProperty("created") String created, + @JsonProperty("modified") String modified, @JsonProperty("typeLink") Link typeLink, + @JsonProperty("vnfId") String vnfId, @JsonProperty("vnfLink") Link vnfLink, + @JsonProperty("vnfType") String vnfType, @JsonProperty("vnfLocation") String vnfLocation, + @JsonProperty("deploymentRef") String deploymentRef, + @JsonProperty("components") Collection<ServiceComponent> components) { this.serviceId = serviceId; this.selfLink = selfLink; this.created = created; @@ -134,10 +135,10 @@ public class Service { // end. public boolean contains(String searchString) { if (StringUtils.containsIgnoreCase(this.getDeploymentRef(), searchString) - || StringUtils.containsIgnoreCase(this.getServiceId(), searchString) - || StringUtils.containsIgnoreCase(this.getCreated(), searchString) - || StringUtils.containsIgnoreCase(this.getModified(), searchString) - || StringUtils.containsIgnoreCase(this.getTenant(), searchString)) { + || StringUtils.containsIgnoreCase(this.getServiceId(), searchString) + || StringUtils.containsIgnoreCase(this.getCreated(), searchString) + || StringUtils.containsIgnoreCase(this.getModified(), searchString) + || StringUtils.containsIgnoreCase(this.getTenant(), searchString)) { return true; } return false; @@ -197,12 +198,12 @@ public class Service { public void setHelmStatus(Boolean helmStatus) { this.helmStatus = helmStatus; } - + public String getHealthStatus() { - return this.healthStatus; + return this.healthStatus; } - + public void setHealthStatus(String healthStatus) { - this.healthStatus = healthStatus; + this.healthStatus = healthStatus; } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponent.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponent.java index a2e525f..2b349b8 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponent.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponent.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.model.inventory; @@ -52,10 +52,12 @@ public class ServiceComponent { @JsonCreator public ServiceComponent(@JsonProperty("componentId") String componentId, - @JsonProperty("componentLink") Link componentLink, @JsonProperty("created") String created, - @JsonProperty("modified") String modified, @JsonProperty("componentType") String componentType, - @JsonProperty("componentSource") String componentSource, @JsonProperty("status") String status, - @JsonProperty("location") String location, @JsonProperty("shareable") Integer shareable) { + @JsonProperty("componentLink") Link componentLink, @JsonProperty("created") String created, + @JsonProperty("modified") String modified, + @JsonProperty("componentType") String componentType, + @JsonProperty("componentSource") String componentSource, + @JsonProperty("status") String status, @JsonProperty("location") String location, + @JsonProperty("shareable") Integer shareable) { this.componentId = componentId; this.componentLink = componentLink; this.created = created; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceList.java index e440477..992b21a 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceList.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.model.inventory; @@ -38,8 +38,9 @@ public class ServiceList extends ECTransportModel { public final PaginationLinks paginationLinks; @JsonCreator - public ServiceList(@JsonProperty("items") Collection<Service> items, @JsonProperty("totalCount") Integer totalCount, - @JsonProperty("links") PaginationLinks paginationLinks) { + public ServiceList(@JsonProperty("items") Collection<Service> items, + @JsonProperty("totalCount") Integer totalCount, + @JsonProperty("links") PaginationLinks paginationLinks) { this.items = items; this.totalCount = totalCount; this.paginationLinks = paginationLinks; @@ -52,9 +53,9 @@ public class ServiceList extends ECTransportModel { @JsonCreator public PaginationLinks(@JsonProperty("previousLink") Link previousLink, - @JsonProperty("nextLink") Link nextLink) { + @JsonProperty("nextLink") Link nextLink) { this.previousLink = previousLink; this.nextLink = nextLink; } } -}
\ No newline at end of file +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceQueryParams.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceQueryParams.java index 62fdfd0..6ad9c6c 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceQueryParams.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceQueryParams.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.model.inventory; @@ -42,8 +42,8 @@ public class ServiceQueryParams { this.created = null; } - private ServiceQueryParams(String typeId, String vnfId, String vnfType, String vnfLocation, String componentType, - Boolean shareable, String created) { + private ServiceQueryParams(String typeId, String vnfId, String vnfType, String vnfLocation, + String componentType, Boolean shareable, String created) { this.typeId = typeId; this.vnfId = vnfId; this.vnfType = vnfType; @@ -98,7 +98,8 @@ public class ServiceQueryParams { } public ServiceQueryParams build() { - return new ServiceQueryParams(typeId, vnfId, vnfType, vnfLocation, componentType, shareable, created); + return new ServiceQueryParams(typeId, vnfId, vnfType, vnfLocation, componentType, + shareable, created); } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRef.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRef.java index 7b70e1c..37f4113 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRef.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRef.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.model.inventory; @@ -33,31 +33,28 @@ public class ServiceRef { /** Last modified date of the Service */ public final String updated_at; public final String tenant_name = ""; - + @JsonCreator - public ServiceRef( - @JsonProperty("id") String serviceId, - @JsonProperty("created_at") String created, - @JsonProperty("updated_at") String modified - ) { + public ServiceRef(@JsonProperty("id") String serviceId, + @JsonProperty("created_at") String created, @JsonProperty("updated_at") String modified) { this.id = serviceId; this.created_at = created; this.updated_at = modified; } -/* - public String getServiceId() { - return serviceId; - } - - public String getCreated() { - return created; - } - - public String getModified() { - return modified; - } -*/ + /* + * public String getServiceId() { + * return serviceId; + * } + * + * public String getCreated() { + * return created; + * } + * + * public String getModified() { + * return modified; + * } + */ /* * private ServiceRef ( String serviceId, String created, String modified) { * this.serviceId = serviceId; this.created = created; this.modified = modified; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRefList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRefList.java index def0e0a..f819e47 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRefList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRefList.java @@ -2,29 +2,27 @@ * =============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.model.inventory; import java.util.Collection; -import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; - import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -32,12 +30,12 @@ public class ServiceRefList { /** Number of Service objects */ public final Integer totalCount; /** Collection containing all of the returned Service objects */ - //public final Collection<CloudifyDeployedTenant> items; + // public final Collection<CloudifyDeployedTenant> items; public final Collection<ServiceRef> items; @JsonCreator public ServiceRefList(@JsonProperty("items") Collection<ServiceRef> items, - @JsonProperty("totalCount") Integer totalCount) { + @JsonProperty("totalCount") Integer totalCount) { this.items = items; this.totalCount = totalCount; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceType.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceType.java index f1351fc..c466bb8 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceType.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceType.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.model.inventory; @@ -126,7 +126,7 @@ public class ServiceType { private Optional<Boolean> canDeploy = Optional.of(true); public Builder(String owner, String typeName, Integer typeVersion, String blueprintTemplate, - String blueprintDescription, String application, String component) { + String blueprintDescription, String application, String component) { this.owner = owner; this.typeName = typeName; this.typeVersion = typeVersion; @@ -192,17 +192,20 @@ public class ServiceType { } @JsonCreator - public ServiceType(@JsonProperty("owner") String owner, @JsonProperty("typeName") String typeName, - @JsonProperty("typeVersion") Integer typeVersion, - @JsonProperty("blueprintTemplate") String blueprintTemplate, - @JsonProperty("application") String application, @JsonProperty("component") String component, - @JsonProperty("serviceIds") Collection<String> serviceIds, - @JsonProperty("vnfTypes") Collection<String> vnfTypes, - @JsonProperty("serviceLocations") Collection<String> serviceLocations, - @JsonProperty("asdcServiceId") String asdcServiceId, @JsonProperty("asdcResourceId") String asdcResourceId, - @JsonProperty("asdcServiceURL") String asdcServiceURL, @JsonProperty("typeId") String typeId, - @JsonProperty("selfLink") Link selfLink, @JsonProperty("created") String created, - @JsonProperty("deactivated") String deactivated, @JsonProperty("canDeploy") Boolean canDeploy) { + public ServiceType(@JsonProperty("owner") String owner, + @JsonProperty("typeName") String typeName, @JsonProperty("typeVersion") Integer typeVersion, + @JsonProperty("blueprintTemplate") String blueprintTemplate, + @JsonProperty("application") String application, + @JsonProperty("component") String component, + @JsonProperty("serviceIds") Collection<String> serviceIds, + @JsonProperty("vnfTypes") Collection<String> vnfTypes, + @JsonProperty("serviceLocations") Collection<String> serviceLocations, + @JsonProperty("asdcServiceId") String asdcServiceId, + @JsonProperty("asdcResourceId") String asdcResourceId, + @JsonProperty("asdcServiceURL") String asdcServiceURL, + @JsonProperty("typeId") String typeId, @JsonProperty("selfLink") Link selfLink, + @JsonProperty("created") String created, @JsonProperty("deactivated") String deactivated, + @JsonProperty("canDeploy") Boolean canDeploy) { if (owner == null) throw new IllegalArgumentException("owner cannot be null"); @@ -222,7 +225,8 @@ public class ServiceType { this.serviceIds = (serviceIds == null) ? new LinkedList<String>() : serviceIds; this.vnfTypes = (vnfTypes == null) ? new LinkedList<String>() : vnfTypes; - this.serviceLocations = (serviceLocations == null) ? new LinkedList<String>() : serviceLocations; + this.serviceLocations = + (serviceLocations == null) ? new LinkedList<String>() : serviceLocations; this.asdcServiceId = Optional.ofNullable(asdcServiceId); this.asdcResourceId = Optional.ofNullable(asdcResourceId); @@ -237,9 +241,10 @@ public class ServiceType { this.blueprintInputs = bpObj.getInputs(); this.blueprintDescription = bpObj.getDescription(); } catch (BlueprintParseException e) { - //this.blueprintDescription = ""; - //throw new RuntimeException( - //"Error while parsing blueprint template for " + this.typeName + " " + this.typeVersion, e); + // this.blueprintDescription = ""; + // throw new RuntimeException( + // "Error while parsing blueprint template for " + this.typeName + " " + + // this.typeVersion, e); } } @@ -331,32 +336,34 @@ public class ServiceType { final ServiceType serviceType = (ServiceType) obj; return (serviceType.getAsdcResourceId().equals(getAsdcResourceId()) - && serviceType.getAsdcServiceId().equals(getAsdcServiceId()) - && serviceType.getAsdcServiceURL().equals(getAsdcServiceURL()) - && serviceType.getBlueprintTemplate().equals(getBlueprintTemplate()) - && serviceType.getCreated().equals(getCreated()) - && serviceType.getDeactivated().equals(getDeactivated()) && serviceType.getOwner().equals(getOwner()) - && serviceType.getSelfLink().equals(getSelfLink()) - && serviceType.getServiceIds().equals(getServiceIds()) - && serviceType.getServiceLocations().equals(getServiceLocations()) - && serviceType.getTypeId().equals(getTypeId()) && serviceType.getTypeName().equals(getTypeName()) - && serviceType.getTypeVersion().equals(getTypeVersion()) - && serviceType.getVnfTypes().equals(getVnfTypes()) - && serviceType.getApplication().equals(getApplication()) - && serviceType.getComponent().equals(getComponent())); + && serviceType.getAsdcServiceId().equals(getAsdcServiceId()) + && serviceType.getAsdcServiceURL().equals(getAsdcServiceURL()) + && serviceType.getBlueprintTemplate().equals(getBlueprintTemplate()) + && serviceType.getCreated().equals(getCreated()) + && serviceType.getDeactivated().equals(getDeactivated()) + && serviceType.getOwner().equals(getOwner()) + && serviceType.getSelfLink().equals(getSelfLink()) + && serviceType.getServiceIds().equals(getServiceIds()) + && serviceType.getServiceLocations().equals(getServiceLocations()) + && serviceType.getTypeId().equals(getTypeId()) + && serviceType.getTypeName().equals(getTypeName()) + && serviceType.getTypeVersion().equals(getTypeVersion()) + && serviceType.getVnfTypes().equals(getVnfTypes()) + && serviceType.getApplication().equals(getApplication()) + && serviceType.getComponent().equals(getComponent())); } // Used for back end search, only searches the fields displayed in the front // end. public boolean contains(String searchString) { if (StringUtils.containsIgnoreCase(this.getOwner(), searchString) - || StringUtils.containsIgnoreCase(this.getBlueprintDescription(), searchString) - || StringUtils.containsIgnoreCase(this.getTypeId().get(), searchString) - || StringUtils.containsIgnoreCase(this.getTypeName(), searchString) - || StringUtils.containsIgnoreCase(Integer.toString(this.getTypeVersion()), searchString) - || StringUtils.containsIgnoreCase(this.getCreated().get(), searchString) - || StringUtils.containsIgnoreCase(this.getComponent(), searchString) - || StringUtils.containsIgnoreCase(this.getApplication(), searchString)) { + || StringUtils.containsIgnoreCase(this.getBlueprintDescription(), searchString) + || StringUtils.containsIgnoreCase(this.getTypeId().get(), searchString) + || StringUtils.containsIgnoreCase(this.getTypeName(), searchString) + || StringUtils.containsIgnoreCase(Integer.toString(this.getTypeVersion()), searchString) + || StringUtils.containsIgnoreCase(this.getCreated().get(), searchString) + || StringUtils.containsIgnoreCase(this.getComponent(), searchString) + || StringUtils.containsIgnoreCase(this.getApplication(), searchString)) { return true; } return false; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeList.java index 938ec6d..3f4aee4 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeList.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.model.inventory; @@ -39,7 +39,8 @@ public class ServiceTypeList extends ECTransportModel { @JsonCreator public ServiceTypeList(@JsonProperty("items") Collection<ServiceType> items, - @JsonProperty("totalCount") Integer totalCount, @JsonProperty("links") PaginationLinks paginationLinks) { + @JsonProperty("totalCount") Integer totalCount, + @JsonProperty("links") PaginationLinks paginationLinks) { this.items = items; this.totalCount = totalCount; this.paginationLinks = paginationLinks; @@ -52,7 +53,7 @@ public class ServiceTypeList extends ECTransportModel { @JsonCreator public PaginationLinks(@JsonProperty("previousLink") Link previousLink, - @JsonProperty("nextLink") Link nextLink) { + @JsonProperty("nextLink") Link nextLink) { this.previousLink = previousLink; this.nextLink = nextLink; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeQueryParams.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeQueryParams.java index 7b733ee..73a3ec4 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeQueryParams.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeQueryParams.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.model.inventory; @@ -36,7 +36,8 @@ public class ServiceTypeQueryParams { private final String owner; // Non-instantiable - private ServiceTypeQueryParams(org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummary.Builder builder) { + private ServiceTypeQueryParams( + org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummary.Builder builder) { this.typeName = null; this.onlyLatest = null; this.onlyActive = null; @@ -50,9 +51,9 @@ public class ServiceTypeQueryParams { this.owner = null; } - private ServiceTypeQueryParams(String typeName, Boolean onlyLatest, Boolean onlyActive, String vnfType, - String serviceId, String serviceLocation, String asdcServiceId, String asdcResourceId, String application, - String component, String owner) { + private ServiceTypeQueryParams(String typeName, Boolean onlyLatest, Boolean onlyActive, + String vnfType, String serviceId, String serviceLocation, String asdcServiceId, + String asdcResourceId, String application, String component, String owner) { this.typeName = typeName; this.onlyLatest = onlyLatest; this.onlyActive = onlyActive; @@ -83,7 +84,7 @@ public class ServiceTypeQueryParams { this.owner = owner; return this; } - + public Builder typeName(String typeName) { this.typeName = typeName; return this; @@ -128,14 +129,15 @@ public class ServiceTypeQueryParams { this.application = application; return this; } - + public Builder component(String component) { this.component = component; return this; } + public ServiceTypeQueryParams build() { - return new ServiceTypeQueryParams(typeName, onlyLatest, onlyActive, vnfType, serviceId, serviceLocation, - asdcServiceId, asdcResourceId, application, component, owner); + return new ServiceTypeQueryParams(typeName, onlyLatest, onlyActive, vnfType, serviceId, + serviceLocation, asdcServiceId, asdcResourceId, application, component, owner); } } @@ -178,7 +180,7 @@ public class ServiceTypeQueryParams { public String getComponent() { return this.component; } - + public String getOwner() { return this.owner; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeRequest.java index 84efcb8..5c64373 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeRequest.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeRequest.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.model.inventory; @@ -69,24 +69,27 @@ public class ServiceTypeRequest { public Optional<String> asdcServiceURL; @JsonCreator - public ServiceTypeRequest(@JsonProperty("owner") String owner, @JsonProperty("typeName") String typeName, - @JsonProperty("typeVersion") Integer typeVersion, - @JsonProperty("blueprintTemplate") String blueprintTemplate, - @JsonProperty("application") String application, @JsonProperty("component") String component, - @JsonProperty("serviceIds") Collection<String> serviceIds, - @JsonProperty("vnfTypes") Collection<String> vnfTypes, - @JsonProperty("serviceLocations") Collection<String> serviceLocations, - @JsonProperty("asdcServiceId") String asdcServiceId, @JsonProperty("asdcResourceId") String asdcResourceId, - @JsonProperty("asdcServiceURL") String asdcServiceURL) { - this(owner, typeName, typeVersion, blueprintTemplate, application, component, serviceIds, vnfTypes, - serviceLocations, Optional.ofNullable(asdcServiceId), Optional.ofNullable(asdcResourceId), - Optional.ofNullable(asdcServiceURL)); + public ServiceTypeRequest(@JsonProperty("owner") String owner, + @JsonProperty("typeName") String typeName, @JsonProperty("typeVersion") Integer typeVersion, + @JsonProperty("blueprintTemplate") String blueprintTemplate, + @JsonProperty("application") String application, + @JsonProperty("component") String component, + @JsonProperty("serviceIds") Collection<String> serviceIds, + @JsonProperty("vnfTypes") Collection<String> vnfTypes, + @JsonProperty("serviceLocations") Collection<String> serviceLocations, + @JsonProperty("asdcServiceId") String asdcServiceId, + @JsonProperty("asdcResourceId") String asdcResourceId, + @JsonProperty("asdcServiceURL") String asdcServiceURL) { + this(owner, typeName, typeVersion, blueprintTemplate, application, component, serviceIds, + vnfTypes, serviceLocations, Optional.ofNullable(asdcServiceId), + Optional.ofNullable(asdcResourceId), Optional.ofNullable(asdcServiceURL)); } - public ServiceTypeRequest(String owner, String typeName, Integer typeVersion, String blueprintTemplate, - String application, String component, Collection<String> serviceIds, Collection<String> vnfTypes, - Collection<String> serviceLocations, Optional<String> asdcServiceId, Optional<String> asdcResourceId, - Optional<String> asdcServiceURL) { + public ServiceTypeRequest(String owner, String typeName, Integer typeVersion, + String blueprintTemplate, String application, String component, + Collection<String> serviceIds, Collection<String> vnfTypes, + Collection<String> serviceLocations, Optional<String> asdcServiceId, + Optional<String> asdcResourceId, Optional<String> asdcServiceURL) { this.owner = owner; this.typeName = typeName; this.typeVersion = typeVersion; @@ -100,9 +103,9 @@ public class ServiceTypeRequest { this.asdcResourceId = asdcResourceId; this.asdcServiceURL = asdcServiceURL; } - - public ServiceTypeRequest(String owner, String typeName, Integer typeVersion, String blueprintTemplate, - String application, String component) { + + public ServiceTypeRequest(String owner, String typeName, Integer typeVersion, + String blueprintTemplate, String application, String component) { this.owner = owner; this.typeName = typeName; this.typeVersion = typeVersion; @@ -112,17 +115,22 @@ public class ServiceTypeRequest { } public static ServiceTypeRequest from(ServiceType serviceType) { - return new ServiceTypeRequest(serviceType.getOwner(), serviceType.getTypeName(), serviceType.getTypeVersion(), - serviceType.getBlueprintTemplate(), serviceType.getApplication(), serviceType.getComponent(), - serviceType.getServiceIds(), serviceType.getVnfTypes(), serviceType.getServiceLocations(), - serviceType.getAsdcServiceId(), serviceType.getAsdcResourceId(), serviceType.getAsdcServiceURL()); - } -/* - public static ServiceTypeRequest from(ServiceType serviceType) { - return new ServiceTypeRequest(serviceType.getOwner(), serviceType.getTypeName(), serviceType.getTypeVersion(), - serviceType.getBlueprintTemplate(), serviceType.getApplication(), serviceType.getComponent()); + return new ServiceTypeRequest(serviceType.getOwner(), serviceType.getTypeName(), + serviceType.getTypeVersion(), serviceType.getBlueprintTemplate(), + serviceType.getApplication(), serviceType.getComponent(), serviceType.getServiceIds(), + serviceType.getVnfTypes(), serviceType.getServiceLocations(), + serviceType.getAsdcServiceId(), serviceType.getAsdcResourceId(), + serviceType.getAsdcServiceURL()); } -*/ + + /* + * public static ServiceTypeRequest from(ServiceType serviceType) { + * return new ServiceTypeRequest(serviceType.getOwner(), serviceType.getTypeName(), + * serviceType.getTypeVersion(), + * serviceType.getBlueprintTemplate(), serviceType.getApplication(), + * serviceType.getComponent()); + * } + */ public String getBlueprintTemplate() { return this.blueprintTemplate; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeServiceMap.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeServiceMap.java index 3b2f541..2e5f5b5 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeServiceMap.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeServiceMap.java @@ -2,19 +2,19 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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========================================================= * *******************************************************************************/ @@ -31,7 +31,7 @@ public class ServiceTypeServiceMap { @JsonCreator public ServiceTypeServiceMap(@JsonProperty("serviceTypeId") String serviceTypeId, - @JsonProperty("serviceRefList") Object serviceRefList) { + @JsonProperty("serviceRefList") Object serviceRefList) { this.serviceTypeId = serviceTypeId; this.serviceRefList = serviceRefList; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeSummary.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeSummary.java index 877a8ed..714ef72 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeSummary.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeSummary.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.model.inventory; @@ -36,7 +36,9 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ public class ServiceTypeSummary { - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ @Override @@ -57,33 +59,29 @@ public class ServiceTypeSummary { /** controller application name */ private final String application; - + /** onboarding component name */ private final String component; - + /** Unique identifier for this ServiceType */ private final Optional<String> typeId; /** Creation date of the ServiceType */ private final Optional<String> created; - + /** internal role based setting */ private Optional<Boolean> canDeploy; - + private ServiceRefCfyList deployments; - + private Optional<Boolean> expanded; - + @JsonCreator - public ServiceTypeSummary( - @JsonProperty("owner") String owner, - @JsonProperty("typeName") String typeName, - @JsonProperty("typeVersion") Integer typeVersion, - @JsonProperty("application") String application, - @JsonProperty("component") String component, - @JsonProperty("typeId") String typeId, - @JsonProperty("created") String created, - @JsonProperty("canDeploy") Boolean canDeploy) { + public ServiceTypeSummary(@JsonProperty("owner") String owner, + @JsonProperty("typeName") String typeName, @JsonProperty("typeVersion") Integer typeVersion, + @JsonProperty("application") String application, + @JsonProperty("component") String component, @JsonProperty("typeId") String typeId, + @JsonProperty("created") String created, @JsonProperty("canDeploy") Boolean canDeploy) { this.owner = owner; this.typeName = typeName; @@ -106,7 +104,7 @@ public class ServiceTypeSummary { this.created = builder.created; this.canDeploy = builder.canDeploy; } - + public static class Builder { private String owner; private String typeName; @@ -116,7 +114,7 @@ public class ServiceTypeSummary { private Optional<String> typeId = Optional.empty(); private Optional<String> created = Optional.empty(); private Optional<Boolean> canDeploy = Optional.empty(); - + public Builder owner(String owner) { this.owner = owner; return this; @@ -131,21 +129,22 @@ public class ServiceTypeSummary { this.typeVersion = typeVersion; return this; } - + public Builder application(String application) { this.application = application; return this; } - + public Builder component(String component) { this.component = component; return this; } + public ServiceTypeSummary build() { return new ServiceTypeSummary(this); } } - + public String getTypeName() { return typeName; } @@ -180,7 +179,7 @@ public class ServiceTypeSummary { public void setCanDeploy(Optional<Boolean> canDeploy) { this.canDeploy = canDeploy; - } + } public ServiceRefCfyList getDeployments() { return deployments; @@ -189,23 +188,25 @@ public class ServiceTypeSummary { public void setDeployments(ServiceRefCfyList deployments) { this.deployments = deployments; } - + // Used for back end search, only searches the fields displayed in the front // end. public boolean contains(String searchString) { if (StringUtils.containsIgnoreCase(this.getOwner(), searchString) - || StringUtils.containsIgnoreCase(this.getTypeId().get(), searchString) - || StringUtils.containsIgnoreCase(this.getTypeName(), searchString) - || StringUtils.containsIgnoreCase(Integer.toString(this.getTypeVersion()), searchString) - || StringUtils.containsIgnoreCase(this.getCreated().get(), searchString) - || StringUtils.containsIgnoreCase(this.getComponent(), searchString) - || StringUtils.containsIgnoreCase(this.getApplication(), searchString)) { + || StringUtils.containsIgnoreCase(this.getTypeId().get(), searchString) + || StringUtils.containsIgnoreCase(this.getTypeName(), searchString) + || StringUtils.containsIgnoreCase(Integer.toString(this.getTypeVersion()), searchString) + || StringUtils.containsIgnoreCase(this.getCreated().get(), searchString) + || StringUtils.containsIgnoreCase(this.getComponent(), searchString) + || StringUtils.containsIgnoreCase(this.getApplication(), searchString)) { return true; } return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ @Override @@ -216,7 +217,9 @@ public class ServiceTypeSummary { return result; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ @Override diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeSummaryList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeSummaryList.java index 149e75b..dba54aa 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeSummaryList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeSummaryList.java @@ -2,19 +2,19 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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========================================================= * *******************************************************************************/ @@ -37,8 +37,7 @@ public class ServiceTypeSummaryList extends ECTransportModel { public final PaginationLinks paginationLinks; @JsonCreator - public ServiceTypeSummaryList( - @JsonProperty("items") Collection<ServiceTypeSummary> items, + public ServiceTypeSummaryList(@JsonProperty("items") Collection<ServiceTypeSummary> items, @JsonProperty("totalCount") Integer totalCount, @JsonProperty("links") PaginationLinks paginationLinks) { this.items = items; @@ -53,7 +52,7 @@ public class ServiceTypeSummaryList extends ECTransportModel { @JsonCreator public PaginationLinks(@JsonProperty("previousLink") Link previousLink, - @JsonProperty("nextLink") Link nextLink) { + @JsonProperty("nextLink") Link nextLink) { this.previousLink = previousLink; this.nextLink = nextLink; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeUploadRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeUploadRequest.java index 2ba8aa7..6585a87 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeUploadRequest.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeUploadRequest.java @@ -2,28 +2,25 @@ * =============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.model.inventory; -import java.util.Collection; -import java.util.Optional; - import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -43,10 +40,11 @@ public class ServiceTypeUploadRequest { public String component; @JsonCreator - public ServiceTypeUploadRequest(@JsonProperty("owner") String owner, @JsonProperty("typeName") String typeName, - @JsonProperty("typeVersion") Integer typeVersion, - @JsonProperty("blueprintTemplate") String blueprintTemplate, - @JsonProperty("application") String application, @JsonProperty("component") String component) { + public ServiceTypeUploadRequest(@JsonProperty("owner") String owner, + @JsonProperty("typeName") String typeName, @JsonProperty("typeVersion") Integer typeVersion, + @JsonProperty("blueprintTemplate") String blueprintTemplate, + @JsonProperty("application") String application, + @JsonProperty("component") String component) { this.owner = owner; this.typeName = typeName; this.typeVersion = typeVersion; @@ -57,8 +55,8 @@ public class ServiceTypeUploadRequest { public static ServiceTypeUploadRequest from(ServiceType serviceType) { return new ServiceTypeUploadRequest(serviceType.getOwner(), serviceType.getTypeName(), - serviceType.getTypeVersion(), serviceType.getBlueprintTemplate(), serviceType.getApplication(), - serviceType.getComponent()); + serviceType.getTypeVersion(), serviceType.getBlueprintTemplate(), + serviceType.getApplication(), serviceType.getComponent()); } public String getBlueprintTemplate() { 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 04a084e..7dbef22 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 @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.rest; import java.util.List; @@ -39,8 +39,9 @@ import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionRequest; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceIdList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyPluginList; -import org.onap.ccsdk.dashboard.model.cloudify.CloudifyTenantList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifySecret; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyTenantList; +import org.springframework.web.client.HttpStatusCodeException; /** * @author rp5662 @@ -49,17 +50,18 @@ import org.onap.ccsdk.dashboard.model.cloudify.CloudifySecret; public interface CloudifyClient { /** - * Get the execution logs + * Get the execution logs. * */ - public CloudifyEventList getEventlogs(String execution_id, String tenant); + public CloudifyEventList getEventlogs(String executionId, String tenant) + throws Exception; /** * Gets the list of Cloudify tenants. * * @return CloudifyTenantList */ - public CloudifyTenantList getTenants(); + public CloudifyTenantList getTenants() throws Exception; /** * Starts a Cloudify execution. @@ -67,66 +69,73 @@ public interface CloudifyClient { * @param execution Execution details * @return CloudifyExecution */ - public CloudifyExecution startExecution(CloudifyExecutionRequest execution); + public CloudifyExecution startExecution(CloudifyExecutionRequest execution) + throws Exception; /** * Deletes the Cloudify execution with the specified ids. * - * @param executionId execution ID + * @param executionId execution ID * @param deploymentId Deployment ID - * @param action either "cancel" or "force-cancel" + * @param action either "cancel" or "force-cancel" * @return Status code; e.g., 200, 202, 204. */ - public CloudifyExecution cancelExecution(final String executionId, Map<String, String> parameters, - final String tenant); + public CloudifyExecution cancelExecution(final String executionId, + Map<String, String> parameters, final String tenant) + throws Exception; /** * Get the node-instance-id. * * @param deploymentId deployment ID - * @param nodeId node ID - * @param tenant tenant name + * @param nodeId node ID + * @param tenant tenant name * @return CloudifyNodeInstanceList */ - public CloudifyNodeInstanceIdList getNodeInstanceId(String deploymentId, String nodeId, String tenant); + public CloudifyNodeInstanceIdList getNodeInstanceId(String deploymentId, String nodeId, + String tenant) throws Exception; /** * Get the node-instance-id. * * @param deploymentId deployment ID - * @param tenant tenant name + * @param tenant tenant name * * @return CloudifyNodeInstanceList */ - public CloudifyNodeInstanceIdList getNodeInstanceId(String id, String tenant); + public CloudifyNodeInstanceIdList getNodeInstanceId(String id, String tenant) + throws Exception; /** - * Query execution information for a deployment ID passed as input + * Query execution information for a deployment ID passed as input. * * @param deploymentId * @param tenant * @return */ - public CloudifyExecutionList getExecutions(final String deploymentId, final String tenant); + public CloudifyExecutionList getExecutions(final String deploymentId, final String tenant) + throws Exception; /** - * Query execution summary for a deployment ID passed as input + * Query execution summary for a deployment ID passed as input. * * @param deploymentId * @param tenant * @return */ - public CloudifyExecutionList getExecutionsSummary(final String deploymentId, final String tenant); + public CloudifyExecutionList getExecutionsSummary(final String deploymentId, + final String tenant) throws Exception; /** * Get cloudify node-instance-revisions. * * @param deploymentId deployment ID - * @param nodeId node ID - * @param tenant tenant name + * @param nodeId node ID + * @param tenant tenant name * @return CloudifyNodeInstanceList */ - public CloudifyNodeInstanceList getNodeInstanceVersion(String deploymentId, String nodeId, String tenant); + public CloudifyNodeInstanceList getNodeInstanceVersion(String deploymentId, String nodeId, + String tenant) throws Exception; /** * Get cloudify node-instance-revisions @@ -135,65 +144,74 @@ public interface CloudifyClient { * @param tenant * @return */ - public CloudifyNodeInstanceList getNodeInstanceVersion(String bp_id, String tenant); + public CloudifyNodeInstanceList getNodeInstanceVersion(String bp_id, String tenant) + throws Exception; /** - * Query deployment object from cloudify + * Query deployment object from cloudify. * * @param id * @param tenant * @return */ - public CloudifyDeploymentList getDeployment(String id, String tenant); + public CloudifyDeploymentList getDeployment(String id, String tenant) + throws Exception; /** - * Query deployment object from cloudify + * Query deployment object from cloudify. * * @param id * @return */ - public CloudifyDeploymentList getDeployment(String id); + public CloudifyDeploymentList getDeployment(String id) + throws Exception; /** - * Query deployments from cloudify + * Query deployments from cloudify. * */ public CloudifyDeploymentList getDeployments(String tenant, int pageSize, int pageOffset); - + /** * Query deployments from cloudify and filter based * on given input key and value * At the moment only supports key "contains" not "equals" - * For value it supports only "equals" not "contains" + * For value it supports only "equals" not "contains". + * * @param inputKey * @param inputValue - * @param returnFullDeployment If true, returns full deployment obj, otherwise only some attributes + * @param returnFullDeployment If true, returns full deployment obj, otherwise only some + * attributes * @return */ - public List<CloudifyDeployment> getDeploymentsByInputFilter(String inputKey, String inputValue) throws Exception; - - public List<CloudifyDeployment> getDeploymentsWithFilter(HttpServletRequest request, String filter) throws Exception; + public List<CloudifyDeployment> getDeploymentsByInputFilter(String inputKey, String inputValue) + throws Exception; + + public List<CloudifyDeployment> getDeploymentsWithFilter(HttpServletRequest request, + String filter) throws Exception; /** - * Query a blueprint object matching the blueprint ID in cloudify + * Query a blueprint object matching the blueprint ID in cloudify. * * @param id * @param tenant * @return */ - public CloudifyBlueprintList getBlueprint(String id, String tenant); + public CloudifyBlueprintList getBlueprint(String id, String tenant) + throws Exception; /** - * Query deployment inputs for a deployment ID in the cloudify tenant + * Query deployment inputs for a deployment ID in the cloudify tenant. * * @param id * @param tenant * @return */ - public CloudifyDeploymentList getDeploymentInputs(String id, String tenant); - + public CloudifyDeploymentList getDeploymentInputs(String id, String tenant) + throws Exception; + /** - * Query a cloudify secret under a tenant scope + * Query a cloudify secret under a tenant scope. * * @param secretName * @param tenant @@ -202,59 +220,168 @@ public interface CloudifyClient { public CloudifySecret getSecret(String secretName, String tenant); /** - * Query install workflow execution summary for a deployment ID + * Query install workflow execution summary for a deployment ID. * * @param deploymentId * @param tenant * @return */ public CloudifyExecutionList getInstallExecutionSummary(String deploymentId, String tenant); - + /** * - * Delete Blueprint + * Delete Blueprint. * * @param blueprint ID + * @throws Exception + * @throws HttpStatusCodeException */ - public void deleteBlueprint(String bpName, String tenant); + public void deleteBlueprint(String bpName, String tenant) + throws Exception; + /** * - * Query deployment node instances + * Query deployment node instances. * * @param deploymentId * @param tenant * @return */ - public CloudifyNodeInstanceIdList getNodeInstances(String deploymentId, String tenant); - + public CloudifyNodeInstanceIdList getNodeInstances(String deploymentId, String tenant) + throws Exception; + /** + * Get the full list of deployments in the tenant. + * + * @param tenant + * @param pageSize + * @param pageOffset + * @param recurse + * @return + */ public List<CloudifyDeployment> getDeployments(String tenant, int pageSize, int pageOffset, boolean recurse); + /** + * Get the full list of deployments in the tenant (use cache). + * + * @param tenant + * @param pageSize + * @param pageOffset + * @param recurse + * @param cache + * @return + */ public List<CloudifyDeployment> getDeployments(String tenant, int pageSize, int pageOffset, boolean recurse, boolean cache); - - public byte[] viewBlueprint(String tenant, String id); + /** + * Fetch the blueprint YAML content. + * + * @param tenant + * @param id + * @return + * @throws HttpStatusCodeException + * @throws Exception + */ + public byte[] viewBlueprint(String tenant, String id) throws Exception; + + /** + * Store the latest set of deployments in cache, refresh periodically. + */ public void cacheDeployments(); + /** + * Fetch a deployment object that contains all the details. + * + * @param id + * @param tenant + * @return + */ public CloudifyDeployment getDeploymentResource(final String id, final String tenant); - public List<CloudifyDeployment> getDeploymentsWithFilter(HttpServletRequest request) throws Exception; + /** + * Find matching deployments using the input query filters. + * + * @param request + * @return + * @throws Exception + */ + public List<CloudifyDeployment> getDeploymentsWithFilter(HttpServletRequest request) + throws Exception; + + /** + * Get the list of node instance resources for the given inputs. + * + * @param deploymentId + * @param tenant + * @return + * @throws HttpStatusCodeException + * @throws Exception + */ + public CloudifyNodeInstanceList getNodeInstanceDetails(String deploymentId, String tenant) + throws Exception; - public CloudifyNodeInstanceList getNodeInstanceDetails(String deploymentId, String tenant); - + /** + * Lookup the matching deployments associated with a blueprint ID. + * + * @param bpId + * @return + */ public List<CloudifyDeployedTenant> getDeploymentForBlueprint(final String bpId); + /** + * Utility method to append execution workflow details to a deployment resource. + * + * @param itemList + * @return + */ public List<CloudifyDeploymentExt> updateWorkflowStatus(List<CloudifyDeployment> itemList); - + + /** + * Utility method to append helm info details to a deployment resource. + * + * @param itemList + * @return + */ public List<CloudifyDeploymentHelm> updateHelmInfo(List<CloudifyDeployment> itemList); - public List<String> getDeploymentNamesWithFilter(HttpServletRequest request) + /** + * extension method to fetch deployment names for given inputs. + * + * @param request + * @return + * @throws Exception + */ + public List<String> getDeploymentNamesWithFilter(HttpServletRequest request) throws Exception; + + /** + * Get the list of plugin resources available in cloudify. + * + * @return + * @throws HttpStatusCodeException + * @throws Exception + */ + public CloudifyPluginList getPlugins() throws Exception; + + /** + * Get the collection of execution summary per tenant. + * @param tenant + * @return + * @throws HttpStatusCodeException + * @throws Exception + */ + public CloudifyExecutionList getExecutionsSummaryPerTenant(String tenant) throws Exception; - - public CloudifyPluginList getPlugins(); - public CloudifyExecutionList getExecutionsSummaryPerTenant(String tenant); - - public CloudifyExecution getExecutionIdSummary(final String id, final String tenant); + /** + * Get an execution summary for the given execution ID and tenant. + * + * @param id + * @param tenant + * @return + * @throws HttpStatusCodeException + * @throws Exception + */ + public CloudifyExecution getExecutionIdSummary(final String id, final String tenant) + throws Exception; } 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 0e64ef0..ab9dd59 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 @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.rest; import java.net.MalformedURLException; @@ -33,11 +33,13 @@ import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Predicate; import java.util.stream.Collectors; + import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.json.JSONObject; +import org.onap.ccsdk.dashboard.exceptions.DashboardControllerException; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyBlueprint; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyBlueprintList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; @@ -54,9 +56,9 @@ import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeIdList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceIdList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyPluginList; -import org.onap.ccsdk.dashboard.model.cloudify.CloudifyTenantList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifySecret; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyTenant; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyTenantList; import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.objectcache.AbstractCacheManager; @@ -70,6 +72,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.web.client.HttpStatusCodeException; @org.springframework.stereotype.Service public class CloudifyRestClientImpl extends RestClientBase implements CloudifyClient { @@ -88,12 +91,12 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl private static final String SECRETS = "secrets"; private static final String SERVICE_ID = "service-list"; private static final String PLUGINS = "plugins"; - + /** - * For caching data + * For caching data */ - private AbstractCacheManager cacheManager; - + private AbstractCacheManager cacheManager; + @Autowired public void setCacheManager(AbstractCacheManager cacheManager) { this.cacheManager = cacheManager; @@ -102,9 +105,9 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl public AbstractCacheManager getCacheManager() { return cacheManager; } - + @PostConstruct - public void init() { + public void init() throws DashboardControllerException { String webapiUrl = DashboardProperties.getControllerProperty("site.primary", DashboardProperties.SITE_SUBKEY_CLOUDIFY_URL); if (webapiUrl == null) { @@ -119,7 +122,7 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl url = new URL(webapiUrl); baseUrl = url.toExternalForm(); } catch (MalformedURLException ex) { - throw new RuntimeException("Failed to parse URL", ex); + throw new DashboardControllerException("Failed to parse URL", ex); } String urlScheme = webapiUrl.split(":")[0]; if (restTemplate == null) { @@ -132,7 +135,7 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl boolean isHelm = false; boolean helmStatus = false; List<CloudifyDeploymentHelm> result = new ArrayList<>(); - for (CloudifyDeployment srvc : (List<CloudifyDeployment>) itemList) { + for (CloudifyDeployment srvc : (List<CloudifyDeployment>) itemList) { try { isHelm = false; helmStatus = false; @@ -149,12 +152,12 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl if (workflows.containsKey("status")) { helmStatus = true; } - CloudifyDeploymentHelm cfyDeplHelm = + CloudifyDeploymentHelm cfyDeplHelm = new CloudifyDeploymentHelm(srvc.id, isHelm, helmStatus); result.add(cfyDeplHelm); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "getBlueprint failed"); - CloudifyDeploymentHelm cfyDeplHelm = + CloudifyDeploymentHelm cfyDeplHelm = new CloudifyDeploymentHelm(srvc.id, false, false); result.add(cfyDeplHelm); continue; @@ -162,7 +165,7 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl } return result; } - + public List<CloudifyDeploymentExt> updateWorkflowStatus(List<CloudifyDeployment> itemList) { List<CloudifyDeploymentExt> result = new ArrayList<>(); for (CloudifyDeployment srvc : (List<CloudifyDeployment>) itemList) { @@ -171,11 +174,9 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl CloudifyExecutionList execResults = this.getExecutionsSummary(srvc.id, srvc.tenant_name); if (execResults.items != null && !execResults.items.isEmpty()) { - CloudifyDeploymentExt cfyDeplExt = - new CloudifyDeploymentExt(srvc.id, - srvc.blueprint_id, srvc.tenant_name); - cfyDeplExt.lastExecution = - execResults.items.get(0); + CloudifyDeploymentExt cfyDeplExt = + new CloudifyDeploymentExt(srvc.id, srvc.blueprint_id, srvc.tenant_name); + cfyDeplExt.lastExecution = execResults.items.get(0); result.add(cfyDeplExt); } } catch (Exception e) { @@ -186,30 +187,30 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl } return result; } - + public List<CloudifyDeployedTenant> getDeploymentForBlueprint(final String bpId) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, - new String[] { "blueprint_id", bpId, "_all_tenants", "true", "_include", "id,created_at,updated_at,tenant_name"}); - logger.debug(EELFLoggerDelegate.debugLogger, "getDeploymentForBlueprint begin: url {}", url); - ResponseEntity<CloudifyDeployedTenantList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<CloudifyDeployedTenantList>() { - }); + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, new String[] {"blueprint_id", + bpId, "_all_tenants", "true", "_include", "id,created_at,updated_at,tenant_name"}); + logger.debug(EELFLoggerDelegate.debugLogger, "getDeploymentForBlueprint begin: url {}", + url); + ResponseEntity<CloudifyDeployedTenantList> response = restTemplate.exchange(url, + HttpMethod.GET, null, new ParameterizedTypeReference<CloudifyDeployedTenantList>() {}); return response.getBody().items; } - + public CloudifyDeployment getDeploymentResource(final String id, final String tenant) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, - new String[] { "id", id, "_include", "id,blueprint_id,created_at,updated_at,created_by,description,tenant_name", - "_sort","-updated_at", "_sort", "-created_at"}); + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, + new String[] {"id", id, "_include", + "id,blueprint_id,created_at,updated_at,created_by,description,tenant_name", "_sort", + "-updated_at", "_sort", "-created_at"}); logger.debug(EELFLoggerDelegate.debugLogger, "getDeploymentResource begin: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyDeploymentList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyDeploymentList>() { - }); + ResponseEntity<CloudifyDeploymentList> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyDeploymentList>() {}); return response.getBody().items.get(0); } - - @Scheduled(fixedRate=86400000, initialDelay=15000) + + @Scheduled(fixedRate = 86400000, initialDelay = 15000) public void cacheTenants() { logger.debug(EELFLoggerDelegate.debugLogger, "cacheTenants begin"); CloudifyTenantList tenantsList = this.getTenants(); @@ -219,14 +220,14 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl lock.writeLock().unlock(); logger.debug(EELFLoggerDelegate.debugLogger, "cacheTenants end"); } - + @SuppressWarnings("unchecked") - @Scheduled(fixedDelay=3600000, initialDelay=360000) + @Scheduled(fixedDelay = 3600000, initialDelay = 360000) public void cacheDeploymentExecInfo() { logger.debug(EELFLoggerDelegate.debugLogger, "cacheDeploymentExecInfo begin"); ReadWriteLock lock = new ReentrantReadWriteLock(); lock.readLock().lock(); - List<CloudifyTenant> tenantItems = + List<CloudifyTenant> tenantItems = (List<CloudifyTenant>) getCacheManager().getObject(TENANTS); lock.readLock().unlock(); String cfyTen = ""; @@ -234,29 +235,29 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl for (CloudifyTenant item : tenantItems) { cfyTen = item.name; lock.readLock().lock(); - List<CloudifyDeployment> cfyDeplList = - (List<CloudifyDeployment>)getCacheManager(). - getObject(SERVICE_ID + ":" + cfyTen); - lock.readLock().unlock(); + List<CloudifyDeployment> cfyDeplList = (List<CloudifyDeployment>) getCacheManager() + .getObject(SERVICE_ID + ":" + cfyTen); + lock.readLock().unlock(); if (cfyDeplList != null) { - List<CloudifyDeploymentExt> cfyDeplExecList = + List<CloudifyDeploymentExt> cfyDeplExecList = this.updateWorkflowStatus(cfyDeplList); lock.writeLock().lock(); - getCacheManager().putObject(SERVICE_ID + ":" + cfyTen + ":ext", cfyDeplExecList); + getCacheManager().putObject(SERVICE_ID + ":" + cfyTen + ":ext", + cfyDeplExecList); lock.writeLock().unlock(); } } } logger.debug(EELFLoggerDelegate.debugLogger, "cacheDeploymentExecInfo end"); } - + @SuppressWarnings("unchecked") - @Scheduled(fixedDelay=3900000, initialDelay=600000) + @Scheduled(fixedDelay = 3900000, initialDelay = 600000) public void cacheDeploymentHelmInfo() { logger.debug(EELFLoggerDelegate.debugLogger, "cacheDeploymentHelmInfo begin"); ReadWriteLock lock = new ReentrantReadWriteLock(); lock.readLock().lock(); - List<CloudifyTenant> tenantItems = + List<CloudifyTenant> tenantItems = (List<CloudifyTenant>) getCacheManager().getObject(TENANTS); lock.readLock().unlock(); String cfyTen = ""; @@ -264,29 +265,28 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl for (CloudifyTenant item : tenantItems) { cfyTen = item.name; lock.readLock().lock(); - List<CloudifyDeployment> cfyDeplList = - (List<CloudifyDeployment>)getCacheManager(). - getObject(SERVICE_ID + ":" + cfyTen); + List<CloudifyDeployment> cfyDeplList = (List<CloudifyDeployment>) getCacheManager() + .getObject(SERVICE_ID + ":" + cfyTen); lock.readLock().unlock(); if (cfyDeplList != null) { - List<CloudifyDeploymentHelm> cfyDeplHelmList = - this.updateHelmInfo(cfyDeplList); + List<CloudifyDeploymentHelm> cfyDeplHelmList = this.updateHelmInfo(cfyDeplList); lock.writeLock().lock(); - getCacheManager().putObject(SERVICE_ID + ":" + cfyTen + ":helm", cfyDeplHelmList); - lock.writeLock().unlock(); + getCacheManager().putObject(SERVICE_ID + ":" + cfyTen + ":helm", + cfyDeplHelmList); + lock.writeLock().unlock(); } } } logger.debug(EELFLoggerDelegate.debugLogger, "cacheDeploymentHelmInfo end"); } - - @Scheduled(fixedDelay=300000, initialDelay=90000) + + @Scheduled(fixedDelay = 300000, initialDelay = 90000) public void cacheDeployments() { logger.debug(EELFLoggerDelegate.debugLogger, "cacheDeployments begin"); int pageSize = 500; ReadWriteLock lock = new ReentrantReadWriteLock(); lock.readLock().lock(); - List<CloudifyTenant> tenantItems = + List<CloudifyTenant> tenantItems = (List<CloudifyTenant>) getCacheManager().getObject(TENANTS); lock.readLock().unlock(); String cfyTen = "default_tenant"; @@ -309,8 +309,7 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl int deplPgOffset = 0; deplPgOffset += pageSize; while (deplPgOffset < totalItems) { - url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, new String[] { - "_include", + url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, new String[] {"_include", "id,blueprint_id,created_at,updated_at,created_by,description,tenant_name", "_sort", "-updated_at", "_sort", "-created_at", "_size", new Integer(pageSize).toString(), "_offset", @@ -325,179 +324,193 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl lock.writeLock().unlock(); } } - logger.debug(EELFLoggerDelegate.debugLogger, "cacheDeployments done putting deployment data"); + logger.debug(EELFLoggerDelegate.debugLogger, + "cacheDeployments done putting deployment data"); } @Override public CloudifyTenantList getTenants() { - String url = buildUrl(new String[] { baseUrl, TENANTS }, null); + String url = buildUrl(new String[] {baseUrl, TENANTS}, null); logger.debug(EELFLoggerDelegate.debugLogger, "getTenants: url {}", url); - ResponseEntity<CloudifyTenantList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<CloudifyTenantList>() { - }); + ResponseEntity<CloudifyTenantList> response = restTemplate.exchange(url, HttpMethod.GET, + null, new ParameterizedTypeReference<CloudifyTenantList>() {}); return response.getBody(); } @Override - public CloudifyEventList getEventlogs(String executionId, String tenant) { - String url = buildUrl(new String[] { baseUrl, EVENTS }, new String[] { "execution_id", executionId }); + public CloudifyEventList getEventlogs(String executionId, String tenant) + throws Exception { + String url = + buildUrl(new String[] {baseUrl, EVENTS}, new String[] {"execution_id", executionId}); logger.debug(EELFLoggerDelegate.debugLogger, "getEventlogs: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyEventList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyEventList>() { - }); + ResponseEntity<CloudifyEventList> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyEventList>() {}); return response.getBody(); } @Override - public CloudifyNodeInstanceIdList getNodeInstanceId(String deploymentId, String nodeId, String tenant) { - String url = buildUrl(new String[] { baseUrl, NODE_INSTANCES }, - new String[] { "deployment_id", deploymentId, "node_id", nodeId, "_include", "id" }); + public CloudifyNodeInstanceIdList getNodeInstanceId(String deploymentId, String nodeId, + String tenant) throws Exception { + String url = buildUrl(new String[] {baseUrl, NODE_INSTANCES}, + new String[] {"deployment_id", deploymentId, "node_id", nodeId, "_include", "id"}); logger.debug(EELFLoggerDelegate.debugLogger, "getNodeInstanceId: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyNodeInstanceIdList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyNodeInstanceIdList>() { - }); + ResponseEntity<CloudifyNodeInstanceIdList> response = + restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference<CloudifyNodeInstanceIdList>() {}); return response.getBody(); } @Override - public CloudifyNodeInstanceList getNodeInstanceDetails(String deploymentId, String tenant) { - String url = buildUrl(new String[] { baseUrl, NODE_INSTANCES }, - new String[] { "deployment_id", deploymentId}); + public CloudifyNodeInstanceList getNodeInstanceDetails(String deploymentId, String tenant) + throws Exception { + String url = buildUrl(new String[] {baseUrl, NODE_INSTANCES}, + new String[] {"deployment_id", deploymentId}); logger.debug(EELFLoggerDelegate.debugLogger, "getNodeInstanceDetails: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyNodeInstanceList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyNodeInstanceList>() { - }); + ResponseEntity<CloudifyNodeInstanceList> response = restTemplate.exchange(url, + HttpMethod.GET, entity, new ParameterizedTypeReference<CloudifyNodeInstanceList>() {}); return response.getBody(); } - + @Override - public CloudifyNodeInstanceIdList getNodeInstances(String deploymentId, String tenant) { - String url = buildUrl(new String[] { baseUrl, NODE_INSTANCES }, - new String[] { "deployment_id", deploymentId, "_include", "id" }); + public CloudifyNodeInstanceIdList getNodeInstances(String deploymentId, String tenant) + throws Exception { + String url = buildUrl(new String[] {baseUrl, NODE_INSTANCES}, + new String[] {"deployment_id", deploymentId, "_include", "id"}); logger.debug(EELFLoggerDelegate.debugLogger, "getNodeInstanceId: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyNodeInstanceIdList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyNodeInstanceIdList>() { - }); + ResponseEntity<CloudifyNodeInstanceIdList> response = + restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference<CloudifyNodeInstanceIdList>() {}); return response.getBody(); } @Override - public CloudifyNodeInstanceList getNodeInstanceVersion(String deploymentId, String nodeId, String tenant) { - String url = buildUrl(new String[] { baseUrl, NODE_INSTANCES }, - new String[] { "deployment_id", deploymentId, "node_id", nodeId, "_include", "runtime_properties,id" }); + public CloudifyNodeInstanceList getNodeInstanceVersion(String deploymentId, String nodeId, + String tenant) throws Exception { + String url = buildUrl(new String[] {baseUrl, NODE_INSTANCES}, new String[] {"deployment_id", + deploymentId, "node_id", nodeId, "_include", "runtime_properties,id"}); logger.debug(EELFLoggerDelegate.debugLogger, "getNodeInstanceVersion: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyNodeInstanceList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyNodeInstanceList>() { - }); + ResponseEntity<CloudifyNodeInstanceList> response = restTemplate.exchange(url, + HttpMethod.GET, entity, new ParameterizedTypeReference<CloudifyNodeInstanceList>() {}); return response.getBody(); } @Override - public CloudifyNodeInstanceList getNodeInstanceVersion(String bpId, String tenant) { - String url = buildUrl(new String[] { baseUrl, NODES }, - new String[] { "deployment_id", bpId, "type", "onap.nodes.component", "_include", "id" }); + public CloudifyNodeInstanceList getNodeInstanceVersion(String bpId, String tenant) + throws Exception { + 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, - new ParameterizedTypeReference<CloudifyNodeIdList>() { - }); + ResponseEntity<CloudifyNodeIdList> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyNodeIdList>() {}); CloudifyNodeIdList result = response.getBody(); String nodeId = result.items.get(0).id; return getNodeInstanceVersion(bpId, nodeId, tenant); } @Override - public CloudifyNodeInstanceIdList getNodeInstanceId(final String bpId, String tenant) { + public CloudifyNodeInstanceIdList getNodeInstanceId(final String bpId, String tenant) + throws Exception { 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, - new ParameterizedTypeReference<CloudifyNodeIdList>() { - }); + ResponseEntity<CloudifyNodeIdList> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyNodeIdList>() {}); CloudifyNodeIdList result = response.getBody(); String nodeId = result.items.get(0).id; return getNodeInstanceId(bpId, nodeId, tenant); } @Override - public CloudifyExecutionList getExecutions(final String deploymentId, final String tenant) { - String url = buildUrl(new String[] { baseUrl, EXECUTIONS }, new String[] { "deployment_id", deploymentId }); + public CloudifyExecutionList getExecutions(final String deploymentId, final String tenant) + throws Exception { + String url = buildUrl(new String[] {baseUrl, EXECUTIONS}, + new String[] {"deployment_id", deploymentId}); logger.debug(EELFLoggerDelegate.debugLogger, "getExecutions: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyExecutionList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyExecutionList>() { - }); + ResponseEntity<CloudifyExecutionList> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyExecutionList>() {}); return response.getBody(); } @Override - public CloudifyExecutionList getExecutionsSummary(final String deploymentId, final String tenant) { - String url = buildUrl(new String[] { baseUrl, EXECUTIONS }, new String[] { "deployment_id", deploymentId, - "_include", "deployment_id,id,status,workflow_id,tenant_name,created_at,ended_at", "_sort", "-created_at" }); + public CloudifyExecutionList getExecutionsSummary(final String deploymentId, + final String tenant) throws Exception { + String url = buildUrl(new String[] {baseUrl, EXECUTIONS}, + new String[] {"deployment_id", deploymentId, "_include", + "deployment_id,id,status,workflow_id,tenant_name,created_at,ended_at", "_sort", + "-created_at"}); logger.debug(EELFLoggerDelegate.debugLogger, "getExecutions: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyExecutionList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyExecutionList>() { - }); + ResponseEntity<CloudifyExecutionList> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyExecutionList>() {}); return response.getBody(); } @Override - public CloudifyExecutionList getExecutionsSummaryPerTenant(final String tenant) { - String url = buildUrl(new String[] { baseUrl, EXECUTIONS }, new String[] { - "_include","deployment_id,id,status,workflow_id,tenant_name,created_at,ended_at", "_sort", "-created_at" }); + public CloudifyExecutionList getExecutionsSummaryPerTenant(final String tenant) + throws Exception { + String url = buildUrl(new String[] {baseUrl, EXECUTIONS}, + new String[] {"_include", + "deployment_id,id,status,workflow_id,tenant_name,created_at,ended_at", "_sort", + "-created_at"}); logger.debug(EELFLoggerDelegate.debugLogger, "getExecutionsSummaryPerTenant: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyExecutionList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyExecutionList>() { - }); + ResponseEntity<CloudifyExecutionList> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyExecutionList>() {}); return response.getBody(); } - public CloudifyExecution getExecutionIdSummary(final String id, final String tenant) { - String url = buildUrl(new String[] { baseUrl, EXECUTIONS, id }, new String[] { - "_include","deployment_id,id,status,workflow_id,tenant_name,created_at,ended_at", "_sort", "-created_at" }); + public CloudifyExecution getExecutionIdSummary(final String id, final String tenant) + throws Exception { + String url = buildUrl(new String[] {baseUrl, EXECUTIONS, id}, + new String[] {"_include", + "deployment_id,id,status,workflow_id,tenant_name,created_at,ended_at", "_sort", + "-created_at"}); logger.debug(EELFLoggerDelegate.debugLogger, "getExecutionIdSummary: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyExecution> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyExecution>() { - }); + ResponseEntity<CloudifyExecution> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyExecution>() {}); return response.getBody(); } - + @Override - public CloudifyExecutionList getInstallExecutionSummary(final String deploymentId, final String tenant) { - String url = buildUrl(new String[] { baseUrl, EXECUTIONS }, new String[] { "deployment_id", deploymentId, - "workflow_id", "install", "_include", "deployment_id,id,status,workflow_id,tenant_name,created_at" }); + public CloudifyExecutionList getInstallExecutionSummary(final String deploymentId, + final String tenant) { + String url = buildUrl(new String[] {baseUrl, EXECUTIONS}, + new String[] {"deployment_id", deploymentId, "workflow_id", "install", "_include", + "deployment_id,id,status,workflow_id,tenant_name,created_at"}); logger.debug(EELFLoggerDelegate.debugLogger, "getExecutions: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyExecutionList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyExecutionList>() { - }); + ResponseEntity<CloudifyExecutionList> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyExecutionList>() {}); return response.getBody(); } - + @Override - public CloudifyExecution startExecution(CloudifyExecutionRequest execution) { - String url = buildUrl(new String[] { baseUrl, EXECUTIONS }, null); + public CloudifyExecution startExecution(CloudifyExecutionRequest execution) + throws Exception { + String url = buildUrl(new String[] {baseUrl, EXECUTIONS}, null); logger.debug(EELFLoggerDelegate.debugLogger, "startExecution: url {}", url); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Tenant", execution.tenant); - HttpEntity<CloudifyExecutionRequest> entity = new HttpEntity<CloudifyExecutionRequest>(execution, headers); + HttpEntity<CloudifyExecutionRequest> entity = + new HttpEntity<CloudifyExecutionRequest>(execution, headers); return restTemplate.postForObject(url, entity, CloudifyExecution.class); } @Override - public CloudifyExecution cancelExecution(final String executionId, Map<String, String> parameters, - final String tenant) { - String url = buildUrl(new String[] { baseUrl, EXECUTIONS, executionId }, null); + public CloudifyExecution cancelExecution(final String executionId, + Map<String, String> parameters, final String tenant) + throws Exception { + String url = buildUrl(new String[] {baseUrl, EXECUTIONS, executionId}, null); logger.debug(EELFLoggerDelegate.debugLogger, "deleteExecution: url {}", url); JSONObject requestJson = new JSONObject(parameters); @@ -512,68 +525,69 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl } @Override - public CloudifyBlueprintList getBlueprint(final String id, String tenant) { - String url = buildUrl(new String[] { baseUrl, BLUEPRINTS }, new String[] { "id", id }); + public CloudifyBlueprintList getBlueprint(final String id, String tenant) + throws Exception { + String url = buildUrl(new String[] {baseUrl, BLUEPRINTS}, new String[] {"id", id}); logger.debug(EELFLoggerDelegate.debugLogger, "getBlueprint: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyBlueprintList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyBlueprintList>() { - }); + ResponseEntity<CloudifyBlueprintList> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyBlueprintList>() {}); return response.getBody(); } @Override - public byte[] viewBlueprint(String tenant, final String id) { - String url = buildUrl(new String[] { baseUrl, BLUEPRINTS, id, "archive" }, null); + public byte[] viewBlueprint(String tenant, final String id) + throws Exception { + String url = buildUrl(new String[] {baseUrl, BLUEPRINTS, id, "archive"}, null); logger.debug(EELFLoggerDelegate.debugLogger, "viewBlueprint: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<byte[]> response = + ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class); if (response.getStatusCode() == HttpStatus.OK) { return response.getBody(); } return null; } - + @Override - public List<CloudifyDeployment> getDeployments(String tenant, int pageSize, int pageOffset, boolean recurse) { + public List<CloudifyDeployment> getDeployments(String tenant, int pageSize, int pageOffset, + boolean recurse) { return this.getDeployments(tenant, pageSize, pageOffset, true, true); } - + @SuppressWarnings("unchecked") @Override - public List<CloudifyDeployment> getDeployments(String tenant, int pageSize, int pageOffset, boolean recurse, boolean cache) { + public List<CloudifyDeployment> getDeployments(String tenant, int pageSize, int pageOffset, + boolean recurse, boolean cache) { List<CloudifyDeployment> cfyDeplList = null; if (cache) { - cfyDeplList = - (List<CloudifyDeployment>)getCacheManager().getObject(SERVICE_ID + ":" + tenant); + cfyDeplList = + (List<CloudifyDeployment>) getCacheManager().getObject(SERVICE_ID + ":" + tenant); } if (cfyDeplList == null || cfyDeplList.isEmpty()) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, - new String[] { "_include", "id,blueprint_id,created_at,updated_at,created_by,description,tenant_name", - "_sort","-updated_at", "_sort", "-created_at", - "_size", new Integer(pageSize).toString(), - "_offset" , new Integer(pageOffset).toString()}); + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, new String[] {"_include", + "id,blueprint_id,created_at,updated_at,created_by,description,tenant_name", "_sort", + "-updated_at", "_sort", "-created_at", "_size", new Integer(pageSize).toString(), + "_offset", new Integer(pageOffset).toString()}); logger.debug(EELFLoggerDelegate.debugLogger, "getDeployments: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyDeploymentList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyDeploymentList>() { - }); + ResponseEntity<CloudifyDeploymentList> response = + restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference<CloudifyDeploymentList>() {}); cfyDeplList = new ArrayList<CloudifyDeployment>(); cfyDeplList.addAll(response.getBody().items); if (recurse) { - int totalItems = (int)response.getBody().metadata.pagination.total; + int totalItems = (int) response.getBody().metadata.pagination.total; int deplPgOffset = 0; deplPgOffset += pageSize; while (deplPgOffset < totalItems) { - url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, - new String[] { "_include", "id,blueprint_id,created_at,updated_at,created_by,description,tenant_name", - "_sort","-updated_at", "_sort", "-created_at", - "_size", new Integer(pageSize).toString(), - "_offset" , new Integer(deplPgOffset).toString()}); + url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, new String[] {"_include", + "id,blueprint_id,created_at,updated_at,created_by,description,tenant_name", + "_sort", "-updated_at", "_sort", "-created_at", "_size", + new Integer(pageSize).toString(), "_offset", + new Integer(deplPgOffset).toString()}); response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyDeploymentList>() { - }); + new ParameterizedTypeReference<CloudifyDeploymentList>() {}); deplPgOffset += pageSize; cfyDeplList.addAll(response.getBody().items); } @@ -581,54 +595,51 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl } return cfyDeplList; } - + public CloudifyDeploymentList getDeployments(String tenant, int pageSize, int pageOffset) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, - new String[] { "_include", "id,blueprint_id,created_at,updated_at,created_by,description", - "_sort","-updated_at", "_sort", "-created_at", - "_size", new Integer(pageSize).toString(), - "_offset" , new Integer(pageOffset).toString()}); + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, + new String[] {"_include", + "id,blueprint_id,created_at,updated_at,created_by,description", "_sort", + "-updated_at", "_sort", "-created_at", "_size", new Integer(pageSize).toString(), + "_offset", new Integer(pageOffset).toString()}); logger.debug(EELFLoggerDelegate.debugLogger, "getDeployments: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyDeploymentList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyDeploymentList>() { - }); + ResponseEntity<CloudifyDeploymentList> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyDeploymentList>() {}); return response.getBody(); } - + @Override - public List<CloudifyDeployment> getDeploymentsByInputFilter(String inputKey, String inputValue) throws Exception { - JSONObject inputObject = new JSONObject() - .put("inputKey", inputKey) - .put("inputValue", inputValue); - String filter = new JSONObject() - .put("input", inputObject) - .toString(); - return getDeploymentsWithFilter(null, filter); + public List<CloudifyDeployment> getDeploymentsByInputFilter(String inputKey, String inputValue) + throws Exception { + JSONObject inputObject = + new JSONObject().put("inputKey", inputKey).put("inputValue", inputValue); + String filter = new JSONObject().put("input", inputObject).toString(); + return getDeploymentsWithFilter(null, filter); } - + @SuppressWarnings("unchecked") @Override - public List<String> getDeploymentNamesWithFilter(HttpServletRequest request) - throws Exception { + public List<String> getDeploymentNamesWithFilter(HttpServletRequest request) throws Exception { List<CloudifyDeployment> itemList = this.getDeploymentsWithFilter(request); Set<String> svcIdList = new HashSet<String>(); if (itemList != null) { - svcIdList = - (Set) itemList.stream().map(x -> ((CloudifyDeployment)x).id).collect(Collectors.toSet()); + svcIdList = (Set) itemList.stream().map(x -> ((CloudifyDeployment) x).id) + .collect(Collectors.toSet()); } List<String> response = new ArrayList<String>(); response.addAll(svcIdList); return response; } - + @SuppressWarnings("unchecked") @Override - public List<CloudifyDeployment> getDeploymentsWithFilter(HttpServletRequest request) throws Exception { + public List<CloudifyDeployment> getDeploymentsWithFilter(HttpServletRequest request) + throws Exception { String filters = request.getParameter("filters"); List<CloudifyDeployment> deployments = new ArrayList<CloudifyDeployment>(); - if (filters != null) { + if (filters != null) { deployments = getDeploymentsWithFilter(request, filters); } else { List<CloudifyTenant> selectedTenants = new ArrayList<CloudifyTenant>(); @@ -638,137 +649,136 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl itemList = this.getDeployments(tenant.name, 500, 0, true); deployments.addAll(itemList); } - // apply user role based auth + // apply user role based auth Set<String> userApps = null; - Set<String> userRoleSet = null; + Set<String> userRoleSet = null; try { HttpSession session = AppUtils.getSession(request); userApps = (Set<String>) session.getAttribute("authComponents"); userRoleSet = (Set<String>) session.getAttribute("user_roles"); } catch (Exception e) { // requester is REST API - userRoleSet = (Set<String>)request.getAttribute("userRoles"); + userRoleSet = (Set<String>) request.getAttribute("userRoles"); userApps = (Set<String>) request.getAttribute("userApps"); } - + if (userApps == null) { userApps = new TreeSet<String>(); } - + if (userRoleSet == null) { userRoleSet = new TreeSet<String>(); } - + Predicate<String> adminPred = p -> p.contains("System_Administrator") || p.contains("Write_Access"); Predicate<String> ecompSuperPred = p -> p.contains("ECOMPC_WRITE") || p.contains("ECOMPC_READ"); - + if (userRoleSet.size() > 0) { if (userRoleSet.stream().noneMatch(adminPred)) { List<String> myApps = new ArrayList(userApps); if (userRoleSet.stream().noneMatch(ecompSuperPred)) { - deployments = (List<CloudifyDeployment>) deployments.stream().filter(s -> myApps.stream() - .anyMatch(roleFilter -> ((CloudifyDeployment)s).id.toLowerCase().startsWith(roleFilter))) - .collect(Collectors.toList()); + deployments = + (List<CloudifyDeployment>) deployments.stream() + .filter(s -> myApps.stream() + .anyMatch(roleFilter -> ((CloudifyDeployment) s).id + .toLowerCase().startsWith(roleFilter))) + .collect(Collectors.toList()); } else { - Predicate<CloudifyDeployment> appFilter = - p -> p.id.toLowerCase().indexOf("dcae") == -1 || p.id.toLowerCase().indexOf("d2a") == -1; - deployments = (List<CloudifyDeployment>) deployments.stream().filter(appFilter) - .collect(Collectors.toList()); + Predicate<CloudifyDeployment> appFilter = + p -> p.id.toLowerCase().indexOf("dcae") == -1 + || p.id.toLowerCase().indexOf("d2a") == -1; + deployments = (List<CloudifyDeployment>) deployments.stream() + .filter(appFilter).collect(Collectors.toList()); } } } } return deployments; } - + @Override - public List<CloudifyDeployment> getDeploymentsWithFilter(HttpServletRequest request, String filter) - throws Exception { - String url = ""; - JSONObject filterJson = new JSONObject(filter); + public List<CloudifyDeployment> getDeploymentsWithFilter(HttpServletRequest request, + String filter) throws Exception { + String url = ""; + JSONObject filterJson = new JSONObject(filter); ReadWriteLock lock = new ReentrantReadWriteLock(); - - //---------Handle Tenant filter---------// - List<CloudifyTenant> selectedTenants = new ArrayList<CloudifyTenant>(); - if (filterJson.has("tenant")) { - String tenantFilterString = ""; - Object tenantObject = filterJson.get("tenant"); - - //Check for logic operators - if (tenantObject instanceof JSONObject) { - JSONObject tenantJsonObject = filterJson.getJSONObject("tenant"); - if (tenantJsonObject.has("$not")) { - tenantFilterString = tenantJsonObject.getString("$not"); - selectedTenants = tenantFilter(tenantFilterString, true); - } - else { - throw new Exception("ERROR: Not a valid logic operator"); - } - } - else if (tenantObject instanceof String) { - tenantFilterString = filterJson.getString("tenant"); - selectedTenants = tenantFilter(tenantFilterString, false); - } - } - else { - selectedTenants = getTenants().items; - } - //---------Get Deployments based on tenants selected---------// - List<CloudifyDeployment> deployments = new ArrayList<CloudifyDeployment>(); - List<CloudifyDeployment> itemList = null; + + // ---------Handle Tenant filter---------// + List<CloudifyTenant> selectedTenants = new ArrayList<CloudifyTenant>(); + if (filterJson.has("tenant")) { + String tenantFilterString = ""; + Object tenantObject = filterJson.get("tenant"); + + // Check for logic operators + if (tenantObject instanceof JSONObject) { + JSONObject tenantJsonObject = filterJson.getJSONObject("tenant"); + if (tenantJsonObject.has("$not")) { + tenantFilterString = tenantJsonObject.getString("$not"); + selectedTenants = tenantFilter(tenantFilterString, true); + } else { + throw new Exception("ERROR: Not a valid logic operator"); + } + } else if (tenantObject instanceof String) { + tenantFilterString = filterJson.getString("tenant"); + selectedTenants = tenantFilter(tenantFilterString, false); + } + } else { + selectedTenants = getTenants().items; + } + // ---------Get Deployments based on tenants selected---------// + List<CloudifyDeployment> deployments = new ArrayList<CloudifyDeployment>(); + List<CloudifyDeployment> itemList = null; HttpEntity<String> entity; - String tenantFilterStr = ""; + String tenantFilterStr = ""; int pageSize = 500; - - //---------Handle the _include filter---------// - String include = filterJson.has("_include") ? filterJson.getString("_include") : null; + + // ---------Handle the _include filter---------// + String include = filterJson.has("_include") ? filterJson.getString("_include") : null; for (CloudifyTenant tenant : selectedTenants) { - tenantFilterStr = tenant.name; - lock.readLock().lock(); - itemList = - (List<CloudifyDeployment>)getCacheManager(). - getObject("service-list" + ":" + tenantFilterStr); - lock.readLock().unlock(); - - if (itemList == null || include != null) { - if (include == null || include.isEmpty()) { - include = "id,blueprint_id,created_at,updated_at,created_by,description,tenant_name"; - } - url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, new String[] {"_include", - include,"_sort", "-updated_at", "_sort", "-created_at", "_size", - new Integer(pageSize).toString(), "_offset", new Integer(0).toString()}); + tenantFilterStr = tenant.name; + lock.readLock().lock(); + itemList = (List<CloudifyDeployment>) getCacheManager() + .getObject("service-list" + ":" + tenantFilterStr); + lock.readLock().unlock(); - logger.debug(EELFLoggerDelegate.debugLogger, "getDeployments: url {}", url); - - entity = getTenantHeader(tenant.name); - ResponseEntity<CloudifyDeploymentList> response = - restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyDeploymentList>() { - }); - deployments.addAll(response.getBody().items); - int totalItems = (int) response.getBody().metadata.pagination.total; - int deplPgOffset = 0; - deplPgOffset += pageSize; - while (deplPgOffset < totalItems) { - url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, new String[] { - "_include", - include, - "_sort", "-updated_at", "_sort", "-created_at", "_size", - new Integer(pageSize).toString(), "_offset", - new Integer(deplPgOffset).toString()}); - response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyDeploymentList>() {}); - deplPgOffset += pageSize; - deployments.addAll(response.getBody().items); - } - } else { - deployments.addAll(itemList); + if (itemList == null || include != null) { + if (include == null || include.isEmpty()) { + include = + "id,blueprint_id,created_at,updated_at,created_by,description,tenant_name"; } - } - // apply user role based auth + url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, + new String[] {"_include", include, "_sort", "-updated_at", "_sort", + "-created_at", "_size", new Integer(pageSize).toString(), "_offset", + new Integer(0).toString()}); + + logger.debug(EELFLoggerDelegate.debugLogger, "getDeployments: url {}", url); + + entity = getTenantHeader(tenant.name); + ResponseEntity<CloudifyDeploymentList> response = + restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference<CloudifyDeploymentList>() {}); + deployments.addAll(response.getBody().items); + int totalItems = (int) response.getBody().metadata.pagination.total; + int deplPgOffset = 0; + deplPgOffset += pageSize; + while (deplPgOffset < totalItems) { + url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, + new String[] {"_include", include, "_sort", "-updated_at", "_sort", + "-created_at", "_size", new Integer(pageSize).toString(), "_offset", + new Integer(deplPgOffset).toString()}); + response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference<CloudifyDeploymentList>() {}); + deplPgOffset += pageSize; + deployments.addAll(response.getBody().items); + } + } else { + deployments.addAll(itemList); + } + } + // apply user role based auth Set<String> userRoleSet = (Set<String>) request.getAttribute("userRoles"); Set<String> userApps = (Set<String>) request.getAttribute("userApps"); @@ -777,290 +787,299 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl Predicate<String> ecompSuperPred = p -> p.contains("ECOMPC_WRITE") || p.contains("ECOMPC_READ"); - + if (userRoleSet.stream().noneMatch(adminPred)) { if (userRoleSet.stream().noneMatch(ecompSuperPred)) { - deployments = (List<CloudifyDeployment>) deployments.stream().filter(s -> userApps - .stream() - .anyMatch(appFilter -> (((CloudifyDeployment) s).id.toLowerCase().indexOf(appFilter) == 0))) + deployments = (List<CloudifyDeployment>) deployments.stream() + .filter(s -> userApps.stream() + .anyMatch(appFilter -> (((CloudifyDeployment) s).id.toLowerCase() + .indexOf(appFilter) == 0))) .collect(Collectors.<CloudifyDeployment>toList()); } else { - Predicate<CloudifyDeployment> appFilter = p -> p.id.toLowerCase().indexOf("dcae") == -1; + Predicate<CloudifyDeployment> appFilter = + p -> p.id.toLowerCase().indexOf("dcae") == -1; deployments = (List<CloudifyDeployment>) deployments.stream().filter(appFilter) .collect(Collectors.toList()); } } List<CloudifyDeployment> filteredDeployments = deployments; - //-------------------ServiceId Filter-------------------// - if (filterJson.has("serviceId")) { - String serviceIdFilterString; - Object serviceIdObject = filterJson.get("serviceId"); - - //Check for logic operators - if (serviceIdObject instanceof JSONObject) { - JSONObject serviceIdJsonObject = filterJson.getJSONObject("serviceId"); - if (serviceIdJsonObject.has("$not")) { - serviceIdFilterString = serviceIdJsonObject.getString("$not"); - filteredDeployments = serviceIdFilter(serviceIdFilterString, filteredDeployments, true); - } - else { - throw new Exception("ERROR: Not a valid logic operator"); - } - } - else if (serviceIdObject instanceof String) { - serviceIdFilterString = filterJson.getString("serviceId"); - filteredDeployments = serviceIdFilter(serviceIdFilterString, filteredDeployments, false); - } - } - - //------------------Handle Input Filter--------------// - if (filterJson.has("input")) { - JSONObject inputFilterObject; - Object inputObject = filterJson.get("input"); - - //Check for logic operators - if (inputObject instanceof JSONObject) { - JSONObject inputJsonObject = filterJson.getJSONObject("input"); - if (inputJsonObject.has("$not")) { - inputFilterObject = inputJsonObject.getJSONObject("$not"); - filteredDeployments = inputFilter(inputFilterObject, filteredDeployments, true); - } - //If no operators, pass to filter func - else { - inputFilterObject = inputJsonObject; - filteredDeployments = inputFilter(inputFilterObject, filteredDeployments, false); - } - } - } - - //-------------------Install Status Filter-------------------// - if (filterJson.has("installStatus")) { - String installStatusFilterString; - Object installStatusObject = filterJson.get("installStatus"); - - //Check for logic operators - if (installStatusObject instanceof JSONObject) { - JSONObject installStatusJsonObject = filterJson.getJSONObject("installStatus"); - if (installStatusJsonObject.has("$not")) { - installStatusFilterString = installStatusJsonObject.getString("$not"); - filteredDeployments = installStatusFilter(installStatusFilterString, filteredDeployments, true); - } - else { - throw new Exception("ERROR: Not a valid logic operator"); - } - } - else if (installStatusObject instanceof String) { - installStatusFilterString = filterJson.getString("installStatus"); - filteredDeployments = installStatusFilter(installStatusFilterString, filteredDeployments, false); - } - } - - //-------------------isHelm Filter-------------------// - if (filterJson.has("isHelm")) { - String helmFilterString; - Object helmObject = filterJson.get("isHelm"); - - //Check for logic operators - if (helmObject instanceof JSONObject) { - JSONObject helmJsonObject = filterJson.getJSONObject("isHelm"); - if (helmJsonObject.has("$not")) { - helmFilterString = helmJsonObject.getString("$not"); - filteredDeployments = helmFilter(helmFilterString, filteredDeployments, true); - } - else { - throw new Exception("ERROR: Not a valid logic operator"); - } - } - else if (helmObject instanceof String) { - helmFilterString = filterJson.getString("isHelm"); - filteredDeployments = helmFilter(helmFilterString, filteredDeployments, false); - } - } - //CloudifyDeploymentList filteredDepList = new CloudifyDeploymentList(filteredDeployments, null); + // -------------------ServiceId Filter-------------------// + if (filterJson.has("serviceId")) { + String serviceIdFilterString; + Object serviceIdObject = filterJson.get("serviceId"); + + // Check for logic operators + if (serviceIdObject instanceof JSONObject) { + JSONObject serviceIdJsonObject = filterJson.getJSONObject("serviceId"); + if (serviceIdJsonObject.has("$not")) { + serviceIdFilterString = serviceIdJsonObject.getString("$not"); + filteredDeployments = + serviceIdFilter(serviceIdFilterString, filteredDeployments, true); + } else { + throw new Exception("ERROR: Not a valid logic operator"); + } + } else if (serviceIdObject instanceof String) { + serviceIdFilterString = filterJson.getString("serviceId"); + filteredDeployments = + serviceIdFilter(serviceIdFilterString, filteredDeployments, false); + } + } + + // ------------------Handle Input Filter--------------// + if (filterJson.has("input")) { + JSONObject inputFilterObject; + Object inputObject = filterJson.get("input"); + + // Check for logic operators + if (inputObject instanceof JSONObject) { + JSONObject inputJsonObject = filterJson.getJSONObject("input"); + if (inputJsonObject.has("$not")) { + inputFilterObject = inputJsonObject.getJSONObject("$not"); + filteredDeployments = inputFilter(inputFilterObject, filteredDeployments, true); + } + // If no operators, pass to filter func + else { + inputFilterObject = inputJsonObject; + filteredDeployments = + inputFilter(inputFilterObject, filteredDeployments, false); + } + } + } + + // -------------------Install Status Filter-------------------// + if (filterJson.has("installStatus")) { + String installStatusFilterString; + Object installStatusObject = filterJson.get("installStatus"); + + // Check for logic operators + if (installStatusObject instanceof JSONObject) { + JSONObject installStatusJsonObject = filterJson.getJSONObject("installStatus"); + if (installStatusJsonObject.has("$not")) { + installStatusFilterString = installStatusJsonObject.getString("$not"); + filteredDeployments = + installStatusFilter(installStatusFilterString, filteredDeployments, true); + } else { + throw new Exception("ERROR: Not a valid logic operator"); + } + } else if (installStatusObject instanceof String) { + installStatusFilterString = filterJson.getString("installStatus"); + filteredDeployments = + installStatusFilter(installStatusFilterString, filteredDeployments, false); + } + } + + // -------------------isHelm Filter-------------------// + if (filterJson.has("isHelm")) { + String helmFilterString; + Object helmObject = filterJson.get("isHelm"); + + // Check for logic operators + if (helmObject instanceof JSONObject) { + JSONObject helmJsonObject = filterJson.getJSONObject("isHelm"); + if (helmJsonObject.has("$not")) { + helmFilterString = helmJsonObject.getString("$not"); + filteredDeployments = helmFilter(helmFilterString, filteredDeployments, true); + } else { + throw new Exception("ERROR: Not a valid logic operator"); + } + } else if (helmObject instanceof String) { + helmFilterString = filterJson.getString("isHelm"); + filteredDeployments = helmFilter(helmFilterString, filteredDeployments, false); + } + } return filteredDeployments; } - + /* * Helper function to handle the tenant filter */ private List<CloudifyTenant> tenantFilter(String filterString, boolean isNot) throws Exception { - CloudifyTenantList availableTenants = getTenants(); - List<CloudifyTenant> selectedTenants = new ArrayList<CloudifyTenant>(); - - //If using tenant filter, verify its valid tenant name - if (filterString != null && !filterString.isEmpty()) { - for (CloudifyTenant tenant : availableTenants.items) { - if (!isNot && tenant.name.equals(filterString)) { - selectedTenants.add(tenant); - } - else if (isNot && !tenant.name.equals(filterString)) { - selectedTenants.add(tenant); - } + CloudifyTenantList availableTenants = getTenants(); + List<CloudifyTenant> selectedTenants = new ArrayList<CloudifyTenant>(); + + // If using tenant filter, verify its valid tenant name + if (filterString != null && !filterString.isEmpty()) { + for (CloudifyTenant tenant : availableTenants.items) { + if (!isNot && tenant.name.equals(filterString)) { + selectedTenants.add(tenant); + } else if (isNot && !tenant.name.equals(filterString)) { + selectedTenants.add(tenant); + } } - if (selectedTenants.isEmpty()) { - throw new Exception("ERROR: Tenant filter was used but resulted in no selected tenants"); - } - } - //If no proper tenants given - else { - throw new Exception("ERROR: Tenant filter was used but no tenants were given"); - } - return selectedTenants; + if (selectedTenants.isEmpty()) { + throw new Exception( + "ERROR: Tenant filter was used but resulted in no selected tenants"); + } + } + // If no proper tenants given + else { + throw new Exception("ERROR: Tenant filter was used but no tenants were given"); + } + return selectedTenants; } - - + /* * Helper function to filter deployments by serviceId */ - private List<CloudifyDeployment> serviceIdFilter(String filterString, List<CloudifyDeployment> deployments, boolean isNot) throws Exception { - List<CloudifyDeployment> newFilteredDeployments = new ArrayList<CloudifyDeployment>(); + private List<CloudifyDeployment> serviceIdFilter(String filterString, + List<CloudifyDeployment> deployments, boolean isNot) throws Exception { + List<CloudifyDeployment> newFilteredDeployments = new ArrayList<CloudifyDeployment>(); if (filterString != null && !filterString.isEmpty()) { - for (CloudifyDeployment dep : deployments) { - if (!isNot && dep.id.contains(filterString)) - newFilteredDeployments.add(dep); - else if (isNot && !dep.id.contains(filterString)) - newFilteredDeployments.add(dep); - } - } - else { - throw new Exception("ERROR: Service ID filter was used but a valid serviceId String was not provided"); + for (CloudifyDeployment dep : deployments) { + if (!isNot && dep.id.contains(filterString)) + newFilteredDeployments.add(dep); + else if (isNot && !dep.id.contains(filterString)) + newFilteredDeployments.add(dep); + } + } else { + throw new Exception( + "ERROR: Service ID filter was used but a valid serviceId String was not provided"); } return newFilteredDeployments; } - - + /* * Helper function to filter deployments by input */ - private List<CloudifyDeployment> inputFilter(JSONObject filterJson, List<CloudifyDeployment> deployments, boolean isNot) throws Exception { - List<CloudifyDeployment> newFilteredDeployments = new ArrayList<CloudifyDeployment>(); - if (filterJson != null && filterJson.has("inputKey") && filterJson.has("inputValue") && - !filterJson.isNull("inputKey") && !filterJson.isNull("inputValue")) { - String inputKey = filterJson.getString("inputKey"); - String inputValue = filterJson.getString("inputValue"); - - ///For now, only allow the use of aaf_username and dcaeTargetType input key - if (!inputKey.equals("aaf_username") && !inputKey.equals("dcae_target_type")) - throw new Exception("ERROR: This input key is NOT supported"); - - //For each deployment, get the input keys that contain <inputKey> - //then check their value to see if it contains the desired <inputValue> - for (CloudifyDeployment dep : deployments) { - if (dep.inputs == null) - throw new Exception("ERROR: Deployment inputs not found, 'inputs' must be in the include filter for input filtering"); - Set<String> filteredDepInputKeys = dep.inputs.keySet().stream() - .filter(s -> s.contains(inputKey)).collect(Collectors.toSet()); - for (String filteredKey : filteredDepInputKeys) { - String value = dep.inputs.get(filteredKey).toString(); - if (!isNot && value.equals(inputValue)) { - newFilteredDeployments.add(dep); - break; - } - else if (isNot && !value.equals(inputValue)) { - newFilteredDeployments.add(dep); - break; - } - } - } - } - else { //If filter used but no valid KV found - throw new Exception("ERROR: Input filter was used but a valid inputKey and inputValue was not provided"); + private List<CloudifyDeployment> inputFilter(JSONObject filterJson, + List<CloudifyDeployment> deployments, boolean isNot) throws Exception { + List<CloudifyDeployment> newFilteredDeployments = new ArrayList<CloudifyDeployment>(); + if (filterJson != null && filterJson.has("inputKey") && filterJson.has("inputValue") + && !filterJson.isNull("inputKey") && !filterJson.isNull("inputValue")) { + String inputKey = filterJson.getString("inputKey"); + String inputValue = filterJson.getString("inputValue"); + + /// For now, only allow the use of aaf_username and dcaeTargetType input key + if (!inputKey.equals("aaf_username") && !inputKey.equals("dcae_target_type")) + throw new Exception("ERROR: This input key is NOT supported"); + + // For each deployment, get the input keys that contain <inputKey> + // then check their value to see if it contains the desired <inputValue> + for (CloudifyDeployment dep : deployments) { + if (dep.inputs == null) + throw new Exception( + "ERROR: Deployment inputs not found, 'inputs' must be in the include filter for input filtering"); + Set<String> filteredDepInputKeys = dep.inputs.keySet().stream() + .filter(s -> s.contains(inputKey)).collect(Collectors.toSet()); + for (String filteredKey : filteredDepInputKeys) { + String value = dep.inputs.get(filteredKey).toString(); + if (!isNot && value.equals(inputValue)) { + newFilteredDeployments.add(dep); + break; + } else if (isNot && !value.equals(inputValue)) { + newFilteredDeployments.add(dep); + break; + } + } + } + } else { // If filter used but no valid KV found + throw new Exception( + "ERROR: Input filter was used but a valid inputKey and inputValue was not provided"); } return newFilteredDeployments; } - + /* * Helper function to filter deployments by install status */ - private List<CloudifyDeployment> installStatusFilter(String filterString, List<CloudifyDeployment> deployments, boolean isNot) throws Exception { - List<CloudifyDeployment> newFilteredDeployments = new ArrayList<CloudifyDeployment>(); + private List<CloudifyDeployment> installStatusFilter(String filterString, + List<CloudifyDeployment> deployments, boolean isNot) throws Exception { + List<CloudifyDeployment> newFilteredDeployments = new ArrayList<CloudifyDeployment>(); if (filterString != null && !filterString.isEmpty()) { - - //For each deployment, get execution status and compare to filter - for (CloudifyDeployment dep : deployments) { - List<CloudifyExecution> executions = getInstallExecutionSummary(dep.id, dep.tenant_name).items; - if (executions.size() > 0) { - String status = executions.get(0).status; - if (!isNot && status.equals(filterString)) { - newFilteredDeployments.add(dep); - } - else if (isNot && !status.equals(filterString)) { - newFilteredDeployments.add(dep); - } - } - } - } - else { //If using filter but invalid install status given - throw new Exception("ERROR: Install Status filter was used but a valid installStatus String was not provided"); + + // For each deployment, get execution status and compare to filter + for (CloudifyDeployment dep : deployments) { + List<CloudifyExecution> executions = + getInstallExecutionSummary(dep.id, dep.tenant_name).items; + if (executions.size() > 0) { + String status = executions.get(0).status; + if (!isNot && status.equals(filterString)) { + newFilteredDeployments.add(dep); + } else if (isNot && !status.equals(filterString)) { + newFilteredDeployments.add(dep); + } + } + } + } else { // If using filter but invalid install status given + throw new Exception( + "ERROR: Install Status filter was used but a valid installStatus String was not provided"); } return newFilteredDeployments; } - + /* * Helper function to filter by isHelm */ - private List<CloudifyDeployment> helmFilter(String filterJson, List<CloudifyDeployment> deployments, boolean isNot) { - List<CloudifyDeployment> newFilteredDeployments = new ArrayList<CloudifyDeployment>(); + private List<CloudifyDeployment> helmFilter(String filterJson, + List<CloudifyDeployment> deployments, boolean isNot) + throws HttpStatusCodeException, Exception { + List<CloudifyDeployment> newFilteredDeployments = new ArrayList<CloudifyDeployment>(); if (filterJson != null && !filterJson.isEmpty()) { - - //For each deployment, get blueprint and see if it has helm plugin and compare to filter - for (CloudifyDeployment dep : deployments) { + + // For each deployment, get blueprint and see if it has helm plugin and compare to + // filter + for (CloudifyDeployment dep : deployments) { CloudifyBlueprintList bpList = getBlueprint(dep.blueprint_id, dep.tenant_name); - Map<String, Object> bpPlan = bpList.items.get(0).plan; + 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")) { - if (!isNot && (filterJson.equals("true") || filterJson.equals("True") || filterJson.equals("TRUE"))) - newFilteredDeployments.add(dep); - else if (isNot && (filterJson.equals("false") || filterJson.equals("False") || filterJson.equals("FALSE"))) - newFilteredDeployments.add(dep); - } - else - if (!isNot && (filterJson.equals("false") || filterJson.equals("False") || filterJson.equals("FALSE"))) - newFilteredDeployments.add(dep); - else if (isNot && (filterJson.equals("true") || filterJson.equals("True") || filterJson.equals("TRUE"))) - newFilteredDeployments.add(dep); - } - } - else { //If not using filter, just return original deployments - newFilteredDeployments = deployments; + if (!isNot && (filterJson.equals("true") || filterJson.equals("True") + || filterJson.equals("TRUE"))) + newFilteredDeployments.add(dep); + else if (isNot && (filterJson.equals("false") || filterJson.equals("False") + || filterJson.equals("FALSE"))) + newFilteredDeployments.add(dep); + } else if (!isNot && (filterJson.equals("false") || filterJson.equals("False") + || filterJson.equals("FALSE"))) + newFilteredDeployments.add(dep); + else if (isNot && (filterJson.equals("true") || filterJson.equals("True") + || filterJson.equals("TRUE"))) + newFilteredDeployments.add(dep); + } + } else { // If not using filter, just return original deployments + newFilteredDeployments = deployments; } return newFilteredDeployments; } @Override - public CloudifyDeploymentList getDeployment(final String id) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, new String[] { "id", id, "_all_tenants", "true" }); + public CloudifyDeploymentList getDeployment(final String id) + throws HttpStatusCodeException, Exception { + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, + new String[] {"id", id, "_all_tenants", "true"}); logger.debug(EELFLoggerDelegate.debugLogger, "getDeployment: url {}", url); - ResponseEntity<CloudifyDeploymentList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<CloudifyDeploymentList>() { - }); + ResponseEntity<CloudifyDeploymentList> response = restTemplate.exchange(url, HttpMethod.GET, + null, new ParameterizedTypeReference<CloudifyDeploymentList>() {}); return response.getBody(); } @Override - public CloudifyDeploymentList getDeployment(final String id, final String tenant) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, new String[] { "id", id}); + public CloudifyDeploymentList getDeployment(final String id, final String tenant) + throws Exception { + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, new String[] {"id", id}); logger.debug(EELFLoggerDelegate.debugLogger, "getDeployment: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - ResponseEntity<CloudifyDeploymentList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyDeploymentList>() { - }); + ResponseEntity<CloudifyDeploymentList> response = restTemplate.exchange(url, HttpMethod.GET, + entity, new ParameterizedTypeReference<CloudifyDeploymentList>() {}); return response.getBody(); } @Override - public CloudifyDeploymentList getDeploymentInputs(final String id, final String tenant) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, new String[] { "id", id, "_include", "inputs" }); + public CloudifyDeploymentList getDeploymentInputs(final String id, final String tenant) + throws Exception { + 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(); } - + /** * Get a cloudify secret * @@ -1068,12 +1087,11 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl */ @Override public CloudifySecret getSecret(String secretName, String tenant) { - String url = buildUrl(new String[] { baseUrl, SECRETS, secretName }, null); + String url = buildUrl(new String[] {baseUrl, SECRETS, secretName}, null); logger.debug(EELFLoggerDelegate.debugLogger, "getSecrets: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); ResponseEntity<CloudifySecret> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifySecret>() { - }); + new ParameterizedTypeReference<CloudifySecret>() {}); return response.getBody(); } @@ -1082,22 +1100,22 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl * * @return List<CloudifyPlugin> */ - public CloudifyPluginList getPlugins() { - String url = buildUrl(new String[] { baseUrl, PLUGINS }, null); + public CloudifyPluginList getPlugins() throws Exception { + String url = buildUrl(new String[] {baseUrl, PLUGINS}, null); logger.debug(EELFLoggerDelegate.debugLogger, "getPlugins: url {}", url); - ResponseEntity<CloudifyPluginList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<CloudifyPluginList>() { - }); + ResponseEntity<CloudifyPluginList> response = restTemplate.exchange(url, HttpMethod.GET, + null, new ParameterizedTypeReference<CloudifyPluginList>() {}); CloudifyPluginList result = response.getBody(); return result; } - + @Override - public void deleteBlueprint(String bpName, String tenant) { - String url = buildUrl(new String[] { baseUrl, BLUEPRINTS, bpName }, null); + public void deleteBlueprint(String bpName, String tenant) + throws Exception { + String url = buildUrl(new String[] {baseUrl, BLUEPRINTS, bpName}, null); logger.debug(EELFLoggerDelegate.debugLogger, "deleteBlueprint: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); - restTemplate.exchange(url, HttpMethod.DELETE, entity, new ParameterizedTypeReference<CloudifyBlueprint>() { - }); + restTemplate.exchange(url, HttpMethod.DELETE, entity, + new ParameterizedTypeReference<CloudifyBlueprint>() {}); } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulClient.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulClient.java index 90da400..7b393a3 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulClient.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/ConsulClient.java @@ -2,35 +2,33 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.rest; -import java.net.URL; import java.util.List; import org.onap.ccsdk.dashboard.model.consul.ConsulDatacenter; import org.onap.ccsdk.dashboard.model.consul.ConsulDeploymentHealth; -import org.onap.ccsdk.dashboard.model.consul.ConsulHealthServiceRegistration; import org.onap.ccsdk.dashboard.model.consul.ConsulNodeInfo; import org.onap.ccsdk.dashboard.model.consul.ConsulServiceHealth; import org.onap.ccsdk.dashboard.model.consul.ConsulServiceInfo; -import org.springframework.web.client.RestTemplate; +import org.springframework.web.client.HttpStatusCodeException; /** * Defines the interface of the Consul REST client. @@ -42,7 +40,7 @@ public interface ConsulClient { * * @return List of ConsulServiceHealth */ - public List<ConsulServiceInfo> getServices(String datacenter); + public List<ConsulServiceInfo> getServices(String datacenter) throws Exception; /** * Gets the status for the specified service on all nodes. @@ -50,24 +48,26 @@ public interface ConsulClient { * @param serviceName Service name * @return List of ConsulServiceHealth */ - public List<ConsulServiceHealth> getServiceHealth(String datacenter, String srvcName); - + public List<ConsulServiceHealth> getServiceHealth(String datacenter, String srvcName) + throws Exception; + /** * Gets the status for the service which corresponds to deployment Id on all nodes. - * Filters services on Consul to find services that contain service tag that + * Filters services on Consul to find services that contain service tag that * matches the given deployment id * * @param deploymentId Deployment Id * @return List of ConsulServiceHealth */ - public ConsulDeploymentHealth getServiceHealthByDeploymentId(String deploymentId); + public ConsulDeploymentHealth getServiceHealthByDeploymentId(String deploymentId) + throws Exception; /** * Gets all the nodes that are monitored by Consul. * * @return List of ConsulNodeHealth */ - public List<ConsulNodeInfo> getNodes(String datacenter); + public List<ConsulNodeInfo> getNodes(String datacenter) throws Exception; /** * Gets the status for all registered services running on the specified node. @@ -75,7 +75,8 @@ public interface ConsulClient { * @param nodeId Node ID * @return List of ConsulServiceHealth */ - public List<ConsulServiceHealth> getNodeServicesHealth(String datacenter, String nodeId); + public List<ConsulServiceHealth> getNodeServicesHealth(String datacenter, String nodeId) + throws Exception; /** * Gets all the data centers that are monitored by Consul. 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 911e342..bc9b6d1 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 @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.rest; import java.net.MalformedURLException; @@ -36,40 +36,30 @@ import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.json.JSONArray; -import org.json.JSONObject; +import org.onap.ccsdk.dashboard.exceptions.DashboardControllerException; import org.onap.ccsdk.dashboard.model.cloudify.CloudifySecret; -import org.onap.ccsdk.dashboard.model.cloudify.CloudifyTenantList; import org.onap.ccsdk.dashboard.model.consul.ConsulDatacenter; -import org.onap.ccsdk.dashboard.model.consul.ConsulHealthServiceRegistration; -import org.onap.ccsdk.dashboard.model.consul.ConsulHealthServiceRegistration.EndpointCheck; +import org.onap.ccsdk.dashboard.model.consul.ConsulDeploymentHealth; import org.onap.ccsdk.dashboard.model.consul.ConsulNodeInfo; import org.onap.ccsdk.dashboard.model.consul.ConsulServiceHealth; import org.onap.ccsdk.dashboard.model.consul.ConsulServiceInfo; -import org.onap.ccsdk.dashboard.model.consul.ConsulDeploymentHealth; 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; -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.HttpStatusCodeException; -import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; -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 String baseUrl; - private String consul_acl_token; - private HttpEntity<String> token_entity; + private String consulAclToken; + private HttpEntity<String> tokenEntity; private static final String API_VER = "v1"; private static final String CATALOG = "catalog"; @@ -78,16 +68,17 @@ public class ConsulRestClientImpl extends RestClientBase implements ConsulClient private static final String CHECKS = "checks"; private static final String STATE = "state"; private static final String ANY = "any"; + private static final String APP_PROP_PREFIX = "site.primary"; @PostConstruct - public void init() { - if (consul_acl_token == null || consul_acl_token.isEmpty()) { - consul_acl_token = getConsulAcl(); + public void init() throws DashboardControllerException { + if (consulAclToken == null || consulAclToken.isEmpty()) { + consulAclToken = getConsulAcl(); } - if (consul_acl_token != null && !consul_acl_token.isEmpty()) { - token_entity = getConsulTokenHeader(consul_acl_token); + if (consulAclToken != null && !consulAclToken.isEmpty()) { + tokenEntity = getConsulTokenHeader(consulAclToken); } - String webapiUrl = DashboardProperties.getControllerProperty("site.primary", + String webapiUrl = DashboardProperties.getControllerProperty(APP_PROP_PREFIX, DashboardProperties.SITE_SUBKEY_CONSUL_URL); if (webapiUrl == null) throw new IllegalArgumentException("Null URL not permitted"); @@ -96,7 +87,7 @@ public class ConsulRestClientImpl extends RestClientBase implements ConsulClient url = new URL(webapiUrl); baseUrl = url.toExternalForm(); } catch (MalformedURLException ex) { - throw new RuntimeException("Failed to parse URL", ex); + throw new DashboardControllerException("Failed to parse URL", ex); } String urlScheme = webapiUrl.split(":")[0]; if (restTemplate == null) { @@ -107,16 +98,16 @@ public class ConsulRestClientImpl extends RestClientBase implements ConsulClient protected String getConsulAcl() { return getConsulAcl(null); } - + protected String getConsulAcl(RestTemplate cfyRest) { - String acl_token = null; - String webapiUrl = DashboardProperties.getControllerProperty("site.primary", + String aclToken = null; + String webapiUrl = DashboardProperties.getControllerProperty(APP_PROP_PREFIX, DashboardProperties.SITE_SUBKEY_CLOUDIFY_URL); String cfyBaseUrl = ""; - if (webapiUrl != null) { - String user = DashboardProperties.getControllerProperty("site.primary", + if (webapiUrl != null) { + String user = DashboardProperties.getControllerProperty(APP_PROP_PREFIX, DashboardProperties.SITE_SUBKEY_CLOUDIFY_USERNAME); - String pass = DashboardProperties.getControllerProperty("site.primary", + String pass = DashboardProperties.getControllerProperty(APP_PROP_PREFIX, DashboardProperties.SITE_SUBKEY_CLOUDIFY_PASS); URL url = null; try { @@ -124,28 +115,28 @@ public class ConsulRestClientImpl extends RestClientBase implements ConsulClient cfyBaseUrl = url.toExternalForm(); String urlScheme = webapiUrl.split(":")[0]; if (cfyRest == null) { - cfyRest = - createCfyRestTemplate(url, user, pass, urlScheme); + cfyRest = createCfyRestTemplate(url, user, pass, urlScheme); } - String urlStr = buildUrl(new String[] { cfyBaseUrl, "secrets", "eom-dashboard-acl-token" }, null); + String urlStr = + buildUrl(new String[] {cfyBaseUrl, "secrets", "eom-dashboard-acl-token"}, null); logger.debug(EELFLoggerDelegate.debugLogger, "getAclSecret: url {}", urlStr); - ResponseEntity<CloudifySecret> response = cfyRest.exchange(urlStr, HttpMethod.GET, null, - new ParameterizedTypeReference<CloudifySecret>() { - }); - acl_token = response.getBody().getValue(); + ResponseEntity<CloudifySecret> response = cfyRest.exchange(urlStr, HttpMethod.GET, + null, new ParameterizedTypeReference<CloudifySecret>() {}); + aclToken = response.getBody().getValue(); } catch (MalformedURLException me) { - //throw new RuntimeException("Failed to parse URL", ex); - logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse URL - malformed" + me.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, + "Failed to parse URL - malformed" + me.getMessage()); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); - acl_token = ""; + aclToken = ""; } } - return acl_token; + return aclToken; } - - protected RestTemplate createCfyRestTemplate(URL url, String user, String pass, String urlScheme) throws Exception { + + protected RestTemplate createCfyRestTemplate(URL url, String user, String pass, + String urlScheme) throws Exception { RestTemplate restTempl = null; final HttpHost httpHost = new HttpHost(url.getHost(), url.getPort(), urlScheme); // Build a client with a credentials provider @@ -153,222 +144,214 @@ public class ConsulRestClientImpl extends RestClientBase implements ConsulClient if (user != null && pass != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(new AuthScope(httpHost), new UsernamePasswordCredentials(user, pass)); - httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build(); + credsProvider.setCredentials(new AuthScope(httpHost), + new UsernamePasswordCredentials(user, pass)); + httpClient = + HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build(); } else { httpClient = HttpClientBuilder.create().build(); } // Create request factory - HttpComponentsClientHttpRequestFactoryBasicAuth requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth( - httpHost); + HttpComponentsClientHttpRequestFactoryBasicAuth requestFactory = + new HttpComponentsClientHttpRequestFactoryBasicAuth(httpHost); requestFactory.setHttpClient(httpClient); restTempl = new RestTemplate(); restTempl.setRequestFactory(requestFactory); return restTempl; } - + /** * @param consul_acl_token the consul_acl_token to set */ - public void setConsul_acl_token(String consul_acl_token) { - this.consul_acl_token = consul_acl_token; + public void setConsulAclToken(String consulAclToken) { + this.consulAclToken = consulAclToken; } - + @Override - public List<ConsulServiceHealth> getServiceHealth(String dc, String srvc) { - String url = buildUrl(new String[] { baseUrl, API_VER, HEALTH, CHECKS, srvc }, new String[] { "dc", dc }); + public List<ConsulServiceHealth> getServiceHealth(String dc, String srvc) throws Exception { + String url = buildUrl(new String[] {baseUrl, API_VER, HEALTH, CHECKS, srvc}, + new String[] {"dc", dc}); logger.debug(EELFLoggerDelegate.debugLogger, "getServiceHealth: url {}", url); ResponseEntity<List<ConsulServiceHealth>> response = null; + List<ConsulServiceHealth> result = new ArrayList<>(); try { - response = restTemplate.exchange(url, HttpMethod.GET, token_entity, - new ParameterizedTypeReference<List<ConsulServiceHealth>>() { - }); + response = restTemplate.exchange(url, HttpMethod.GET, tokenEntity, + new ParameterizedTypeReference<List<ConsulServiceHealth>>() {}); } catch (HttpStatusCodeException e) { if (e.getStatusCode().value() == 403) { // update consul ACL token header and retry - consul_acl_token = getConsulAcl(); - if (consul_acl_token != null && !consul_acl_token.isEmpty()) { - token_entity = getConsulTokenHeader(consul_acl_token); - response = restTemplate.exchange(url, HttpMethod.GET, token_entity, - new ParameterizedTypeReference<List<ConsulServiceHealth>>() { - }); + consulAclToken = getConsulAcl(); + if (consulAclToken != null && !consulAclToken.isEmpty()) { + tokenEntity = getConsulTokenHeader(consulAclToken); + response = restTemplate.exchange(url, HttpMethod.GET, tokenEntity, + new ParameterizedTypeReference<List<ConsulServiceHealth>>() {}); } else { throw e; - } + } } } - if (!response.getBody().isEmpty()) { - return response.getBody(); - } else { - return null; + if (response != null && !response.getBody().isEmpty()) { + result = response.getBody(); } + return result; } - + @Override - public ConsulDeploymentHealth getServiceHealthByDeploymentId(String deploymentId) { - String url = buildUrl(new String[] { baseUrl, API_VER, HEALTH, STATE, ANY }, - new String[] {"filter", "ServiceTags contains " + "\"" + deploymentId + "\""}); + public ConsulDeploymentHealth getServiceHealthByDeploymentId(String deploymentId) + throws Exception { + String url = buildUrl(new String[] {baseUrl, API_VER, HEALTH, STATE, ANY}, + new String[] {"filter", "ServiceTags contains " + "\"" + deploymentId + "\""}); logger.debug(EELFLoggerDelegate.debugLogger, "getServiceHealthByDeploymentId: url {}", url); ResponseEntity<List<ConsulServiceHealth>> response = null; + ConsulDeploymentHealth result = null; try { - response = restTemplate.exchange(url, HttpMethod.GET, token_entity, - new ParameterizedTypeReference<List<ConsulServiceHealth>>() { - }); + response = restTemplate.exchange(url, HttpMethod.GET, tokenEntity, + new ParameterizedTypeReference<List<ConsulServiceHealth>>() {}); } catch (HttpStatusCodeException e) { if (e.getStatusCode().value() == 403) { // update consul ACL token header and retry - consul_acl_token = getConsulAcl(); - if (consul_acl_token != null && !consul_acl_token.isEmpty()) { - token_entity = getConsulTokenHeader(consul_acl_token); - response = restTemplate.exchange(url, HttpMethod.GET, token_entity, - new ParameterizedTypeReference<List<ConsulServiceHealth>>() { - }); + consulAclToken = getConsulAcl(); + if (consulAclToken != null && !consulAclToken.isEmpty()) { + tokenEntity = getConsulTokenHeader(consulAclToken); + response = restTemplate.exchange(url, HttpMethod.GET, tokenEntity, + new ParameterizedTypeReference<List<ConsulServiceHealth>>() {}); } else { throw e; - } + } } } - if (!response.getBody().isEmpty()) { - return new ConsulDeploymentHealth.Builder(response.getBody().get(0)).build(); - } else { - return null; + if (response != null && !response.getBody().isEmpty()) { + result = new ConsulDeploymentHealth.Builder(response.getBody().get(0)).build(); } + return result; } @Override - public List<ConsulServiceInfo> getServices(String dc) { - String url = buildUrl(new String[] { baseUrl, API_VER, CATALOG, SERVICES }, new String[] { "dc", dc }); + public List<ConsulServiceInfo> getServices(String dc) throws Exception { + String url = + buildUrl(new String[] {baseUrl, API_VER, CATALOG, SERVICES}, new String[] {"dc", dc}); logger.debug(EELFLoggerDelegate.debugLogger, "getServices: url {}", url); ResponseEntity<Map<String, Object>> response = null; + List<ConsulServiceInfo> result = new ArrayList<>(); try { - response = restTemplate.exchange(url, HttpMethod.GET, token_entity, - new ParameterizedTypeReference<Map<String, Object>>() { - }); + response = restTemplate.exchange(url, HttpMethod.GET, tokenEntity, + new ParameterizedTypeReference<Map<String, Object>>() {}); } catch (HttpStatusCodeException e) { if (e.getStatusCode().value() == 403) { // update consul ACL token header and retry - consul_acl_token = getConsulAcl(); - if (consul_acl_token != null && !consul_acl_token.isEmpty()) { - token_entity = getConsulTokenHeader(consul_acl_token); - response = restTemplate.exchange(url, HttpMethod.GET, token_entity, - new ParameterizedTypeReference<Map<String, Object>>() { - }); + consulAclToken = getConsulAcl(); + if (consulAclToken != null && !consulAclToken.isEmpty()) { + tokenEntity = getConsulTokenHeader(consulAclToken); + response = restTemplate.exchange(url, HttpMethod.GET, tokenEntity, + new ParameterizedTypeReference<Map<String, Object>>() {}); } else { throw e; - } + } } } - if (!response.getBody().isEmpty()) { + if (response != null && !response.getBody().isEmpty()) { Map<String, Object> serviceInfo = response.getBody(); - List<ConsulServiceInfo> list = new ArrayList<>(); for (Map.Entry<String, Object> entry : serviceInfo.entrySet()) { // Be defensive List<String> addrs = null; - if (entry.getValue() instanceof List<?>) + if (entry.getValue() instanceof List<?>) { addrs = (List<String>) entry.getValue(); - else + } + else { addrs = new ArrayList<>(); - list.add(new ConsulServiceInfo(entry.getKey(), addrs)); + } + result.add(new ConsulServiceInfo(entry.getKey(), addrs)); } - return list; - } else { - return null; } + return result; } @Override - public List<ConsulNodeInfo> getNodes(String dc) { - String url = buildUrl(new String[] { baseUrl, API_VER, CATALOG, "nodes" }, new String[] { "dc", dc }); + public List<ConsulNodeInfo> getNodes(String dc) throws Exception { + String url = + buildUrl(new String[] {baseUrl, API_VER, CATALOG, "nodes"}, new String[] {"dc", dc}); logger.debug(EELFLoggerDelegate.debugLogger, "getNodesHealth: url {}", url); ResponseEntity<List<ConsulNodeInfo>> response = null; + List<ConsulNodeInfo> result = new ArrayList<>(); try { - response = restTemplate.exchange(url, HttpMethod.GET, token_entity, - new ParameterizedTypeReference<List<ConsulNodeInfo>>() { - }); + response = restTemplate.exchange(url, HttpMethod.GET, tokenEntity, + new ParameterizedTypeReference<List<ConsulNodeInfo>>() {}); } catch (HttpStatusCodeException e) { if (e.getStatusCode().value() == 403) { // update consul ACL token header and retry - consul_acl_token = getConsulAcl(); - if (consul_acl_token != null && !consul_acl_token.isEmpty()) { - token_entity = getConsulTokenHeader(consul_acl_token); - response = restTemplate.exchange(url, HttpMethod.GET, token_entity, - new ParameterizedTypeReference<List<ConsulNodeInfo>>() { - }); + consulAclToken = getConsulAcl(); + if (consulAclToken != null && !consulAclToken.isEmpty()) { + tokenEntity = getConsulTokenHeader(consulAclToken); + response = restTemplate.exchange(url, HttpMethod.GET, tokenEntity, + new ParameterizedTypeReference<List<ConsulNodeInfo>>() {}); } else { throw e; - } + } } } - if (!response.getBody().isEmpty()) { - return response.getBody(); - } else { - return null; - } + if (response != null && !response.getBody().isEmpty()) { + result = response.getBody(); + } + return result; } @Override - public List<ConsulServiceHealth> getNodeServicesHealth(String dc, String nodeId) { - String url = buildUrl(new String[] { baseUrl, API_VER, HEALTH, "node", nodeId }, new String[] { "dc", dc }); + public List<ConsulServiceHealth> getNodeServicesHealth(String dc, String nodeId) + throws Exception { + String url = buildUrl(new String[] {baseUrl, API_VER, HEALTH, "node", nodeId}, + new String[] {"dc", dc}); logger.debug(EELFLoggerDelegate.debugLogger, "getNodeServicesHealth: url {}", url); ResponseEntity<List<ConsulServiceHealth>> response = null; + List<ConsulServiceHealth> result = new ArrayList<>(); try { - response = restTemplate.exchange(url, HttpMethod.GET, token_entity, - new ParameterizedTypeReference<List<ConsulServiceHealth>>() { - }); + response = restTemplate.exchange(url, HttpMethod.GET, tokenEntity, + new ParameterizedTypeReference<List<ConsulServiceHealth>>() {}); } catch (HttpStatusCodeException e) { if (e.getStatusCode().value() == 403) { // update consul ACL token header and retry - consul_acl_token = getConsulAcl(); - if (consul_acl_token != null && !consul_acl_token.isEmpty()) { - token_entity = getConsulTokenHeader(consul_acl_token); - response = restTemplate.exchange(url, HttpMethod.GET, token_entity, - new ParameterizedTypeReference<List<ConsulServiceHealth>>() { - }); + consulAclToken = getConsulAcl(); + if (consulAclToken != null && !consulAclToken.isEmpty()) { + tokenEntity = getConsulTokenHeader(consulAclToken); + response = restTemplate.exchange(url, HttpMethod.GET, tokenEntity, + new ParameterizedTypeReference<List<ConsulServiceHealth>>() {}); } else { throw e; - } + } } } - if (!response.getBody().isEmpty()) { - return response.getBody(); - } else { - return null; + if (response != null && !response.getBody().isEmpty()) { + result = response.getBody(); } + return result; } @Override public List<ConsulDatacenter> getDatacenters() { - String url = buildUrl(new String[] { baseUrl, API_VER, CATALOG, "datacenters" }, null); + String url = buildUrl(new String[] {baseUrl, API_VER, CATALOG, "datacenters"}, null); logger.debug(EELFLoggerDelegate.debugLogger, "getDatacentersHealth: url {}", url); ResponseEntity<List<String>> response = null; + List<ConsulDatacenter> result = new ArrayList<>(); try { - response = restTemplate.exchange(url, HttpMethod.GET, token_entity, - new ParameterizedTypeReference<List<String>>() { - }); + response = restTemplate.exchange(url, HttpMethod.GET, tokenEntity, + new ParameterizedTypeReference<List<String>>() {}); } catch (HttpStatusCodeException e) { if (e.getStatusCode().value() == 403) { // update consul ACL token header and retry - consul_acl_token = getConsulAcl(); - if (consul_acl_token != null && !consul_acl_token.isEmpty()) { - token_entity = getConsulTokenHeader(consul_acl_token); - response = restTemplate.exchange(url, HttpMethod.GET, token_entity, - new ParameterizedTypeReference<List<String>>() { - }); + consulAclToken = getConsulAcl(); + if (consulAclToken != null && !consulAclToken.isEmpty()) { + tokenEntity = getConsulTokenHeader(consulAclToken); + response = restTemplate.exchange(url, HttpMethod.GET, tokenEntity, + new ParameterizedTypeReference<List<String>>() {}); } else { throw e; - } + } } } - if (!response.getBody().isEmpty()) { - List<String> list = response.getBody(); - List<ConsulDatacenter> result = new ArrayList<>(); - for (String dc : list) - result.add(new ConsulDatacenter(dc)); - return result; - } else { - return null; - } - + if (response != null && !response.getBody().isEmpty()) { + for (String dc : response.getBody()) + result.add(new ConsulDatacenter(dc)); + } + return result; } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClient.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClient.java index 012ec32..3535db0 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClient.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClient.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.rest; import java.util.stream.Stream; @@ -41,6 +41,7 @@ public interface DeploymentHandlerClient { * */ public String checkHealth(); + /** * Gets a list of all service deployments known to the orchestrator. * @@ -53,7 +54,7 @@ public interface DeploymentHandlerClient { * to a single service type. * * @param serviceTypeId Service type identifier for the type whose deployments - * are to be listed. + * are to be listed. * * @return Stream<String> */ @@ -62,35 +63,35 @@ public interface DeploymentHandlerClient { /** * Request deployment of a DCAE Service. * - * @param deploymentId Unique deployment identifier assigned by the API - * client. + * @param deploymentId Unique deployment identifier assigned by the API + * client. * * @param deploymentRequest Deployment request object that contains the - * necessary fields for service deployment. + * necessary fields for service deployment. * * @return DeploymentResponse Response body for a PUT or DELETE to - * /dcae-deployments/{deploymentId} + * /dcae-deployments/{deploymentId} * */ - public DeploymentResponse putDeployment(String deploymentId, String tenant, DeploymentRequest deploymentRequest, - HttpServletRequest request) - throws BadRequestException, ServiceAlreadyExistsException, ServerErrorException, DownstreamException; + public DeploymentResponse putDeployment(String deploymentId, String tenant, + DeploymentRequest deploymentRequest, HttpServletRequest request) throws Exception; /** * For API use, Request deployment of a DCAE Service. + * s * - * @param deploymentId Unique deployment identifier assigned by the API - * client. + * @param deploymentId Unique deployment identifier assigned by the API + * client. * * @param deploymentRequest Deployment request object that contains the - * necessary fields for service deployment. + * necessary fields for service deployment. * * @return DeploymentResponse Response body for a PUT or DELETE to - * /dcae-deployments/{deploymentId} + * /dcae-deployments/{deploymentId} * */ - public DeploymentResponse putDeployment(String deploymentId, String tenant, DeploymentRequest deploymentRequest) - throws BadRequestException, ServiceAlreadyExistsException, ServerErrorException, DownstreamException; + public DeploymentResponse putDeployment(String deploymentId, String tenant, + DeploymentRequest deploymentRequest) throws Exception; /** * Uninstall the DCAE service and remove all associated data from the @@ -100,8 +101,8 @@ public interface DeploymentHandlerClient { * */ public void deleteDeployment(String deploymentId, String tenant, HttpServletRequest request) - throws BadRequestException, ServerErrorException, DownstreamException, DeploymentNotFoundException; - + throws Exception; + /** * For API use, Uninstall the DCAE service and remove all associated data from the * orchestrator. @@ -109,6 +110,5 @@ public interface DeploymentHandlerClient { * @param deploymentId Unique deployment identifier assigned by the API client. * */ - public void deleteDeployment(String deploymentId, String tenant) - throws BadRequestException, ServerErrorException, DownstreamException, DeploymentNotFoundException; + public void deleteDeployment(String deploymentId, String tenant) throws Exception; } 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 803c710..0eb51bc 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 @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.rest; import java.io.IOException; @@ -36,6 +36,7 @@ import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import org.onap.ccsdk.dashboard.exceptions.BadRequestException; +import org.onap.ccsdk.dashboard.exceptions.DashboardControllerException; import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; import org.onap.ccsdk.dashboard.exceptions.DownstreamException; import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; @@ -70,15 +71,14 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo private String baseUrl; private static final String DEPLOYMENTS = "dcae-deployments"; - private static final String UPDATE_PATH = "dcae-deployment-update"; private static final String HEALTH_CHECK = "healthcheck"; private static final String SERVICE_ID = "service-list"; @Autowired CloudifyClient cloudifyClient; - - private AbstractCacheManager cacheManager; - + + private AbstractCacheManager cacheManager; + @Autowired public void setCacheManager(AbstractCacheManager cacheManager) { this.cacheManager = cacheManager; @@ -87,10 +87,11 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo public AbstractCacheManager getCacheManager() { return cacheManager; } + protected final ObjectMapper objectMapper = new ObjectMapper(); @PostConstruct - public void init() { + public void init() throws DashboardControllerException { String webapiUrl = DashboardProperties.getControllerProperty("site.primary", DashboardProperties.SITE_SUBKEY_DHANDLER_URL); if (webapiUrl == null) @@ -100,7 +101,7 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo url = new URL(webapiUrl); baseUrl = url.toExternalForm(); } catch (MalformedURLException ex) { - throw new RuntimeException("Failed to parse URL", ex); + throw new DashboardControllerException("Failed to parse URL", ex); } String urlScheme = webapiUrl.split(":")[0]; if (restTemplate == null) { @@ -110,44 +111,42 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo } public String checkHealth() { - String url = buildUrl(new String[] { baseUrl, HEALTH_CHECK }, null); + String url = buildUrl(new String[] {baseUrl, HEALTH_CHECK}, null); ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<String>() { - }); + new ParameterizedTypeReference<String>() {}); return response.getBody(); } - + public Stream<DeploymentLink> getDeployments() { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, null); - ResponseEntity<DeploymentsListResponse> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<DeploymentsListResponse>() { - }); + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, null); + ResponseEntity<DeploymentsListResponse> response = restTemplate.exchange(url, + HttpMethod.GET, null, new ParameterizedTypeReference<DeploymentsListResponse>() {}); DeploymentsListResponse result = response.getBody(); return result.getDeployments().stream(); } @Override public Stream<DeploymentLink> getDeployments(String serviceTypeId) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, new String[] { "serviceTypeId", serviceTypeId }); - ResponseEntity<DeploymentsListResponse> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<DeploymentsListResponse>() { - }); + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS}, + new String[] {"serviceTypeId", serviceTypeId}); + ResponseEntity<DeploymentsListResponse> response = restTemplate.exchange(url, + HttpMethod.GET, null, new ParameterizedTypeReference<DeploymentsListResponse>() {}); DeploymentsListResponse result = response.getBody(); return result.getDeployments().stream(); } @Override - public DeploymentResponse putDeployment(String deploymentId, String tenant, DeploymentRequest deploymentRequest) - throws BadRequestException, ServiceAlreadyExistsException, ServerErrorException, DownstreamException { + public DeploymentResponse putDeployment(String deploymentId, String tenant, + DeploymentRequest deploymentRequest) throws Exception { return putDeployment(deploymentId, tenant, deploymentRequest, null); } - + + @SuppressWarnings("unchecked") @Override - public DeploymentResponse putDeployment(String deploymentId, String tenant, DeploymentRequest deploymentRequest, - HttpServletRequest request) - throws BadRequestException, ServiceAlreadyExistsException, ServerErrorException, DownstreamException { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS, deploymentId }, - new String[] { "cfy_tenant_name", tenant }); + public DeploymentResponse putDeployment(String deploymentId, String tenant, + DeploymentRequest deploymentRequest, HttpServletRequest request) throws Exception { + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS, deploymentId}, + new String[] {"cfy_tenant_name", tenant}); String user = ""; if (request != null) { user = UserUtils.getUserSession(request).getLoginId(); @@ -156,22 +155,21 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ResponseEntity<DeploymentResponse> result = restTemplate.exchange(url, HttpMethod.PUT, - new HttpEntity<DeploymentRequest>(deploymentRequest, headers), - new ParameterizedTypeReference<DeploymentResponse>() { - }); - //cache handling + new HttpEntity<DeploymentRequest>(deploymentRequest, headers), + new ParameterizedTypeReference<DeploymentResponse>() {}); + // cache handling ReadWriteLock lock = new ReentrantReadWriteLock(); lock.readLock().lock(); - List itemList = - (List<CloudifyDeployment>)getCacheManager().getObject(SERVICE_ID + ":" + tenant); - List itemExecList = (List<CloudifyDeploymentExt>)getCacheManager().getObject( - SERVICE_ID + ":" + tenant + ":ext"); - List itemHelmList = (List<CloudifyDeploymentExt>)getCacheManager().getObject( - SERVICE_ID + ":" + tenant + ":helm"); + List<CloudifyDeployment> itemList = + (List<CloudifyDeployment>) getCacheManager().getObject(SERVICE_ID + ":" + tenant); + List<CloudifyDeploymentExt> itemExecList = (List<CloudifyDeploymentExt>) getCacheManager() + .getObject(SERVICE_ID + ":" + tenant + ":ext"); + List<CloudifyDeploymentHelm> itemHelmList = (List<CloudifyDeploymentHelm>) getCacheManager() + .getObject(SERVICE_ID + ":" + tenant + ":helm"); lock.readLock().unlock(); if (itemList != null) { // add the new resource into app cache - CloudifyDeployment cfyDepl = + CloudifyDeployment cfyDepl = cloudifyClient.getDeploymentResource(deploymentId, tenant); lock.writeLock().lock(); itemList.add(0, cfyDepl); @@ -179,9 +177,9 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo if (itemExecList != null) { List<CloudifyDeployment> thisDep = new ArrayList<CloudifyDeployment>(); thisDep.add(cfyDepl); - List<CloudifyDeploymentExt> thisDepExec = + List<CloudifyDeploymentExt> thisDepExec = cloudifyClient.updateWorkflowStatus(thisDep); - List<CloudifyDeploymentHelm> thisDepHelm = + List<CloudifyDeploymentHelm> thisDepHelm = cloudifyClient.updateHelmInfo(thisDep); lock.writeLock().lock(); itemExecList.add(0, thisDepExec.get(0)); @@ -190,29 +188,28 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo } // handle the owner deployment map cache if (!user.isEmpty()) { - CloudifyDeployedTenant updDepl = - new CloudifyDeployedTenant(cfyDepl.id, cfyDepl.tenant_name, - cfyDepl.created_at, cfyDepl.updated_at); + CloudifyDeployedTenant updDepl = new CloudifyDeployedTenant(cfyDepl.id, + cfyDepl.tenant_name, cfyDepl.created_at, cfyDepl.updated_at); lock.readLock().lock(); - Map<String, List<CloudifyDeployedTenant>> deplPerOwner = - (Map<String, List<CloudifyDeployedTenant>>) - getCacheManager().getObject("owner_deploy_map"); + Map<String, List<CloudifyDeployedTenant>> deplPerOwner = + (Map<String, List<CloudifyDeployedTenant>>) getCacheManager() + .getObject("owner_deploy_map"); lock.readLock().unlock(); if (deplPerOwner != null) { - List<CloudifyDeployedTenant> currOwnedDepls = deplPerOwner.get(user); + List<CloudifyDeployedTenant> currOwnedDepls = deplPerOwner.get(user); if (currOwnedDepls != null) { currOwnedDepls.add(0, updDepl); } else { - currOwnedDepls = - new ArrayList<CloudifyDeployedTenant>(); - currOwnedDepls.add(updDepl); + currOwnedDepls = new ArrayList<CloudifyDeployedTenant>(); + currOwnedDepls.add(updDepl); } lock.writeLock().lock(); deplPerOwner.put(user, currOwnedDepls); lock.writeLock().unlock(); } else { deplPerOwner = new HashMap<String, List<CloudifyDeployedTenant>>(); - List<CloudifyDeployedTenant> deplForBpAggr = new ArrayList<CloudifyDeployedTenant>(); + List<CloudifyDeployedTenant> deplForBpAggr = + new ArrayList<CloudifyDeployedTenant>(); deplForBpAggr.add(updDepl); deplPerOwner.put(user, deplForBpAggr); } @@ -225,7 +222,7 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo StringBuilder errDetails = new StringBuilder(); errDetails.append(e.getMessage()).append(" ").append(errBody); if (e.getStatusCode().value() == 400 || e.getStatusCode().value() == 415 - || e.getStatusCode().value() == 404) { + || e.getStatusCode().value() == 404) { throw new BadRequestException(errDetails.toString()); } else if (e.getStatusCode().value() == 409) { throw new ServiceAlreadyExistsException(errDetails.toString()); @@ -239,29 +236,29 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo } @Override - public void deleteDeployment(String deploymentId, String tenant) - throws BadRequestException, ServerErrorException, DownstreamException, DeploymentNotFoundException { + public void deleteDeployment(String deploymentId, String tenant) throws Exception { deleteDeployment(deploymentId, tenant, null); } + @Override public void deleteDeployment(String deploymentId, String tenant, HttpServletRequest request) - throws BadRequestException, ServerErrorException, DownstreamException, DeploymentNotFoundException { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS, deploymentId }, - new String[] { "cfy_tenant_name", tenant, "force_uninstall", "true" }); + throws Exception { + String url = buildUrl(new String[] {baseUrl, DEPLOYMENTS, deploymentId}, + new String[] {"cfy_tenant_name", tenant, "force_uninstall", "true"}); try { String user = ""; if (request != null) { user = UserUtils.getUserSession(request).getLoginId(); } - restTemplate.exchange(url, HttpMethod.DELETE, null, new ParameterizedTypeReference<DeploymentResponse>() { - }); - CloudifyDeployment cfyDepl = - cloudifyClient.getDeploymentResource(deploymentId, tenant); + restTemplate.exchange(url, HttpMethod.DELETE, null, + new ParameterizedTypeReference<DeploymentResponse>() {}); + CloudifyDeployment cfyDepl = cloudifyClient.getDeploymentResource(deploymentId, tenant); // remove resource from app cache ReadWriteLock lock = new ReentrantReadWriteLock(); lock.readLock().lock(); - List itemList = - (List<CloudifyDeployment>)getCacheManager().getObject(SERVICE_ID + ":" + tenant); + @SuppressWarnings("unchecked") + List itemList = + (List<CloudifyDeployment>) getCacheManager().getObject(SERVICE_ID + ":" + tenant); lock.readLock().unlock(); if (itemList != null) { lock.writeLock().lock(); @@ -270,19 +267,19 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo // put updated collection back into cache getCacheManager().putObject(SERVICE_ID + ":" + tenant, itemList); lock.writeLock().unlock(); - } + } // handle the owner deployment map cache if (!user.isEmpty()) { lock.readLock().lock(); - Map<String, List<CloudifyDeployedTenant>> deplPerOwner = - (Map<String, List<CloudifyDeployedTenant>>) - getCacheManager().getObject("owner_deploy_map"); + @SuppressWarnings("unchecked") + Map<String, List<CloudifyDeployedTenant>> deplPerOwner = + (Map<String, List<CloudifyDeployedTenant>>) getCacheManager() + .getObject("owner_deploy_map"); lock.readLock().unlock(); if (deplPerOwner != null) { - List<CloudifyDeployedTenant> currOwnedDepls = deplPerOwner.get(user); - CloudifyDeployedTenant updDepl = - new CloudifyDeployedTenant(cfyDepl.id, cfyDepl.tenant_name, - cfyDepl.created_at, cfyDepl.updated_at); + List<CloudifyDeployedTenant> currOwnedDepls = deplPerOwner.get(user); + CloudifyDeployedTenant updDepl = new CloudifyDeployedTenant(cfyDepl.id, + cfyDepl.tenant_name, cfyDepl.created_at, cfyDepl.updated_at); if (currOwnedDepls != null) { currOwnedDepls.remove(updDepl); lock.writeLock().lock(); @@ -295,7 +292,8 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo DeploymentErrorResponse errBody = null; String errMsg = ""; try { - errBody = objectMapper.readValue(e.getResponseBodyAsString(), DeploymentErrorResponse.class); + errBody = objectMapper.readValue(e.getResponseBodyAsString(), + DeploymentErrorResponse.class); } catch (IOException e1) { errBody = null; } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java index 0c4053c..86f6773 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.rest; import java.net.URI; @@ -36,10 +36,9 @@ import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; /** * Utility class to enable Basic HTTP Authentication with Spring REST templates. * - * From: - * http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1/ */ -public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpComponentsClientHttpRequestFactory { +public class HttpComponentsClientHttpRequestFactoryBasicAuth + extends HttpComponentsClientHttpRequestFactory { private HttpHost host; 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 8f19e9b..0259838 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 @@ -2,42 +2,38 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.rest; import java.util.Optional; -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.inventory.InventoryProperty; -import org.onap.ccsdk.dashboard.model.inventory.Service; 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.ServiceTypeQueryParams; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummary; +import org.springframework.web.client.HttpStatusCodeException; /** * Defines the interface of the Inventory Client. @@ -56,24 +52,25 @@ public interface InventoryClient { * @return void */ public void cacheServiceTypes(); - + /** * Gets a list of all DCAE Service Type objects. * * @return Collection<ServiceType> */ - public Stream<ServiceTypeSummary> getServiceTypes(); - + public Stream<ServiceTypeSummary> getServiceTypes() throws Exception; + /** * Gets a list of all DCAE Service Type objects that fall under a specified * filter. * * @param serviceTypeQueryParams ServiceTypeQueryParams object containing query - * parameters. + * parameters. * * @return Collection<ServiceType> */ - public Stream<ServiceTypeSummary> getServiceTypes(ServiceTypeQueryParams serviceTypeQueryParams); + public Stream<ServiceTypeSummary> getServiceTypes( + ServiceTypeQueryParams serviceTypeQueryParams); /** * Inserts a new DCAE Service Type, or updates an existing instance associated @@ -85,9 +82,10 @@ public interface InventoryClient { * @return ServiceType * * @throws ServiceTypeActiveException if the service type exists and has active - * instances + * instances */ - public ServiceType addServiceType(ServiceType serviceType) throws ServiceTypeActiveException; + public ServiceType addServiceType(ServiceType serviceType) + throws Exception; /** * Inserts a new DCAE Service Type, or updates an existing instance associated @@ -98,9 +96,10 @@ public interface InventoryClient { * @return * * @throws ServiceTypeActiveException if the service type exists and has active - * instances + * instances */ - public ServiceType addServiceType(ServiceTypeRequest serviceTypeRequest) throws ServiceTypeActiveException; + public ServiceType addServiceType(ServiceTypeRequest serviceTypeRequest) + throws Exception; /** * Gets a single DCAE Service Type object with the ID typeId. @@ -109,72 +108,34 @@ public interface InventoryClient { * * @return Optional<ServiceType> */ - public Optional<ServiceType> getServiceType(String typeId); + public Optional<ServiceType> getServiceType(String typeId) + throws Exception; /** * Deactivates an existing DCAE Service Type instance with the ID typeId. * * @param typeId ID of the DCAE Service Type to be deactivated. * - * @exception ServiceTypeNotFoundException Thrown if the DCAE Service - * Type is not found. + * @exception ServiceTypeNotFoundException Thrown if the DCAE Service + * Type is not found. * * @exception ServiceTypeAlreadyDeactivatedException Thrown if the DCAE Service - * Type is already - * deactivated. + * Type is already + * deactivated. */ public void deleteServiceType(String typeId) - throws ServiceTypeNotFoundException, ServiceTypeAlreadyDeactivatedException; - - /** - * Gets a list of all DCAE Service objects. - * - * @return Collection<Service> - */ - //public Stream<Service> getServices(); - - /** - * Gets a list of all DCAE Service objects that fall under a specified filter. - * - * @param serviceQueryParams ServiceQueryParams object containing query - * parameters. - * - * @return Collection<Service> - */ - //public Stream<Service> getServices(ServiceQueryParams serviceQueryParams); + throws Exception; /** * Gets a list of all DCAE Service References that match a service type filter. * * @param serviceQueryParams ServiceQueryParams object containing query - * parameters. + * parameters. * * @return ServiceRefList */ public ServiceRefList getServicesForType(ServiceQueryParams serviceQueryParams); - /** - * Gets a set of properties on Service objects that match the provided - * propertyName - * - * @param propertyName Property to find unique values. Restricted to type, - * vnfType, vnfLocation. - * - * @return Set<InventoryProperty> - */ - /* - * public Set<InventoryProperty> getPropertiesOfServices(String propertyName); - */ - /** - * Gets a single DCAE Service object corresponding to the specified serviceId. - * - * @param serviceId Service ID of the DCAE Service to be retrieved. - * - * @return Service - */ - - //public Optional<Service> getService(String serviceId); - public String getBaseUrl(); } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestClientBase.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestClientBase.java index 69fca94..28bc7b7 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestClientBase.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/rest/RestClientBase.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.rest; import java.net.URL; @@ -30,7 +30,6 @@ import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentList; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.web.client.RestTemplate; @@ -38,7 +37,6 @@ import org.springframework.web.client.RestTemplate; /** * Base class for all the Rest client implementations * - * @author rp5662 * */ public class RestClientBase { @@ -60,18 +58,17 @@ public class RestClientBase { if (user != null && pass != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(new AuthScope(httpHost), new UsernamePasswordCredentials(user, pass)); - httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build(); + credsProvider.setCredentials(new AuthScope(httpHost), + new UsernamePasswordCredentials(user, pass)); + httpClient = + HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build(); } else { httpClient = HttpClientBuilder.create().build(); } // Create request factory - HttpComponentsClientHttpRequestFactoryBasicAuth requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth( - httpHost); + HttpComponentsClientHttpRequestFactoryBasicAuth requestFactory = + new HttpComponentsClientHttpRequestFactoryBasicAuth(httpHost); requestFactory.setHttpClient(httpClient); - //requestFactory.setReadTimeout(10000); - //requestFactory.setConnectionRequestTimeout(2000); - //requestFactory.setConnectTimeout(10000); // Put the factory in the template restTempl = new RestTemplate(); restTempl.setRequestFactory(requestFactory); @@ -85,7 +82,7 @@ public class RestClientBase { * @param base * @param suffix * @param queryParams key-value pairs; i.e. must have an even number of entries. - * Ignored if null. + * Ignored if null. * @return */ protected String buildUrl(final String[] path, final String[] queryParams) { 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 100170c..df4ce08 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 @@ -2,23 +2,23 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2020 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. *******************************************************************************/ + package org.onap.ccsdk.dashboard.rest; import java.net.MalformedURLException; @@ -28,15 +28,16 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; +import java.util.Optional; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Predicate; -import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.PostConstruct; +import org.onap.ccsdk.dashboard.exceptions.DashboardControllerException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; import org.onap.ccsdk.dashboard.model.inventory.ApiResponseMessage; @@ -67,7 +68,7 @@ import org.springframework.web.client.HttpClientErrorException; public class RestInventoryClientImpl extends RestClientBase implements InventoryClient { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestInventoryClientImpl.class); - + private String baseUrl; public static final String SERVICE_TYPES = "dcae-service-types"; public static final String SERVICES = "dcae-services"; @@ -75,54 +76,50 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory public static final String HEALTH_CHECK = "healthcheck"; /** - * For caching data + * For caching data */ private AbstractCacheManager cacheManager; - + @PostConstruct - public void init() { + public void init() throws DashboardControllerException { String webapiUrl = DashboardProperties.getControllerProperty("site.primary", DashboardProperties.SITE_SUBKEY_INVENTORY_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); + throw new DashboardControllerException("Failed to parse URL", ex); } - urlScheme = webapiUrl.split(":")[0]; + String urlScheme = webapiUrl.split(":")[0]; if (restTemplate == null) { createRestTemplate(url, null, null, urlScheme); } - } public String checkHealth() { - String url = buildUrl(new String[] { baseUrl, HEALTH_CHECK }, null); + String url = buildUrl(new String[] {baseUrl, HEALTH_CHECK}, null); ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<String>() { - }); + new ParameterizedTypeReference<String>() {}); return response.getBody(); } - - @Scheduled(fixedDelay=300000, initialDelay=30000) + + @Scheduled(fixedDelay = 300000, initialDelay = 30000) public void cacheServiceTypes() { logger.debug(EELFLoggerDelegate.debugLogger, "cacheServiceTypes begin"); - String url = buildUrl(new String[] { baseUrl, SERVICE_TYPES }, new String[] {"onlyLatest", "false"}); - ResponseEntity<ServiceTypeSummaryList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceTypeSummaryList>() { - }); + String url = + buildUrl(new String[] {baseUrl, SERVICE_TYPES}, new String[] {"onlyLatest", "false"}); + ResponseEntity<ServiceTypeSummaryList> response = restTemplate.exchange(url, HttpMethod.GET, + null, new ParameterizedTypeReference<ServiceTypeSummaryList>() {}); Collection<ServiceTypeSummary> collection = response.getBody().items; // Continue retrieving items on the next page if they exist Link nextLink = response.getBody().paginationLinks.nextLink; while (nextLink != null) { url = response.getBody().paginationLinks.nextLink.href; response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceTypeSummaryList>() { - }); + new ParameterizedTypeReference<ServiceTypeSummaryList>() {}); collection.addAll(response.getBody().items); nextLink = response.getBody().paginationLinks.nextLink; } @@ -134,19 +131,18 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory logger.debug(EELFLoggerDelegate.debugLogger, "cacheServiceTypes end"); } - public Stream<ServiceTypeSummary> getServiceTypes() { - String url = buildUrl(new String[] { baseUrl, SERVICE_TYPES }, new String[] {"onlyLatest", "false"}); - ResponseEntity<ServiceTypeSummaryList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceTypeSummaryList>() { - }); + public Stream<ServiceTypeSummary> getServiceTypes() throws Exception { + String url = + buildUrl(new String[] {baseUrl, SERVICE_TYPES}, new String[] {"onlyLatest", "false"}); + ResponseEntity<ServiceTypeSummaryList> response = restTemplate.exchange(url, HttpMethod.GET, + null, new ParameterizedTypeReference<ServiceTypeSummaryList>() {}); Collection<ServiceTypeSummary> collection = response.getBody().items; // Continue retrieving items on the next page if they exist Link nextLink = response.getBody().paginationLinks.nextLink; while (nextLink != null) { url = response.getBody().paginationLinks.nextLink.href; response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceTypeSummaryList>() { - }); + new ParameterizedTypeReference<ServiceTypeSummaryList>() {}); collection.addAll(response.getBody().items); nextLink = response.getBody().paginationLinks.nextLink; } @@ -157,7 +153,7 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory lock.writeLock().unlock(); return collection.stream(); } - + @Autowired public void setCacheManager(AbstractCacheManager cacheManager) { this.cacheManager = cacheManager; @@ -166,8 +162,9 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory public AbstractCacheManager getCacheManager() { return cacheManager; } - - public Stream<ServiceTypeSummary> getServiceTypes(ServiceTypeQueryParams serviceTypeQueryParams) { + + public Stream<ServiceTypeSummary> getServiceTypes( + ServiceTypeQueryParams serviceTypeQueryParams) { // Only utilize the parameters that aren't null HashMap<String, String> map = new HashMap<>(); @@ -207,10 +204,10 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory params.add(ent.getValue()); } - String url = buildUrl(new String[] { baseUrl, SERVICE_TYPES }, params.toArray(new String[params.size()])); - ResponseEntity<ServiceTypeSummaryList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceTypeSummaryList>() { - }); + String url = buildUrl(new String[] {baseUrl, SERVICE_TYPES}, + params.toArray(new String[params.size()])); + ResponseEntity<ServiceTypeSummaryList> response = restTemplate.exchange(url, HttpMethod.GET, + null, new ParameterizedTypeReference<ServiceTypeSummaryList>() {}); Collection<ServiceTypeSummary> collection = response.getBody().items; // Continue retrieving items on the next page if they exist @@ -218,17 +215,16 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory while (nextLink != null) { url = response.getBody().paginationLinks.nextLink.href; response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceTypeSummaryList>() { - }); + new ParameterizedTypeReference<ServiceTypeSummaryList>() {}); collection.addAll(response.getBody().items); nextLink = response.getBody().paginationLinks.nextLink; } - return collection.stream(); } - public ServiceType addServiceType(ServiceType serviceType) { - String url = buildUrl(new String[] { baseUrl, SERVICE_TYPES }, null); + public ServiceType addServiceType(ServiceType serviceType) + throws Exception { + String url = buildUrl(new String[] {baseUrl, SERVICE_TYPES}, null); // Take the ServiceType object and create a ServiceTypeRequest from it ServiceTypeRequest serviceTypeRequest = ServiceTypeRequest.from(serviceType); @@ -244,11 +240,12 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory } @SuppressWarnings("unchecked") - public ServiceType addServiceType(ServiceTypeRequest serviceTypeRequest) { - String url = buildUrl(new String[] { baseUrl, SERVICE_TYPES }, null); + public ServiceType addServiceType(ServiceTypeRequest serviceTypeRequest) + throws Exception { + String url = buildUrl(new String[] {baseUrl, SERVICE_TYPES}, null); ServiceType uplBp = restTemplate.postForObject(url, serviceTypeRequest, ServiceType.class); // update application cache with new record to refresh screen immediately - // query inventory for the newly uploaded entry, + // query inventory for the newly uploaded entry, // using query params (typeName, owner, app, component) List<ServiceTypeSummary> itemList = this.getServiceTypes().collect(Collectors.toList()); ReadWriteLock lock = new ReentrantReadWriteLock(); @@ -259,36 +256,34 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory return uplBp; } - public Optional<ServiceType> getServiceType(String typeId) { - String url = buildUrl(new String[] { baseUrl, SERVICE_TYPES, typeId }, null); + public Optional<ServiceType> getServiceType(String typeId) + throws Exception { + String url = buildUrl(new String[] {baseUrl, SERVICE_TYPES, typeId}, null); ResponseEntity<ServiceType> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceType>() { - }); + new ParameterizedTypeReference<ServiceType>() {}); return Optional.ofNullable(response.getBody()); } @SuppressWarnings("unchecked") public void deleteServiceType(String typeId) - throws ServiceTypeNotFoundException, ServiceTypeAlreadyDeactivatedException { - String url = buildUrl(new String[] { baseUrl, SERVICE_TYPES, typeId }, null); + throws Exception { + String url = buildUrl(new String[] {baseUrl, SERVICE_TYPES, typeId}, null); ReadWriteLock lock = new ReentrantReadWriteLock(); try { - ResponseEntity<ApiResponseMessage> response = - restTemplate.exchange(url, HttpMethod.DELETE, null, - new ParameterizedTypeReference<ApiResponseMessage>() { - }); + restTemplate.exchange(url, + HttpMethod.DELETE, null, new ParameterizedTypeReference<ApiResponseMessage>() {}); // update the application cache lock.readLock().lock(); - List<ServiceTypeSummary> itemList = - (List<ServiceTypeSummary>)getCacheManager().getObject(SERVICE_TYPES); + List<ServiceTypeSummary> itemList = + (List<ServiceTypeSummary>) getCacheManager().getObject(SERVICE_TYPES); lock.readLock().unlock(); if (itemList == null) { itemList = getServiceTypes().collect(Collectors.toList()); } Predicate<ServiceTypeSummary> typeIdFilter = p -> p.getTypeId().isPresent() && !p.getTypeId().get().equals(typeId); - itemList = (List<ServiceTypeSummary>)itemList.stream().filter(typeIdFilter). - collect(Collectors.toList()); + itemList = (List<ServiceTypeSummary>) itemList.stream().filter(typeIdFilter) + .collect(Collectors.toList()); lock.writeLock().lock(); getCacheManager().removeObject(SERVICE_TYPES); // put updated collection back into cache @@ -303,28 +298,7 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory } } -/* public Stream<Service> getServices() { - String url = buildUrl(new String[] { baseUrl, SERVICES }, null); - ResponseEntity<ServiceList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceList>() { - }); - Collection<Service> collection = response.getBody().items; - - // Continue retrieving items on the next page if they exist - Link nextLink = response.getBody().paginationLinks.nextLink; - while (nextLink != null) { - url = response.getBody().paginationLinks.nextLink.href; - response = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<ServiceList>() { - }); - collection.addAll(response.getBody().items); - nextLink = response.getBody().paginationLinks.nextLink; - } - - return collection.stream(); - } -*/ public ServiceRefList getServicesForType(ServiceQueryParams serviceQueryParams) { - // Only utilize the typeId HashMap<String, String> map = new HashMap<>(); if (serviceQueryParams.getTypeId() != null) { @@ -335,11 +309,10 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory params.add(ent.getKey()); params.add(ent.getValue()); } - - String url = buildUrl(new String[] { baseUrl, SERVICES }, params.toArray(new String[params.size()])); + String url = + buildUrl(new String[] {baseUrl, SERVICES}, params.toArray(new String[params.size()])); ResponseEntity<ServiceList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceList>() { - }); + new ParameterizedTypeReference<ServiceList>() {}); Collection<Service> collection = response.getBody().items; int itemCnt = response.getBody().totalCount; @@ -347,83 +320,18 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory Link nextLink = response.getBody().paginationLinks.nextLink; while (nextLink != null) { url = response.getBody().paginationLinks.nextLink.href; - response = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<ServiceList>() { - }); + response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference<ServiceList>() {}); collection.addAll(response.getBody().items); nextLink = response.getBody().paginationLinks.nextLink; } - - List<ServiceRef> srvcRefList = collection.stream().map(e -> e.createServiceRef()).collect(Collectors.toList()); + List<ServiceRef> srvcRefList = + collection.stream().map(e -> e.createServiceRef()).collect(Collectors.toList()); return new ServiceRefList(srvcRefList, itemCnt); } -/* - public Stream<Service> getServices(ServiceQueryParams serviceQueryParams) { - // Only utilize the parameters that aren't null - HashMap<String, String> map = new HashMap<>(); - if (serviceQueryParams.getTypeId() != null) { - map.put("typeId", serviceQueryParams.getTypeId()); - } - if (serviceQueryParams.getVnfId() != null) { - map.put("vnfId", serviceQueryParams.getVnfId()); - } - if (serviceQueryParams.getVnfType() != null) { - map.put("vnfType", serviceQueryParams.getVnfType()); - } - if (serviceQueryParams.getVnfLocation() != null) { - map.put("vnfLocation", serviceQueryParams.getVnfLocation()); - } - if (serviceQueryParams.getComponentType() != null) { - map.put("componentType", serviceQueryParams.getComponentType()); - } - if (serviceQueryParams.getShareable() != null) { - map.put("shareable", Boolean.toString(serviceQueryParams.getShareable())); - } - if (serviceQueryParams.getCreated() != null) { - map.put("created", serviceQueryParams.getCreated()); - } - ArrayList<String> params = new ArrayList<>(); - for (Entry<String, String> ent : map.entrySet()) { - params.add(ent.getKey()); - params.add(ent.getValue()); - } - - String url = buildUrl(new String[] { baseUrl, SERVICES }, params.toArray(new String[params.size()])); - ResponseEntity<ServiceList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceList>() { - }); - Collection<Service> collection = response.getBody().items; - - // Continue retrieving items on the next page if they exist - Link nextLink = response.getBody().paginationLinks.nextLink; - while (nextLink != null) { - url = response.getBody().paginationLinks.nextLink.href; - response = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<ServiceList>() { - }); - collection.addAll(response.getBody().items); - nextLink = response.getBody().paginationLinks.nextLink; - } - - return collection.stream(); - } - - public Optional<Service> getService(String serviceId) { - String url = buildUrl(new String[] { baseUrl, SERVICES, serviceId }, null); - ResponseEntity<Service> response = null; - try { - response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<Service>() { - }); - } - catch(HttpClientErrorException e) { - return null; - } - - return Optional.ofNullable(response.getBody()); - } - */ public String getBaseUrl() { - return this.baseUrl; + return this.baseUrl; } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/util/DashboardProperties.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/util/DashboardProperties.java index d785ea5..3d0962e 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/util/DashboardProperties.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/util/DashboardProperties.java @@ -2,22 +2,21 @@ * =============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. *******************************************************************************/ package org.onap.ccsdk.dashboard.util; @@ -39,61 +38,61 @@ import org.springframework.core.env.Environment; * </pre> */ @Configuration -@PropertySource(value = { "${container.classpath:}/WEB-INF/conf/dashboard.properties" }) +@PropertySource(value = {"${container.classpath:}/WEB-INF/conf/dashboard.properties"}) public class DashboardProperties { /** - * Key for property with list of sites + * Key for property with list of sites. */ public static final String CONTROLLER_SITE_LIST = "controller.site.list"; /** - * Subkey for property with site name + * Subkey for property with site name. */ public static final String SITE_SUBKEY_NAME = "name"; /** - * Subkey for property with Cloudify URL + * Subkey for property with Cloudify URL. */ public static final String SITE_SUBKEY_CLOUDIFY_URL = "cloudify.url"; /** - * Subkey for property with Inventory URL + * Subkey for property with Inventory URL. */ public static final String SITE_SUBKEY_INVENTORY_URL = "inventory.url"; /** - * Subkey for property with Deployment Handler URL + * Subkey for property with Deployment Handler URL. */ public static final String SITE_SUBKEY_DHANDLER_URL = "dhandler.url"; /** - * Subkey for property with Consul URL + * Subkey for property with Consul URL. */ public static final String SITE_SUBKEY_CONSUL_URL = "consul.url"; /** - * Subkey for property with DBCL URL + * Subkey for property with DBCL URL. */ public static final String SITE_SUBKEY_DBCL_URL = "dbcl.url"; /** - * Subkey for property with DBCL URL + * Subkey for property with Feed Mgmt URL. */ public static final String SITE_SUBKEY_FEED_URL = "feed_m.url"; /** - * Subkey for property with Controller user name for authentication + * Subkey for property with Controller user name for authentication. */ public static final String SITE_SUBKEY_CLOUDIFY_USERNAME = "cloudify.username"; /** - * Subkey for property with Controller password + * Subkey for property with Controller password. */ public static final String SITE_SUBKEY_CLOUDIFY_PASS = "cloudify.password"; /** - * Subkey for property with Controller password encryption status + * Subkey for property with Controller password encryption status. */ public static final String SITE_SUBKEY_CLOUDIFY_ENCRYPTED = "is_encrypted"; - + /** - * Key for dashboard deployment environment - dev/uat/prod + * Key for dashboard deployment environment. */ public static final String CONTROLLER_IN_ENV = "controller.env"; /** - * Key for K8s deploy permission string + * Key for K8s deploy permission string. * */ public static final String APP_K8S_PERM = "k8s.deploy.perm"; @@ -150,7 +149,7 @@ public class DashboardProperties { * * @param key Property key * @return Array of values with leading and trailing whitespace removed; null if - * key is not found. + * key is not found. */ public static String[] getCsvListProperty(final String key) { String listVal = getProperty(key); @@ -161,11 +160,11 @@ public class DashboardProperties { } /** - * Convenience method to get a property from the fake hierarchical key-value + * Convenience method to get a property from the fake hierarchical key-value. * set. * * @param controllerKey First part of key - * @param propKey Second part of key + * @param propKey Second part of key * @return Property value for key "controllerKey.propKey" */ public static String getControllerProperty(final String controllerKey, final String propKey) { @@ -178,10 +177,11 @@ public class DashboardProperties { * set. * * @param controllerKey First part of key - * @param propKey Second part of key + * @param propKey Second part of key * @return Property value for key "controllerKey.propKey" */ - public static String getControllerPropertyDef(final String controllerKey, final String propKey, String defVal) { + public static String getControllerPropertyDef(final String controllerKey, final String propKey, + String defVal) { final String key = controllerKey + '.' + propKey; return getPropertyDef(key, defVal); } diff --git a/ccsdk-app-common/src/main/java/org/onap/fusionapp/model/Result.java b/ccsdk-app-common/src/main/java/org/onap/fusionapp/model/Result.java index bc0a43a..4d9c579 100644 --- a/ccsdk-app-common/src/main/java/org/onap/fusionapp/model/Result.java +++ b/ccsdk-app-common/src/main/java/org/onap/fusionapp/model/Result.java @@ -2,23 +2,23 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * 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.fusionapp.model; /** diff --git a/ccsdk-app-common/src/main/java/org/onap/fusionapp/service/AdminAuthExtension.java b/ccsdk-app-common/src/main/java/org/onap/fusionapp/service/AdminAuthExtension.java index 0f2a1db..d91f914 100644 --- a/ccsdk-app-common/src/main/java/org/onap/fusionapp/service/AdminAuthExtension.java +++ b/ccsdk-app-common/src/main/java/org/onap/fusionapp/service/AdminAuthExtension.java @@ -2,29 +2,29 @@ * =============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.
*******************************************************************************/
+
package org.onap.fusionapp.service;
import org.onap.portalsdk.core.domain.User;
-//@Service("adminAuthExtension")
-//@Transactional
+// @Service("adminAuthExtension")
+// @Transactional
/**
* Extension supporting action on authorization of user
*/
diff --git a/ccsdk-app-common/src/main/java/org/onap/fusionapp/util/CustomLoggingFilter.java b/ccsdk-app-common/src/main/java/org/onap/fusionapp/util/CustomLoggingFilter.java index 13c36e6..f91a82c 100644 --- a/ccsdk-app-common/src/main/java/org/onap/fusionapp/util/CustomLoggingFilter.java +++ b/ccsdk-app-common/src/main/java/org/onap/fusionapp/util/CustomLoggingFilter.java @@ -2,23 +2,23 @@ * =============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. *******************************************************************************/ + package org.onap.fusionapp.util; import ch.qos.logback.classic.Level; @@ -43,9 +43,9 @@ public class CustomLoggingFilter extends Filter<ILoggingEvent> { public FilterReply decide(ILoggingEvent event) { try { if ((event.getLevel() != Level.ERROR || event.getLevel() != Level.WARN) - && ("UEBConsumerThread".equalsIgnoreCase(event.getThreadName())) - && (event.getLoggerName().contains("com.att.nsa") - || event.getLoggerName().contains("org.apache.http"))) { + && ("UEBConsumerThread".equalsIgnoreCase(event.getThreadName())) + && (event.getLoggerName().contains("com.att.nsa") + || event.getLoggerName().contains("org.apache.http"))) { return FilterReply.DENY; } else { return FilterReply.NEUTRAL; diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/api/controller/NbApiControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/api/controller/NbApiControllerTest.java index 3c33bda..a620608 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/api/controller/NbApiControllerTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/api/controller/NbApiControllerTest.java @@ -21,7 +21,10 @@ package org.onap.ccsdk.api.controller; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; @@ -47,7 +50,6 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -76,6 +78,7 @@ import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentInput; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponseLinks; +import org.onap.ccsdk.dashboard.model.inventory.Blueprint; import org.onap.ccsdk.dashboard.model.inventory.Service; import org.onap.ccsdk.dashboard.model.inventory.ServiceList; import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; @@ -94,6 +97,9 @@ import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; import org.onap.ccsdk.dashboard.rest.InventoryClient; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.util.CacheManager; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -108,6 +114,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PrepareForTest({Blueprint.class}) public class NbApiControllerTest extends MockitoTestSuite { @Mock @@ -124,10 +132,10 @@ public class NbApiControllerTest extends MockitoTestSuite { @Mock ServletUriComponentsBuilder uriBuilder; - + @InjectMocks - NbApiController subject = new NbApiController(); - + NbApiController subject; + private HttpStatusCodeException httpException = new HttpServerErrorException(HttpStatus.BAD_GATEWAY); @@ -140,7 +148,6 @@ public class NbApiControllerTest extends MockitoTestSuite { ServiceList deplList = null; Service deplItem = null; - ServiceTypeSummary bpItem, bpItem2 = null; ServiceTypeSummaryList bpList, bpList2 = null; ServiceType bpItemFull = null; @@ -171,13 +178,14 @@ public class NbApiControllerTest extends MockitoTestSuite { downStrmError = new DownstreamException("error occured in downstream"); notFoundError = new DeploymentNotFoundException("item not found"); CacheManager testCache = new CacheManager(); - subject.setCacheManager(testCache); + subject.setCacheManager(testCache); User user = mockUser.mockUser(); user.setLoginId("tester"); StringBuffer urlBuff = new StringBuffer(); urlBuff.append("http://orcl.com"); - //Mockito.when(mockedRequest.getRemoteUser()).thenReturn("tester"); + // Mockito.when(mockedRequest.getRemoteUser()).thenReturn("tester"); Mockito.when(mockedRequest.getRequestURL()).thenReturn(urlBuff); + PowerMockito.mockStatic(Blueprint.class); } public void getExpectedDeployments() @@ -199,15 +207,17 @@ public class NbApiControllerTest extends MockitoTestSuite { public void getExpectedBueprints() throws JsonParseException, JsonMappingException, IOException { - - /*bpItem = new ServiceTypeSummary.Builder().application("DCAE").component("dcae"). - typeName("xyz1731-helm-1906").owner("xyz1731").typeVersion(1906).build();*/ - - bpItem = new ServiceTypeSummary("xyz1730", "xyz1730-helm-1905", 1905, "DCAE", "dcae", "123-456-321", - "342343", true); - - bpItem2 = new ServiceTypeSummary("xyz1731", "xyz1731-helm-1906", 1906, "DCAE", "dcae", "123-456-789", - "342343", true); + + /* + * bpItem = new ServiceTypeSummary.Builder().application("DCAE").component("dcae"). + * typeName("xyz1731-helm-1906").owner("xyz1731").typeVersion(1906).build(); + */ + + bpItem = new ServiceTypeSummary("xyz1730", "xyz1730-helm-1905", 1905, "DCAE", "dcae", + "123-456-321", "342343", true); + + bpItem2 = new ServiceTypeSummary("xyz1731", "xyz1731-helm-1906", 1906, "DCAE", "dcae", + "123-456-789", "342343", true); bpItemFull = new ServiceType.Builder("xyz1731", "xyz1731-helm-1906", 1906, "tosca_definitions_version: cloudify_dsl_1_3", "", "DCAE", "dcae").build(); @@ -216,7 +226,7 @@ public class NbApiControllerTest extends MockitoTestSuite { Collection<ServiceTypeSummary> items2 = new ArrayList<ServiceTypeSummary>(); items2.add(bpItem2); - + String pageLinks2 = "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; ServiceTypeSummaryList.PaginationLinks paginationLinks = @@ -224,7 +234,7 @@ public class NbApiControllerTest extends MockitoTestSuite { int totalCount = 1; bpList = new ServiceTypeSummaryList(items, totalCount, paginationLinks); bpList2 = new ServiceTypeSummaryList(items2, totalCount, paginationLinks); - + } public void createBpUploadItem() { @@ -237,52 +247,66 @@ public class NbApiControllerTest extends MockitoTestSuite { @Test public final void testCreateBlueprint() throws Exception { + // Given String bpTemplate = "tosca_definitions_version: cloudify_dsl_1_3"; - ServiceTypeUploadRequest bpUploadReq = + ServiceTypeUploadRequest bpUploadReq = new ServiceTypeUploadRequest("dcae_user", "mod1", 2008, bpTemplate, "DCAE", "dcae"); - - when(inventoryClient.addServiceType(Matchers.<ServiceTypeRequest>any())) - .thenThrow(BlueprintParseException.class).thenThrow(httpException) - .thenThrow(Exception.class).thenReturn(bpItemFull); - - //when(mockedRequest.getRequestURI()).thenReturn("https://invt-svc:8080/dcae-service-types"); - String actual = subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); - assertTrue(actual.contains("error")); - actual = subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); + + // When + when(inventoryClient.addServiceType(Mockito.<ServiceTypeRequest>any())) + .thenThrow(httpException).thenThrow(Exception.class).thenReturn(bpItemFull); + + // Then + String actual = + subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); assertTrue(actual.contains("error")); actual = subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); assertTrue(actual.contains("error")); actual = subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); assertTrue(actual.contains("xyz")); } - + + @Test + public final void testCreateBlueprint_badBp() throws Exception { + + String bpTemplate = "tosca_definitions_version: cloudify_dsl_1_3"; + ServiceTypeUploadRequest bpUploadReq = + new ServiceTypeUploadRequest("dcae_user", "mod1", 2008, bpTemplate, "DCAE", "dcae"); + + when(Blueprint.parse(bpUploadReq.getBlueprintTemplate())) + .thenThrow(BlueprintParseException.class); + + String actual1 = + subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); + assertTrue(actual1.contains("error")); + } + @Test public final void testCreateBlueprint_badReq() throws Exception { String bpTemplate = "tosca_definitions_version: cloudify_dsl_1_3"; - ServiceTypeUploadRequest bpUploadReq = + ServiceTypeUploadRequest bpUploadReq = new ServiceTypeUploadRequest("dcae_user", "mod1", 2008, bpTemplate, "DCAE", ""); - - when(inventoryClient.addServiceType(Matchers.<ServiceTypeRequest>any())) - .thenThrow(BlueprintParseException.class).thenThrow(httpException) - .thenThrow(Exception.class).thenReturn(null); - - String actual = subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); + + String actual = + subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); assertTrue(actual.contains("error")); } - + @Test public final void testQueryBlueprint() throws Exception { - + Optional<ServiceType> optionBp = Optional.ofNullable(bpItemFull); - when(inventoryClient.getServiceType(Mockito.any())).thenReturn(optionBp).thenThrow(Exception.class); - - String actual = subject.queryBlueprint("123-343", mockedRequest, mockedResponse, uriBuilder); + when(inventoryClient.getServiceType(Mockito.any())).thenReturn(optionBp) + .thenThrow(Exception.class); + + String actual = + subject.queryBlueprint("123-343", mockedRequest, mockedResponse, uriBuilder); assertTrue(actual.contains("xyz")); - + actual = subject.queryBlueprint("123-343", mockedRequest, mockedResponse, uriBuilder); assertTrue(actual.contains("error")); } - + @Test public final void testGetTenants() throws Exception { String tenantsList = @@ -301,38 +325,41 @@ public class NbApiControllerTest extends MockitoTestSuite { String tenantStr = subject.getTenants(mockedRequest); assertTrue(tenantStr.contains("dyh1b")); } - + @Test - public final void testGetBlueprintsByPage() { + public final void testGetBlueprintsByPage() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - String filterStr = "{\"owner\": \"xyz1730\", \"name\": \"xyz1730-helm-1905\", \"id\": \"123\"}"; - + String filterStr = + "{\"owner\": \"xyz1730\", \"name\": \"xyz1730-helm-1905\", \"id\": \"123\"}"; + mockedRequest.addParameter("filters", filterStr); mockedRequest.addParameter("sort", "name"); Set<String> userRoleSet = new HashSet<String>(); Set<String> userApps = new TreeSet<>(); userRoleSet.add("Standard User"); - userRoleSet.add("ECOMPC_DCAE_WRITE"); + userRoleSet.add("DCAE_WRITE"); userApps.add("dcae"); - + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); Collection<ServiceTypeSummary> items = bpList.items; Stream<ServiceTypeSummary> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1).thenThrow(Exception.class); - String result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); - assertTrue(result.contains("xyz")); - + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1) + .thenThrow(Exception.class); + String result = + subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("xyz")); + result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); assertTrue(result.contains("error")); } - + @Test - public final void testGetBlueprintsByPage_sortByOwner() { + public final void testGetBlueprintsByPage_sortByOwner() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); @@ -343,22 +370,24 @@ public class NbApiControllerTest extends MockitoTestSuite { userRoleSet.add("Standard User"); userRoleSet.add("ECOMPC_DCAE_WRITE"); userApps.add("dcae"); - + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); Collection<ServiceTypeSummary> items = bpList.items; Stream<ServiceTypeSummary> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1).thenThrow(Exception.class); - String result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); - assertTrue(result.contains("xyz")); - + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1) + .thenThrow(Exception.class); + String result = + subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("xyz")); + result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); assertTrue(result.contains("error")); } - + @Test - public final void testGetBlueprintsByPage_sortByTypeId() { + public final void testGetBlueprintsByPage_sortByTypeId() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); @@ -369,22 +398,24 @@ public class NbApiControllerTest extends MockitoTestSuite { userRoleSet.add("Standard User"); userRoleSet.add("ECOMPC_DCAE_WRITE"); userApps.add("dcae"); - + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); Collection<ServiceTypeSummary> items = bpList.items; Stream<ServiceTypeSummary> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1).thenThrow(Exception.class); - String result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); - assertTrue(result.contains("xyz")); - + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1) + .thenThrow(Exception.class); + String result = + subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("xyz")); + result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); assertTrue(result.contains("error")); } - + @Test - public final void testGetBlueprintsByPage_sortByCreated() { + public final void testGetBlueprintsByPage_sortByCreated() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); @@ -395,22 +426,24 @@ public class NbApiControllerTest extends MockitoTestSuite { userRoleSet.add("Standard User"); userRoleSet.add("ECOMPC_DCAE_WRITE"); userApps.add("dcae"); - + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); Collection<ServiceTypeSummary> items = bpList.items; Stream<ServiceTypeSummary> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1).thenThrow(Exception.class); - String result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); - assertTrue(result.contains("xyz")); - + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1) + .thenThrow(Exception.class); + String result = + subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("xyz")); + result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); assertTrue(result.contains("error")); } - + @Test - public final void testGetBlueprintsByPage_sortByVersion() { + public final void testGetBlueprintsByPage_sortByVersion() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); @@ -421,23 +454,25 @@ public class NbApiControllerTest extends MockitoTestSuite { userRoleSet.add("Standard User"); userRoleSet.add("ECOMPC_DCAE_WRITE"); userApps.add("dcae"); - + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); Collection<ServiceTypeSummary> items = bpList.items; Stream<ServiceTypeSummary> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1).thenThrow(Exception.class); - String result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); - assertTrue(result.contains("xyz")); - + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1) + .thenThrow(Exception.class); + String result = + subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("xyz")); + result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); assertTrue(result.contains("error")); } - + @SuppressWarnings("unchecked") @Test - public final void testGetDeployment() { + public final void testGetDeployment() throws HttpStatusCodeException, Exception { CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", "id1", null, null, null, null, null, null, null, "tenant1"); @@ -451,15 +486,16 @@ public class NbApiControllerTest extends MockitoTestSuite { CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); - when(cfyClient.getDeployment(Mockito.any())).thenReturn(cldDeplList).thenThrow(Exception.class); - + when(cfyClient.getDeployment(Mockito.any())).thenReturn(cldDeplList) + .thenThrow(Exception.class); + String actual = subject.getDeployment("id1", mockedRequest); assertTrue(actual.contains("id1")); - + actual = subject.getDeployment("id1", mockedRequest); assertTrue(actual.contains("error")); } - + @Test public final void testGetDeploymentsByPage() throws Exception { CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", @@ -475,15 +511,17 @@ public class NbApiControllerTest extends MockitoTestSuite { CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); - when(cfyClient.getDeploymentsWithFilter(Mockito.any())).thenReturn(items).thenThrow(Exception.class); - - String actual = subject.getDeploymentsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + when(cfyClient.getDeploymentsWithFilter(Mockito.any())).thenReturn(items) + .thenThrow(Exception.class); + + String actual = + subject.getDeploymentsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); assertTrue(actual.contains("id1")); - + actual = subject.getDeploymentsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); assertTrue(actual.contains("error")); } - + @Test public final void testGetDeploymentInputs() throws Exception { CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", @@ -499,8 +537,9 @@ public class NbApiControllerTest extends MockitoTestSuite { CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); - when(cfyClient.getDeploymentInputs(Mockito.any(), Mockito.any())).thenReturn(cldDeplList).thenThrow(httpException).thenThrow(Exception.class); - + when(cfyClient.getDeploymentInputs(Mockito.any(), Mockito.any())).thenReturn(cldDeplList) + .thenThrow(httpException).thenThrow(Exception.class); + String actual = subject.getDeploymentInputs("dep_id", "tenant1", mockedRequest); assertTrue(actual.contains("id1")); @@ -511,7 +550,7 @@ public class NbApiControllerTest extends MockitoTestSuite { assertTrue(actual.contains("error")); } - + @Test public final void testGetServicesForType() throws Exception { String testTypeIds = "44234234"; @@ -520,56 +559,58 @@ public class NbApiControllerTest extends MockitoTestSuite { expectedSrvcIds.add(expectedSrvc); ServiceRefList expectedSrvcRefList = new ServiceRefList(expectedSrvcIds, 1); - when(inventoryClient.getServicesForType(Matchers.<ServiceQueryParams>any())) + when(inventoryClient.getServicesForType(any(ServiceQueryParams.class))) .thenReturn(expectedSrvcRefList); String actual = subject.getServicesForType(mockedRequest, testTypeIds); assertTrue(actual.contains(testTypeIds)); } - + @SuppressWarnings("unchecked") @Test public final void testCreateDeployment() throws Exception { + // Given Map<String, Object> inputs = new HashMap<>(); inputs.put("key1", "value1"); inputs.put("key2", "value2"); inputs.put("key3", "value3"); inputs.put("key4", 100); - DeploymentInput deployInput1 = new DeploymentInput("component1", "tag1", - "xyz1731-helm-1906", 1906, "blueprintId", inputs, "tenant1", - null, true, true, true, false, true, false); + DeploymentInput deployInput1 = + new DeploymentInput("component1", "tag1", "xyz1731-helm-1906", 1906, "blueprintId", + inputs, "tenant1", null, true, true, true, false, true, false); - DeploymentInput deployInput2 = new DeploymentInput("component1", "tag1", - "xyz1731-helm-1906", 1906, null, inputs, "tenant1", - null, true, true, true, false, true, false); + DeploymentInput deployInput2 = + new DeploymentInput("component1", "tag1", "xyz1731-helm-1906", 1906, null, inputs, + "tenant1", null, true, true, true, false, true, false); DeploymentResponseLinks expectLink = new DeploymentResponseLinks("self", "status"); DeploymentResponse expectResp = new DeploymentResponse("req1", expectLink); Collection<ServiceTypeSummary> items = bpList2.items; Stream<ServiceTypeSummary> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream1); - -/* String actualResp0 = subject.createDeployment(mockedRequest, mockedResponse, deployInput2); - assertTrue(actualResp0.contains("error"));*/ Optional<ServiceType> optionBp = Optional.ofNullable(bpItemFull); - Mockito.when(inventoryClient.getServiceType(Matchers.anyString())).thenReturn(optionBp); - + StringBuffer expectedStrBuff = new StringBuffer(); expectedStrBuff.append("http://oom.s2.com"); + + // When + when(inventoryClient.getServiceTypes(any(ServiceTypeQueryParams.class))) + .thenReturn(sampleStream1); + + when(inventoryClient.getServiceType(anyString())).thenReturn(optionBp); + when(mockedRequest.getRequestURL()).thenReturn(expectedStrBuff); - when(deploymentHandlerClient.putDeployment(Matchers.anyString(), Matchers.anyString(), - Matchers.<DeploymentRequest>any())).thenReturn(expectResp).thenReturn(expectResp) - .thenThrow(badReqError) - .thenThrow(srvcExistError).thenThrow(serverError).thenThrow(downStrmError) - .thenThrow(Exception.class); + when(deploymentHandlerClient.putDeployment(anyString(), anyString(), + any(DeploymentRequest.class))).thenReturn(expectResp).thenReturn(expectResp) + .thenThrow(badReqError).thenThrow(srvcExistError).thenThrow(serverError) + .thenThrow(downStrmError).thenThrow(Exception.class); + // Then String actualResp = subject.createDeployment(mockedRequest, mockedResponse, deployInput1); assertTrue(actualResp.contains("component1")); - + actualResp = subject.createDeployment(mockedRequest, mockedResponse, deployInput2); assertTrue(actualResp.contains("component1")); @@ -589,83 +630,82 @@ public class NbApiControllerTest extends MockitoTestSuite { assertTrue(actualResp.contains("error")); } - + @Test public final void testGetExecutionByDeploymentId() throws Exception { - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); - + CloudifyExecution cldExecution = new CloudifyExecution("successful", "created_at", + "ended_at", "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); cldExecutionList.add(cldExecution); CloudifyExecutionList cloudifyExecutionList = new CloudifyExecutionList(cldExecutionList, null); - + when(cfyClient.getExecutionsSummary(Mockito.any(), Mockito.any())) .thenReturn(cloudifyExecutionList).thenThrow(httpException).thenThrow(Exception.class);; - + String actual = subject.getExecutionByDeploymentId("deploymentId", "tenant", mockedRequest); assertTrue(actual.contains("execution_id1")); - + actual = subject.getExecutionByDeploymentId("deploymentId", "tenant", mockedRequest); assertTrue(actual.contains("error")); - + actual = subject.getExecutionByDeploymentId("deploymentId", "tenant", mockedRequest); assertTrue(actual.contains("error")); } - + @Test public final void testGetServiceHealthByDeploymentId() throws Exception { - String[] svcTags = {"cfytenantname=onap"}; + String[] svcTags = {"cfytenantname=onap"}; ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", "This is a pgaas1_Service_ID health check", "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", "pgaas1_Service_ID", "pgaasServer1", svcTags, 190199, 199395); - - ConsulDeploymentHealth cnslDeployHlth = + + ConsulDeploymentHealth cnslDeployHlth = new ConsulDeploymentHealth.Builder(consulSrvcHlth).build(); - + when(consulClient.getServiceHealthByDeploymentId(Mockito.any())).thenReturn(cnslDeployHlth) .thenThrow(httpException).thenThrow(Exception.class); String actual = subject.getServiceHealthByDeploymentId("deploymentId", mockedRequest); assertTrue(actual.contains("cjlvmcnsl00")); - + actual = subject.getServiceHealthByDeploymentId("deploymentId", mockedRequest); assertTrue(actual.contains("error")); - + actual = subject.getServiceHealthByDeploymentId("deploymentId", mockedRequest); assertTrue(actual.contains("error")); } - + @Test public final void testDeleteBlueprint() throws Exception { - //String expected = "{\"202\": \"OK\"}"; + // String expected = "{\"202\": \"OK\"}"; String expected = "{\"204\": \"Blueprint deleted\"}"; List<CloudifyDeployedTenant> deplForBp = new ArrayList<>(); deplForBp.clear(); - Mockito.when(cfyClient.getDeploymentForBlueprint(Matchers.<String>any())) - .thenReturn(deplForBp); - + Mockito.when(cfyClient.getDeploymentForBlueprint(anyString())).thenReturn(deplForBp); + Optional<ServiceType> optionBp = Optional.ofNullable(bpItemFull); - Mockito.when(inventoryClient.getServiceType(Matchers.anyString())).thenReturn(optionBp); + Mockito.when(inventoryClient.getServiceType(anyString())).thenReturn(optionBp); List<ServiceRef> srvcRefList = new ArrayList<>(); srvcRefList.clear(); int itemCnt = 0; ServiceRefList mockSvcRefList = new ServiceRefList(srvcRefList, itemCnt); - Mockito.when(inventoryClient.getServicesForType(Matchers.<ServiceQueryParams>any())) + Mockito.when(inventoryClient.getServicesForType(any(ServiceQueryParams.class))) .thenReturn(mockSvcRefList); - + doNothing().doThrow(serviceTypeException).doThrow(Exception.class).when(inventoryClient) - .deleteServiceType(Matchers.anyString()); + .deleteServiceType(anyString()); - String actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse, uriBuilder); + String actual = + subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse, uriBuilder); assertEquals(expected, actual); actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse, uriBuilder); @@ -677,25 +717,26 @@ public class NbApiControllerTest extends MockitoTestSuite { @Test public final void testDeleteBlueprint_withDepl() throws Exception { - CloudifyDeployedTenant mockCfyDeplTen = + CloudifyDeployedTenant mockCfyDeplTen = new CloudifyDeployedTenant("id1", "tenant", "45435435", "54543534"); - + Optional<ServiceType> optionBp = Optional.ofNullable(bpItemFull); - Mockito.when(inventoryClient.getServiceType(Matchers.anyString())).thenReturn(optionBp); - + Mockito.when(inventoryClient.getServiceType(anyString())).thenReturn(optionBp); + List<CloudifyDeployedTenant> deplForBp = new ArrayList<>(); deplForBp.add(mockCfyDeplTen); - Mockito.when(cfyClient.getDeploymentForBlueprint(Matchers.<String>any())) - .thenReturn(deplForBp); - - String actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse, uriBuilder); + Mockito.when(cfyClient.getDeploymentForBlueprint(anyString())).thenReturn(deplForBp); + + String actual = + subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse, uriBuilder); assertTrue(actual.contains("error")); } - + @Test public final void testDeleteDeployment() throws Exception { - CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", - "created_at", "updated_at", "dcae_dep_id", null, null, null, null, null, null, null, "tenant1"); + CloudifyDeployment cldDepl = + new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", + "dcae_dep_id", null, null, null, null, null, null, null, "tenant1"); List<CloudifyDeployment> items = new ArrayList<CloudifyDeployment>(); items.add(cldDepl); @@ -707,27 +748,28 @@ public class NbApiControllerTest extends MockitoTestSuite { CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); - Mockito.when(cfyClient.getDeployment(Matchers.anyString(), Matchers.anyString())).thenReturn(cldDeplList); - + Mockito.when(cfyClient.getDeployment(anyString(), anyString())).thenReturn(cldDeplList); + doNothing().doThrow(badReqError).doThrow(serverError).doThrow(downStrmError) - .doThrow(notFoundError).doThrow(Exception.class).when(deploymentHandlerClient) - .deleteDeployment(Matchers.anyString(), Matchers.anyString()); + .doThrow(notFoundError).doThrow(Exception.class).when(deploymentHandlerClient) + .deleteDeployment(anyString(), anyString()); - String actual = subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); + String actual = + subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); assertTrue(actual.contains("dcae_dep_id")); - + actual = subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); assertTrue(actual.contains("error")); - + actual = subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); assertTrue(actual.contains("error")); - + actual = subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); assertTrue(actual.contains("error")); - + actual = subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); assertTrue(actual.contains("error")); - + actual = subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); assertTrue(actual.contains("error")); @@ -742,9 +784,8 @@ public class NbApiControllerTest extends MockitoTestSuite { HttpHeaders httpHeader = new HttpHeaders(); httpHeader.put("tenant", tenants); - CloudifyExecution cfyExecObj = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); + CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "ended_at", + "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); when(cfyClient.cancelExecution(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(cfyExecObj).thenThrow(Exception.class).thenThrow(httpException); @@ -761,13 +802,12 @@ public class NbApiControllerTest extends MockitoTestSuite { subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); assertTrue(actualResult.contains("error")); } - + @SuppressWarnings("unchecked") @Test public final void testModifyDeployment() throws Exception { - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); + CloudifyExecution cldExecution = new CloudifyExecution("successful", "created_at", + "ended_at", "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); Map<String, Object> params = new HashMap<String, Object>(); params.put("tenant", "tenant1"); @@ -775,7 +815,7 @@ public class NbApiControllerTest extends MockitoTestSuite { CloudifyExecutionRequest cfyExecReq = new CloudifyExecutionRequest("deployment_id", "upgrade", false, false, "tenant1", params); - + CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); List<CloudifyNodeInstanceId> cfyNodeInstItems = new ArrayList<CloudifyNodeInstanceId>(); @@ -786,18 +826,18 @@ public class NbApiControllerTest extends MockitoTestSuite { new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); when(cfyClient.getNodeInstanceId(Mockito.any(), Mockito.any())).thenReturn(cfyNodeInstList); - + String secretTokenStr = - "{\"created_at\": \"created_ts\", \"key\": \"acl_key\", \"updated_at\": \"updated_ts\", \"value\": \"acl_token_val\", \"visibility\": \"global\", \"is_hidden_value\": \"false\", \"tenant_name\": \"tenant\", \"resource_availability\": \"rsrc\"}"; + "{\"created_at\": \"created_ts\", \"key\": \"acl_key\", \"updated_at\": \"updated_ts\", \"value\": \"acl_token_val\", \"visibility\": \"global\", \"is_hidden_value\": \"false\", \"tenant_name\": \"tenant\", \"resource_availability\": \"rsrc\"}"; CloudifySecret secretData = null; try { secretData = objectMapper.readValue(secretTokenStr, CloudifySecret.class); } catch (Exception e) { - + } when(cfyClient.getSecret(Mockito.any(), Mockito.any())).thenReturn(secretData); - when(cfyClient.startExecution(Matchers.<CloudifyExecutionRequest>any())) - .thenReturn(cldExecution).thenThrow(Exception.class).thenThrow(httpException); + when(cfyClient.startExecution(any(CloudifyExecutionRequest.class))).thenReturn(cldExecution) + .thenThrow(Exception.class).thenThrow(httpException); String inputParamStr = "{\"tenant\": \"tenant1\", \"workflow\":\"upgrade\"}"; @@ -805,7 +845,7 @@ public class NbApiControllerTest extends MockitoTestSuite { String actualResult = subject.modifyDeployment("depId", mockedRequest, is1); assertTrue(actualResult.contains("execution_id1")); - InputStream is2 = new ByteArrayInputStream(inputParamStr.getBytes()); + InputStream is2 = new ByteArrayInputStream(inputParamStr.getBytes()); actualResult = subject.modifyDeployment("depId", mockedRequest, is2); assertTrue(actualResult.contains("error")); diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dasboard/exceptions/DahboardControllerExceptionTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dasboard/exceptions/DahboardControllerExceptionTest.java index ab98400..dbf0e2a 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dasboard/exceptions/DahboardControllerExceptionTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dasboard/exceptions/DahboardControllerExceptionTest.java @@ -2,24 +2,24 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. - * - * Modifications Copyright (C) 2019 IBM. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * + * Modifications Copyright (C) 2019 IBM. * ================================================================================ - * 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.dasboard.exceptions; @@ -30,38 +30,41 @@ import org.onap.ccsdk.dashboard.exceptions.DashboardControllerException; public class DahboardControllerExceptionTest { - @Test - public void TestException1() { - - DashboardControllerException sta = new DashboardControllerException(); - assertEquals("org.onap.ccsdk.dashboard.exceptions.DashboardControllerException",sta.getClass().getName()); - - } + @Test + public void TestException1() { - @Test - public void TestException2() { - - DashboardControllerException sta= new DashboardControllerException("org.onap.ccsdk.dashboard.exceptions.DashboardControllerException"); - assertEquals(sta.getMessage(), "org.onap.ccsdk.dashboard.exceptions.DashboardControllerException"); - - } + DashboardControllerException sta = new DashboardControllerException(); + assertEquals("org.onap.ccsdk.dashboard.exceptions.DashboardControllerException", + sta.getClass().getName()); + } - @Test - public void TestException3() { - - DashboardControllerException sta= new DashboardControllerException(new Throwable()); - assertEquals("org.onap.ccsdk.dashboard.exceptions.DashboardControllerException", sta.getClass().getName()); - - } + @Test + public void TestException2() { - + DashboardControllerException sta = new DashboardControllerException( + "org.onap.ccsdk.dashboard.exceptions.DashboardControllerException"); + assertEquals(sta.getMessage(), + "org.onap.ccsdk.dashboard.exceptions.DashboardControllerException"); - @Test - public void TestException4() { - - DashboardControllerException sta= new DashboardControllerException("org.onap.ccsdk.dashboard.exceptions.DashboardControllerException", new Throwable()); - assertEquals("org.onap.ccsdk.dashboard.exceptions.DashboardControllerException",sta.getClass().getName()); - - } + } + + @Test + public void TestException3() { + + DashboardControllerException sta = new DashboardControllerException(new Throwable()); + assertEquals("org.onap.ccsdk.dashboard.exceptions.DashboardControllerException", + sta.getClass().getName()); + + } + + @Test + public void TestException4() { + + DashboardControllerException sta = new DashboardControllerException( + "org.onap.ccsdk.dashboard.exceptions.DashboardControllerException", new Throwable()); + assertEquals("org.onap.ccsdk.dashboard.exceptions.DashboardControllerException", + sta.getClass().getName()); + + } } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java index d88e530..6744fd4 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java @@ -25,6 +25,8 @@ package org.onap.ccsdk.dashboard.controller; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; @@ -35,11 +37,9 @@ import java.util.List; import java.util.Map; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -73,26 +73,28 @@ import org.onap.ccsdk.dashboard.rest.InventoryClient; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.util.CacheManager; import org.onap.portalsdk.core.web.support.UserUtils; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpStatusCodeException; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) public class CloudifyControllerTest extends MockitoTestSuite { @Mock private CloudifyClient restClient; - + @Mock private InventoryClient invClient; @InjectMocks - private CloudifyController subject = new CloudifyController(); + private CloudifyController subject; protected final ObjectMapper objectMapper = new ObjectMapper(); @@ -112,7 +114,7 @@ public class CloudifyControllerTest extends MockitoTestSuite { objectMapper.registerModule(new Jdk8Module()); httpException = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "statusText"); CacheManager testCache = new CacheManager(); - subject.setCacheManager(testCache); + subject.setCacheManager(testCache); } @SuppressWarnings("unchecked") @@ -150,10 +152,10 @@ public class CloudifyControllerTest extends MockitoTestSuite { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - //mockedRequest.addParameter("searchBy", "xyz"); + // mockedRequest.addParameter("searchBy", "xyz"); mockedRequest.addParameter("sortBy", "owner"); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - + CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", "id1", null, null, null, null, null, null, null, "tenant1"); @@ -166,14 +168,14 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); - - Mockito.when(restClient.getDeployments( - Mockito.any(),Mockito.anyInt(), Mockito.anyInt(), Mockito.anyBoolean())) - .thenReturn(items); - + + Mockito.when(restClient.getDeployments(Mockito.any(), Mockito.anyInt(), Mockito.anyInt(), + Mockito.anyBoolean())).thenReturn(items); + String actual = subject.getAllServiceNames(mockedRequest); assertTrue(actual.contains("id1")); } + @Test public final void testGetDeploymentsByPage() { User user = mockUser.mockUser(); @@ -182,7 +184,7 @@ public class CloudifyControllerTest extends MockitoTestSuite { mockedRequest.addParameter("searchBy", "tenant:default_tenant;cache:false;serviceRef:id1"); mockedRequest.addParameter("sortBy", "owner"); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - + CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", "id1", null, null, null, null, null, null, null, "tenant1"); @@ -195,43 +197,38 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); - - Mockito.when(restClient.getDeployments( - Mockito.any(),Mockito.anyInt(), Mockito.anyInt(), Mockito.anyBoolean(), Mockito.anyBoolean())) - .thenReturn(items); - List<CloudifyDeploymentExt> cfyDepExList = - new ArrayList<CloudifyDeploymentExt>(); - List<CloudifyDeploymentHelm> cfyDeplHelmList = - new ArrayList<CloudifyDeploymentHelm>(); - - Mockito.when(restClient.updateWorkflowStatus(Mockito.any())). - thenReturn(cfyDepExList); - Mockito.when(restClient.updateHelmInfo(Mockito.any())). - thenReturn(cfyDeplHelmList); - + + Mockito.when(restClient.getDeployments(Mockito.any(), Mockito.anyInt(), Mockito.anyInt(), + Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(items); + List<CloudifyDeploymentExt> cfyDepExList = new ArrayList<CloudifyDeploymentExt>(); + List<CloudifyDeploymentHelm> cfyDeplHelmList = new ArrayList<CloudifyDeploymentHelm>(); + + Mockito.when(restClient.updateWorkflowStatus(Mockito.any())).thenReturn(cfyDepExList); + Mockito.when(restClient.updateHelmInfo(Mockito.any())).thenReturn(cfyDeplHelmList); + String actual = subject.getDeploymentsByPage(mockedRequest); assertTrue(actual.contains("id1")); } - + @Test public final void testViewBlueprintContentById() throws Exception { byte[] result = "sample blueprint yaml content".getBytes(); - + when(restClient.viewBlueprint(Mockito.any(), Mockito.any())).thenReturn(result); - + byte[] actual = subject.viewBlueprintContentById("id", "tenant", mockedRequest); assertArrayEquals(result, actual); } - + @Test public final void testGetDepCount() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - //mockedRequest.addParameter("searchBy", "xyz"); + // mockedRequest.addParameter("searchBy", "xyz"); mockedRequest.addParameter("sortBy", "owner"); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - + CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", "id1", null, null, null, null, null, null, null, "tenant1"); @@ -244,17 +241,16 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); - - Mockito.when(restClient.getDeploymentsWithFilter(Mockito.any())) - .thenReturn(items); - + + Mockito.when(restClient.getDeploymentsWithFilter(Mockito.any())).thenReturn(items); + String actual = subject.getDepCount(mockedRequest); assertTrue(actual.contains("items")); } - + @Test - public final void testGetPluginCount() throws JsonProcessingException { - CloudifyPlugin sampleData = + public final void testGetPluginCount() throws HttpStatusCodeException, Exception { + CloudifyPlugin sampleData = new CloudifyPlugin("plugin1", "202001", "linux", "linux_k8s_plugin", "20200801"); List<CloudifyPlugin> cfyPlugins = new ArrayList<CloudifyPlugin>(); @@ -265,56 +261,51 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyPluginList.Metadata metadata = new CloudifyPluginList.Metadata(pageObj); CloudifyPluginList cfyPluginList = new CloudifyPluginList(cfyPlugins, metadata); - + when(restClient.getPlugins()).thenReturn(cfyPluginList); String actual = subject.getPluginCount(mockedRequest); assertTrue(actual.contains("1")); } - + @Test public final void testDeleteBlueprint() throws Exception { - String json = "{\"202\": \"OK\"}"; - - doNothing().doThrow(httpException).doThrow(Exception.class).when(restClient).deleteBlueprint(Mockito.any(), Mockito.any()); - + String json = "{\"202\": \"OK\"}"; + + doNothing().doThrow(httpException).doThrow(Exception.class).when(restClient) + .deleteBlueprint(Mockito.any(), Mockito.any()); + String actual = subject.deleteBlueprint("id", "tenant", mockedRequest, mockedResponse); assertTrue(actual.equals(json)); - + actual = subject.deleteBlueprint("id", "tenant", mockedRequest, mockedResponse); assertTrue(actual.contains("error")); - + actual = subject.deleteBlueprint("id", "tenant", mockedRequest, mockedResponse); assertTrue(actual.contains("error")); } - + @Test - public final void testGetDeploymentsForType() throws Exception { + public final void testGetDeploymentsForType() throws Exception { String[] testTypeIds = {"44234234"}; ServiceRef expectedSrvc = new ServiceRef("dcae_dtiapi_1902", "432423", "433434"); Collection<ServiceRef> expectedSrvcIds = new ArrayList<ServiceRef>(); expectedSrvcIds.add(expectedSrvc); ServiceRefList expectedSrvcRefList = new ServiceRefList(expectedSrvcIds, 1); - CloudifyDeployedTenant cfyDepTen = + CloudifyDeployedTenant cfyDepTen = new CloudifyDeployedTenant("id", "tenant_name", "created_at", "updated_at"); - + List<CloudifyDeployedTenant> cfyDeplTenList = new ArrayList<>(); cfyDeplTenList.add(cfyDepTen); - + when(restClient.getDeploymentForBlueprint(Mockito.any())).thenReturn(cfyDeplTenList); - - when(invClient.getServicesForType(Matchers.<ServiceQueryParams>any())) + + when(invClient.getServicesForType(any(ServiceQueryParams.class))) .thenReturn(expectedSrvcRefList); String actual = subject.getDeploymentsForType(mockedRequest, testTypeIds); assertTrue(actual.contains(testTypeIds[0])); } - - @Test - @Ignore - public final void testCacheOwnerDeployMap() { - - } - + @Test public final void testGetExecutionsPerTenant() throws Exception { String tenantsList = @@ -328,22 +319,21 @@ public class CloudifyControllerTest extends MockitoTestSuite { } MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); Mockito.when(restClient.getTenants()).thenReturn(tenantData); - - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); - + + CloudifyExecution cldExecution = new CloudifyExecution("successful", "created_at", + "ended_at", "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); cldExecutionList.add(cldExecution); CloudifyExecutionList cloudifyExecutionList = new CloudifyExecutionList(cldExecutionList, null); - + when(restClient.getExecutionsSummaryPerTenant(Mockito.any())) .thenReturn(cloudifyExecutionList).thenReturn(cloudifyExecutionList) .thenReturn(cloudifyExecutionList); - + String actual = subject.getExecutionsPerTenant(mockedRequest, "default_tenant", "failed"); assertFalse(actual.contains("execution_id1")); actual = subject.getExecutionsPerTenant(mockedRequest, "default_tenant", "successful"); @@ -351,7 +341,7 @@ public class CloudifyControllerTest extends MockitoTestSuite { actual = subject.getExecutionsPerTenant(mockedRequest, null, "successful"); assertTrue(actual.contains("execution_id1")); } - + @Test public final void testGetExecutionsPerTenant_error() throws Exception { String tenantsList = @@ -365,46 +355,44 @@ public class CloudifyControllerTest extends MockitoTestSuite { } MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); Mockito.when(restClient.getTenants()).thenReturn(tenantData); - - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); - + + CloudifyExecution cldExecution = new CloudifyExecution("successful", "created_at", + "ended_at", "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); cldExecutionList.add(cldExecution); CloudifyExecutionList cloudifyExecutionList = new CloudifyExecutionList(cldExecutionList, null); - - when(restClient.getExecutionsSummaryPerTenant(Mockito.any())) - .thenThrow(Exception.class).thenThrow(Exception.class).thenThrow(Exception.class); - + + when(restClient.getExecutionsSummaryPerTenant(Mockito.any())).thenThrow(Exception.class) + .thenThrow(Exception.class).thenThrow(Exception.class); + String actual = subject.getExecutionsPerTenant(mockedRequest, "default_tenant", "failed"); assertTrue(actual.contains("error")); - + actual = subject.getExecutionsPerTenant(mockedRequest, "default_tenant", "successful"); assertTrue(actual.contains("error")); - + actual = subject.getExecutionsPerTenant(mockedRequest, null, "failed"); assertTrue(actual.contains("error")); } - + @Test - public final void testQueryExecution() throws Exception { - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); + public final void testQueryExecution() throws Exception { + CloudifyExecution cldExecution = new CloudifyExecution("successful", "created_at", + "ended_at", "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); cldExecutionList.add(cldExecution); - - when(restClient.getExecutionIdSummary( - Mockito.any(), Mockito.any())).thenReturn(cldExecution); - + + when(restClient.getExecutionIdSummary(Mockito.any(), Mockito.any())) + .thenReturn(cldExecution); + String actual = subject.queryExecution("id", "tenant", mockedRequest); assertTrue(actual.contains("items")); } - + @SuppressWarnings("unchecked") @Test public final void testGetActiveExecutions() throws Exception { @@ -419,36 +407,34 @@ public class CloudifyControllerTest extends MockitoTestSuite { } MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); Mockito.when(restClient.getTenants()).thenReturn(tenantData).thenThrow(Exception.class); - - CloudifyExecution cldExecution = - new CloudifyExecution("started", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); - + + CloudifyExecution cldExecution = new CloudifyExecution("started", "created_at", "ended_at", + "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); cldExecutionList.add(cldExecution); CloudifyExecutionList cloudifyExecutionList = new CloudifyExecutionList(cldExecutionList, null); - + when(restClient.getExecutionsSummaryPerTenant(Mockito.any())) .thenReturn(cloudifyExecutionList).thenReturn(cloudifyExecutionList); - + String actual = subject.getActiveExecutions(mockedRequest); assertTrue(actual.contains("execution_id1")); actual = subject.getActiveExecutions(mockedRequest); assertTrue(actual.contains("error")); - + } - + @Test public final void testGetNodeInstanceDetails() throws Exception { - - Map<String, Object> runtime_properties = - new HashMap<>(); + + Map<String, Object> runtime_properties = new HashMap<>(); runtime_properties.put("key1", "value1"); - - CloudifyNodeInstance cfyNodeInst = + + CloudifyNodeInstance cfyNodeInst = new CloudifyNodeInstance("node_instance_id1", runtime_properties); List<CloudifyNodeInstance> cfyNodeInstItems = new ArrayList<CloudifyNodeInstance>(); @@ -457,24 +443,20 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyNodeInstanceList cfyNodeInstList = new CloudifyNodeInstanceList(cfyNodeInstItems, null); - - when(restClient.getNodeInstanceDetails(Mockito.any(), Mockito.any())). - thenReturn(cfyNodeInstList).thenThrow(httpException). - thenThrow(Exception.class); - - String actual = - subject.getNodeInstanceDetails("deploymentId", "tenant", mockedRequest); + + when(restClient.getNodeInstanceDetails(Mockito.any(), Mockito.any())) + .thenReturn(cfyNodeInstList).thenThrow(httpException).thenThrow(Exception.class); + + String actual = subject.getNodeInstanceDetails("deploymentId", "tenant", mockedRequest); assertTrue(actual.contains("node_instance_id1")); - - actual = - subject.getNodeInstanceDetails("deploymentId", "tenant", mockedRequest); + + actual = subject.getNodeInstanceDetails("deploymentId", "tenant", mockedRequest); + assertTrue(actual.contains("error")); + + actual = subject.getNodeInstanceDetails("deploymentId", "tenant", mockedRequest); assertTrue(actual.contains("error")); - - actual = - subject.getNodeInstanceDetails("deploymentId", "tenant", mockedRequest); - assertTrue(actual.contains("error")); } - + @Test public final void testGetNodeInstances() throws Exception { CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); @@ -485,27 +467,23 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyNodeInstanceIdList cfyNodeInstList = new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); - - when(restClient.getNodeInstances(Mockito.any(), Mockito.any())). - thenReturn(cfyNodeInstList).thenThrow(httpException). - thenThrow(Exception.class); - - String actual = - subject.getNodeInstances("deploymentId", "tenant", mockedRequest); + + when(restClient.getNodeInstances(Mockito.any(), Mockito.any())).thenReturn(cfyNodeInstList) + .thenThrow(httpException).thenThrow(Exception.class); + + String actual = subject.getNodeInstances("deploymentId", "tenant", mockedRequest); assertTrue(actual.contains("node_instance_id1")); - - actual = - subject.getNodeInstances("deploymentId", "tenant", mockedRequest); + + actual = subject.getNodeInstances("deploymentId", "tenant", mockedRequest); assertTrue(actual.contains("error")); - - actual = - subject.getNodeInstances("deploymentId", "tenant", mockedRequest); + + actual = subject.getNodeInstances("deploymentId", "tenant", mockedRequest); assertTrue(actual.contains("error")); } - + @Test public final void testGetPlugins() throws Exception { - CloudifyPlugin sampleData = + CloudifyPlugin sampleData = new CloudifyPlugin("plugin1", "202001", "linux", "linux_k8s_plugin", "20200801"); List<CloudifyPlugin> cfyPlugins = new ArrayList<CloudifyPlugin>(); @@ -516,38 +494,15 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyPluginList.Metadata metadata = new CloudifyPluginList.Metadata(pageObj); CloudifyPluginList cfyPluginList = new CloudifyPluginList(cfyPlugins, metadata); - + when(restClient.getPlugins()).thenReturn(cfyPluginList).thenThrow(Exception.class); String actual = subject.getPlugins(mockedRequest); assertTrue(actual.contains("plugin1")); - + actual = subject.getPlugins(mockedRequest); assertTrue(actual.contains("error")); } - - @Test - @Ignore - public final void testGetSecrets() { - - } - - @Test - @Ignore - public final void testGetSecret() { - - } - - @Test - @Ignore - public final void testDeleteSecret() { - - } - - @Test - @Ignore - public final void testCreateSecret() { - } - + @SuppressWarnings({"unchecked", "unchecked"}) @Test public final void testGetBlueprintById() throws Exception { @@ -619,13 +574,12 @@ public class CloudifyControllerTest extends MockitoTestSuite { actualResult = subject.getDeploymentById("id1", null, mockedRequest); assertTrue(actualResult.contains("error")); } - + @Test public void testGetExecutionsByPage() throws Exception { - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); - + CloudifyExecution cldExecution = new CloudifyExecution("successful", "created_at", + "ended_at", "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); cldExecutionList.add(cldExecution); @@ -644,8 +598,9 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); - - when(restClient.getDeployments(Mockito.any(), Mockito.anyInt(), Mockito.anyInt())).thenReturn(cldDeployList); + + when(restClient.getDeployments(Mockito.any(), Mockito.anyInt(), Mockito.anyInt())) + .thenReturn(cldDeployList); when(restClient.getExecutions(Mockito.any(), Mockito.any())) .thenReturn(cloudifyExecutionList).thenThrow(Exception.class) .thenReturn(cloudifyExecutionList); @@ -660,37 +615,39 @@ public class CloudifyControllerTest extends MockitoTestSuite { actualResult = subject.getExecutionsByPage(mockedRequest, null, "successful", "tenant1"); assertTrue(actualResult.contains("successful")); } -/* - @SuppressWarnings("unchecked") - @Test - public void testGetExecutionByIdAndDeploymentId() throws Exception { - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); - - List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); - - cldExecutionList.add(cldExecution); - - CloudifyExecutionList cloudifyExecutionList = - new CloudifyExecutionList(cldExecutionList, null); - - when(restClient.getExecutions(Mockito.any(), Mockito.any())) - .thenReturn(cloudifyExecutionList).thenThrow(Exception.class).thenThrow(httpException); - - String actualResult = subject.getExecutionByIdAndDeploymentId("execution_id", - "deployment_id", "tenant", mockedRequest); - assertTrue(actualResult.contains("successful")); - - actualResult = subject.getExecutionByIdAndDeploymentId("execution_id", "deployment_id", - "tenant", mockedRequest); - assertTrue(actualResult.contains("error")); - actualResult = subject.getExecutionByIdAndDeploymentId("execution_id", "deployment_id", - "tenant", mockedRequest); - assertTrue(actualResult.contains("error")); - } -*/ + /* + * @SuppressWarnings("unchecked") + * + * @Test + * public void testGetExecutionByIdAndDeploymentId() throws Exception { + * CloudifyExecution cldExecution = + * new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + * "tenant1", "error", "execution_id1", null); + * + * List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + * + * cldExecutionList.add(cldExecution); + * + * CloudifyExecutionList cloudifyExecutionList = + * new CloudifyExecutionList(cldExecutionList, null); + * + * when(restClient.getExecutions(Mockito.any(), Mockito.any())) + * .thenReturn(cloudifyExecutionList).thenThrow(Exception.class).thenThrow(httpException); + * + * String actualResult = subject.getExecutionByIdAndDeploymentId("execution_id", + * "deployment_id", "tenant", mockedRequest); + * assertTrue(actualResult.contains("successful")); + * + * actualResult = subject.getExecutionByIdAndDeploymentId("execution_id", "deployment_id", + * "tenant", mockedRequest); + * assertTrue(actualResult.contains("error")); + * + * actualResult = subject.getExecutionByIdAndDeploymentId("execution_id", "deployment_id", + * "tenant", mockedRequest); + * assertTrue(actualResult.contains("error")); + * } + */ @SuppressWarnings("unchecked") @Test public void testGetExecutionEventsById() throws Exception { @@ -708,7 +665,7 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyEventList cfyEventsList = new CloudifyEventList(cfyEventItems, null); - when(restClient.getEventlogs(Mockito.any(), Mockito.any())).thenReturn(cfyEventsList) + when(restClient.getEventlogs(anyString(), anyString())).thenReturn(cfyEventsList) .thenThrow(Exception.class).thenThrow(httpException); String actualResult = @@ -727,9 +684,8 @@ public class CloudifyControllerTest extends MockitoTestSuite { @SuppressWarnings("unchecked") @Test public void testStartExecution() throws Exception { - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); + CloudifyExecution cldExecution = new CloudifyExecution("successful", "created_at", + "ended_at", "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); Map<String, Object> params = new HashMap<String, Object>(); params.put("key1", "value1"); @@ -745,21 +701,20 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyNodeInstanceIdList cfyNodeInstList = new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); - + String secretTokenStr = - "{\"created_at\": \"created_ts\", \"key\": \"acl_key\", \"updated_at\": \"updated_ts\", \"value\": \"acl_token_val\", \"visibility\": \"global\", \"is_hidden_value\": \"false\", \"tenant_name\": \"tenant\", \"resource_availability\": \"rsrc\"}"; + "{\"created_at\": \"created_ts\", \"key\": \"acl_key\", \"updated_at\": \"updated_ts\", \"value\": \"acl_token_val\", \"visibility\": \"global\", \"is_hidden_value\": \"false\", \"tenant_name\": \"tenant\", \"resource_availability\": \"rsrc\"}"; CloudifySecret secretData = null; try { secretData = objectMapper.readValue(secretTokenStr, CloudifySecret.class); } catch (Exception e) { - + } - when(restClient.getSecret(Mockito.any(), Mockito.any())).thenReturn(secretData); - - when(restClient.getNodeInstanceId(Mockito.any(), Mockito.any())) - .thenReturn(cfyNodeInstList); + when(restClient.getSecret(anyString(), anyString())).thenReturn(secretData); + + when(restClient.getNodeInstanceId(anyString(), anyString())).thenReturn(cfyNodeInstList); - when(restClient.startExecution(Matchers.<CloudifyExecutionRequest>any())) + when(restClient.startExecution(any(CloudifyExecutionRequest.class))) .thenReturn(cldExecution).thenThrow(Exception.class).thenThrow(httpException); String actualResult = subject.startExecution(mockedRequest, cfyExecReq); @@ -785,7 +740,7 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyNodeInstanceIdList cfyNodeInstList = new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); - when(restClient.getNodeInstanceId(Mockito.any(), Mockito.any(), Mockito.any())) + when(restClient.getNodeInstanceId(anyString(), anyString(), anyString())) .thenReturn(cfyNodeInstList).thenThrow(Exception.class).thenThrow(httpException); String actualResult = @@ -811,7 +766,7 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyNodeInstanceList cfyNodeInstList = new CloudifyNodeInstanceList(cfyNodeInstanceItems, null); - when(restClient.getNodeInstanceVersion(Mockito.any(), Mockito.any())) + when(restClient.getNodeInstanceVersion(anyString(), anyString())) .thenReturn(cfyNodeInstList).thenThrow(Exception.class).thenThrow(httpException); String actualResult = @@ -834,11 +789,10 @@ public class CloudifyControllerTest extends MockitoTestSuite { HttpHeaders httpHeader = new HttpHeaders(); httpHeader.put("tenant", tenants); - CloudifyExecution cfyExecObj = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); + CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "ended_at", + "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); - when(restClient.cancelExecution(Mockito.any(), Mockito.any(), Mockito.any())) + when(restClient.cancelExecution(anyString(), Mockito.any(), anyString())) .thenReturn(cfyExecObj).thenThrow(Exception.class).thenThrow(httpException); String actualResult = diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ConsulControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ConsulControllerTest.java index 53657ed..2642164 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ConsulControllerTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ConsulControllerTest.java @@ -23,28 +23,22 @@ package org.onap.ccsdk.dashboard.controller; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; -import javax.servlet.http.HttpServletRequest; - import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.onap.ccsdk.dashboard.controller.ConsulController.ConsulDataItem; import org.onap.ccsdk.dashboard.core.MockUser; import org.onap.ccsdk.dashboard.core.MockitoTestSuite; -import org.onap.ccsdk.dashboard.model.RestResponseSuccess; import org.onap.ccsdk.dashboard.model.consul.ConsulDatacenter; -import org.onap.ccsdk.dashboard.model.consul.ConsulHealthServiceRegistration; import org.onap.ccsdk.dashboard.model.consul.ConsulNodeInfo; import org.onap.ccsdk.dashboard.model.consul.ConsulServiceHealth; import org.onap.ccsdk.dashboard.model.consul.ConsulServiceInfo; @@ -63,15 +57,15 @@ public class ConsulControllerTest extends MockitoTestSuite { ConsulClient consulClient; @InjectMocks - ConsulController subject = new ConsulController(); + ConsulController subject; protected final ObjectMapper objectMapper = new ObjectMapper(); MockUser mockUser = new MockUser(); HttpClientErrorException httpException; - String[] svcTags = {"cfytenantname=onap"}; - + String[] svcTags = {"cfytenantname=onap"}; + @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); @@ -97,7 +91,7 @@ public class ConsulControllerTest extends MockitoTestSuite { List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); expectedCnslSrvcHlth.add(consulSrvcHlth); - when(consulClient.getServiceHealth(Matchers.anyString(), Matchers.anyString())) + when(consulClient.getServiceHealth(anyString(), anyString())) .thenReturn(expectedCnslSrvcHlth).thenThrow(Exception.class); String actualResult = subject.getServiceHealthDetails(mockedRequest, "dc1", "srvc1"); @@ -128,8 +122,8 @@ public class ConsulControllerTest extends MockitoTestSuite { List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); expectedCnslSrvcHlth.add(consulSrvcHlth); - when(consulClient.getServices(Matchers.anyString())).thenReturn(expectedCnslSrvcs); - when(consulClient.getServiceHealth(Matchers.anyString(), Matchers.anyString())) + when(consulClient.getServices(anyString())).thenReturn(expectedCnslSrvcs); + when(consulClient.getServiceHealth(anyString(), anyString())) .thenReturn(expectedCnslSrvcHlth).thenThrow(Exception.class); String actualResult = subject.getServicesHealth(mockedRequest, "dc1"); @@ -140,7 +134,7 @@ public class ConsulControllerTest extends MockitoTestSuite { } @Test - public final void testGetNodesInfo() { + public final void testGetNodesInfo() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); user.setId(1000L); @@ -152,7 +146,7 @@ public class ConsulControllerTest extends MockitoTestSuite { List<ConsulNodeInfo> cnslNodeList = new ArrayList<ConsulNodeInfo>(); cnslNodeList.add(cnslNode); - when(consulClient.getNodes(Matchers.anyString())).thenReturn(cnslNodeList); + when(consulClient.getNodes(anyString())).thenReturn(cnslNodeList); String actualResult = subject.getNodesInfo(mockedRequest, "dc1"); assertTrue(actualResult.contains("cjlvmcnsl00")); @@ -170,7 +164,7 @@ public class ConsulControllerTest extends MockitoTestSuite { List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); expectedCnslSrvcHlth.add(consulSrvcHlth); - when(consulClient.getNodeServicesHealth(Matchers.anyString(), Matchers.anyString())) + when(consulClient.getNodeServicesHealth(anyString(), anyString())) .thenReturn(expectedCnslSrvcHlth).thenThrow(Exception.class); String actualResult = subject.getNodeServicesHealth(mockedRequest, "dc1", "node1"); @@ -204,9 +198,9 @@ public class ConsulControllerTest extends MockitoTestSuite { user.setLoginId("tester"); user.setId(1000L); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - String actualResult = - subject.getItemListForPageWrapper(mockedRequest, "dc1", ConsulController.ConsulDataItem.SERVICE_INFO); + String actualResult = subject.getItemListForPageWrapper(mockedRequest, "dc1", + ConsulController.ConsulDataItem.SERVICE_INFO); assertTrue(actualResult.contains("error")); - + } } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerControllerTest.java index 4833c12..962d995 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerControllerTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerControllerTest.java @@ -58,7 +58,7 @@ public class DeploymentHandlerControllerTest extends MockitoTestSuite { DeploymentHandlerClient restClient; @InjectMocks - DeploymentHandlerController subject = new DeploymentHandlerController(); + DeploymentHandlerController subject; protected final ObjectMapper objectMapper = new ObjectMapper(); @@ -91,14 +91,14 @@ public class DeploymentHandlerControllerTest extends MockitoTestSuite { public final void testPutDeployment_create() throws Exception { DeploymentRequestObject expectReq = new DeploymentRequestObject("dep1", "dep1", "create", null, "tenant1"); - + DeploymentResponseLinks expectLink = new DeploymentResponseLinks("self", "status"); DeploymentResponse expectResp = new DeploymentResponse("req1", expectLink); - + when(restClient.putDeployment(Matchers.anyString(), Matchers.anyString(), - Matchers.<DeploymentRequest>any(), Matchers.<HttpServletRequest>any()) ).thenReturn(expectResp).thenThrow(badReqError) - .thenThrow(srvcExistError).thenThrow(serverError).thenThrow(downStrmError) - .thenThrow(Exception.class); + Matchers.<DeploymentRequest>any(), Matchers.<HttpServletRequest>any())) + .thenReturn(expectResp).thenThrow(badReqError).thenThrow(srvcExistError) + .thenThrow(serverError).thenThrow(downStrmError).thenThrow(Exception.class); String actualResp = subject.putDeployment(mockedRequest, expectReq); assertTrue(actualResp.contains("req1")); @@ -123,8 +123,8 @@ public class DeploymentHandlerControllerTest extends MockitoTestSuite { public final void testDeleteDeployment() throws Exception { doNothing().doThrow(badReqError).doThrow(serverError).doThrow(downStrmError) - .doThrow(notFoundError).doThrow(Exception.class).when(restClient) - .deleteDeployment(Matchers.anyString(), Matchers.anyString(), Matchers.<HttpServletRequest>any()); + .doThrow(notFoundError).doThrow(Exception.class).when(restClient).deleteDeployment( + Matchers.anyString(), Matchers.anyString(), Matchers.<HttpServletRequest>any()); StringBuffer expectedStrBuff = new StringBuffer(); expectedStrBuff.append("http://oom.s2.com"); diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnControllerTest.java index 771c085..f0c7102 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnControllerTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ECDSingleSignOnControllerTest.java @@ -34,7 +34,7 @@ import org.springframework.web.servlet.ModelAndView; public class ECDSingleSignOnControllerTest extends MockitoTestSuite { @InjectMocks - ECDSingleSignOnController subject = new ECDSingleSignOnController(); + ECDSingleSignOnController subject; @Before public void setUp() throws Exception { diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/HealthCheckControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/HealthCheckControllerTest.java index 4e44c39..dd245e4 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/HealthCheckControllerTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/HealthCheckControllerTest.java @@ -35,15 +35,17 @@ import org.onap.ccsdk.dashboard.core.MockitoTestSuite; import org.onap.ccsdk.dashboard.model.HealthStatus; import org.onap.portalsdk.core.util.SystemProperties; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) @PrepareForTest({SystemProperties.class}) public class HealthCheckControllerTest extends MockitoTestSuite { @InjectMocks - HealthCheckController subject = new HealthCheckController(); + HealthCheckController subject; @Before public void setUp() throws Exception { diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/InventoryControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/InventoryControllerTest.java index 9cce55e..9a3f662 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/InventoryControllerTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/InventoryControllerTest.java @@ -47,36 +47,31 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.ccsdk.dashboard.core.MockUser; import org.onap.ccsdk.dashboard.core.MockitoTestSuite; import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; -import org.onap.ccsdk.dashboard.model.inventory.Service; -import org.onap.ccsdk.dashboard.model.inventory.ServiceList; +import org.onap.ccsdk.dashboard.model.inventory.Blueprint; import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; import org.onap.ccsdk.dashboard.model.inventory.ServiceRef; import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; import org.onap.ccsdk.dashboard.model.inventory.ServiceType; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeList; -import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummary; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummaryList; 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.util.CacheManager; -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.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.http.HttpStatus; @@ -89,6 +84,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PrepareForTest({Blueprint.class}) public class InventoryControllerTest extends MockitoTestSuite { @Mock @@ -98,16 +95,13 @@ public class InventoryControllerTest extends MockitoTestSuite { private InventoryClient inventoryClient; @InjectMocks - private InventoryController subject = new InventoryController(); + private InventoryController subject; protected final ObjectMapper objectMapper = new ObjectMapper(); private HttpServerErrorException httpException = new HttpServerErrorException(HttpStatus.BAD_GATEWAY); - private ServiceNotFoundException serviceException = - new ServiceNotFoundException("Invalid deployment"); - private ServiceTypeNotFoundException serviceTypeException = new ServiceTypeNotFoundException("Invalid blueprint"); @@ -130,7 +124,7 @@ public class InventoryControllerTest extends MockitoTestSuite { ServiceType bpItemFull = null; ServiceTypeList bpItemFullList = null; - + ServiceTypeRequest bpUploadItem = null; @Before @@ -142,25 +136,27 @@ public class InventoryControllerTest extends MockitoTestSuite { mockedRequest = getMockedRequest(); mockedResponse = getMockedResponse(); CacheManager testCache = new CacheManager(); - Map<String, List<ServiceTypeSummary>> bpPerOwner = new HashMap<String, List<ServiceTypeSummary>>(); - bpPerOwner.put("xyz1731", (List<ServiceTypeSummary>)bpList2.items); + Map<String, List<ServiceTypeSummary>> bpPerOwner = + new HashMap<String, List<ServiceTypeSummary>>(); + bpPerOwner.put("xyz1731", (List<ServiceTypeSummary>) bpList2.items); testCache.putObject("owner_bp_map", bpPerOwner); - subject.setCacheManager(testCache); + subject.setCacheManager(testCache); /* - PowerMockito.mockStatic(SystemProperties.class); - Mockito - .when(SystemProperties.getProperty("cache_switch")) - .thenReturn("1"); - */ + * PowerMockito.mockStatic(SystemProperties.class); + * Mockito + * .when(SystemProperties.getProperty("cache_switch")) + * .thenReturn("1"); + */ + PowerMockito.mockStatic(Blueprint.class); } public void getExpectedBlueprints() throws JsonParseException, JsonMappingException, IOException { - bpItem = new ServiceTypeSummary.Builder().application("app1").component("comp1"). - typeName("xyz1731-helm-1906").owner("xyz1731").typeVersion(1906).build(); - - bpItem2 = new ServiceTypeSummary("xyz1731", "xyz1731-helm-1906", 1906, "app1", "comp1", "123-456-789", - "342343", true); + bpItem = new ServiceTypeSummary.Builder().application("app1").component("comp1") + .typeName("xyz1731-helm-1906").owner("xyz1731").typeVersion(1906).build(); + + bpItem2 = new ServiceTypeSummary("xyz1731", "xyz1731-helm-1906", 1906, "app1", "comp1", + "123-456-789", "342343", true); bpItemFull = new ServiceType.Builder("xyz1731", "xyz1731-helm-1906", 1906, "tosca_definitions_version: cloudify_dsl_1_3", "", "app1", "comp1").build(); @@ -169,7 +165,7 @@ public class InventoryControllerTest extends MockitoTestSuite { Collection<ServiceTypeSummary> items2 = new ArrayList<ServiceTypeSummary>(); items2.add(bpItem2); - + String pageLinks2 = "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; ServiceTypeSummaryList.PaginationLinks paginationLinks = @@ -188,7 +184,7 @@ public class InventoryControllerTest extends MockitoTestSuite { } @Test - public final void testGetOwnersByPage() { + public final void testGetOwnersByPage() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); @@ -199,9 +195,9 @@ public class InventoryControllerTest extends MockitoTestSuite { String result = subject.getServiceTypesByPage(mockedRequest); assertTrue(result.contains("xyz")); } - + @Test - public final void testGetAllServiceTypeNames() { + public final void testGetAllServiceTypeNames() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); @@ -210,11 +206,11 @@ public class InventoryControllerTest extends MockitoTestSuite { Stream<ServiceTypeSummary> sampleStream1 = items.stream(); Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); String result = subject.getAllServiceTypeNames(mockedRequest); - assertTrue(result.contains("xyz")); + assertTrue(result.contains("xyz")); } - + @Test - public final void testGetAllServiceTypeIds() { + public final void testGetAllServiceTypeIds() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); @@ -223,15 +219,15 @@ public class InventoryControllerTest extends MockitoTestSuite { Stream<ServiceTypeSummary> sampleStream1 = items.stream(); Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); String result = subject.getAllServiceTypeIds(mockedRequest); - assertTrue(result.contains("xyz")); + assertTrue(result.contains("xyz")); } - + @Test - public final void testGetServiceTypesByPage() { + public final void testGetServiceTypesByPage() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - //mockedRequest.addParameter("searchBy", "xyz"); + // mockedRequest.addParameter("searchBy", "xyz"); mockedRequest.addParameter("sortBy", "owner"); // # 1st case @@ -241,7 +237,7 @@ public class InventoryControllerTest extends MockitoTestSuite { Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); String result = subject.getServiceTypesByPage(mockedRequest); assertTrue(result.contains("xyz")); - + // # 2nd case HttpSession session = mockedRequest.getSession(); HashMap<String, Boolean> comp_deploy_tab = new HashMap<String, Boolean>(); @@ -253,19 +249,18 @@ public class InventoryControllerTest extends MockitoTestSuite { when(session.getAttribute("authComponents")).thenReturn(userApps); Stream<ServiceTypeSummary> sampleStream2 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes()) - .thenReturn(sampleStream2); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream2); /* - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream2); - */ + * Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + * .thenReturn(sampleStream2); + */ String result2 = subject.getServiceTypesByPage(mockedRequest); assertTrue(result2.contains("xyz")); } - + @Test - public final void testGetServiceTypesByPage_appDevUser() { + public final void testGetServiceTypesByPage_appDevUser() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); @@ -286,9 +281,9 @@ public class InventoryControllerTest extends MockitoTestSuite { String result = subject.getServiceTypesByPage(mockedRequest); assertTrue(result.contains("xyz")); } - + @Test - public final void testGetServiceTypesByPage_containsFilter() { + public final void testGetServiceTypesByPage_containsFilter() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); @@ -302,13 +297,14 @@ public class InventoryControllerTest extends MockitoTestSuite { String result = subject.getServiceTypesByPage(mockedRequest); assertTrue(result.contains("error")); } - + @Test - public final void testGetServiceTypesByPage_AllFilters() { + public final void testGetServiceTypesByPage_AllFilters() throws Exception { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - mockedRequest.addParameter("searchBy", "serviceRef:xyz1731-helm-1906;app:app1;comp:comp1;owner:xyz1731;"); + mockedRequest.addParameter("searchBy", + "serviceRef:xyz1731-helm-1906;app:app1;comp:comp1;owner:xyz1731;"); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); Collection<ServiceTypeSummary> items = bpList.items; @@ -317,13 +313,13 @@ public class InventoryControllerTest extends MockitoTestSuite { String result = subject.getServiceTypesByPage(mockedRequest); assertTrue(result.contains("xyz")); - + } - + @Test - public final void testGetServiceTypesByPage_comp() { + public final void testGetServiceTypesByPage_comp() throws Exception { User user = mockUser.mockUser(); - user.setLoginId("tester"); + user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); mockedRequest.addParameter("sortBy", "component"); @@ -338,9 +334,9 @@ public class InventoryControllerTest extends MockitoTestSuite { } @Test - public final void testGetServiceTypesByPage_typeId() { + public final void testGetServiceTypesByPage_typeId() throws Exception { User user = mockUser.mockUser(); - user.setLoginId("tester"); + user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); mockedRequest.addParameter("sortBy", "typeId"); @@ -353,9 +349,9 @@ public class InventoryControllerTest extends MockitoTestSuite { } @Test - public final void testGetServiceTypesByPage_typeName() { + public final void testGetServiceTypesByPage_typeName() throws Exception { User user = mockUser.mockUser(); - user.setLoginId("tester"); + user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); mockedRequest.addParameter("sortBy", "typeName"); @@ -367,9 +363,9 @@ public class InventoryControllerTest extends MockitoTestSuite { } @Test - public final void testGetServiceTypesByPage_typeVer() { + public final void testGetServiceTypesByPage_typeVer() throws Exception { User user = mockUser.mockUser(); - user.setLoginId("tester"); + user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); mockedRequest.addParameter("sortBy", "typeVersion"); @@ -382,9 +378,9 @@ public class InventoryControllerTest extends MockitoTestSuite { } @Test - public final void testGetServiceTypesByPage_created() { + public final void testGetServiceTypesByPage_created() throws Exception { User user = mockUser.mockUser(); - user.setLoginId("tester"); + user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); mockedRequest.addParameter("sortBy", "created"); @@ -396,10 +392,9 @@ public class InventoryControllerTest extends MockitoTestSuite { assertTrue(result.contains("xyz")); } - @SuppressWarnings("unchecked") @Test - public final void testGetServiceTypesByPage_Exception() { + public final void testGetServiceTypesByPage_Exception() throws Exception { when(inventoryClient.getServiceTypes()).thenThrow(RestClientException.class) .thenThrow(httpException); @@ -410,19 +405,14 @@ public class InventoryControllerTest extends MockitoTestSuite { assertTrue(errResp.contains("error")); } - - @SuppressWarnings("unchecked") @Test public final void testUploadServiceTypeBlueprint() throws Exception { MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); String expected = "{\"201\": \"OK\"}"; - when(inventoryClient.addServiceType(Matchers.<ServiceTypeRequest>any())) - .thenThrow(BlueprintParseException.class).thenThrow(httpException) - .thenThrow(Exception.class).thenReturn(null); - String actual1 = subject.uploadServiceTypeBlueprint(mockedRequest, bpUploadItem); - assertTrue(actual1.contains("error")); + when(inventoryClient.addServiceType(Mockito.<ServiceTypeRequest>any())) + .thenThrow(httpException).thenThrow(Exception.class).thenReturn(null); String actual2 = subject.uploadServiceTypeBlueprint(mockedRequest, bpUploadItem); assertTrue(actual2.contains("error")); @@ -437,15 +427,25 @@ public class InventoryControllerTest extends MockitoTestSuite { @SuppressWarnings("unchecked") @Test + public final void testUploadServiceTypeBlueprint_badBp() throws Exception { + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + + when(Blueprint.parse(bpUploadItem.getBlueprintTemplate())) + .thenThrow(BlueprintParseException.class); + + String actual1 = subject.uploadServiceTypeBlueprint(mockedRequest, bpUploadItem); + assertTrue(actual1.contains("error")); + + } + + @SuppressWarnings("unchecked") + @Test public final void testUpdateServiceTypeBlueprint() throws Exception { MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); String expected = "{\"201\": \"OK\"}"; - Mockito.when(inventoryClient.addServiceType(Matchers.<ServiceType>any())) - .thenThrow(BlueprintParseException.class).thenThrow(httpException) - .thenThrow(Exception.class).thenReturn(null); - String actual1 = subject.updateServiceTypeBlueprint(mockedRequest, bpItemFull); - assertTrue(actual1.contains("error")); + Mockito.when(inventoryClient.addServiceType(Mockito.<ServiceType>any())) + .thenThrow(httpException).thenThrow(Exception.class).thenReturn(null); String actual2 = subject.updateServiceTypeBlueprint(mockedRequest, bpItemFull); assertTrue(actual2.contains("error")); @@ -458,24 +458,36 @@ public class InventoryControllerTest extends MockitoTestSuite { } @Test + public final void testUpdateServiceTypeBlueprint_badBp() throws Exception { + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + + when(Blueprint.parse(bpUploadItem.getBlueprintTemplate())) + .thenThrow(BlueprintParseException.class); + + String actual1 = subject.updateServiceTypeBlueprint(mockedRequest, bpItemFull); + assertTrue(actual1.contains("error")); + + } + + @Test public final void testDeleteServiceType() throws Exception { - //String expected = "{\"202\": \"OK\"}"; + // String expected = "{\"202\": \"OK\"}"; String expected = "{\"204\": \"Blueprint deleted\"}"; List<CloudifyDeployedTenant> deplForBp = new ArrayList<>(); deplForBp.clear(); - Mockito.when(cfyClient.getDeploymentForBlueprint(Matchers.<String>any())) - .thenReturn(deplForBp); - + Mockito.when(cfyClient.getDeploymentForBlueprint(Mockito.anyString())) + .thenReturn(deplForBp); + List<ServiceRef> srvcRefList = new ArrayList<>(); srvcRefList.clear(); int itemCnt = 0; ServiceRefList mockSvcRefList = new ServiceRefList(srvcRefList, itemCnt); - Mockito.when(inventoryClient.getServicesForType(Matchers.<ServiceQueryParams>any())) + Mockito.when(inventoryClient.getServicesForType(Mockito.<ServiceQueryParams>any())) .thenReturn(mockSvcRefList); - + doNothing().doThrow(serviceTypeException).doThrow(Exception.class).when(inventoryClient) - .deleteServiceType(Matchers.anyString()); + .deleteServiceType(Mockito.anyString()); String actual = subject.deleteServiceType("srvcId", mockedRequest, mockedResponse); assertEquals(expected, actual); @@ -489,23 +501,23 @@ public class InventoryControllerTest extends MockitoTestSuite { @Test public final void testDeleteServiceType_withDepl() throws Exception { - CloudifyDeployedTenant mockCfyDeplTen = + CloudifyDeployedTenant mockCfyDeplTen = new CloudifyDeployedTenant("id1", "tenant", "45435435", "54543534"); - + List<CloudifyDeployedTenant> deplForBp = new ArrayList<>(); deplForBp.add(mockCfyDeplTen); - Mockito.when(cfyClient.getDeploymentForBlueprint(Matchers.<String>any())) - .thenReturn(deplForBp); - + Mockito.when(cfyClient.getDeploymentForBlueprint(Mockito.anyString())) + .thenReturn(deplForBp); + String actual = subject.deleteServiceType("srvcId", mockedRequest, mockedResponse); assertTrue(actual.contains("error")); } - + @SuppressWarnings("unchecked") @Test public final void testViewServiceTypeBlueprintContentById() throws Exception { Optional<ServiceType> expected = Optional.of(bpItemFull); - when(inventoryClient.getServiceType(Matchers.anyString())).thenReturn(expected) + when(inventoryClient.getServiceType(Mockito.anyString())).thenReturn(expected) .thenThrow(httpException).thenThrow(Exception.class); String result = subject.viewServiceTypeBlueprintContentById("typeId", mockedRequest); @@ -526,49 +538,10 @@ public class InventoryControllerTest extends MockitoTestSuite { expectedSrvcIds.add(expectedSrvc); ServiceRefList expectedSrvcRefList = new ServiceRefList(expectedSrvcIds, 1); - when(inventoryClient.getServicesForType(Matchers.<ServiceQueryParams>any())) + when(inventoryClient.getServicesForType(Mockito.<ServiceQueryParams>any())) .thenReturn(expectedSrvcRefList); String actual = subject.getServicesForType(mockedRequest, testTypeIds); assertTrue(actual.contains(testTypeIds[0])); } - /* - * @Test public final void testGetItemListForPageWrapper() { - * fail("Not yet implemented"); // TODO } - * - * @Test public final void testGetServicesForType() { - * fail("Not yet implemented"); // TODO } - * - * - * - * @Test public final void testViewServiceTypeBlueprintContentById() { - * fail("Not yet implemented"); // TODO } - * - * @Test public final void testDeleteServiceType() { - * fail("Not yet implemented"); // TODO } - * - * @Test public final void testDeleteService() { fail("Not yet implemented"); // - * TODO } - * - * @Test public final void testUpdateServiceTypeBlueprint() { - * fail("Not yet implemented"); // TODO } - * - * @Test public final void testUploadServiceTypeBlueprint() { - * fail("Not yet implemented"); // TODO } - * - * @Test public final void testGetAppProperties() { fail("Not yet implemented"); - * // TODO } - * - * @Test public final void testGetOrSetControllerEndpointSelectionLong() { - * fail("Not yet implemented"); // TODO } - * - * @Test public final void testGetOrSetControllerEndpointSelection() { - * fail("Not yet implemented"); // TODO } - * - * @Test public final void testGetInventoryClientHttpServletRequest() { - * fail("Not yet implemented"); // TODO } - * - * @Test public final void testGetInventoryClientLong() { - * fail("Not yet implemented"); // TODO } - */ } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/BlueprintParseExceptionTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/BlueprintParseExceptionTest.java index c28bc42..0becbe0 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/BlueprintParseExceptionTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/BlueprintParseExceptionTest.java @@ -2,42 +2,41 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. - * - * Modifications Copyright (C) 2019 IBM. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * + * Modifications Copyright (C) 2019 IBM. * ================================================================================ - * 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.exceptions.inventory; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; public class BlueprintParseExceptionTest { - @Test - public void TestException3() { - - BlueprintParseException mae = new BlueprintParseException(new Throwable()); - assertEquals("org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException", mae.getClass().getName()); - - } + @Test + public void TestException3() { + + BlueprintParseException mae = new BlueprintParseException(new Throwable()); + assertEquals("org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException", + mae.getClass().getName()); + } } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceAlreadyDeactivatedExceptionTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceAlreadyDeactivatedExceptionTest.java index 95cccc7..66ba372 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceAlreadyDeactivatedExceptionTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceAlreadyDeactivatedExceptionTest.java @@ -2,39 +2,41 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. - * - * Modifications Copyright (C) 2019 IBM. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * + * Modifications Copyright (C) 2019 IBM. * ================================================================================ - * 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.exceptions.inventory; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; public class ServiceAlreadyDeactivatedExceptionTest { - @Test - public void TestException1() { - - ServiceAlreadyDeactivatedException sad = new ServiceAlreadyDeactivatedException("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceAlreadyDeactivatedException"); - assertEquals(sad.getMessage(),"org.onap.ccsdk.dashboard.exceptions.inventory.ServiceAlreadyDeactivatedException"); - - } - + @Test + public void TestException1() { + + ServiceAlreadyDeactivatedException sad = new ServiceAlreadyDeactivatedException( + "org.onap.ccsdk.dashboard.exceptions.inventory.ServiceAlreadyDeactivatedException"); + assertEquals(sad.getMessage(), + "org.onap.ccsdk.dashboard.exceptions.inventory.ServiceAlreadyDeactivatedException"); + + } + } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceNotFoundExceptionTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceNotFoundExceptionTest.java index ea9359b..39529fb 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceNotFoundExceptionTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceNotFoundExceptionTest.java @@ -2,38 +2,39 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. - * - * Modifications Copyright (C) 2019 IBM. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * + * Modifications Copyright (C) 2019 IBM. * ================================================================================ - * 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.exceptions.inventory; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; public class ServiceNotFoundExceptionTest { - @Test - public void TestException1() { - - ServiceNotFoundException sad = new ServiceNotFoundException(); - assertEquals("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException", sad.getClass().getName()); - - } + @Test + public void TestException1() { + + ServiceNotFoundException sad = new ServiceNotFoundException(); + assertEquals("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException", + sad.getClass().getName()); + + } } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeActiveExceptionTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeActiveExceptionTest.java index 913c36c..72ee5fe 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeActiveExceptionTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeActiveExceptionTest.java @@ -2,28 +2,28 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. - * - * Modifications Copyright (C) 2019 IBM. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * + * Modifications Copyright (C) 2019 IBM. * ================================================================================ - * 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.exceptions.inventory; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; @@ -31,42 +31,41 @@ public class ServiceTypeActiveExceptionTest { @Test public void TestException1() { - - ServiceTypeActiveException sta = new ServiceTypeActiveException(); - assertEquals("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException", sta.getClass().getName()); - + + ServiceTypeActiveException sta = new ServiceTypeActiveException(); + assertEquals("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException", + sta.getClass().getName()); + } @Test public void TestException2() { - - ServiceTypeActiveException sta= new ServiceTypeActiveException("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException"); - assertEquals(sta.getMessage(), "org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException"); - - } + ServiceTypeActiveException sta = new ServiceTypeActiveException( + "org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException"); + assertEquals(sta.getMessage(), + "org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException"); + + } @Test public void TestException3() { - - ServiceTypeActiveException sta= new ServiceTypeActiveException(new Throwable()); - assertEquals("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException", sta.getClass().getName()); - - } - + ServiceTypeActiveException sta = new ServiceTypeActiveException(new Throwable()); + assertEquals("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException", + sta.getClass().getName()); - @Test - public void TestException4() { - - ServiceTypeActiveException sta= new ServiceTypeActiveException("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException", new Throwable()); - assertEquals("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException",sta.getClass().getName()); - } - -} + @Test + public void TestException4() { - + ServiceTypeActiveException sta = new ServiceTypeActiveException( + "org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException", + new Throwable()); + assertEquals("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException", + sta.getClass().getName()); + } +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeAlreadyDeactivatedExceptionTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeAlreadyDeactivatedExceptionTest.java index 0ec2cb5..5ebdf5e 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeAlreadyDeactivatedExceptionTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/exceptions/inventory/ServiceTypeAlreadyDeactivatedExceptionTest.java @@ -2,39 +2,42 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. - * - * Modifications Copyright (C) 2019 IBM. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * + * Modifications Copyright (C) 2019 IBM. * ================================================================================ - * 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.exceptions.inventory; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; public class ServiceTypeAlreadyDeactivatedExceptionTest { - @Test - public void TestException3() { - - ServiceTypeAlreadyDeactivatedException mae = new ServiceTypeAlreadyDeactivatedException("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException"); - assertEquals("org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException", mae.getClass().getName()); - - } + @Test + public void TestException3() { + + ServiceTypeAlreadyDeactivatedException mae = new ServiceTypeAlreadyDeactivatedException( + "org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException"); + assertEquals( + "org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException", + mae.getClass().getName()); + + } } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java index 68223da..a6f5038 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java @@ -17,8 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ + package org.onap.ccsdk.dashboard.rest; import static org.hamcrest.CoreMatchers.is; @@ -27,6 +27,11 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.contains; import java.io.IOException; import java.util.ArrayList; @@ -44,13 +49,12 @@ import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.ccsdk.dashboard.core.MockitoTestSuite; -import org.onap.ccsdk.dashboard.core.MockitoTestSuite.MockHttpServletRequestWrapper; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyBlueprint; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyBlueprintList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; @@ -60,6 +64,7 @@ import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyEvent; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyEventList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyEventList.Metadata; +import org.onap.ccsdk.dashboard.model.consul.ConsulServiceHealth; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecution; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionList; import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionRequest; @@ -76,6 +81,7 @@ import org.onap.ccsdk.dashboard.model.cloudify.CloudifyTenantList; import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.portalsdk.core.util.CacheManager; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.core.ParameterizedTypeReference; @@ -83,6 +89,7 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; @@ -92,6 +99,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) @PrepareForTest({DashboardProperties.class}) public class CloudifyRestClientImplTest extends MockitoTestSuite { @@ -99,8 +107,8 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { RestTemplate mockRest; @InjectMocks - CloudifyRestClientImpl subject = new CloudifyRestClientImpl(); - + CloudifyRestClientImpl subject; + HttpServletRequest mockedRequest; HttpServletResponse mockedResponse; protected final static ObjectMapper objectMapper = new ObjectMapper(); @@ -113,13 +121,12 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { when(DashboardProperties.getControllerProperty("site.primary", DashboardProperties.SITE_SUBKEY_CLOUDIFY_URL)).thenReturn("https://orcl.com"); CacheManager testCache = new CacheManager(); - subject.setCacheManager(testCache); + subject.setCacheManager(testCache); this.subject.init(); } @Test - public final void getEventlogsTest() - throws JsonParseException, JsonMappingException, IOException { + public final void getEventlogsTest() throws HttpStatusCodeException, Exception { String executionId = "123a123a"; String tenant = "thisTenant"; List<CloudifyEvent> items = new ArrayList<CloudifyEvent>(); @@ -146,11 +153,8 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyEventList> response = new ResponseEntity<CloudifyEventList>(expected, HttpStatus.OK); - Mockito - .when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyEventList>>any())) - .thenReturn(response); + Mockito.when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyEventList>() {}))).thenReturn(response); CloudifyEventList actual = subject.getEventlogs(executionId, tenant); assertTrue(actual.items.size() == 2); @@ -158,7 +162,7 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { @Test public final void testGetTenants_GetData() { - // define the entity you want the exchange to return + // Given String tenantsList = "{\"items\": [{\"id\": 1, \"dName\": null, \"name\": \"default_tenant\"}, {\"id\": 2, \"dName\": null, \"name\": \"dyh1b1902\"}], \"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; CloudifyTenantList sampleData = null; @@ -169,12 +173,12 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyTenantList> response = new ResponseEntity<CloudifyTenantList>(sampleData, HttpStatus.OK); - Mockito - .when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyTenantList>>any())) - .thenReturn(response); + // When + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<CloudifyTenantList>() {}))).thenReturn(response); + + // Then CloudifyTenantList res = subject.getTenants(); assertNotNull(res); assertThat(res.items.get(1).name, is("dyh1b1902")); @@ -183,17 +187,17 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { @SuppressWarnings("unchecked") @Test(expected = RestClientException.class) public final void testGetTenants_withException() { - // define the entity you want the exchange to return - Mockito - .when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyTenantList>>any())) - .thenThrow(RestClientException.class); + // When + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<CloudifyTenantList>() {}))) + .thenThrow(RestClientException.class); + + // Then subject.getTenants(); } @Test - public final void testGetNodeInstanceId() { + public final void testGetNodeInstanceId() throws HttpStatusCodeException, Exception { CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); List<CloudifyNodeInstanceId> cfyNodeInstItems = new ArrayList<CloudifyNodeInstanceId>(); cfyNodeInstItems.add(cfyNodeInst); @@ -203,9 +207,8 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyNodeInstanceIdList> response = new ResponseEntity<CloudifyNodeInstanceIdList>(cfyNodeInstList, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyNodeInstanceIdList>>any())) + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyNodeInstanceIdList>() {}))) .thenReturn(response); CloudifyNodeInstanceIdList actualResult = @@ -214,7 +217,7 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { } @Test - public final void testGetNodeInstanceVersion() { + public final void testGetNodeInstanceVersion() throws HttpStatusCodeException, Exception { CloudifyNodeInstance cfyNodeInstance = new CloudifyNodeInstance("id1", null); List<CloudifyNodeInstance> cfyNodeInstanceItems = new ArrayList<CloudifyNodeInstance>(); @@ -225,9 +228,8 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyNodeInstanceList> response = new ResponseEntity<CloudifyNodeInstanceList>(cfyNodeInstList, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyNodeInstanceList>>any())) + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyNodeInstanceList>() {}))) .thenReturn(response); CloudifyNodeInstanceList actualResult = @@ -236,7 +238,8 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { } @Test - public final void testGetNodeInstanceVersion_blueprint() { + public final void testGetNodeInstanceVersion_blueprint() + throws HttpStatusCodeException, Exception { CloudifyNodeId cfyNodeId = new CloudifyNodeId("node_id"); List<CloudifyNodeId> cfyNodeIdItems = new ArrayList<CloudifyNodeId>(); cfyNodeIdItems.add(cfyNodeId); @@ -245,10 +248,6 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyNodeIdList> response1 = new ResponseEntity<CloudifyNodeIdList>(cfyNodeIdList, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("nodes"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyNodeIdList>>any())).thenReturn(response1); - CloudifyNodeInstance cfyNodeInstance = new CloudifyNodeInstance("id1", null); List<CloudifyNodeInstance> cfyNodeInstanceItems = new ArrayList<CloudifyNodeInstance>(); @@ -259,10 +258,14 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyNodeInstanceList> response2 = new ResponseEntity<CloudifyNodeInstanceList>(cfyNodeInstList, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("node-instances"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyNodeInstanceList>>any())) - .thenReturn(response2); + + when(mockRest.exchange(contains("nodes"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyNodeIdList>() {}))).thenReturn(response1); + + when( + mockRest.exchange(contains("node-instances"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyNodeInstanceList>() {}))) + .thenReturn(response2); CloudifyNodeInstanceList actualResult = subject.getNodeInstanceVersion("blueprintId", "tenant"); @@ -270,7 +273,7 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { } @Test - public final void testGetNodeInstanceId_blueprint() { + public final void testGetNodeInstanceId_blueprint() throws HttpStatusCodeException, Exception { CloudifyNodeId cfyNodeId = new CloudifyNodeId("node_id"); List<CloudifyNodeId> cfyNodeIdItems = new ArrayList<CloudifyNodeId>(); cfyNodeIdItems.add(cfyNodeId); @@ -279,9 +282,8 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyNodeIdList> response1 = new ResponseEntity<CloudifyNodeIdList>(cfyNodeIdList, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("nodes"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyNodeIdList>>any())).thenReturn(response1); + when(mockRest.exchange(contains("nodes"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyNodeIdList>() {}))).thenReturn(response1); CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); List<CloudifyNodeInstanceId> cfyNodeInstItems = new ArrayList<CloudifyNodeInstanceId>(); @@ -292,20 +294,19 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyNodeInstanceIdList> response = new ResponseEntity<CloudifyNodeInstanceIdList>(cfyNodeInstList, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("node-instances"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyNodeInstanceIdList>>any())) - .thenReturn(response); + when( + mockRest.exchange(contains("node-instances"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyNodeInstanceIdList>() {}))) + .thenReturn(response); CloudifyNodeInstanceIdList actualResult = subject.getNodeInstanceId("bpId", "tenant"); assertTrue(actualResult.items.get(0).id.equals("node_instance_id1")); } @Test - public void testGetExecutions() { - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, - "bp1", "id1","tenant1", "error", "execution_id1", null); + public void testGetExecutions() throws Exception { + CloudifyExecution cldExecution = new CloudifyExecution("successful", "created_at", + "ended_at", "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); @@ -317,20 +318,17 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyExecutionList> response = new ResponseEntity<CloudifyExecutionList>(cloudifyExecutionList, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("deployment_id"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyExecutionList>>any())) - .thenReturn(response); + when(mockRest.exchange(contains("deployment_id"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyExecutionList>() {}))).thenReturn(response); CloudifyExecutionList actualResult = subject.getExecutions("deploymentId1", "tenant1"); assertTrue(actualResult.items.get(0).id.contains("id1")); } @Test - public void testGetExecutionsSummary() { - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); + public void testGetExecutionsSummary() throws HttpStatusCodeException, Exception { + CloudifyExecution cldExecution = new CloudifyExecution("successful", "created_at", + "ended_at", "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); @@ -342,10 +340,8 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyExecutionList> response = new ResponseEntity<CloudifyExecutionList>(cloudifyExecutionList, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("include"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyExecutionList>>any())) - .thenReturn(response); + when(mockRest.exchange(contains("include"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyExecutionList>() {}))).thenReturn(response); CloudifyExecutionList actualResult = subject.getExecutionsSummary("deploymentId1", "tenant1"); @@ -353,9 +349,9 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { } @Test - public void testStartExecution() { - CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "ended-at", "install", - false, "bp1", "id1", "tenant1", "error", "execution_id1", null); + public void testStartExecution() throws HttpStatusCodeException, Exception { + CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "ended-at", + "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); Map<String, Object> params = new HashMap<String, Object>(); params.put("key1", "value1"); @@ -363,18 +359,16 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { CloudifyExecutionRequest cfyExecReq = new CloudifyExecutionRequest("deployment_id", "upgrade", false, false, "tenant1", params); - when(mockRest.postForObject(Matchers.anyString(), Matchers.<HttpEntity<?>>any(), - Matchers.<Class<CloudifyExecution>>any())).thenReturn(cfyExecObj); + when(mockRest.postForObject(anyString(), any(), any())).thenReturn(cfyExecObj); CloudifyExecution actualResult = subject.startExecution(cfyExecReq); assertTrue(actualResult.status.equals("successful")); } @Test - @Ignore - public void testCancelExecution() { - CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "end_at", "install", - false, "bp1", "id1", "tenant1", "error", "execution_id1", null); + public void testCancelExecution() throws HttpStatusCodeException, Exception { + CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "end_at", + "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); Map<String, Object> params = new HashMap<String, Object>(); params.put("key1", "value1"); @@ -382,9 +376,8 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyExecution> response = new ResponseEntity<CloudifyExecution>(cfyExecObj, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("executions"), Matchers.eq(HttpMethod.POST), - Matchers.<HttpEntity<?>>any(), Matchers.<Class<CloudifyExecution>>any())) - .thenReturn(response); + when(mockRest.exchange(contains("executions"), eq(HttpMethod.POST), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyExecution>() {}))).thenReturn(response); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("key1", "value1"); @@ -395,7 +388,7 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { } @Test - public void testGetBlueprint() { + public void testGetBlueprint() throws HttpStatusCodeException, Exception { CloudifyBlueprint cldBp = new CloudifyBlueprint("file1", "description1", "343242", "3423423", "id1", null); @@ -412,9 +405,8 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyBlueprintList> response = new ResponseEntity<CloudifyBlueprintList>(cldBpList, HttpStatus.OK); - doReturn(response).when(mockRest).exchange(Matchers.anyString(), - Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyBlueprintList>>any()); + doReturn(response).when(mockRest).exchange(anyString(), eq(HttpMethod.GET), + any(HttpEntity.class), eq(new ParameterizedTypeReference<CloudifyBlueprintList>() {})); CloudifyBlueprintList actualResult = subject.getBlueprint("id1", "tenant1"); assertTrue(actualResult.items.get(0).id.equals("id1")); @@ -437,14 +429,13 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyDeploymentList> response = new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<CloudifyDeploymentList>>any())) - .thenReturn(response); - + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyDeploymentList>() {}))).thenReturn(response); + CloudifyDeploymentList actualResult = subject.getDeployments("tenant", 10, 0); assertTrue(actualResult.items.get(0).id.equals("id")); } - + @Test public void testGetDeployments_from_cache() { CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", @@ -462,41 +453,41 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyDeploymentList> response = new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<CloudifyDeploymentList>>any())) - .thenReturn(response); - + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyDeploymentList>() {}))).thenReturn(response); + List<CloudifyDeployment> actualResult = subject.getDeployments("tenant", 10, 0, true, true); assertTrue(actualResult.get(0).id.equals("id")); } - + @Test public void testGetDeploymentForBlueprint() { - CloudifyDeployedTenant cfyDepTenant = + CloudifyDeployedTenant cfyDepTenant = new CloudifyDeployedTenant("id", "tenant", "created_at", "updated_at"); List<CloudifyDeployedTenant> cfyDepTenantList = new ArrayList<>(); cfyDepTenantList.add(cfyDepTenant); - + CloudifyDeployedTenantList.Metadata.Pagination pageObj = new CloudifyDeployedTenantList.Metadata.Pagination(1, 0, 1); - CloudifyDeployedTenantList.Metadata metadata = new CloudifyDeployedTenantList.Metadata(pageObj); + CloudifyDeployedTenantList.Metadata metadata = + new CloudifyDeployedTenantList.Metadata(pageObj); - CloudifyDeployedTenantList cldDeployList = new CloudifyDeployedTenantList(cfyDepTenantList, metadata); + CloudifyDeployedTenantList cldDeployList = + new CloudifyDeployedTenantList(cfyDepTenantList, metadata); ResponseEntity<CloudifyDeployedTenantList> response = new ResponseEntity<CloudifyDeployedTenantList>(cldDeployList, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyDeployedTenantList>>any())) + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<CloudifyDeployedTenantList>() {}))) .thenReturn(response); - + List<CloudifyDeployedTenant> actuals = subject.getDeploymentForBlueprint("bpId"); assertTrue(actuals.get(0).id.equals("id")); } - + @Test - public void testGetDeploymentResource() { + public void testGetDeploymentResource() { CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); @@ -512,16 +503,15 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyDeploymentList> response = new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<CloudifyDeploymentList>>any())) - .thenReturn(response); + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyDeploymentList>() {}))).thenReturn(response); - CloudifyDeployment actualResult = subject.getDeploymentResource("id", "tenant"); + CloudifyDeployment actualResult = subject.getDeploymentResource("id", "tenant"); assertTrue(actualResult.id.equals("id")); } - + @Test - public void testGetNodeInstanceDetails() { + public void testGetNodeInstanceDetails() throws HttpStatusCodeException, Exception { CloudifyNodeInstance cfyNodeInstance = new CloudifyNodeInstance("id1", null); List<CloudifyNodeInstance> cfyNodeInstanceItems = new ArrayList<CloudifyNodeInstance>(); @@ -532,18 +522,18 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyNodeInstanceList> response2 = new ResponseEntity<CloudifyNodeInstanceList>(cfyNodeInstList, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("node-instances"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyNodeInstanceList>>any())) - .thenReturn(response2); - - CloudifyNodeInstanceList actualResult = - subject.getNodeInstanceDetails("id", "tenant"); + + when( + mockRest.exchange(contains("node-instances"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyNodeInstanceList>() {}))) + .thenReturn(response2); + + CloudifyNodeInstanceList actualResult = subject.getNodeInstanceDetails("id", "tenant"); assertTrue(actualResult.items.get(0).id.equals("id1")); } - + @Test - public void testGetNodeInstances() { + public void testGetNodeInstances() throws HttpStatusCodeException, Exception { CloudifyNodeInstanceId cfyNodeInstance = new CloudifyNodeInstanceId("id1"); List<CloudifyNodeInstanceId> cfyNodeInstanceItems = new ArrayList<CloudifyNodeInstanceId>(); @@ -554,22 +544,20 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyNodeInstanceIdList> response2 = new ResponseEntity<CloudifyNodeInstanceIdList>(cfyNodeInstList, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("node-instances"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyNodeInstanceIdList>>any())) - .thenReturn(response2); - - CloudifyNodeInstanceIdList actualResult = - subject.getNodeInstances("id", "tenant"); + + when( + mockRest.exchange(contains("node-instances"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyNodeInstanceIdList>() {}))) + .thenReturn(response2); + + CloudifyNodeInstanceIdList actualResult = subject.getNodeInstances("id", "tenant"); assertTrue(actualResult.items.get(0).id.equals("id1")); } - - - @Test - public void testGetExecutionsSummaryPerTenant() { - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); + + @Test + public void testGetExecutionsSummaryPerTenant() throws HttpStatusCodeException, Exception { + CloudifyExecution cldExecution = new CloudifyExecution("successful", "created_at", + "ended_at", "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); @@ -581,36 +569,31 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyExecutionList> response = new ResponseEntity<CloudifyExecutionList>(cloudifyExecutionList, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("include"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyExecutionList>>any())) - .thenReturn(response); + when(mockRest.exchange(contains("include"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyExecutionList>() {}))).thenReturn(response); - CloudifyExecutionList actualResult = - subject.getExecutionsSummaryPerTenant("tenant1"); + CloudifyExecutionList actualResult = subject.getExecutionsSummaryPerTenant("tenant1"); assertTrue(actualResult.items.get(0).id.contains("id1")); } - + @Test - public void testGetExecutionIdSummary() { - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); + public void testGetExecutionIdSummary() throws HttpStatusCodeException, Exception { + CloudifyExecution cldExecution = new CloudifyExecution("successful", "created_at", + "ended_at", "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); ResponseEntity<CloudifyExecution> response = new ResponseEntity<CloudifyExecution>(cldExecution, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("include"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyExecution>>any())) - .thenReturn(response); + + when(mockRest.exchange(contains("include"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyExecution>() {}))).thenReturn(response); + CloudifyExecution actuals = subject.getExecutionIdSummary("execution_id1", "tenant"); assertTrue(actuals.id.contains("execution_id1")); } - + @Test public void testGetInstallExecutionSummary() { - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null); + CloudifyExecution cldExecution = new CloudifyExecution("successful", "created_at", + "ended_at", "install", false, "bp1", "id1", "tenant1", "error", "execution_id1", null); List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); @@ -622,43 +605,39 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyExecutionList> response = new ResponseEntity<CloudifyExecutionList>(cloudifyExecutionList, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("include"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyExecutionList>>any())) - .thenReturn(response); + when(mockRest.exchange(contains("include"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyExecutionList>() {}))).thenReturn(response); - CloudifyExecutionList actualResult = - subject.getInstallExecutionSummary("id1", "tenant1"); + CloudifyExecutionList actualResult = subject.getInstallExecutionSummary("id1", "tenant1"); assertTrue(actualResult.items.get(0).id.contains("id1")); } - + @Test - public void testViewBlueprint() { - byte[] outArr = "Any String you want".getBytes(); - ResponseEntity<byte[]> response = - new ResponseEntity<byte[]>(outArr, HttpStatus.OK); - - doReturn(response).when(mockRest).exchange(Matchers.anyString(), - Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), - Matchers.<Class<?>>any()); - + public void testViewBlueprint() throws HttpStatusCodeException, Exception { + byte[] outArr = "Any String you want".getBytes(); + ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(outArr, HttpStatus.OK); + + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + ArgumentMatchers.any(Class.class))).thenReturn(response); + + /* + * doReturn(response).when(mockRest).exchange(Matchers.anyString(), + * Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), + * Matchers.<Class<?>>any()); + */ + subject.viewBlueprint("tenant1", "id1"); } - + @Test public void testGetDeploymentNamesWithFilter() throws Exception { MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - //mockedRequest.addParameter("filters", filterStr); - //mockedRequest.addParameter("sort", "name"); Set<String> userRoleSet = new HashSet<String>(); Set<String> userApps = new TreeSet<>(); userRoleSet.add("Standard User"); userRoleSet.add("ECOMPC_DCAE_WRITE"); userApps.add("dcae"); - - Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); - Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); - + String tenantsList = "{\"items\": [{\"id\": 1, \"dName\": null, \"name\": \"default_tenant\"}, {\"id\": 2, \"dName\": null, \"name\": \"dyh1b1902\"}], \"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; CloudifyTenantList sampleData = null; @@ -670,7 +649,6 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyTenantList> response1 = new ResponseEntity<CloudifyTenantList>(sampleData, HttpStatus.OK); - CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); @@ -686,34 +664,34 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyDeploymentList> response2 = new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); - Mockito - .when(mockRest.exchange(Matchers.contains("tenants"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyTenantList>>any())) - .thenReturn(response1); + // When + when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); + when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); + + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<CloudifyTenantList>() {}))).thenReturn(response1); + + when(mockRest.exchange(contains("deployments"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyDeploymentList>() {}))).thenReturn(response2); - Mockito.when(mockRest.exchange(Matchers.contains("deployments"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<CloudifyDeploymentList>>any())) - .thenReturn(response2); - List<String> actual = subject.getDeploymentNamesWithFilter(mockedRequest); assertTrue(actual.size() > 0); } - + @Test public void testGetDeploymentsWithFilter() throws Exception { MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - //mockedRequest.addParameter("filters", filterStr); - //mockedRequest.addParameter("sort", "name"); + // mockedRequest.addParameter("filters", filterStr); + // mockedRequest.addParameter("sort", "name"); Set<String> userRoleSet = new HashSet<String>(); Set<String> userApps = new TreeSet<>(); userRoleSet.add("Standard User"); userRoleSet.add("ECOMPC_DCAE_WRITE"); userApps.add("dcae"); - + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); - + String tenantsList = "{\"items\": [{\"id\": 1, \"dName\": null, \"name\": \"default_tenant\"}, {\"id\": 2, \"dName\": null, \"name\": \"dyh1b1902\"}], \"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; CloudifyTenantList sampleData = null; @@ -725,7 +703,6 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyTenantList> response1 = new ResponseEntity<CloudifyTenantList>(sampleData, HttpStatus.OK); - CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); @@ -741,54 +718,47 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyDeploymentList> response2 = new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); - Mockito - .when(mockRest.exchange(Matchers.contains("tenants"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyTenantList>>any())) - .thenReturn(response1); + when(mockRest.exchange(contains("tenants"), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<CloudifyTenantList>() {}))).thenReturn(response1); + + when(mockRest.exchange(contains("deployments"), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyDeploymentList>() {}))).thenReturn(response2); - Mockito.when(mockRest.exchange(Matchers.contains("deployments"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<CloudifyDeploymentList>>any())) - .thenReturn(response2); - List<CloudifyDeployment> actuals = subject.getDeploymentsWithFilter(mockedRequest); assertTrue(actuals.size() > 0); } - + @Test public void testGetSecret() { String secretTokenStr = - "{\"created_at\": \"created_ts\", \"key\": \"acl_key\", \"updated_at\": \"updated_ts\", \"value\": \"acl_token_val\", \"visibility\": \"global\", \"is_hidden_value\": \"false\", \"tenant_name\": \"tenant\", \"resource_availability\": \"rsrc\"}"; + "{\"created_at\": \"created_ts\", \"key\": \"acl_key\", \"updated_at\": \"updated_ts\", \"value\": \"acl_token_val\", \"visibility\": \"global\", \"is_hidden_value\": \"false\", \"tenant_name\": \"tenant\", \"resource_availability\": \"rsrc\"}"; CloudifySecret sampleData = null; try { sampleData = objectMapper.readValue(secretTokenStr, CloudifySecret.class); } catch (Exception e) { - + } - + ResponseEntity<CloudifySecret> response = new ResponseEntity<CloudifySecret>(sampleData, HttpStatus.OK); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifySecret>>any())) - .thenReturn(response); - + + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifySecret>() {}))).thenReturn(response); + CloudifySecret actuals = subject.getSecret("acl_key", "tenant"); assertTrue(actuals.getKey().equals("acl_key")); } - + @Test - public void testDeleteBlueprint() { - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyBlueprint>>any())).thenReturn(null); + public void testDeleteBlueprint() throws HttpStatusCodeException, Exception { + when(mockRest.exchange(anyString(), eq(HttpMethod.DELETE), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyBlueprint>() {}))).thenReturn(null); subject.deleteBlueprint("bp", "tenant"); } - + @Test - public void testGetPlugins() { - CloudifyPlugin sampleData = + public void testGetPlugins() throws HttpStatusCodeException, Exception { + CloudifyPlugin sampleData = new CloudifyPlugin("plugin1", "202001", "linux", "linux_k8s_plugin", "20200801"); List<CloudifyPlugin> cfyPlugins = new ArrayList<CloudifyPlugin>(); @@ -801,18 +771,16 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { CloudifyPluginList cfyPluginList = new CloudifyPluginList(cfyPlugins, metadata); ResponseEntity<CloudifyPluginList> response = new ResponseEntity<CloudifyPluginList>(cfyPluginList, HttpStatus.OK); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyPluginList>>any())) - .thenReturn(response); - + + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<CloudifyPluginList>() {}))).thenReturn(response); + CloudifyPluginList actuals = subject.getPlugins(); assertTrue(actuals.items.get(0).package_name.equals("plugin1")); } - + @Test - public void testGetDeploymentInputs() { + public void testGetDeploymentInputs() throws HttpStatusCodeException, Exception { CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); @@ -828,14 +796,64 @@ public class CloudifyRestClientImplTest extends MockitoTestSuite { ResponseEntity<CloudifyDeploymentList> response = new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<CloudifyDeploymentList>>any())) - .thenReturn(response); - + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyDeploymentList>() {}))).thenReturn(response); + CloudifyDeploymentList actualResult = subject.getDeploymentInputs("id", "tenant"); assertTrue(actualResult.items.get(0).id.equals("id")); } - -} + @Test + public void testGetDeployment_noTenant() throws HttpStatusCodeException, Exception { + // Given + CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); + List<CloudifyDeployment> cfyDeployItems = new ArrayList<CloudifyDeployment>(); + cfyDeployItems.add(cldDeployment); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); + + ResponseEntity<CloudifyDeploymentList> response = + new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); + + // When + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<CloudifyDeploymentList>() {}))).thenReturn(response); + + // Then + CloudifyDeploymentList actualResult = subject.getDeployment("id"); + assertTrue(actualResult.items.get(0).id.equals("id")); + } + + @Test + public void testGetDeployment() throws HttpStatusCodeException, Exception { + // Given + CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); + + List<CloudifyDeployment> cfyDeployItems = new ArrayList<CloudifyDeployment>(); + cfyDeployItems.add(cldDeployment); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); + + ResponseEntity<CloudifyDeploymentList> response = + new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); + + // When + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<CloudifyDeploymentList>() {}))).thenReturn(response); + + // Then + CloudifyDeploymentList actualResult = subject.getDeployment("id", "tenant"); + assertTrue(actualResult.items.get(0).id.equals("id")); + } +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImplTest.java index 7d85196..306fc1d 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImplTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImplTest.java @@ -17,13 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ package org.onap.ccsdk.dashboard.rest; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.eq; import java.net.MalformedURLException; import java.net.URL; @@ -38,7 +41,6 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.ccsdk.dashboard.model.cloudify.CloudifySecret; @@ -47,8 +49,10 @@ import org.onap.ccsdk.dashboard.model.consul.ConsulDeploymentHealth; import org.onap.ccsdk.dashboard.model.consul.ConsulNodeInfo; import org.onap.ccsdk.dashboard.model.consul.ConsulServiceHealth; import org.onap.ccsdk.dashboard.model.consul.ConsulServiceInfo; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummaryList; import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.core.ParameterizedTypeReference; @@ -57,33 +61,34 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) @PrepareForTest({DashboardProperties.class}) public class ConsulRestClientImplTest { @Mock RestTemplate mockRest; - + @InjectMocks ConsulRestClientImpl subject; - String[] svcTags = {"cfytenantname=onap"}; - + String[] svcTags = {"cfytenantname=onap"}; + protected final static ObjectMapper objectMapper = new ObjectMapper(); static HttpClientErrorException httpException; - @BeforeClass public static void setUpBeforeClass() throws Exception { httpException = new HttpClientErrorException(HttpStatus.FORBIDDEN, "statusText"); - objectMapper.registerModule(new Jdk8Module()); + objectMapper.registerModule(new Jdk8Module()); } - + @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); @@ -91,12 +96,12 @@ public class ConsulRestClientImplTest { when(DashboardProperties.getControllerProperty("site.primary", DashboardProperties.SITE_SUBKEY_CONSUL_URL)).thenReturn("https://cnsl-svc.com"); when(DashboardProperties.getControllerProperty("site.primary", - DashboardProperties.SITE_SUBKEY_CLOUDIFY_URL)).thenReturn("https://orcl-svc.com"); + DashboardProperties.SITE_SUBKEY_CLOUDIFY_URL)).thenReturn("https://orcl-svc.com"); when(DashboardProperties.getControllerProperty("site.primary", - DashboardProperties.SITE_SUBKEY_CLOUDIFY_USERNAME)).thenReturn("admin"); + DashboardProperties.SITE_SUBKEY_CLOUDIFY_USERNAME)).thenReturn("admin"); when(DashboardProperties.getControllerProperty("site.primary", - DashboardProperties.SITE_SUBKEY_CLOUDIFY_PASS)).thenReturn("admin"); - subject.setConsul_acl_token("consul_acl_token_for_dash"); + DashboardProperties.SITE_SUBKEY_CLOUDIFY_PASS)).thenReturn("admin"); + subject.setConsulAclToken("consul_acl_token_for_dash"); subject.init(); } @@ -107,20 +112,19 @@ public class ConsulRestClientImplTest { @Test public final void testGetConsulAcl() { String secretTokenStr = - "{\"created_at\": \"created_ts\", \"key\": \"acl_key\", \"updated_at\": \"updated_ts\", \"value\": \"acl_token_val\", \"visibility\": \"global\", \"is_hidden_value\": \"false\", \"tenant_name\": \"tenant\", \"resource_availability\": \"rsrc\"}"; + "{\"created_at\": \"created_ts\", \"key\": \"acl_key\", \"updated_at\": \"updated_ts\", \"value\": \"acl_token_val\", \"visibility\": \"global\", \"is_hidden_value\": \"false\", \"tenant_name\": \"tenant\", \"resource_availability\": \"rsrc\"}"; CloudifySecret sampleData = null; try { sampleData = objectMapper.readValue(secretTokenStr, CloudifySecret.class); } catch (Exception e) { } - + ResponseEntity<CloudifySecret> response = new ResponseEntity<CloudifySecret>(sampleData, HttpStatus.OK); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifySecret>>any())) - .thenReturn(response); + + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<CloudifySecret>() {}))).thenReturn(response); + String actualSecretStr = subject.getConsulAcl(mockRest); assertTrue(actualSecretStr.equals("acl_token_val")); } @@ -128,7 +132,7 @@ public class ConsulRestClientImplTest { @Test(expected = Exception.class) public final void testCreateCfyRestTemplate() throws Exception { String webapiUrl = DashboardProperties.getControllerProperty("site.primary", - DashboardProperties.SITE_SUBKEY_CLOUDIFY_URL); + DashboardProperties.SITE_SUBKEY_CLOUDIFY_URL); String user = DashboardProperties.getControllerProperty("site.primary", DashboardProperties.SITE_SUBKEY_CLOUDIFY_USERNAME); String pass = DashboardProperties.getControllerProperty("site.primary", @@ -143,25 +147,23 @@ public class ConsulRestClientImplTest { String urlScheme = webapiUrl.split(":")[0]; subject.createCfyRestTemplate(url, user, pass, urlScheme); } - + @Test - public final void testGetServiceHealth() { + public final void testGetServiceHealth() throws Exception { ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", - "This is a pgaas1_Service_ID health check", - "OK Output:", - "pgaas1_Service_ID", "pgaasServer1", svcTags, 34234, 4234); + "This is a pgaas1_Service_ID health check", "OK Output:", "pgaas1_Service_ID", + "pgaasServer1", svcTags, 34234, 4234); - // new ConsulServiceHealth() + // new ConsulServiceHealth() List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); expectedCnslSrvcHlth.add(consulSrvcHlth); ResponseEntity<List<ConsulServiceHealth>> response = new ResponseEntity<List<ConsulServiceHealth>>(expectedCnslSrvcHlth, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<List<ConsulServiceHealth>>>any())) + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<List<ConsulServiceHealth>>() {}))) .thenReturn(response); List<ConsulServiceHealth> actualCnslSrvcHlth = subject.getServiceHealth("dc1", "srvc1"); @@ -169,26 +171,23 @@ public class ConsulRestClientImplTest { } @Test(expected = Exception.class) - public final void get_svc_health_rest_client_exception() { - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<List<ConsulServiceHealth>>>any())) + public final void get_svc_health_rest_client_exception() throws Exception { + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<List<ConsulServiceHealth>>() {}))) .thenThrow(httpException); - - subject.getServiceHealth("dc1", "srvc1"); + + subject.getServiceHealth("dc1", "srvc1"); } - + @Test(expected = Exception.class) - public final void get_services_rest_client_exception() { - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<Map<String, Object>>>any())) - .thenThrow(httpException); + public final void get_services_rest_client_exception() throws Exception { + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<Map<String, Object>>() {}))).thenThrow(httpException); subject.getServices("dc1"); } - + @Test - public final void testGetServices() { + public final void testGetServices() throws Exception { List<String> srvcIps = new ArrayList<String>(); srvcIps.add("135.91.224.136"); srvcIps.add("135.91.224.138"); @@ -196,23 +195,22 @@ public class ConsulRestClientImplTest { Map<String, Object> respObj = new HashMap<String, Object>(); respObj.put("pgaasServer1", srvcIps); - + List<ConsulServiceInfo> expectedCnslSrvcs = new ArrayList<ConsulServiceInfo>(); expectedCnslSrvcs.add(consulSrvcInfo); - ResponseEntity<Map<String, Object>> response = - new ResponseEntity<Map<String,Object>>(respObj, HttpStatus.OK); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<Map<String, Object>>>any())).thenReturn(response); + ResponseEntity<Map<String, Object>> response = + new ResponseEntity<Map<String, Object>>(respObj, HttpStatus.OK); + + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<Map<String, Object>>() {}))).thenReturn(response); List<ConsulServiceInfo> actualSvcList = subject.getServices("dc1"); assertTrue(actualSvcList.get(0).name.equals("pgaasServer1")); } @Test - public final void testGetNodes() { + public final void testGetNodes() throws Exception { ConsulNodeInfo cnslNode = new ConsulNodeInfo("a2788806-6e2e-423e-8ee7-6cad6f3d3de6", "cjlvmcnsl00", "10.170.8.13", null, null, 6, 17980); @@ -222,9 +220,8 @@ public class ConsulRestClientImplTest { ResponseEntity<List<ConsulNodeInfo>> response = new ResponseEntity<List<ConsulNodeInfo>>(cnslNodeList, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<List<ConsulNodeInfo>>>any())).thenReturn(response); + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<List<ConsulNodeInfo>>() {}))).thenReturn(response); List<ConsulNodeInfo> actualNodeList = subject.getNodes("dc1"); assertTrue(actualNodeList.get(0).node.equals("cjlvmcnsl00")); @@ -232,16 +229,15 @@ public class ConsulRestClientImplTest { } @Test(expected = Exception.class) - public final void get_nodes_rest_client_exception() { - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<List<ConsulNodeInfo>>>any())) - .thenThrow(httpException); + public final void get_nodes_rest_client_exception() throws Exception { + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<List<ConsulNodeInfo>>() {}))) + .thenThrow(httpException); subject.getNodes("dc1"); } - + @Test - public final void testGetNodeServicesHealth() { + public final void testGetNodeServicesHealth() throws Exception { ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", "This is a pgaas1_Service_ID health check", @@ -254,9 +250,8 @@ public class ConsulRestClientImplTest { ResponseEntity<List<ConsulServiceHealth>> response = new ResponseEntity<List<ConsulServiceHealth>>(expectedCnslSrvcHlth, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<List<ConsulServiceHealth>>>any())) + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<List<ConsulServiceHealth>>() {}))) .thenReturn(response); List<ConsulServiceHealth> actualNodeHlthList = @@ -265,14 +260,13 @@ public class ConsulRestClientImplTest { } @Test(expected = Exception.class) - public final void get_node_svc_rest_client_exception() { - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<List<ConsulServiceHealth>>>any())) - .thenThrow(httpException); + public final void get_node_svc_rest_client_exception() throws Exception { + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<List<ConsulServiceHealth>>() {}))) + .thenThrow(httpException); subject.getNodeServicesHealth("dc1", "nodeId1"); } - + @Test public final void testGetDatacenters() { ConsulDatacenter cnslDc = new ConsulDatacenter("dc1"); @@ -285,24 +279,22 @@ public class ConsulRestClientImplTest { ResponseEntity<List<String>> response = new ResponseEntity<List<String>>(dcItems, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<List<String>>>any())).thenReturn(response); + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<List<String>>() {}))).thenReturn(response); List<ConsulDatacenter> actualDcList = subject.getDatacenters(); assertTrue(actualDcList.get(0).name.equals("dc1")); } @Test(expected = Exception.class) public final void get_dc_rest_client_exception() { - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<List<String>>>any())) - .thenThrow(httpException); + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<List<String>>() {}))).thenThrow(httpException); subject.getDatacenters(); } - + @Test - public final void testGetServiceHealthByDeploymentId() { + public final void testGetServiceHealthByDeploymentId() + throws HttpStatusCodeException, Exception { ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", "This is a pgaas1_Service_ID health check", @@ -315,22 +307,21 @@ public class ConsulRestClientImplTest { ResponseEntity<List<ConsulServiceHealth>> response = new ResponseEntity<List<ConsulServiceHealth>>(expectedCnslSrvcHlth, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<List<ConsulServiceHealth>>>any())) + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<List<ConsulServiceHealth>>() {}))) .thenReturn(response); ConsulDeploymentHealth cdh = subject.getServiceHealthByDeploymentId("deploymentId"); assertTrue(cdh.getNode().equals("cjlvmcnsl00")); } - + @Test(expected = Exception.class) - public final void get_svc_health_by_depId_rest_client_exception() { - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<List<ConsulServiceHealth>>>any())) - .thenThrow(httpException); + public final void get_svc_health_by_depId_rest_client_exception() + throws HttpStatusCodeException, Exception { + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), + eq(new ParameterizedTypeReference<List<ConsulServiceHealth>>() {}))) + .thenThrow(httpException); subject.getServiceHealthByDeploymentId("deploymentId"); } - + } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImplTest.java index 2024d72..035b005 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImplTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImplTest.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ package org.onap.ccsdk.dashboard.rest; @@ -51,6 +50,7 @@ import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentsListResponse; import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.portalsdk.core.util.CacheManager; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.core.ParameterizedTypeReference; @@ -63,6 +63,7 @@ import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestTemplate; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) @PrepareForTest({DashboardProperties.class}) public class DeploymentHandlerClientImplTest { @@ -71,7 +72,7 @@ public class DeploymentHandlerClientImplTest { @Mock CloudifyClient cfyClient; - + @InjectMocks DeploymentHandlerClientImpl subject; @@ -82,7 +83,7 @@ public class DeploymentHandlerClientImplTest { when(DashboardProperties.getControllerProperty("site.primary", DashboardProperties.SITE_SUBKEY_DHANDLER_URL)).thenReturn("https://dplh.com"); CacheManager testCache = new CacheManager(); - subject.setCacheManager(testCache); + subject.setCacheManager(testCache); this.subject.init(); } @@ -93,14 +94,12 @@ public class DeploymentHandlerClientImplTest { @Test public final void testCheckHealth() { String expectStr = "DH mS health check"; - ResponseEntity<String> response = - new ResponseEntity<String>(expectStr, HttpStatus.OK); - + ResponseEntity<String> response = new ResponseEntity<String>(expectStr, HttpStatus.OK); + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<String>>any())).thenReturn(response) - .thenReturn(response); - + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<String>>any())) + .thenReturn(response).thenReturn(response); + String actualStr = subject.checkHealth(); assertTrue(actualStr.equals(expectStr)); } @@ -241,11 +240,12 @@ public class DeploymentHandlerClientImplTest { Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())).thenReturn(response); - CloudifyDeployment cfyDepl = - new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", - "id", null, null, null, null, null, null, null, "tenant_name"); + CloudifyDeployment cfyDepl = + new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", "id", + null, null, null, null, null, null, null, "tenant_name"); - when(cfyClient.getDeploymentResource(Matchers.anyString(), Matchers.anyString())).thenReturn(cfyDepl); + when(cfyClient.getDeploymentResource(Matchers.anyString(), Matchers.anyString())) + .thenReturn(cfyDepl); subject.deleteDeployment("deploymentId", "tenant"); } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImplTest.java index e0452d0..192946e 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImplTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImplTest.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ package org.onap.ccsdk.dashboard.rest; @@ -26,6 +25,10 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.eq; import java.io.IOException; import java.util.ArrayList; @@ -44,7 +47,9 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeActiveException; import org.onap.ccsdk.dashboard.model.inventory.ApiResponseMessage; import org.onap.ccsdk.dashboard.model.inventory.Service; import org.onap.ccsdk.dashboard.model.inventory.ServiceList; @@ -61,6 +66,7 @@ import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummaryList; import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.portalsdk.core.util.CacheManager; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.core.ParameterizedTypeReference; @@ -68,6 +74,8 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.core.JsonParseException; @@ -76,6 +84,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) @PrepareForTest({DashboardProperties.class}) public class RestInventoryClientImplTest { @@ -83,7 +92,7 @@ public class RestInventoryClientImplTest { RestTemplate mockRest; @InjectMocks - RestInventoryClientImpl subject = new RestInventoryClientImpl(); + RestInventoryClientImpl subject; protected final ObjectMapper objectMapper = new ObjectMapper(); @@ -96,11 +105,13 @@ public class RestInventoryClientImplTest { ServiceType bpItemFull = null; ServiceTypeList bpItemFullList = null; - + ServiceTypeSummaryList bpListNext = null; ServiceTypeRequest bpUploadItem = null; + HttpClientErrorException httpException = new HttpClientErrorException(HttpStatus.GONE, "gone"); + @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); @@ -111,7 +122,7 @@ public class RestInventoryClientImplTest { when(DashboardProperties.getControllerProperty("site.primary", DashboardProperties.SITE_SUBKEY_INVENTORY_URL)).thenReturn("https://invt.com"); CacheManager testCache = new CacheManager(); - subject.setCacheManager(testCache); + subject.setCacheManager(testCache); this.subject.init(); } @@ -126,12 +137,8 @@ public class RestInventoryClientImplTest { Collection<Service> items = new ArrayList<Service>(); items.add(deplItem); - String pageLinks = - "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; String pageLinks2 = "{\"previousLink\":null,\"nextLink\":null}"; - ServiceList.PaginationLinks paginationLinks = - objectMapper.readValue(pageLinks, ServiceList.PaginationLinks.class); ServiceList.PaginationLinks paginationLinks2 = objectMapper.readValue(pageLinks2, ServiceList.PaginationLinks.class); @@ -139,23 +146,23 @@ public class RestInventoryClientImplTest { deplList = new ServiceList(items, totalCount, paginationLinks2); deplListNext = new ServiceList(items, totalCount, paginationLinks2); } - + public void getExpectedBlueprints() throws JsonParseException, JsonMappingException, IOException { - - bpItem = new ServiceTypeSummary.Builder().application("app1").component("comp1"). - typeName("xyz1731-helm-1906").owner("xyz1731").typeVersion(1906).build(); - - bpItem2 = new ServiceTypeSummary("xyz1731", "xyz1731-helm-1906", 1906, "app1", "comp1", "123-456-789", - "342343", true); + + bpItem = new ServiceTypeSummary.Builder().application("app1").component("comp1") + .typeName("xyz1731-helm-1906").owner("xyz1731").typeVersion(1906).build(); + + bpItem2 = new ServiceTypeSummary("xyz1731", "xyz1731-helm-1906", 1906, "app1", "comp1", + "123-456-789", "342343", true); bpItemFull = new ServiceType.Builder("xyz1731", "xyz1731-helm-1906", 1906, "tosca_definitions_version: cloudify_dsl_1_3", "", "app1", "comp1").build(); Collection<ServiceTypeSummary> items = new ArrayList<ServiceTypeSummary>(); items.add(bpItem); Collection<ServiceTypeSummary> items2 = new ArrayList<ServiceTypeSummary>(); - items2.add(bpItem2); - + items2.add(bpItem2); + String pageLinks = "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-service-types/?offset=25\"}}"; String pageLinks2 = "{\"previousLink\":null,\"nextLink\":null}"; @@ -170,23 +177,21 @@ public class RestInventoryClientImplTest { bpListNext = new ServiceTypeSummaryList(items, totalCount, paginationLinks2); } + @SuppressWarnings("unchecked") @Test public final void testCheckHealth() { String expectStr = "Inventory mS health check"; - ResponseEntity<String> response = - new ResponseEntity<String>(expectStr, HttpStatus.OK); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<String>>any())).thenReturn(response) - .thenReturn(response); - + ResponseEntity<String> response = new ResponseEntity<String>(expectStr, HttpStatus.OK); + + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<String>() {}))).thenReturn(response); + String actualStr = subject.checkHealth(); assertTrue(actualStr.equals(expectStr)); } @Test - public final void testGetServiceTypes() { + public final void testGetServiceTypes() throws Exception { Collection<ServiceTypeSummary> items = bpList.items; Stream<ServiceTypeSummary> expectedResult = items.stream(); @@ -196,9 +201,8 @@ public class RestInventoryClientImplTest { ResponseEntity<ServiceTypeSummaryList> response2 = new ResponseEntity<ServiceTypeSummaryList>(bpListNext, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<ServiceTypeSummaryList>>any())).thenReturn(response) + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<ServiceTypeSummaryList>() {}))).thenReturn(response) .thenReturn(response2); Stream<ServiceTypeSummary> actualResult = subject.getServiceTypes(); @@ -214,14 +218,13 @@ public class RestInventoryClientImplTest { ResponseEntity<ServiceTypeSummaryList> response2 = new ResponseEntity<ServiceTypeSummaryList>(bpListNext, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<ServiceTypeSummaryList>>any())).thenReturn(response) + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<ServiceTypeSummaryList>() {}))).thenReturn(response) .thenReturn(response2); - + subject.cacheServiceTypes(); } - + @Test public final void testGetServiceTypesServiceTypeQueryParams() { ServiceTypeQueryParams qryParms = new ServiceTypeQueryParams.Builder() @@ -237,9 +240,8 @@ public class RestInventoryClientImplTest { ResponseEntity<ServiceTypeSummaryList> response2 = new ResponseEntity<ServiceTypeSummaryList>(bpListNext, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<ServiceTypeSummaryList>>any())).thenReturn(response) + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<ServiceTypeSummaryList>() {}))).thenReturn(response) .thenReturn(response2); Stream<ServiceTypeSummary> actualResult = subject.getServiceTypes(qryParms); @@ -248,22 +250,27 @@ public class RestInventoryClientImplTest { } @Test - public final void testGetServiceType() { + public final void testGetServiceType() throws HttpStatusCodeException, Exception { + + // Given Optional<ServiceType> expectedResult = Optional.of(bpItemFull); ResponseEntity<ServiceType> response = new ResponseEntity<ServiceType>(bpItemFull, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<ServiceType>>any())) - .thenReturn(response); + // When + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<ServiceType>() {}))).thenReturn(response); + // Then Optional<ServiceType> actualResult = subject.getServiceType("432432423"); assertTrue(expectedResult.get().getTypeName().equals(actualResult.get().getTypeName())); } @Test public final void testGetServicesForType() throws Exception { + + // Given String typeId = "44234234"; ServiceRef expectedSrvc = new ServiceRef("dcae_dtiapi_1902", "432423", "433434"); Collection<ServiceRef> expectedSrvcIds = new ArrayList<ServiceRef>(); @@ -272,78 +279,80 @@ public class RestInventoryClientImplTest { ResponseEntity<ServiceList> response = new ResponseEntity<ServiceList>(deplList, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<ServiceList>>any())) - .thenReturn(response); - + // When + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<ServiceList>() {}))).thenReturn(response); + + // Then ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); ServiceRefList actualSvcRefList = subject.getServicesForType(qryParams); - assertTrue(actualSvcRefList.totalCount == expectedSvcRefList.totalCount); + assertTrue(actualSvcRefList.totalCount == expectedSvcRefList.totalCount); } - - @Test - public final void testAddServiceTypeServiceType() { - - when(mockRest.postForObject(Matchers.anyString(), Matchers.<HttpEntity<?>>any(), - Matchers.<Class<ServiceType>>any())).thenReturn(bpItemFull); - - ResponseEntity<ServiceTypeSummaryList> response = - new ResponseEntity<ServiceTypeSummaryList>(bpList, HttpStatus.OK); + @Test + public final void testAddServiceType() throws ServiceTypeActiveException, Exception { + // Given ResponseEntity<ServiceTypeSummaryList> response2 = new ResponseEntity<ServiceTypeSummaryList>(bpListNext, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<ServiceTypeSummaryList>>any())).thenReturn(response) - .thenReturn(response2); - + // When + when(mockRest.postForObject(anyString(), any(ServiceTypeRequest.class), + eq(ServiceType.class))).thenReturn(bpItemFull); + + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<ServiceTypeSummaryList>() {}))).thenReturn(response2); + + // Then ServiceType actualResult = subject.addServiceType(bpItemFull); assertTrue(actualResult.getTypeName().contains("xyz")); } @Test - public final void testAddServiceTypeServiceTypeRequest() { + public final void testAddServiceTypeServiceTypeRequest() + throws ServiceTypeActiveException, Exception { + // Given ServiceTypeRequest srvcReq = ServiceTypeRequest.from(bpItemFull); - when(mockRest.postForObject(Matchers.anyString(), Matchers.<HttpEntity<?>>any(), - Matchers.<Class<ServiceType>>any())).thenReturn(bpItemFull); - ResponseEntity<ServiceTypeSummaryList> response = new ResponseEntity<ServiceTypeSummaryList>(bpList, HttpStatus.OK); ResponseEntity<ServiceTypeSummaryList> response2 = new ResponseEntity<ServiceTypeSummaryList>(bpListNext, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<ServiceTypeSummaryList>>any())).thenReturn(response) - .thenReturn(response2); + // When + when(mockRest.postForObject(anyString(), any(ServiceTypeRequest.class), + eq(ServiceType.class))).thenReturn(bpItemFull); + + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<ServiceTypeSummaryList>() {}))).thenReturn(response2); + + // Then ServiceType actualResult = subject.addServiceType(srvcReq); assertTrue(actualResult.getTypeName().contains("xyz")); } @Test public final void testDeleteServiceType() throws Exception { + // Given ResponseEntity<ApiResponseMessage> response = new ResponseEntity<ApiResponseMessage>(HttpStatus.OK); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<ApiResponseMessage>>any())).thenReturn(response); - ResponseEntity<ServiceTypeSummaryList> response1 = new ResponseEntity<ServiceTypeSummaryList>(bpList, HttpStatus.OK); - ResponseEntity<ServiceTypeSummaryList> response2 = new ResponseEntity<ServiceTypeSummaryList>(bpListNext, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<ServiceTypeSummaryList>>any())).thenReturn(response1) + // When + when(mockRest.exchange(anyString(), eq(HttpMethod.DELETE), isNull(), + eq(new ParameterizedTypeReference<ApiResponseMessage>() {}))).thenReturn(response); + // .thenThrow(httpException); + + when(mockRest.exchange(anyString(), eq(HttpMethod.GET), isNull(), + eq(new ParameterizedTypeReference<ServiceTypeSummaryList>() {}))).thenReturn(response1) .thenReturn(response2); - + + // Then subject.deleteServiceType("4243234"); + // subject.deleteServiceType("4243234"); } } |