diff options
Diffstat (limited to 'ccsdk-app-common/src/main')
91 files changed, 6914 insertions, 4724 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 new file mode 100644 index 0000000..ec30b92 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/ApiBaseController.java @@ -0,0 +1,145 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * 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. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ +package org.onap.ccsdk.api.controller; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.onap.portalsdk.core.controller.UnRestrictedBaseController; +import org.springframework.beans.factory.annotation.Autowired; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +public class ApiBaseController extends UnRestrictedBaseController { + + /** + * Application name + */ + protected static final String APP_NAME = "ecd-app"; + + /** + * EELF-approved format + */ + protected static final DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + /** + * Query parameter for desired page number + */ + protected static final String PAGE_NUM_QUERY_PARAM = "page"; + + /** + * Query parameter for desired items per page + */ + protected static final String PAGE_SIZE_QUERY_PARAM = "size"; + + /** + * For general use in these methods and subclasses + */ + protected final ObjectMapper objectMapper = new ObjectMapper(); + + /** + * Application properties - NOT available to constructor. + */ + @Autowired + protected DashboardProperties appProperties; + + + /** + * Hello Spring, here's your no-arg constructor. + */ + public ApiBaseController() { + // Do not serialize null values + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + // Register Jdk8Module() for Stream and Optional types + objectMapper.registerModule(new Jdk8Module()); + } + + /** + * Access method for subclasses. + * + * @return DbcappProperties object that was autowired by Spring. + */ + protected DashboardProperties getAppProperties() { + return appProperties; + } + + /** + * Gets the requested page number from a query parameter in the + * HttpServletRequest. Defaults to 1, which is useful to allow manual testing of + * endpoints without supplying those pesky parameters. + * + * @param request HttpServletRequest + * @return Value of query parameter {@link #PAGE_NUM_QUERY_PARAM}; 1 if not + * found. + */ + protected int getRequestPageNumber(HttpServletRequest request) { + int pageNum = 1; + String param = request.getParameter(PAGE_NUM_QUERY_PARAM); + if (param != null) + pageNum = Integer.parseInt(param); + return pageNum; + } + + /** + * Gets the requested page size from a query parameter in the + * HttpServletRequest. Defaults to 50, which is useful to allow manual testing + * of endpoints without supplying those pesky parameters. + * + * @param request HttpServletRequest + * @return Value of query parameter {@link #PAGE_SIZE_QUERY_PARAM}; 50 if not + * found. + */ + protected int getRequestPageSize(HttpServletRequest request) { + int pageSize = 25; + String param = request.getParameter(PAGE_SIZE_QUERY_PARAM); + 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 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) { + 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(); + 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 new file mode 100644 index 0000000..525711d --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/NbApiController.java @@ -0,0 +1,1394 @@ +/******************************************************************************* + * =============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========================================================= + * + *******************************************************************************/ + +package org.onap.ccsdk.api.controller; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.http.HttpStatus; +import org.json.JSONObject; +import org.onap.aaf.cadi.CadiWrap; +import org.onap.ccsdk.dashboard.exceptions.BadRequestException; +import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.DownstreamException; +import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; +import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; +import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; +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.cloudify.CloudifyDeployedTenant; +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.deploymenthandler.DeploymentInput; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResource; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResourceLinks; +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.BlueprintInput; +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.ServiceTypeUploadRequest; +import org.onap.ccsdk.dashboard.rest.CloudifyClient; +import org.onap.ccsdk.dashboard.rest.ConsulClient; +import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; +import org.onap.ccsdk.dashboard.rest.InventoryClient; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.objectcache.AbstractCacheManager; +import org.onap.portalsdk.core.util.SystemProperties; +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.PathVariable; +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 org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; + +@RestController +@RequestMapping("/nb-api/v2") +public class NbApiController extends ApiBaseController { + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(NbApiController.class); + + private static final String DEPLOYMENTS_PATH = "deployments"; + private static final String SERVICE_TYPES_PATH = "blueprints"; + private static final String EXECUTIONS_PATH = "executions"; + private static final String TENANTS_PATH = "tenants"; + private static final String SERVICE_HEALTH_PATH = "health"; + + @Autowired + InventoryClient inventoryClient; + + @Autowired + DeploymentHandlerClient deploymentHandlerClient; + + @Autowired + CloudifyClient cloudifyClient; + + @Autowired + ConsulClient consulClient; + + @Autowired + ApplicationEventPublisher eventPub; + + private AbstractCacheManager cacheManager; + + @Autowired + public void setCacheManager(AbstractCacheManager cacheManager) { + this.cacheManager = cacheManager; + } + + public AbstractCacheManager getCacheManager() { + return cacheManager; + } + + /** + * Enum for selecting an item type. + */ + public enum InventoryDataItem { + DEPLOYMENTS, BLUEPRINTS, SERVICES_GROUPBY; + } + + private static Date begin, end; + + /** + * 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 + public String getTenants(HttpServletRequest request) throws Exception { + preLogAudit(request); + List 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) + itemList = getPageOfList(pageNum, pageSize, itemList); + RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); + String outboundJson = objectMapper.writeValueAsString(model); + return outboundJson; + } + + private boolean isAuthorized(HttpServletRequest request, String component) { + boolean auth = true; + return auth; + } + + @RequestMapping( + value = {SERVICE_TYPES_PATH}, + method = RequestMethod.POST, + produces = "application/json") + public String createBlueprint(HttpServletRequest request, HttpServletResponse response, + @RequestBody ServiceTypeUploadRequest serviceTypeUplReq, + ServletUriComponentsBuilder uriBuilder) throws Exception { + preLogAudit(request); + String json = null; + try { + Blueprint.parse(serviceTypeUplReq.getBlueprintTemplate()); + + if (serviceTypeUplReq.component == null || serviceTypeUplReq.component.isEmpty()) { + json = objectMapper.writeValueAsString( + new RestResponseError("Component name missing in blueprint request body")); + logger.error(EELFLoggerDelegate.errorLogger, + "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>(); + Optional<String> asdcServiceId = null; + Optional<String> asdcResourceId = null; + Optional<String> asdcServiceURL = null; + + ServiceTypeRequest invSrvcTypeReq = + new ServiceTypeRequest(serviceTypeUplReq.owner, serviceTypeUplReq.typeName, + serviceTypeUplReq.typeVersion, serviceTypeUplReq.blueprintTemplate, + serviceTypeUplReq.application, serviceTypeUplReq.component, serviceIds, + vnfTypes, serviceLocations, asdcServiceId, asdcResourceId, asdcServiceURL); + ServiceType apiResponse = inventoryClient.addServiceType(invSrvcTypeReq); + 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()); + } + } 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"); + 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"); + json = + objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); + } catch (Throwable 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"); + json = objectMapper + .writeValueAsString(new RestResponseError("updateServiceTypeBlueprint failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + @SuppressWarnings("unchecked") + @RequestMapping( + value = {SERVICE_TYPES_PATH}, + method = RequestMethod.GET, + 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; + if (page == null || page == 0) { + page = 1; + } + if (size == null) { + size = 25; + } + int pageNum = page; + int totalItems = 0; + List itemList = null; + try { + itemList = getItemListForPageWrapper(request, InventoryDataItem.BLUEPRINTS); + // Shrink if needed + if (itemList != null) { + totalItems = itemList.size(); + } + final int pageCount = (int) Math.ceil((double) totalItems / size); + if (totalItems > size) + itemList = getPageOfList(pageNum, size, itemList); + + RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); + json = objectMapper.writeValueAsString(model); + + try { + uriBuilder = ServletUriComponentsBuilder.fromCurrentRequest(); + eventPub.publishEvent(new PaginatedResultsRetrievedEvent<String>(String.class, + uriBuilder, response, page, pageCount, size)); + } catch (Exception e) { + // skip exception + } + } 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() + "\"}"; + } + 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()); + } + + 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()); + } + + 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); + } + return itemList; + } + + @RequestMapping( + value = {DEPLOYMENTS_PATH + "/{deploymentId}"}, + method = RequestMethod.GET, + produces = "application/json") + public String getDeployment(@PathVariable("deploymentId") String deploymentId, + HttpServletRequest request) { + preLogAudit(request); + String json = null; + try { + List<CloudifyDeployment> items = cloudifyClient.getDeployment(deploymentId).items; + json = objectMapper.writeValueAsString(items); + } 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); + try { + json = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + json = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } + } finally { + postLogAudit(request); + } + return json; + } + + @SuppressWarnings("unchecked") + @RequestMapping( + value = {DEPLOYMENTS_PATH}, + method = RequestMethod.GET, + produces = "application/json") + public String getDeploymentsByPage(HttpServletRequest request, + @RequestParam(value = "page", required = false) Integer page, + @RequestParam(value = "size", required = false) Integer size, + ServletUriComponentsBuilder uriBuilder, HttpServletResponse response) { + preLogAudit(request); + String outboundJson = null; + if (page == null || page == 0) { + page = 1; + } + if (size == null) { + size = 25; + } + int pageNum = page; + int totalItems = 0; + List<CloudifyDeployment> itemList = null; + try { + itemList = cloudifyClient.getDeploymentsWithFilter(request); + + // Shrink if needed + if (itemList != null) { + totalItems = itemList.size(); + } + final int pageCount = (int) Math.ceil((double) totalItems / size); + if (totalItems > size) { + itemList = getPageOfList(pageNum, size, itemList); + } + RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); + outboundJson = objectMapper.writeValueAsString(model); + try { + uriBuilder = ServletUriComponentsBuilder.fromCurrentRequest(); + eventPub.publishEvent(new PaginatedResultsRetrievedEvent<String>(String.class, + uriBuilder, response, page, pageCount, size)); + } catch (Exception e) { + // skip the pagination links logic + } + 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!"); + 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); + try { + outboundJson = objectMapper.writeValueAsString(result); + } catch (JsonProcessingException jpe) { + // Should never, ever happen + outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; + } + return outboundJson; + } finally { + postLogAudit(request); + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private ServiceTypeSummary getBlueprintItem(String searchBy, Optional<Integer> version, + String typeId) throws Exception { + ServiceTypeQueryParams serviceQueryParams = null; + ServiceTypeSummary item = null; + if (version.isPresent()) { + serviceQueryParams = + new ServiceTypeQueryParams.Builder().typeName(searchBy).onlyLatest(false).build(); + } else { + serviceQueryParams = new ServiceTypeQueryParams.Builder().typeName(searchBy).build(); + } + + List itemList = + inventoryClient.getServiceTypes(serviceQueryParams).collect(Collectors.toList()); + + if (version.isPresent()) { + itemList = (List) itemList.stream() + .filter(s -> ((ServiceTypeSummary) s).contains(version.get().toString())) + .collect(Collectors.toList()); + } + if (typeId != null && typeId.equals("typeId")) { + item = (ServiceTypeSummary) ((List) itemList).get(0); + } + return item; + } + + /** + * Query inputs used to create a deployment + * + * @param deploymentId + * @param tenant + * @param request + * @return + * @throws Exception + */ + @RequestMapping( + 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 { + preLogAudit(request); + ECTransportModel result = null; + String json = ""; + 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"); + 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); + json = objectMapper.writeValueAsString(result); + } finally { + postLogAudit(request); + } + return json; + } + + /** + * Create an upgrade/rollback workflow execution for a deployment. + * + * @param request HttpServletRequest + * @param execution Execution model + * @return Information about the execution + * @throws Exception on serialization failure + */ + @RequestMapping( + value = {DEPLOYMENTS_PATH + "/{deploymentId}"}, + method = RequestMethod.PUT, + produces = "application/json") + public String modifyDeployment(@PathVariable("deploymentId") String deploymentId, + HttpServletRequest request, InputStream upgParams) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + String nodeInstId = ""; + Map<String, Object> parameters = + objectMapper.readValue(upgParams, new TypeReference<Map<String, Object>>() {}); + String tenant = (String) parameters.get("tenant"); + String workflow = (String) parameters.get("workflow"); + parameters.remove("tenant"); + parameters.remove("workflow"); + // get the node instance ID for the deployment + CloudifyNodeInstanceIdList nodeInstList = + cloudifyClient.getNodeInstanceId(deploymentId, tenant); + if (nodeInstList != null) { + nodeInstId = nodeInstList.items.get(0).id; + } + parameters.put("node_instance_id", nodeInstId); + if (workflow.equals("upgrade")) { + String repo_user = cloudifyClient.getSecret("controller_helm_user", tenant).value; + String repo_user_password = + cloudifyClient.getSecret("controller_helm_password", tenant).value; + parameters.put("repo_user", repo_user); + parameters.put("repo_user_password", repo_user_password); + } + 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"); + 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"); + result = new RestResponseError("updateDeployment failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + @RequestMapping( + 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>(); + ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); + ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); + ServiceTypeServiceMap srvcMap = new ServiceTypeServiceMap(typeId, srvcRefs); + result.add(srvcMap); + return objectMapper.writeValueAsString(result); + } + + private static void mergeInputData(Map<String, Object> bpInputs, Map<String, Object> dataSet, + String key, Object val) { + Object keyVal = dataSet.get(key); + if (keyVal != null) { + bpInputs.put(key, keyVal); + } else { + Object bpInput = ((BlueprintInput) val).getDefaultValue(); + if (bpInput != null) { + bpInputs.put(key, bpInput); + } else { + bpInputs.put(key, ""); + } + } + } + + private static void translateInputData(Map<String, Object> dataSet, String key, Object val) { + try { + if (val instanceof java.lang.String) { + int numericVal = Integer.parseInt((String) val); + dataSet.put(key, numericVal); + } else { + dataSet.put(key, val); + } + } catch (NumberFormatException ne) { + dataSet.put(key, val); + } catch (Exception e) { + dataSet.put(key, val); + } + } + + @RequestMapping( + value = {DEPLOYMENTS_PATH}, + method = RequestMethod.POST, + produces = "application/json") + public String createDeployment(HttpServletRequest request, HttpServletResponse response, + @RequestBody DeploymentInput deploymentRequestObject) throws Exception { + preLogAudit(request); + String json = null; + StringBuffer status = new StringBuffer(); + Optional<Integer> bpVersion = null; + String srvcTypeId = null; + ServiceTypeSummary bpSummItem = null; + ServiceType bpItem = null; + String bpName = deploymentRequestObject.getBlueprintName(); + String cName = deploymentRequestObject.getComponent(); + String tag = deploymentRequestObject.getTag(); + String depName = cName + "_" + tag; + Map<String, BlueprintInput> bpInputDefs = null; + + if (cName == null || cName.isEmpty()) { + json = objectMapper.writeValueAsString( + new RestResponseError("Component name missing in deployment request body")); + logger.error(EELFLoggerDelegate.errorLogger, + "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 { + 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() + "\"}"; + } + return json; + } finally { + postLogAudit(request); + } + } + try { + // process the JSON inputs + Map<String, Object> processedInputs = new HashMap<String, Object>(); + Map<String, Object> mergedInputs = new HashMap<String, Object>(); + deploymentRequestObject.getInputs() + .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)); + DeploymentResponse resp = + deploymentHandlerClient.putDeployment(depName, deploymentRequestObject.getTenant(), + new DeploymentRequest(srvcTypeId, mergedInputs)); + DeploymentResponseLinks deplLinks = resp.getLinks(); + String deplStatus = deplLinks.getStatus(); + if (!deplStatus.contains("cfy_tenant")) { + deplStatus = deplStatus + "?cfy_tenant_name=" + deploymentRequestObject.getTenant(); + } + String self = request.getRequestURL().append("/").append(depName).toString(); + status.append(self).append("/executions?tenant=") + .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"); + 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"); + json = + objectMapper.writeValueAsString(new RestResponseError("putDeployment failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + /** + * Get the executions for one deployment. + * + * + * @param deployment_id Deployment ID (query parameter) + * @param request HttpServletRequest + * @return CloudifyExecutionList + * @throws Exception on serialization failure + */ + @RequestMapping( + 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 { + preLogAudit(request); + ECTransportModel result = null; + 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"); + 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); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Gets the service health for a deployment + * + * + * @param deployment_id Deployment ID (query parameter) + * @param request HttpServletRequest + * @return String + * @throws Exception on serialization failure + */ + @RequestMapping( + 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; + 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"); + 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); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + /** + * Query the specified blueprint. + * + * @param id Blueprint ID + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return status code on success; error on failure. + * @throws Exception On serialization failure + */ + @SuppressWarnings("unchecked") + @RequestMapping( + value = {SERVICE_TYPES_PATH + "/{typeid}"}, + method = RequestMethod.GET, + produces = "application/json") + @ResponseBody + public String queryBlueprint(@PathVariable("typeid") String typeId, HttpServletRequest request, + HttpServletResponse response, ServletUriComponentsBuilder uriBuilder) throws Exception { + String json = ""; + Optional<ServiceType> resultItem = null; + try { + resultItem = inventoryClient.getServiceType(typeId); + if (resultItem.isPresent()) { + json = objectMapper.writeValueAsString(resultItem.get()); + } + 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()); + } + } 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() + "\"}"; + } + } + return json; + } + + /** + * Deletes the specified blueprint. + * + * @param id Blueprint ID + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return status code on success; error on failure. + * @throws Exception On serialization failure + */ + @SuppressWarnings("unchecked") + @RequestMapping( + value = {SERVICE_TYPES_PATH + "/{typeid}"}, + method = RequestMethod.DELETE, + produces = "application/json") + @ResponseBody + public String deleteBlueprint(@PathVariable("typeid") String typeId, HttpServletRequest request, + HttpServletResponse response, ServletUriComponentsBuilder uriBuilder) throws Exception { + preLogAudit(request); + String json = "{\"204\": \"Blueprint deleted\"}"; + String bpComp = ""; + boolean allow = true; + ReadWriteLock lock = new ReentrantReadWriteLock(); + lock.readLock().lock(); + @SuppressWarnings("unchecked") + List itemList = + (List<ServiceTypeSummary>) getCacheManager().getObject("dcae-service-types"); + lock.readLock().unlock(); + 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"); + } + } + 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 (!allow) { + 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(); + StringBuffer linkHeader = new StringBuffer(); + String linkStr = "<" + uri_all + ">; 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) { + 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 (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"); + json = + objectMapper.writeValueAsString(new RestResponseError("deleteBlueprint failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + /** + * Un-deploy an application or service + * + * @param deploymentId + * @param request + * @param tenant + * @param response + * @return + * @throws Exception + */ + @SuppressWarnings("unchecked") + @RequestMapping( + value = {DEPLOYMENTS_PATH + "/{deploymentId}"}, + method = RequestMethod.DELETE, + produces = "application/json") + public String deleteDeployment(@PathVariable("deploymentId") String deploymentId, + HttpServletRequest request, @RequestParam(value = "tenant", required = true) String tenant, + HttpServletResponse response) throws Exception { + preLogAudit(request); + String json = null; + StringBuffer status = new StringBuffer(); + try { + 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); + lock.readLock().unlock(); + if (itemList != null) { + Predicate<CloudifyDeployment> idFilter = p -> p.id.equals(deploymentId); + itemList = (List<CloudifyDeployment>) itemList.stream().filter(idFilter) + .collect(Collectors.toList()); + } else { + CloudifyDeploymentList cfyDeplList = + cloudifyClient.getDeployment(deploymentId, tenant); + if (cfyDeplList != null && !cfyDeplList.items.isEmpty()) { + itemList = cfyDeplList.items; + } + } + if (itemList != null && !itemList.isEmpty()) { + String depItem = ((CloudifyDeployment) itemList.get(0)).id; + if (depItem.contains("_")) { + String depComp = depItem.split("_")[0]; + if (!isAuthorized(request, depComp)) { + response.setStatus(HttpStatus.SC_FORBIDDEN); + json = objectMapper.writeValueAsString( + new RestResponseError("Un-authorized to perform this operation")); + return json; + } + deploymentHandlerClient.deleteDeployment(deploymentId, tenant); + 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())); + JSONObject statObj = new JSONObject(deplRsrc); + 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"); + 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"); + json = objectMapper + .writeValueAsString(new RestResponseError("deleteDeployment failed", t)); + } finally { + postLogAudit(request); + } + return json; + } + + /** + * Cancels an execution. + * + * @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 + * @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 + 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; + 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"); + 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); + } finally { + postLogAudit(request); + } + if (result == null) + return null; + else + return objectMapper.writeValueAsString(result); + } + + private void preLogAudit(HttpServletRequest request) { + 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(); + MDC.put("AlertSeverity", "0"); + MDC.put("TargetEntity", "API Controller"); + MDC.put("TargetServiceName", "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, + request.getMethod() + " " + request.getRequestURI()); + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/PaginatedResultsRetrievedEvent.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/PaginatedResultsRetrievedEvent.java new file mode 100644 index 0000000..051f6e6 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/PaginatedResultsRetrievedEvent.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * 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. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ +package org.onap.ccsdk.api.controller; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.context.ApplicationEvent; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +public class PaginatedResultsRetrievedEvent<T> extends ApplicationEvent { + + /** + * + */ + private static final long serialVersionUID = 1513813910132068908L; + private Class clazz; + private ServletUriComponentsBuilder uriBuilder; + private HttpServletResponse response; + private int page; + private int maxPages; + private int pageSize; + + public PaginatedResultsRetrievedEvent(Class clazz, + ServletUriComponentsBuilder uriBuilder, HttpServletResponse response, + int page, int maxPages, int pageSize) { + super(clazz); + this.clazz = clazz; + this.uriBuilder = uriBuilder; + this.response = response; + this.page = page; + this.maxPages = maxPages; + this.pageSize = pageSize; + } + + public Class getClazz() { + return clazz; + } + + public ServletUriComponentsBuilder getUriBuilder() { + return uriBuilder; + } + + public HttpServletResponse getResponse() { + return response; + } + + public int getPage() { + return page; + } + + public int getPageSize() { + return pageSize; + } + + public int getMaxPages() { + return maxPages; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/PagingEventListener.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/PagingEventListener.java new file mode 100644 index 0000000..7b310c6 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/api/controller/PagingEventListener.java @@ -0,0 +1,136 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * 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. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ +package org.onap.ccsdk.api.controller; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.context.ApplicationListener; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import org.springframework.web.util.UriComponentsBuilder; + +@Component +public class PagingEventListener implements + ApplicationListener<PaginatedResultsRetrievedEvent> { + + + public static final String REL_COLLECTION = "collection"; + public static final String REL_NEXT = "next"; + public static final String REL_PREV = "prev"; + public static final String REL_FIRST = "first"; + public static final String REL_LAST = "last"; + private static final String PAGE = "page"; + + @Override + public void onApplicationEvent(PaginatedResultsRetrievedEvent event) { + addLinkHeaderOnPagedResourceRetrieval(event.getUriBuilder(), + event.getResponse(), event.getClazz(), event.getPage(), + event.getMaxPages(), event.getPageSize()); + } + + void addLinkHeaderOnPagedResourceRetrieval(ServletUriComponentsBuilder uriBuilder, + HttpServletResponse response, Class clazz, int page, + int totalPages, int size) { + + StringBuilder linkHeader = new StringBuilder(); + if (hasNextPage(page, totalPages)) { + String uriNextPage = constructNextPageUri(uriBuilder, page, size); + linkHeader.append(createLinkHeader(uriNextPage, "next")); + } + if (hasPreviousPage(page)) { + String uriPrevPage = constructPrevPageUri(uriBuilder, page, size); + appendCommaIfNecessary(linkHeader); + linkHeader.append(createLinkHeader(uriPrevPage, "prev")); + } + if (hasFirstPage(page)) { + String uriFirstPage = constructFirstPageUri(uriBuilder, size); + appendCommaIfNecessary(linkHeader); + linkHeader.append(createLinkHeader(uriFirstPage, "first")); + } + if (hasLastPage(page, totalPages)) { + String uriLastPage = constructLastPageUri(uriBuilder, totalPages, + size); + appendCommaIfNecessary(linkHeader); + linkHeader.append(createLinkHeader(uriLastPage, "last")); + } + response.addHeader("Link", linkHeader.toString()); + + } + + final String constructNextPageUri(final UriComponentsBuilder uriBuilder, + final int page, final int size) { + return uriBuilder.replaceQueryParam(PAGE, page + 1) + .replaceQueryParam("size", size).build().toUriString(); + } + + final String constructPrevPageUri(final UriComponentsBuilder uriBuilder, + final int page, final int size) { + return uriBuilder.replaceQueryParam(PAGE, page - 1) + .replaceQueryParam("size", size).build().toUriString(); + } + + final String constructFirstPageUri(final UriComponentsBuilder uriBuilder, + final int size) { + return uriBuilder.replaceQueryParam(PAGE, 1) + .replaceQueryParam("size", size).build().toUriString(); + } + + final String constructLastPageUri(final UriComponentsBuilder uriBuilder, + final int totalPages, final int size) { + return uriBuilder.replaceQueryParam(PAGE, totalPages) + .replaceQueryParam("size", size).build().toUriString(); + } + + final boolean hasNextPage(final int page, final int totalPages) { + return page < totalPages - 1; + } + + final boolean hasPreviousPage(final int page) { + return page > 1; + } + + final boolean hasFirstPage(final int page) { + return hasPreviousPage(page); + } + + final boolean hasLastPage(final int page, final int totalPages) { + return totalPages > 1 && hasNextPage(page, totalPages); + } + + final void appendCommaIfNecessary(final StringBuilder linkHeader) { + if (linkHeader.length() > 0) { + linkHeader.append(", "); + } + } + + // template + + protected void plural(final UriComponentsBuilder uriBuilder, + final Class clazz) { + final String resourceName = clazz.getSimpleName().toString().toLowerCase() + "s"; + //uriMapper.getUriBase(clazz); + uriBuilder.path("/" + resourceName); + } + + public static String createLinkHeader(final String uri, final String rel) { + return "<" + uri + ">; rel=\"" + rel + "\""; + } +} 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 93748f3..ae0e849 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,7 +2,7 @@ * =============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. @@ -22,41 +22,63 @@ 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; import java.util.Iterator; import java.util.List; import java.util.Map; - +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; -import org.onap.ccsdk.dashboard.model.CloudifyDeployment; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; -import org.onap.ccsdk.dashboard.model.CloudifyEvent; -import org.onap.ccsdk.dashboard.model.CloudifyEventList; -import org.onap.ccsdk.dashboard.model.CloudifyExecution; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; -import org.onap.ccsdk.dashboard.model.CloudifyTenant; import org.onap.ccsdk.dashboard.model.ECTransportModel; import org.onap.ccsdk.dashboard.model.RestResponseError; import org.onap.ccsdk.dashboard.model.RestResponsePage; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployment; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentExt; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentHelm; +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.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionRequest; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyPlugin; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyTenant; +import org.onap.ccsdk.dashboard.model.cloudify.ServiceRefCfyList; +import org.onap.ccsdk.dashboard.model.consul.ConsulDeploymentHealth; +import org.onap.ccsdk.dashboard.model.inventory.Service; +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.ServiceTypeServiceMap; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummary; import org.onap.ccsdk.dashboard.rest.CloudifyClient; +import org.onap.ccsdk.dashboard.rest.ConsulClient; +import org.onap.ccsdk.dashboard.rest.InventoryClient; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.objectcache.AbstractCacheManager; 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.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.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -66,7 +88,6 @@ 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 com.fasterxml.jackson.core.JsonProcessingException; /** @@ -83,12 +104,16 @@ public class CloudifyController extends DashboardRestrictedBaseController { @Autowired CloudifyClient cloudifyClient; + @Autowired + InventoryClient inventoryClient; + @Autowired + ConsulClient consulClient; /** * Enum for selecting an item type. */ public enum CloudifyDataItem { - BLUEPRINT, DEPLOYMENT, EXECUTION, TENANT; + BLUEPRINT, DEPLOYMENT, EXECUTION, TENANT, SERVICE_ID, SERVICE_ID_COUNT; } private static Date begin; @@ -98,10 +123,24 @@ public class CloudifyController extends DashboardRestrictedBaseController { private static final String EXECUTIONS_PATH = "executions"; private static final String TENANTS_PATH = "tenants"; private static final String NODE_INSTANCES_PATH = "node-instances"; - private static final String UPDATE_DEPLOYMENT_PATH = "update-deployment"; private static final String EVENTS_PATH = "events"; - private static final String DEP_TENANT_STATUS = "deployment-status"; + private static final String SERVICE_ID = "service-list"; + private static final String SERVICE_ID_COUNT = "service-list-count"; + 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 AbstractCacheManager cacheManager; + + @Autowired + public void setCacheManager(AbstractCacheManager cacheManager) { + this.cacheManager = cacheManager; + } + public AbstractCacheManager getCacheManager() { + return cacheManager; + } + /** * Supports sorting events by timestamp */ @@ -122,6 +161,58 @@ public class CloudifyController extends DashboardRestrictedBaseController { } }; + 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) { + srvc.owner = entry.getKey(); + break; + } + } + } + } + + 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; + } + } + 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; + } + } + /** * Gets one page of objects and supporting information via the REST client. On * success, returns a PaginatedRestResponse object as String. @@ -132,23 +223,300 @@ public class CloudifyController extends DashboardRestrictedBaseController { * @return JSON block as String, see above. * @throws Exception On any error; e.g., Network failure. */ - @SuppressWarnings({"rawtypes"}) - private String getItemListForPage(long userId, CloudifyDataItem option, int pageNum, - int pageSize) throws Exception { - /* - * if (this.restClient == null) { this.restClient = - * getCloudifyRestClient(userId); } - */ + @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); + String user = UserUtils.getUserSession(request).getLoginId(); + HashMap<String, Boolean> comp_deploy_tab = + (HashMap<String, Boolean>) session.getAttribute("comp_access"); + String roleLevel = (String) session.getAttribute("role_level"); + String roleAuth = (String) session.getAttribute("auth_role"); + if (roleAuth == null) { + roleAuth = "READ"; + } + if (roleLevel == null) { + roleLevel = "dev"; + } + if (comp_deploy_tab == null) { + comp_deploy_tab = new HashMap<String, Boolean>(); + } + Set<String> userApps = (Set<String>) session.getAttribute("authComponents"); + if (userApps == null) { + userApps = new TreeSet<String>(); + } List itemList = null; + new ArrayList<Service>(); + int totalItems = 0; + 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<CloudifyDeploymentHelm> cfyDeplHelm = null; + List<CloudifyDeploymentHelm> cfyDeplHelmList = new ArrayList<CloudifyDeploymentHelm>(); + 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()); + 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("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("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"); + lock.readLock().unlock(); switch (option) { - /* - * case BLUEPRINT: itemList = restClient.getBlueprints().items; - * Collections.sort(itemList, blueprintComparator); break; case DEPLOYMENT: - * itemList = restClient.getDeployments().items; Collections.sort(itemList, - * deploymentComparator); break; - */ + case SERVICE_ID_COUNT: + List items = null; + if (!ownerFilterStr.isEmpty()) { + if (deplPerOwner != null) { + List<CloudifyDeployedTenant> ownerDeplList = deplPerOwner.get(user); + items = ownerDeplList; + } + } else { + List<CloudifyDeployment> itemsList = + cloudifyClient.getDeploymentsWithFilter(request); + items = itemsList; + } + if (items == null) { + items = new ArrayList<CloudifyDeployment>(); + } + totalItems = items.size(); + RestResponsePage<List> model = + new RestResponsePage<>(totalItems, 1, items); + String outboundJson = objectMapper.writeValueAsString(model); + return outboundJson; + case SERVICE_ID: + final String svcIdTenant = tenantFilterStr; + if (useCache) { + lock.readLock().lock(); + itemList = + (List<CloudifyDeployment>)getCacheManager().getObject(SERVICE_ID + ":" + svcIdTenant); + lock.readLock().unlock(); + } + if (itemList == null) { + 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()); + // 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()); + } + } + return objectMapper.writeValueAsString(svcIdList); + case DEPLOYMENT: + itemList = new ArrayList<CloudifyDeployment>(); + List<CloudifyDeployment> cfyDepPerTntList = null; + List<CloudifyDeployment> cfyDepList = null; + try { + if (tenantFilterStr.isEmpty()) { + cfyDepList = new ArrayList<CloudifyDeployment>(); + 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); + 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); + cfyDepList.addAll(cfyDepPerTntList); + } + } + } else { + if (useCache) { + lock.readLock().lock(); + cfyDepList = (List<CloudifyDeployment>)getCacheManager().getObject(SERVICE_ID + ":" + tenantFilterStr); + lock.readLock().unlock(); + } + if (cfyDepList == null) { + 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"); + if (cfyDeplExt != null) { + cfyDepExList.addAll(cfyDeplExt); + } + cfyDeplHelm = + (List<CloudifyDeploymentHelm>)getCacheManager().getObject(SERVICE_ID + ":" + tenantFilterStr + ":helm"); + if (cfyDeplHelm != null) { + cfyDeplHelmList.addAll(cfyDeplHelm); + } + 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()); + } + // 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()); + 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()); + 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()); + 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")) { + 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()); + } else { + cfyDepList = new ArrayList<CloudifyDeployment>(); + } + } + } + if (!svcRefFilterStr.isEmpty()) { + 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()))) + .collect(Collectors.toList()); + } + } + if (!statusFilterStr.isEmpty()) { + List<String> statusFilterList = + new ArrayList<String>(Arrays.asList(statusFilterStr.split(","))); + Predicate<CloudifyDeployment> srvcFilter = + p -> p.lastExecution.status != null; + 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()); + } + } + if (!helmFilterStr.isEmpty()) { + 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 ) { + updateWorkflowHelmStatus(cfyDepList, cfyDepExList, cfyDeplHelmList); + cfyDepList = (List) cfyDepList.stream().filter(helmFilter.and( + s -> ((CloudifyDeployment) s).isHelm == true)) + .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)); + } else if (sortBy.equals("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)); + } else if (sortBy.equals("updated_at")) { + ((List<CloudifyDeployment>)itemList).sort( + (CloudifyDeployment o1, CloudifyDeployment o2) -> o1.updated_at.compareTo(o2.updated_at)); + } + } + break; case TENANT: - itemList = cloudifyClient.getTenants().items; + lock.readLock().lock(); + cfyTenantList = (List<CloudifyTenant>)getCacheManager().getObject(TENANTS_PATH); + lock.readLock().unlock(); + if (cfyTenantList == null || cfyTenantList.isEmpty()) { + cfyTenantList = (List<CloudifyTenant>)cloudifyClient.getTenants().items; + } + + itemList = cfyTenantList; break; default: MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -162,10 +530,78 @@ public class CloudifyController extends DashboardRestrictedBaseController { "getItemListForPage failed: unimplemented case: " + option.name()); } // Shrink if needed - final int totalItems = itemList.size(); + if (itemList != null) { + totalItems = itemList.size(); + } final int pageCount = (int) Math.ceil((double) totalItems / pageSize); - if (totalItems > pageSize) + if (totalItems > pageSize) { itemList = getPageOfList(pageNum, pageSize, itemList); + } + + if (option.equals(CloudifyDataItem.DEPLOYMENT)) { + // update blueprint owner for each deployment record + if (deplPerOwner != null ) { + updateBpOwnerId(itemList, deplPerOwner); + } + if (cfyDepExList == null || cfyDepExList.isEmpty()) { + cfyDepExList = cloudifyClient.updateWorkflowStatus(itemList); + } + if (cfyDeplHelmList == null || cfyDeplHelmList.isEmpty()) { + cfyDeplHelmList = cloudifyClient.updateHelmInfo(itemList); + } + for (CloudifyDeployment srvc: (List<CloudifyDeployment>)itemList) { + try { + ConsulDeploymentHealth serviceHealth = + consulClient.getServiceHealthByDeploymentId(srvc.id); + if (serviceHealth != null) { + srvc.healthStatus = serviceHealth.getStatus(); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "consul getServiceHealth caught exception"); + } + // 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()); + 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()); + if (deplHelmItems != null && !deplHelmItems.isEmpty()) { + srvc.helmStatus = deplHelmItems.get(0).helmStatus; + srvc.isHelm = deplHelmItems.get(0).isHelm; + } + } + } + // check for authorization to perform delete deployed blueprints + if (!roleLevel.equals("ops")) { + if (roleLevel.equals("dev") || roleLevel.equals("app_dev")) { + boolean deployFlag = roleAuth.equals("WRITE") ? true : false; + for (CloudifyDeployment srvc : (List<CloudifyDeployment>) itemList) { + srvc.canDeploy = deployFlag; + } + } 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); + srvc.canDeploy = enableDeploy; + } else { + srvc.canDeploy = false; + } + } + } + } else { + for (CloudifyDeployment srvc : (List<CloudifyDeployment>) itemList) { + srvc.canDeploy = true; + } + } + } RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); String outboundJson = objectMapper.writeValueAsString(model); return outboundJson; @@ -177,9 +613,12 @@ public class CloudifyController extends DashboardRestrictedBaseController { * * @param request Inbound request * @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. */ - protected String getItemListForPageWrapper(HttpServletRequest request, CloudifyDataItem option) { + protected String getItemListForPageWrapper(HttpServletRequest request, CloudifyDataItem option, + String sortBy, String searchBy) { String outboundJson = null; try { User appUser = UserUtils.getUserSession(request); @@ -187,7 +626,8 @@ public class CloudifyController extends DashboardRestrictedBaseController { throw new Exception("getItemListForPageWrapper: Failed to get application user"); int pageNum = getRequestPageNumber(request); int pageSize = getRequestPageSize(request); - outboundJson = getItemListForPage(appUser.getId(), option, pageNum, pageSize); + outboundJson = getItemListForPage(request, appUser.getId(), option, pageNum, pageSize, + sortBy, searchBy); } catch (Exception ex) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); @@ -210,8 +650,163 @@ public class CloudifyController extends DashboardRestrictedBaseController { } return outboundJson; } + /** + * Serves one page of deployments + * + * @param request HttpServletRequest + * @return List of CloudifyDeployment objects + */ + @RequestMapping(value = { DEPLOYMENTS_PATH }, method = RequestMethod.GET, + produces = "application/json") + @ResponseBody + public String getDeploymentsByPage(HttpServletRequest request) + { + preLogAudit(request); + String json = getItemListForPageWrapper(request, + CloudifyDataItem.DEPLOYMENT,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); + } + + /** + * 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 * * @param request HttpServletRequest @@ -221,11 +816,12 @@ public class CloudifyController extends DashboardRestrictedBaseController { @ResponseBody public String getTenants(HttpServletRequest request) { preLogAudit(request); - String json = getItemListForPageWrapper(request, CloudifyDataItem.TENANT); + String json = getItemListForPageWrapper(request, CloudifyDataItem.TENANT, + request.getParameter("sortBy"), request.getParameter("searchBy")); postLogAudit(request); return json; } - + /** * Gets the specified blueprint metadata. * @@ -235,7 +831,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { * @throws Exception on serialization error * */ - @RequestMapping(value = { BLUEPRINTS_PATH + "/{id}" }, method = RequestMethod.GET, produces = "application/json") + @RequestMapping(value = { BLUEPRINTS_PATH + "/{id:.+}" }, method = RequestMethod.GET, produces = "application/json") @ResponseBody public String getBlueprintById(@PathVariable("id") String id, @RequestParam(value = "tenant", required = true) String tenant, HttpServletRequest request) @@ -269,161 +865,208 @@ public class CloudifyController extends DashboardRestrictedBaseController { } /** - * Gets the specified deployment. + * Deletes the specified blueprint. * - * @param id Deployment ID - * @param request HttpServletRequest - * @return Deployment for the specified ID; error on failure. + * @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 = { DEPLOYMENTS_PATH + "/{id}" }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getDeploymentById(@PathVariable("id") String id, - @RequestParam(value = "tenant", required = false) String tenant, HttpServletRequest request) - throws Exception { + @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 { preLogAudit(request); - ECTransportModel result = null; + String json = "{\"202\": \"OK\"}"; try { - if (tenant != null && tenant.length() > 0) { - result = cloudifyClient.getDeployment(id, tenant); - } else { - result = cloudifyClient.getDeployment(id); - } + 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", "Getting deployment " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Exception t) { + MDC.put("ErrorDescription", "Deleting blueprint " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); + 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", "Getting deployment " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); - result = new RestResponseError("getDeploymentById failed", t); + MDC.put("ErrorDescription", "Deleting blueprint " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); + json = objectMapper + .writeValueAsString(new RestResponseError("deleteBlueprint failed on ID " + id, t)); } finally { postLogAudit(request); } - return objectMapper.writeValueAsString(result); + return json; } + + /** + * + * 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; + } + + @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); + } + } + } + } + lock.writeLock().lock(); + getCacheManager().putObject("bp_deploy_map", result); + getCacheManager().putObject("owner_deploy_map", deplPerOwner); + lock.writeLock().unlock(); + } + /** - * Query status and tenant info for deployments + * Gets the specified deployment. + * + * @param id Deployment ID + * @param request HttpServletRequest + * @return Deployment for the specified ID; error on failure. + * @throws Exception On serialization failure * */ - @SuppressWarnings("unchecked") - @RequestMapping(value = { DEP_TENANT_STATUS }, method = RequestMethod.POST, produces = "application/json") + @RequestMapping(value = { DEPLOYMENTS_PATH + "/{id:.+}" }, method = RequestMethod.GET, produces = "application/json") @ResponseBody - public String getTenantStatusForService(HttpServletRequest request, @RequestBody String[] serviceList) + public String getDeploymentById(@PathVariable("id") String id, + @RequestParam(value = "tenant", required = false) String tenant, HttpServletRequest request) throws Exception { preLogAudit(request); - /* - * 1) Get all the tenant names 2) Get the deployment IDs per tenant for all the - * tenants, aggregate the deployments list 3) Get the input deployments list - * (screen input), filter the deployments list from step#2 4) For each item in - * the list from step#3, get the execution status info and generate the final - * response - */ - String outboundJson = ""; - CloudifyDeployedTenantList cfyTenantDeployMapList = null; - new HashMap<String, Object>(); - List<CloudifyDeployedTenant> tenantList = new ArrayList<CloudifyDeployedTenant>(); - List<CloudifyExecution> cfyExecList = new ArrayList<CloudifyExecution>(); + ECTransportModel result = null; try { - List<CloudifyTenant> cldfyTen = cloudifyClient.getTenants().items; - for (CloudifyTenant ct : (List<CloudifyTenant>) cldfyTen) { - cfyTenantDeployMapList = cloudifyClient.getTenantInfoFromDeploy(ct.name); - tenantList.addAll(((CloudifyDeployedTenantList) cfyTenantDeployMapList).items); - } - List<CloudifyDeployedTenant> currSrvcTenants = new ArrayList<CloudifyDeployedTenant>(); - - for (String serviceId : serviceList) { - for (CloudifyDeployedTenant deplTen : tenantList) { - if (serviceId.equals(deplTen.id)) { - currSrvcTenants.add(deplTen); - break; - } - } - } - // Get concise execution status for each of the tenant deployment items - boolean isHelmType = false; - boolean helmStatus = false; - for (CloudifyDeployedTenant deplItem : currSrvcTenants) { - CloudifyExecutionList execResults = - cloudifyClient.getExecutionsSummary(deplItem.id, deplItem.tenant_name); - isHelmType = false; - helmStatus = false; - CloudifyBlueprintList bpList = - cloudifyClient.getBlueprint(deplItem.id, deplItem.tenant_name); - Map<String, Object> bpPlan = bpList.items.get(0).plan; - Map<String, String> workflows = (Map<String, String>) bpPlan.get("workflows"); - Map<String, String> pluginInfo = - ((List<Map<String, String>>) bpPlan.get("deployment_plugins_to_install")) - .get(0); - if (pluginInfo.get("name").equals("helm-plugin")) { - isHelmType = true; - } - if (workflows.containsKey("status")) { - helmStatus = true; - } - for (CloudifyExecution cfyExec : execResults.items) { - if (cfyExec.workflow_id.equalsIgnoreCase("install")) { - cfyExec.is_helm = isHelmType; - cfyExec.helm_status = helmStatus; - cfyExecList.add(cfyExec); - } - } + if (tenant != null && tenant.length() > 0) { + result = cloudifyClient.getDeployment(id, tenant); + } else { + result = cloudifyClient.getDeployment(id); } - outboundJson = objectMapper.writeValueAsString(cfyExecList); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Cloudify Manager"); MDC.put("TargetServiceName", "Cloudify Manager"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting deployments failed!"); - logger.error(EELFLoggerDelegate.errorLogger, - "getTenantStatusForService caught exception"); - RestResponseError result = null; - result = new RestResponseError( - "getTenantStatusForService failed" + e.getResponseBodyAsString()); - try { - outboundJson = objectMapper.writeValueAsString(result); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } - } catch (Throwable t) { + MDC.put("ErrorDescription", "Getting deployment " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); + 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 deployments failed!"); - logger.error(EELFLoggerDelegate.errorLogger, - "getTenantStatusForService caught exception"); - RestResponseError result = null; - result = new RestResponseError("getTenantStatusForService failed"); - try { - outboundJson = objectMapper.writeValueAsString(result); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } + MDC.put("ErrorDescription", "Getting deployment " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception"); + result = new RestResponseError("getDeploymentById failed", t); } finally { postLogAudit(request); } - - return outboundJson; + return objectMapper.writeValueAsString(result); } - + /** * Gets and serves one page of executions: * <OL> @@ -448,7 +1091,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { @RequestMapping(value = { EXECUTIONS_PATH }, method = RequestMethod.GET, produces = "application/json") @ResponseBody public String getExecutionsByPage(HttpServletRequest request, - @RequestParam(value = "deployment_id", required = false) String deployment_id, + @RequestParam(value = "deployment_id", required = true) String deployment_id, @RequestParam(value = "status", required = false) String status, @RequestParam(value = "tenant", required = true) String tenant) throws Exception { preLogAudit(request); @@ -460,7 +1103,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { List<CloudifyExecution> itemList = new ArrayList<CloudifyExecution>(); List<String> depIds = new ArrayList<>(); if (deployment_id == null) { - CloudifyDeploymentList depList = cloudifyClient.getDeployments(); + CloudifyDeploymentList depList = cloudifyClient.getDeployments(tenant, 100, 0); for (CloudifyDeployment cd : depList.items) depIds.add(cd.id); } else { @@ -505,50 +1148,175 @@ public class CloudifyController extends DashboardRestrictedBaseController { return objectMapper.writeValueAsString(result); } - /** - * Gets the specified execution for one deployment. - * - * It's not clear why the deployment ID is needed. - * - * @param execution_id Execution ID (path variable) - * @param deployment_id Deployment ID (query parameter) - * @param request HttpServletRequest - * @return CloudifyExecutionList - * @throws Exception on serialization failure - */ - @RequestMapping(value = { EXECUTIONS_PATH + "/{id}" }, method = RequestMethod.GET, produces = "application/json") + @SuppressWarnings("unchecked") + @RequestMapping(value = { EXECUTIONS_PATH + "/tenant" }, method = RequestMethod.GET, produces = "application/json") @ResponseBody - public String getExecutionByIdAndDeploymentId(@PathVariable("id") String execution_id, - @RequestParam("deployment_id") String deployment_id, - @RequestParam(value = "tenant", required = false) String tenant, HttpServletRequest request) - throws Exception { + public String getExecutionsPerTenant(HttpServletRequest request, + @RequestParam(value = "tenant", required = true) String tenant, + @RequestParam(value = "status", required = false) String status) throws Exception { preLogAudit(request); ECTransportModel result = null; + ReadWriteLock lock = new ReentrantReadWriteLock(); + List<CloudifyTenant> cfyTenantList = null; + List<CloudifyTenant> myTenantsList = null; try { + List<CloudifyExecution> itemList = new ArrayList<CloudifyExecution>(); if (tenant == null) { - throw new Exception("required tenant input missing"); + // process all tenants that are relevant + lock.readLock().lock(); + cfyTenantList = (List<CloudifyTenant>)getCacheManager().getObject(TENANTS_PATH); + lock.readLock().unlock(); + if (cfyTenantList == null || cfyTenantList.isEmpty()) { + cfyTenantList = (List<CloudifyTenant>)cloudifyClient.getTenants().items; + } + myTenantsList = cfyTenantList; + + for (CloudifyTenant tenItem : myTenantsList) { + 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)) + exeIter.remove(); + } + } + itemList.addAll(exeList.items); + } + } else { + CloudifyExecutionList exeList = cloudifyClient.getExecutionsSummaryPerTenant(tenant); + itemList.addAll(exeList.items); + + // Filter down to specified status as needed + if (status != null && !status.isEmpty()) { + Iterator<CloudifyExecution> exeIter = itemList.iterator(); + while (exeIter.hasNext()) { + CloudifyExecution ce = exeIter.next(); + if (!status.equals(ce.status)) + exeIter.remove(); + } + } } - result = cloudifyClient.getExecutions(deployment_id, tenant); - } catch (HttpStatusCodeException e) { + //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) + 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 " + execution_id + " for deployment " + deployment_id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); + MDC.put("ErrorDescription", "Getting executions failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionsByPage caught exception"); + result = new RestResponseError("getExecutionsByPage failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + @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 { + preLogAudit(request); + ECTransportModel result = null; + try { + List<CloudifyExecution> itemList = new ArrayList<CloudifyExecution>(); + CloudifyExecution cfyExecObj = cloudifyClient.getExecutionIdSummary(id, tenant); + itemList.add(cfyExecObj); + 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) + 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 " + execution_id + " for deployment " + deployment_id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); - result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); + MDC.put("ErrorDescription", "Getting executions failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionsByPage caught exception"); + result = new RestResponseError("getExecutionsByPage failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); + } + + @SuppressWarnings("unchecked") + @RequestMapping(value = { EXECUTIONS_PATH + "/active"}, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getActiveExecutions(HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + ReadWriteLock lock = new ReentrantReadWriteLock(); + List<CloudifyTenant> cfyTenantList = null; + List<CloudifyTenant> myTenantsList = null; + String status = "started"; + try { + List<CloudifyExecution> itemList = new ArrayList<CloudifyExecution>(); + // process all tenants that are relevant + lock.readLock().lock(); + cfyTenantList = (List<CloudifyTenant>)getCacheManager().getObject(TENANTS_PATH); + lock.readLock().unlock(); + if (cfyTenantList == null || cfyTenantList.isEmpty()) { + cfyTenantList = (List<CloudifyTenant>)cloudifyClient.getTenants().items; + } + myTenantsList = cfyTenantList; + + for (CloudifyTenant tenItem : myTenantsList) { + CloudifyExecutionList exeList = null; + try { + exeList = + cloudifyClient.getExecutionsSummaryPerTenant(tenItem.name); + } catch (Exception e) { + continue; + } + // Filter down to specified status as needed + Iterator<CloudifyExecution> exeIter = exeList.items.iterator(); + while (exeIter.hasNext()) { + CloudifyExecution ce = exeIter.next(); + if (!status.equals(ce.status)) + exeIter.remove(); + } + 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) + 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); } finally { postLogAudit(request); } @@ -641,7 +1409,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { preLogAudit(request); ECTransportModel result = null; try { - if (!execution.workflow_id.equals("status") + 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 = ""; @@ -654,6 +1422,14 @@ public class CloudifyController extends DashboardRestrictedBaseController { inParms.put("node_instance_id", nodeInstId); 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); + } result = cloudifyClient.startExecution(execution); } catch (HttpStatusCodeException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -680,29 +1456,35 @@ public class CloudifyController extends DashboardRestrictedBaseController { } /** - * Processes request to create an execution based on a deployment. + * Cancels an execution. * - * @param request HttpServletRequest - * @param execution Execution model - * @return Information about the execution + * @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 + * @return Passes thru HTTP status code from remote endpoint; no body on success * @throws Exception on serialization failure */ - @RequestMapping(value = { UPDATE_DEPLOYMENT_PATH }, method = RequestMethod.POST, produces = "application/json") + @RequestMapping(value = { EXECUTIONS_PATH + "/{id}" }, method = RequestMethod.POST, produces = "application/json") @ResponseBody - public String updateDeployment(HttpServletRequest request, @RequestBody CloudifyDeploymentUpdateRequest execution) + 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; try { - result = cloudifyClient.updateDeployment(execution); + 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", "Updating deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateDeployment caught exception"); + MDC.put("ErrorDescription", "Cancelling execution " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -710,45 +1492,48 @@ public class CloudifyController extends DashboardRestrictedBaseController { MDC.put("TargetServiceName", "Cloudify Manager"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Updating Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateDeployment caught exception"); - result = new RestResponseError("updateDeployment failed", t); + MDC.put("ErrorDescription", "Cancelling execution " + id + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); + result = new RestResponseError("cancelExecution failed on ID " + id, t); } finally { postLogAudit(request); } - return objectMapper.writeValueAsString(result); + if (result == null) + return null; + else + return objectMapper.writeValueAsString(result); } /** - * Cancels an execution. + * Gets the specified node-instances details + * + * @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 * - * @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 - * @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") + @RequestMapping(value = {"node-instances-data"}, + method = RequestMethod.GET, produces = "application/json") @ResponseBody - public String cancelExecution(@RequestHeader HttpHeaders headers, @PathVariable("id") String id, - @RequestBody Map<String, String> parameters, HttpServletRequest request, HttpServletResponse response) - throws Exception { + public String getNodeInstanceDetails( + @RequestParam(value = "deployment", required = true) String deployment, + @RequestParam(value = "tenant", required = true) String tenant, + HttpServletRequest request) throws Exception { preLogAudit(request); ECTransportModel result = null; - List<String> tenant = null; try { - tenant = headers.get("tenant"); - result = cloudifyClient.cancelExecution(id, parameters, tenant.get(0)); + 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", "Cancelling execution " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); + MDC.put("ErrorDescription", "Getting node-instance with deploymentId " + deployment + + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getNodeInstance caught exception"); result = new RestResponseError(e.getResponseBodyAsString()); } catch (Exception t) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -756,16 +1541,62 @@ public class CloudifyController extends DashboardRestrictedBaseController { 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"); - result = new RestResponseError("cancelExecution failed on ID " + id, t); + MDC.put("ErrorDescription", "Getting node-instance with deploymentId " + deployment + + " failed!"); + logger.error(EELFLoggerDelegate.errorLogger, "getNodeInstance caught exception"); + result = new RestResponseError("getNodeInstance failed", t); } finally { postLogAudit(request); } - if (result == null) - return null; - else - return objectMapper.writeValueAsString(result); + return objectMapper.writeValueAsString(result); + } + + /** + * Gets the specified node-instances for viewing. + * + * @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 + public String getNodeInstances(@PathVariable("deploymentId") String deploymentId, + @RequestParam(value = "tenant", required = true) String tenant, + HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + 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"); + 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"); + result = new RestResponseError("getNodeInstanceId failed", t); + } finally { + postLogAudit(request); + } + return objectMapper.writeValueAsString(result); } /** @@ -779,7 +1610,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { * */ @RequestMapping(value = { NODE_INSTANCES_PATH - + "/{deploymentId}/{nodeId}" }, method = RequestMethod.GET, produces = "application/yaml") + + "/{deploymentId:.+}/{nodeId}" }, method = RequestMethod.GET, produces = "application/yaml") @ResponseBody public String getNodeInstanceId(@PathVariable("deploymentId") String deploymentId, @RequestParam(value = "tenant", required = true) String tenant, @PathVariable("nodeId") String nodeId, @@ -818,7 +1649,7 @@ public class CloudifyController extends DashboardRestrictedBaseController { } @RequestMapping(value = { - DEPLOYMENTS_PATH + "/{deploymentId}/revisions" }, method = RequestMethod.GET, produces = "application/json") + DEPLOYMENTS_PATH + "/{deploymentId:.+}/revisions" }, method = RequestMethod.GET, produces = "application/json") @ResponseBody public String getDeploymentRevisions(@PathVariable("deploymentId") String deploymentId, @RequestParam(value = "tenant") String tenant, HttpServletRequest request) throws Exception { @@ -853,6 +1684,51 @@ public class CloudifyController extends DashboardRestrictedBaseController { return objectMapper.writeValueAsString(result); } + /** + * Gets the cloudify plugins list + * + * + * @param request + * HttpServletRequest + * @return list of CloudifyPlugin + * @throws Exception + * on serialization failure + */ + @SuppressWarnings("unchecked") + @RequestMapping(value = { PLUGINS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getPlugins( + HttpServletRequest request) throws Exception { + preLogAudit(request); + ECTransportModel result = null; + try { + List<CloudifyPlugin> resultsArr = cloudifyClient.getPlugins().items; + return objectMapper.writeValueAsString(resultsArr); + } 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); + } + } + public void preLogAudit(HttpServletRequest request) { begin = new Date(); MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CommonApiController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CommonApiController.java deleted file mode 100644 index bd53145..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/CommonApiController.java +++ /dev/null @@ -1,1182 +0,0 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ - -package org.onap.ccsdk.dashboard.controller; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.onap.ccsdk.dashboard.domain.EcdComponent; -import org.onap.ccsdk.dashboard.exceptions.BadRequestException; -import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; -import org.onap.ccsdk.dashboard.exceptions.DownstreamException; -import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; -import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; -import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; -import org.onap.ccsdk.dashboard.model.CloudifyExecution; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; -import org.onap.ccsdk.dashboard.model.CloudifyTenant; -import org.onap.ccsdk.dashboard.model.ECTransportModel; -import org.onap.ccsdk.dashboard.model.RestResponseError; -import org.onap.ccsdk.dashboard.model.RestResponsePage; -import org.onap.ccsdk.dashboard.model.RestResponseSuccess; -import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentInput; -import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; -import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResource; -import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResourceLinks; -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.BlueprintResponse; -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.ServiceTypeServiceMap; -import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeUploadRequest; -import org.onap.ccsdk.dashboard.rest.CloudifyClient; -import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; -import org.onap.ccsdk.dashboard.rest.InventoryClient; -import org.onap.ccsdk.dashboard.service.ControllerEndpointService; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpHeaders; -import org.springframework.web.bind.annotation.PathVariable; -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; -import com.fasterxml.jackson.core.type.TypeReference; - -@RestController -@RequestMapping("/nb-api") -public class CommonApiController extends DashboardRestrictedBaseController { - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CommonApiController.class); - - private static final String COMPONENTS_PATH = "components"; - private static final String DEPLOYMENTS_PATH = "deployments"; - private static final String SERVICE_TYPES_PATH = "blueprints"; - private static final String EXECUTIONS_PATH = "executions"; - private static final String DEP_TENANT_STATUS = "deployment-status"; - private static final String TENANTS_PATH = "tenants"; - - @Autowired - private ControllerEndpointService controllerEndpointService; - - @Autowired - InventoryClient inventoryClient; - - @Autowired - DeploymentHandlerClient deploymentHandlerClient; - - @Autowired - CloudifyClient cloudifyClient; - - /** - * Enum for selecting an item type. - */ - public enum InventoryDataItem { - SERVICES, SERVICE_TYPES, SERVICES_GROUPBY; - } - - private static Date begin, end; - - @RequestMapping(value = "/api-docs", method = RequestMethod.GET, produces = "application/json") - public Resource apiDocs() { - return new ClassPathResource("swagger.json"); - } - - @RequestMapping(value = { COMPONENTS_PATH }, method = RequestMethod.POST, produces = "application/json") - public String insertComponent(HttpServletRequest request, @RequestBody EcdComponent newComponent) throws Exception { - String outboundJson = null; - controllerEndpointService.insertComponent(newComponent); - RestResponseSuccess success = new RestResponseSuccess( - "Inserted new component with name " + newComponent.getCname()); - outboundJson = objectMapper.writeValueAsString(success); - return outboundJson; - } - - @RequestMapping(value = { COMPONENTS_PATH }, method = RequestMethod.GET, produces = "application/json") - public String getComponents(HttpServletRequest request) throws Exception { - List<EcdComponent> result = controllerEndpointService.getComponents(); - return objectMapper.writeValueAsString(result); - - } - - /** - * gets the tenants list - * - * @param request HttpServletRequest - * @return List of CloudifyDeployment objects - */ - @SuppressWarnings("rawtypes") - @RequestMapping(value = { TENANTS_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getTenants(HttpServletRequest request) throws Exception { - preLogAudit(request); - List 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) - itemList = getPageOfList(pageNum, pageSize, itemList); - RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); - String outboundJson = objectMapper.writeValueAsString(model); - return outboundJson; - } - - /** - * Query status and tenant info for deployments - * - */ - @RequestMapping(value = { DEP_TENANT_STATUS }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String getTenantStatusForService(HttpServletRequest request, @RequestBody String[] serviceList) - throws Exception { - preLogAudit(request); - /* - * 1) Get all the tenant names 2) Get the deployment IDs per tenant for all the - * tenants, aggregate the deployments list 3) Get the input deployments list - * (screen input), filter the deployments list from step#2 4) For each item in - * the list from step#3, get the execution status info and generate the final - * response - */ - String outboundJson = ""; - ECTransportModel result = null; - List<CloudifyDeployedTenant> tenantList = new ArrayList<CloudifyDeployedTenant>(); - List<CloudifyExecution> cfyExecList = new ArrayList<CloudifyExecution>(); - try { - List<CloudifyTenant> cldfyTen = cloudifyClient.getTenants().items; - for (CloudifyTenant ct : (List<CloudifyTenant>) cldfyTen) { - result = cloudifyClient.getTenantInfoFromDeploy(ct.name); - tenantList.addAll(((CloudifyDeployedTenantList) result).items); - } - result = null; - List<CloudifyDeployedTenant> currSrvcTenants = new ArrayList<CloudifyDeployedTenant>(); - - for (String serviceId : serviceList) { - for (CloudifyDeployedTenant deplTen : tenantList) { - if (serviceId.equals(deplTen.id)) { - currSrvcTenants.add(deplTen); - break; - } - } - } - // Get concise execution status for each of the tenant deployment items - for (CloudifyDeployedTenant deplItem : currSrvcTenants) { - CloudifyExecutionList execResults = - cloudifyClient.getExecutionsSummary(deplItem.id, deplItem.tenant_name); - for (CloudifyExecution cfyExec : execResults.items) { - if (cfyExec.workflow_id.equalsIgnoreCase("install")) { - cfyExecList.add(cfyExec); - } - } - } - outboundJson = objectMapper.writeValueAsString(cfyExecList); - } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting deployments failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getTenantStatusForService caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - try { - outboundJson = objectMapper.writeValueAsString(result); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } - } catch (Exception t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting deployments failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getTenantStatusForService caught exception"); - result = new RestResponseError("getTenantStatusForService failed", t); - try { - outboundJson = objectMapper.writeValueAsString(result); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } - } finally { - postLogAudit(request); - } - - return outboundJson; - } - - @RequestMapping(value = { SERVICE_TYPES_PATH }, method = RequestMethod.POST, produces = "application/json") - public String createBlueprint(HttpServletRequest request, @RequestBody ServiceTypeUploadRequest serviceTypeUplReq) - throws Exception { - String json = null; - try { - Blueprint.parse(serviceTypeUplReq.getBlueprintTemplate()); - // InventoryClient inventoryClient = getInventoryClient(); - Collection<String> serviceIds = new ArrayList<String>(); - Collection<String> vnfTypes = new ArrayList<String>(); - Collection<String> serviceLocations = new ArrayList<String>(); - Optional<String> asdcServiceId = null; - Optional<String> asdcResourceId = null; - Optional<String> asdcServiceURL = null; - - ServiceTypeRequest invSrvcTypeReq = new ServiceTypeRequest(serviceTypeUplReq.owner, - serviceTypeUplReq.typeName, serviceTypeUplReq.typeVersion, serviceTypeUplReq.blueprintTemplate, - serviceTypeUplReq.application, serviceTypeUplReq.component, serviceIds, vnfTypes, serviceLocations, - asdcServiceId, asdcResourceId, asdcServiceURL); - ServiceType response = inventoryClient.addServiceType(invSrvcTypeReq); - // RestResponseSuccess success = new RestResponseSuccess("Uploaded new blueprint - // with name " + serviceTypeUplReq.typeName); - json = objectMapper.writeValueAsString(response); - } catch (BlueprintParseException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Updating service type failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("Invalid blueprint format.", e)); - } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Updating service type failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString())); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Updating service type failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("updateServiceTypeBlueprint failed", t)); - } finally { - postLogAudit(request); - } - return json; - } - - @RequestMapping(value = { SERVICE_TYPES_PATH }, method = RequestMethod.GET, produces = "application/json") - public String getBlueprintsByPage(HttpServletRequest request) { - preLogAudit(request); - String json = null; - json = getItemListForPageWrapper(request, InventoryDataItem.SERVICE_TYPES, request.getParameter("name"), - request.getParameter("_include")); - postLogAudit(request); - return json; - } - - @RequestMapping(value = { - SERVICE_TYPES_PATH + "/findByName" }, method = RequestMethod.GET, produces = "application/json") - public String queryBlueprintFilter(HttpServletRequest request) { - preLogAudit(request); - String json = null; - json = getItemListForPageWrapper(request, InventoryDataItem.SERVICE_TYPES, request.getParameter("name"), - request.getParameter("_include")); - postLogAudit(request); - return json; - } - - @RequestMapping(value = { - DEPLOYMENTS_PATH + "/{deploymentId}" }, method = RequestMethod.GET, produces = "application/json") - public String getDeploymentsByPage(@PathVariable("deploymentId") String deploymentId, HttpServletRequest request) { - preLogAudit(request); - String json = null; - json = getItemListForPageWrapper(request, InventoryDataItem.SERVICES, deploymentId, - request.getParameter("_include")); - postLogAudit(request); - return json; - } - - @RequestMapping(value = { DEPLOYMENTS_PATH }, method = RequestMethod.GET, produces = "application/json") - public String getAllDeploymentsByPage(HttpServletRequest request) { - preLogAudit(request); - String json = null; - json = getItemListForPageWrapper(request, InventoryDataItem.SERVICES, request.getParameter("deploymentId"), - request.getParameter("_include")); - postLogAudit(request); - return json; - } - - /** - * Gets one page of the specified items. This method traps exceptions and - * constructs an appropriate JSON block to report errors. - * - * @param request Inbound request - * @param option Item type to get - * @return JSON with one page of objects; or an error. - */ - protected String getItemListForPageWrapper(HttpServletRequest request, InventoryDataItem option, String searchBy, - String filters) { - preLogAudit(request); - - String outboundJson = null; - try { - int pageNum = getRequestPageNumber(request); - int pageSize = getRequestPageSize(request); - outboundJson = getItemListForPage(option, pageNum, pageSize, searchBy, filters); - } catch (Exception ex) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "ECOMP Inventory"); - MDC.put("TargetServiceName", "ECOMP Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "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); - try { - outboundJson = objectMapper.writeValueAsString(result); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } - } finally { - postLogAudit(request); - } - return outboundJson; - } - - /** - * Gets one page of objects and supporting information via the REST client. On - * success, returns a PaginatedRestResponse object as String. - * - * @param option Specifies which item list type to get - * @param pageNum Page number of results - * @param pageSize Number of items per browser page - * @return JSON block as String, see above. - * @throws Exception On any error; e.g., Network failure. - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - private String getItemListForPage(InventoryDataItem option, int pageNum, int pageSize, String searchBy, - String filters) throws Exception { - String outboundJson = ""; - List itemList = null; - - switch (option) { - case SERVICES: - itemList = inventoryClient.getServices().collect(Collectors.toList()); - if (searchBy != null) { - itemList = (List) itemList.stream() - .filter(s -> ((Service) s).contains(searchBy)).collect(Collectors.toList()); - } - // Get the tenant names for all the deployments from Cloudify/API handler - ECTransportModel result = null; - List<CloudifyDeployedTenant> tenantList = new ArrayList<CloudifyDeployedTenant>(); - try { - List<CloudifyTenant> cldfyTen = cloudifyClient.getTenants().items; - for (CloudifyTenant ct : (List<CloudifyTenant>) cldfyTen) { - result = cloudifyClient.getTenantInfoFromDeploy(ct.name); - tenantList.addAll(((CloudifyDeployedTenantList) result).items); - } - } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting deployments failed!"); - logger.error(EELFLoggerDelegate.errorLogger, - "getTenantInfoFromDeploy caught exception"); - //result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting deployments failed!"); - logger.error(EELFLoggerDelegate.errorLogger, - "getDeploymentById caught exception"); - //result = new RestResponseError("getTenantInfoFromDeploy failed", t); - } finally { - - } - - for (Service depl : (List<Service>) itemList) { - for (CloudifyDeployedTenant deplTen : tenantList) { - if (depl.getDeploymentRef().equals(deplTen.id)) { - depl.setTenant(deplTen.tenant_name); - break; - } - } - } - break; - case SERVICE_TYPES: - ServiceTypeQueryParams serviceQueryParams = null; - serviceQueryParams = new ServiceTypeQueryParams.Builder().onlyLatest(false).build(); - - itemList = inventoryClient.getServiceTypes(serviceQueryParams).collect(Collectors.toList()); - List<BlueprintResponse> filterList = new ArrayList<BlueprintResponse>(); - - if (searchBy != null && searchBy.length() > 1) { - itemList = (List) itemList.stream().filter(s -> ((ServiceType) s).contains(searchBy)) - .collect(Collectors.toList()); - } - if (filters != null && filters.length() > 0) { - String filterArr[] = filters.split(","); - for (ServiceType bp : (List<ServiceType>) itemList) { - BlueprintResponse bpOut = new BlueprintResponse(); - for (String fltr : filterArr) { - switch (fltr) { - case "typeName": - bpOut.setTypeName(bp.getTypeName()); - break; - case "typeId": - if (bp.getTypeId().isPresent()) { - bpOut.setTypeId(bp.getTypeId().get()); - } - break; - case "typeVersion": - bpOut.setTypeVersion(bp.getTypeVersion()); - break; - default: - break; - } - } - filterList.add(bpOut); - } - if (filterList.size() > 0) { - itemList.clear(); - itemList.addAll(filterList); - } - } - break; - default: - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting page of items failed!"); - throw new Exception("getItemListForPage failed: unimplemented case: " + option.name()); - } - // Shrink if needed - final int totalItems = itemList.size(); - final int pageCount = (int) Math.ceil((double) totalItems / pageSize); - if (totalItems > pageSize) - itemList = getPageOfList(pageNum, pageSize, itemList); - - RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); - outboundJson = objectMapper.writeValueAsString(model); - - return outboundJson; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private String getBlueprintTypeId(String searchBy, Optional<Integer> version, String typeId) throws Exception { - - // InventoryClient inventoryClient = getInventoryClient(); - ServiceTypeQueryParams serviceQueryParams = null; - - if (version.isPresent()) { - serviceQueryParams = new ServiceTypeQueryParams.Builder().typeName(searchBy).onlyLatest(false).build(); - } else { - serviceQueryParams = new ServiceTypeQueryParams.Builder().typeName(searchBy).build(); - } - - List itemList = inventoryClient.getServiceTypes(serviceQueryParams).collect(Collectors.toList()); - - if (version.isPresent()) { - itemList = (List) itemList.stream().filter(s -> ((ServiceType) s).contains(version.get().toString())) - .collect(Collectors.toList()); - } - Optional<String> bpId = Optional.of(""); - if (typeId != null && typeId.equals("typeId")) { - ServiceType item = (ServiceType) ((List) itemList).get(0); - bpId = item.getTypeId(); - } - return bpId.get(); - } - - /** - * Query the installed helm package revisions from cloudify - * - * @param deploymentId - * @param tenant - * @param request - * @return - * @throws Exception - */ - @RequestMapping(value = { - DEPLOYMENTS_PATH + "/{deploymentId}/revisions" }, method = RequestMethod.GET, produces = "application/json") - public String getDeploymentRevisions(@PathVariable("deploymentId") String deploymentId, - @RequestParam(value = "tenant") String tenant, HttpServletRequest request) throws Exception { - preLogAudit(request); - ECTransportModel result = null; - try { - if (tenant == null) { - throw new Exception("tenant name is missing"); - } - result = cloudifyClient.getNodeInstanceVersion(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 executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); - result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); - } finally { - postLogAudit(request); - } - return objectMapper.writeValueAsString(result); - } - - /** - * Query inputs used to create a deployment - * - * @param deploymentId - * @param tenant - * @param request - * @return - * @throws Exception - */ - @RequestMapping(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 { - preLogAudit(request); - ECTransportModel result = null; - try { - if (tenant == null) { - throw new Exception("tenant name is missing"); - } - result = cloudifyClient.getDeploymentInputs(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 executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); - result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); - } finally { - postLogAudit(request); - } - return objectMapper.writeValueAsString(result); - } - - /** - * Create an upgrade/rollback workflow execution for a deployment. - * - * @param request HttpServletRequest - * @param execution Execution model - * @return Information about the execution - * @throws Exception on serialization failure - */ - @RequestMapping(value = { - DEPLOYMENTS_PATH + "/{deploymentId}" }, method = RequestMethod.PUT, produces = "application/json") - public String modifyDeployment(@PathVariable("deploymentId") String deploymentId, HttpServletRequest request, - InputStream upgParams) throws Exception { - preLogAudit(request); - ECTransportModel result = null; - try { - String nodeInstId = ""; - Map<String, Object> parameters = objectMapper.readValue(upgParams, - new TypeReference<Map<String, Object>>() { - }); - String tenant = (String) parameters.get("tenant"); - String workflow = (String) parameters.get("workflow"); - parameters.remove("tenant"); - parameters.remove("workflow"); - // get the node instance ID for the deployment - CloudifyNodeInstanceIdList nodeInstList = - cloudifyClient.getNodeInstanceId(deploymentId, tenant); - if (nodeInstList != null) { - nodeInstId = nodeInstList.items.get(0).id; - } - parameters.put("node_instance_id", nodeInstId); - CloudifyExecutionRequest execution = new CloudifyExecutionRequest(deploymentId, - workflow, false, false, tenant, parameters); - result = 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", "Updating deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateDeployment 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", "Updating Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "updateDeployment caught exception"); - result = new RestResponseError("updateDeployment failed", t); - } finally { - postLogAudit(request); - } - return objectMapper.writeValueAsString(result); - } - - @RequestMapping(value = { - SERVICE_TYPES_PATH + "/{typeid}" + "/services" }, 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>(); - // InventoryClient inventoryClient = getInventoryClient(); - ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); - ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams); - ServiceTypeServiceMap srvcMap = new ServiceTypeServiceMap(typeId, srvcRefs); - result.add(srvcMap); - return objectMapper.writeValueAsString(result); - } - - @RequestMapping(value = { DEPLOYMENTS_PATH }, method = RequestMethod.POST, produces = "application/json") - public String createDeployment(HttpServletRequest request, @RequestBody DeploymentInput deploymentRequestObject) - throws Exception { - preLogAudit(request); - String json = null; - StringBuffer status = new StringBuffer(); - // Optional<String> bpId = Optional.empty(); - Optional<Integer> bpVersion = null; - String srvcTypeId = null; - String bpName = deploymentRequestObject.getBlueprintName(); - String cName = deploymentRequestObject.getComponent(); - String tag = deploymentRequestObject.getTag(); - String depName = cName + "_" + tag; - - if (deploymentRequestObject.getBlueprintVersion().isPresent()) { - bpVersion = deploymentRequestObject.getBlueprintVersion(); - } - if (deploymentRequestObject.getBlueprintId().isPresent()) { - srvcTypeId = deploymentRequestObject.getBlueprintId().get(); - // srvcTypeId = bpId.get(); - } - if (srvcTypeId == null) { - // get the serviceTypeId from inventory using the blueprint name - try { - srvcTypeId = getBlueprintTypeId(bpName, bpVersion, "typeId"); - } catch (Exception ex) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "ECOMP Inventory"); - MDC.put("TargetServiceName", "ECOMP Inventory"); - 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); - } - } - try { - DeploymentResponse resp = - deploymentHandlerClient.putDeployment(depName, deploymentRequestObject.getTenant(), - new DeploymentRequest(srvcTypeId, deploymentRequestObject.getInputs())); - DeploymentResponseLinks deplLinks = resp.getLinks(); - String deplStatus = deplLinks.getStatus(); - if (!deplStatus.contains("cfy_tenant")) { - deplStatus = deplStatus + "?cfy_tenant_name=" + deploymentRequestObject.getTenant(); - } - String self = request.getRequestURL().append("/").append(depName).toString(); - status.append(self).append("/executions?tenant=").append(deploymentRequestObject.getTenant()); - DeploymentResource deplRsrc = new DeploymentResource(depName, - new DeploymentResourceLinks(self, deplStatus, 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", "Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(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!"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment 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", "Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment 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", "Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (Throwable 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)); - } finally { - postLogAudit(request); - } - return json; - } - - @RequestMapping(value = { - DEPLOYMENTS_PATH + "/{deploymentId}/update" }, method = RequestMethod.PUT, produces = "application/json") - public String updateDeployment(@PathVariable("deploymentId") String deploymentId, HttpServletRequest request, - @RequestBody DeploymentInput deploymentRequestObject) throws Exception { - preLogAudit(request); - String json = null; - String srvcTypeId = ""; - Optional<Integer> bpVersion = null; - String bpName = deploymentRequestObject.getBlueprintName(); - if (deploymentRequestObject.getBlueprintVersion().isPresent()) { - bpVersion = deploymentRequestObject.getBlueprintVersion(); - } - // get the serviceTypeId from inventory using the blueprint name - try { - srvcTypeId = getBlueprintTypeId(bpName, bpVersion, "typeId"); - } catch (Exception ex) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "ECOMP Inventory"); - MDC.put("TargetServiceName", "ECOMP Inventory"); - 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); - } - try { - json = objectMapper.writeValueAsString(deploymentHandlerClient.updateDeployment( - deploymentId, deploymentRequestObject.getTenant(), - new DeploymentRequest(srvcTypeId, deploymentRequestObject.getInputs()))); - } catch (BadRequestException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Deployment Handler"); - 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(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!"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment 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", "Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment 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", "Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (JsonProcessingException jpe) { - // Should never, ever happen - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Deployment Handler"); - MDC.put("TargetServiceName", "Deployment Handler"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deployment failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "putDeployment caught exception"); - json = "{ \"error\" : \"" + jpe.toString() + "\"}"; - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Deployment Handler"); - 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)); - } finally { - postLogAudit(request); - } - return json; - } - - /** - * Gets the executions for one deployment. - * - * - * @param deployment_id Deployment ID (query parameter) - * @param request HttpServletRequest - * @return CloudifyExecutionList - * @throws Exception on serialization failure - */ - @RequestMapping(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 { - preLogAudit(request); - ECTransportModel result = null; - 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", "Cloudify Manager"); - 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"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Cloudify Manager"); - MDC.put("TargetServiceName", "Cloudify Manager"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting executions for deployment " + deploymentId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "getExecutionByIdAndDeploymentId caught exception"); - result = new RestResponseError("getExecutionByIdAndDeploymentId failed", t); - } finally { - postLogAudit(request); - } - return objectMapper.writeValueAsString(result); - } - - /** - * Deletes the specified blueprint. - * - * @param id Blueprint ID - * @param request HttpServletRequest - * @param response HttpServletResponse - * @return status code on success; error on failure. - * @throws Exception On serialization failure - */ - @RequestMapping(value = { - SERVICE_TYPES_PATH + "/{typeid}" }, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String deleteBlueprint(@PathVariable("typeid") String typeId, HttpServletRequest request, - HttpServletResponse response) throws Exception { - preLogAudit(request); - String json = "{\"202\": \"OK\"}"; - try { - // InventoryClient inventoryClient = getInventoryClient(); - 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"); - } - inventoryClient.deleteServiceType(typeId); - } catch (ServiceTypeNotFoundException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting service type " + typeId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (ServiceTypeAlreadyDeactivatedException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting service type " + typeId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (Throwable t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting service type " + typeId + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteBlueprint caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError("deleteBlueprint failed", t)); - } finally { - postLogAudit(request); - } - return json; - } - - /** - * Un-deploy an application or service - * - * @param deploymentId - * @param request - * @param tenant - * @param response - * @return - * @throws Exception - */ - @RequestMapping( - value = {DEPLOYMENTS_PATH + "/{deploymentId}"}, - method = RequestMethod.DELETE, - produces = "application/json") - public String deleteDeployment(@PathVariable("deploymentId") String deploymentId, - HttpServletRequest request, @RequestParam(value = "tenant", required = true) String tenant, - HttpServletResponse response) throws Exception { - preLogAudit(request); - String json = null; - StringBuffer status = new StringBuffer(); - try { - if (tenant == null) { - throw new Exception("tenant name is missing"); - } - deploymentHandlerClient.deleteDeployment(deploymentId, tenant); - String self = request.getRequestURL().toString().split("\\?")[0]; - status.append(self).append("/executions?tenant=").append(tenant); - DeploymentResource deplRsrc = new DeploymentResource(deploymentId, - 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"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (Throwable 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)); - } finally { - postLogAudit(request); - } - return json; - } - - /** - * Cancels an execution. - * - * @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 - * @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 - 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; - 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"); - 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", "Cancelling execution " + id + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "cancelExecution caught exception"); - result = new RestResponseError("cancelExecution failed on ID " + id, t); - } finally { - postLogAudit(request); - } - if (result == null) - return null; - else - return objectMapper.writeValueAsString(result); - } - - private void preLogAudit(HttpServletRequest request) { - 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"); - } - - private void postLogAudit(HttpServletRequest request) { - end = new Date(); - MDC.put("AlertSeverity", "0"); - MDC.put("TargetEntity", "Deployment Handler"); - MDC.put("TargetServiceName", "Deployment Handler"); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(end)); - MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, logDateFormat.format(end)); - //MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime()))); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI()); - } -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ConsulController.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ConsulController.java index 28f7520..25ab3fd 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 @@ -29,15 +29,15 @@ import java.util.List; import javax.servlet.http.HttpServletRequest; -import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; -import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration.EndpointCheck; -import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; -import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; import org.onap.ccsdk.dashboard.model.ECTransportModel; import org.onap.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; import org.onap.ccsdk.dashboard.rest.ConsulClient; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -333,105 +333,6 @@ public class ConsulController extends DashboardRestrictedBaseController { return json; } - /** - * Processes request to register a service for health checks. - * - * @param request HttpServletRequest - * @param registration Consul service registration - * @return URI of the newly registered resource - * @throws Exception on serialization error - */ - @RequestMapping(value = { "/register" }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String registerService(HttpServletRequest request, @RequestBody ConsulHealthServiceRegistration registration) - throws Exception { - preLogAudit(request); - ECTransportModel result = null; - try { - if (registration.services == null) { - throw new Exception("services[] tag is mandatory"); - } - - List<EndpointCheck> checks = registration.services.get(0).checks; - String service_name = registration.services.get(0).name; - String service_port = registration.services.get(0).port; - String service_address = registration.services.get(0).address; - - if (checks == null || service_port.isEmpty() || service_address.isEmpty() || service_name.isEmpty()) { - throw new Exception("fields : [checks[], port, address, name] are mandatory"); - } - for (EndpointCheck check : checks) { - if (check.endpoint.isEmpty() || check.interval.isEmpty()) { - throw new Exception("Required fields : [endpoint, interval] in checks"); - } - } - result = new RestResponseSuccess(consulClient.registerService(registration)); - } catch (HttpStatusCodeException e) { - 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", "Registering service failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "registerService caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } 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", "Registering service failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "registerService caught exception"); - result = new RestResponseError("registerService failed", t); - } finally { - postLogAudit(request); - } - return objectMapper.writeValueAsString(result); - } - - /** - * Processes request to deregister a service for health checks. - * - * @param request HttpServletRequest - * @param serviceName Consul service name to deregister - * @return Success or error indicator - * @throws Exception on serialization error - */ - @RequestMapping(value = { - "/deregister" + "/{serviceName}" }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String deregisterService(HttpServletRequest request, @PathVariable String serviceName) throws Exception { - preLogAudit(request); - ECTransportModel result = null; - try { - int code = consulClient.deregisterService(serviceName); - result = - new RestResponseSuccess("Deregistration yielded code " + Integer.toString(code)); - } catch (HttpStatusCodeException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "Consul"); - MDC.put("TargetServiceName", "Consul"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "De-registering service " + serviceName + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deregisterService caught exception"); - result = new RestResponseError(e.getResponseBodyAsString()); - } catch (Throwable 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", "De-registering service " + serviceName + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deregisterService caught exception"); - result = new RestResponseError("deregisterService failed", t); - } finally { - postLogAudit(request); - } - return objectMapper.writeValueAsString(result); - } - public void preLogAudit(HttpServletRequest request) { begin = new Date(); MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); 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 cccd8f6..263c3d0 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 @@ -21,28 +21,16 @@ *******************************************************************************/ package org.onap.ccsdk.dashboard.controller; -import java.util.ArrayList; import java.util.Date; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Collectors; - import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import org.onap.ccsdk.dashboard.domain.EcdComponent; -import org.onap.ccsdk.dashboard.model.EcdAppComponent; -import org.onap.ccsdk.dashboard.model.RestResponseError; -import org.onap.ccsdk.dashboard.model.RestResponseSuccess; -import org.onap.ccsdk.dashboard.service.ControllerEndpointService; import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; import org.springframework.stereotype.Controller; -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.ResponseBody; @@ -61,19 +49,14 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardHomeController.class); - @Autowired - private ControllerEndpointService controllerEndpointService; - /** * For general use in these methods */ private final ObjectMapper mapper; private static Date begin, end; - private static final String COMPONENTS_PATH = "components"; - private static final String USER_APPS_PATH = "user-apps"; private static final String APP_LABEL = "app-label"; - + /** * Never forget that Spring autowires fields AFTER the constructor is called. */ @@ -93,79 +76,10 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { return new ModelAndView("ecd_home_tdkey"); } - /** - * Gets the available blueprint component names - * - * @param request HttpServletRequest - * @return List of component name strings, or an error on failure - */ - @RequestMapping( - value = {COMPONENTS_PATH}, - method = RequestMethod.GET, - produces = "application/json") + @RequestMapping(value = "/api-docs", method = RequestMethod.GET, produces = "application/json") @ResponseBody - public String getComponents(HttpServletRequest request) { - preLogAudit(request); - String outboundJson = ""; - try { - HttpSession session = request.getSession(true); - @SuppressWarnings("unchecked") - Set<String> userApps = (Set<String>) session.getAttribute("authComponents"); - if (userApps == null) { - userApps = new TreeSet<String>(); - } - List<EcdComponent> filterList = new ArrayList<EcdComponent>(); - List<EcdAppComponent> ecdApps = new ArrayList<EcdAppComponent>(); - - List<EcdComponent> dbResult = controllerEndpointService.getComponents(); - - List dcaeCompList = (List) dbResult.stream() - .filter(s -> ((EcdComponent) s).contains("dcae")).collect(Collectors.toList()); - - if (!userApps.isEmpty()) { // non-admin role level - for (String userRole : userApps) { - if (userRole.equalsIgnoreCase("dcae")) { - if (dcaeCompList != null && !dcaeCompList.isEmpty()) { - EcdAppComponent dcaeAppComponent = - new EcdAppComponent("DCAE", dcaeCompList); - ecdApps.add(dcaeAppComponent); - } - } else { - List tmpItemList = (List) dbResult.stream() - .filter(s -> ((EcdComponent) s).contains(userRole)) - .collect(Collectors.toList()); - if (tmpItemList != null) { - logger.debug(">>>> adding filtered items"); - filterList.addAll(tmpItemList); - } - } - } - if (!filterList.isEmpty()) { - EcdAppComponent ecdAppComponent = new EcdAppComponent("ECOMP", filterList); - ecdApps.add(ecdAppComponent); - } - } else { - // lookup "dcae" in the db component list - if (dcaeCompList != null && !dcaeCompList.isEmpty()) { - EcdAppComponent dcaeAppComponent = new EcdAppComponent("DCAE", dcaeCompList); - ecdApps.add(dcaeAppComponent); - } - } - outboundJson = mapper.writeValueAsString(ecdApps); - } catch (Exception ex) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DashboardHomeController"); - MDC.put("TargetServiceName", "DashboardHomeController"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Get components failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "Failed to get components list"); - RestResponseError response = new RestResponseError("Failed to get components list", ex); - outboundJson = response.toJson(); - } finally { - postLogAudit(request); - } - return outboundJson; + public Resource apiDocs() { + return new ClassPathResource("swagger.json"); } /** @@ -178,70 +92,7 @@ public class DashboardHomeController extends DashboardRestrictedBaseController { return mapper.writeValueAsString( DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_IN_ENV, "NA")); } - - /** - * Gets the application name(s) for the authenticated user - * - * @param request HttpServletRequest - * @return List of component name strings, or an error on failure - */ - @SuppressWarnings("unchecked") - @RequestMapping( - value = {USER_APPS_PATH}, - method = RequestMethod.GET, - produces = "application/json") - @ResponseBody - public String getUserApps(HttpServletRequest request) { - preLogAudit(request); - String outboundJson = ""; - try { - HttpSession session = request.getSession(true); - Set<String> userApps = (Set<String>) session.getAttribute("authComponents"); - if (userApps == null) { - userApps = new TreeSet<String>(); - } - outboundJson = mapper.writeValueAsString(userApps); - } catch (Exception ex) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DashboardHomeController"); - MDC.put("TargetServiceName", "DashboardHomeController"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Get User Apps failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "Failed to get apps list"); - RestResponseError response = new RestResponseError("Failed to get apps list", ex); - outboundJson = response.toJson(); - } finally { - postLogAudit(request); - } - return outboundJson; - } - - /** - * Sets the controller endpoint selection for the user. - * - * @param request HttpServletRequest - * @param endpoint Body with endpoint details - * @return Result indicating success or failure - * @throws Exception if application user is not found - */ - @RequestMapping( - value = {COMPONENTS_PATH}, - method = RequestMethod.POST, - produces = "application/json") - @ResponseBody - public String insertComponent(HttpServletRequest request, - @RequestBody EcdComponent newComponent) throws Exception { - preLogAudit(request); - String outboundJson = null; - controllerEndpointService.insertComponent(newComponent); - RestResponseSuccess success = - new RestResponseSuccess("Inserted new component with name " + newComponent.getCname()); - outboundJson = mapper.writeValueAsString(success); - postLogAudit(request); - return outboundJson; - } - + public void preLogAudit(HttpServletRequest request) { begin = new Date(); MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin)); 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 f3b6147..cc1e9d8 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 @@ -27,7 +27,6 @@ import java.util.List; import javax.servlet.http.HttpServletRequest; -import org.onap.ccsdk.dashboard.service.ControllerEndpointService; import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.springframework.beans.factory.annotation.Autowired; @@ -72,12 +71,7 @@ public class DashboardRestrictedBaseController extends RestrictedBaseController @Autowired protected DashboardProperties appProperties; - /** - * For getting selected controller - */ - @Autowired - private ControllerEndpointService controllerEndpointService; - + /** * Hello Spring, here's your no-arg constructor. */ 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 0346ad7..d98c404 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 @@ -22,7 +22,6 @@ package org.onap.ccsdk.dashboard.controller; import java.util.Date; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -50,8 +49,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; -import com.fasterxml.jackson.core.JsonProcessingException; - /** * Controller for Deployment Handler features: get/put/delete deployments * Methods serve Ajax requests made by Angular scripts on pages that show @@ -63,14 +60,15 @@ public class DeploymentHandlerController extends DashboardRestrictedBaseControll private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DeploymentHandlerController.class); - + @Autowired DeploymentHandlerClient deploymentHandlerClient; - + private static final String DEPLOYMENTS_PATH = "dcae-deployments"; private static Date begin, end; + @SuppressWarnings("unchecked") @RequestMapping(value = { DEPLOYMENTS_PATH + "/{deploymentId:.+}" }, method = RequestMethod.PUT, produces = "application/json") @ResponseBody @@ -83,13 +81,8 @@ public class DeploymentHandlerController extends DashboardRestrictedBaseControll json = objectMapper.writeValueAsString(deploymentHandlerClient.putDeployment( deploymentRequestObject.getDeploymentId(), deploymentRequestObject.getTenant(), new DeploymentRequest(deploymentRequestObject.getServiceTypeId(), - deploymentRequestObject.getInputs()))); - } else { - json = objectMapper.writeValueAsString(deploymentHandlerClient.updateDeployment( - deploymentRequestObject.getDeploymentId(), deploymentRequestObject.getTenant(), - new DeploymentRequest(deploymentRequestObject.getServiceTypeId(), - deploymentRequestObject.getInputs()))); - } + deploymentRequestObject.getInputs()), request)); + } } catch (BadRequestException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "Deployment Handler"); @@ -151,9 +144,7 @@ public class DeploymentHandlerController extends DashboardRestrictedBaseControll String json = null; StringBuffer status = new StringBuffer(); try { - // DeploymentHandlerClient deploymentHandlerClient = - // getDeploymentHandlerClient(request); - deploymentHandlerClient.deleteDeployment(deploymentId, tenant); + 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, 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 49d5709..ad671ad 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 @@ -26,8 +26,6 @@ package org.onap.ccsdk.dashboard.controller; * ECOMP Portal SDK * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property - * - * 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. @@ -47,6 +45,7 @@ import java.net.URLDecoder; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; +import java.util.TreeSet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; @@ -56,12 +55,16 @@ import javax.servlet.http.HttpSession; import org.onap.portalsdk.core.auth.LoginStrategy; import org.onap.portalsdk.core.command.LoginBean; import org.onap.portalsdk.core.controller.UnRestrictedBaseController; +import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.domain.UserApp; +import org.onap.portalsdk.core.domain.FusionObject.Parameters; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.menu.MenuProperties; import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler; import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; +import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.service.LoginService; import org.onap.portalsdk.core.service.RoleService; import org.onap.portalsdk.core.util.SystemProperties; @@ -98,9 +101,84 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { @Autowired private RoleService roleService; + @Autowired + private DataAccessService dataAccessService; + private String viewName; private String welcomeView; + @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 + * + * @param request + * @return + * @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"); + if (loginId.isEmpty() || password.isEmpty()) { + String loginErrorMessage = "User name and/or password missing"; + 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()); + + if (commandBean.getUser() == null) { + // add new user + User user = new User(); + user.setLoginId(loginId); + user.setLoginPwd(password); + user.setActive(true); + user.setOrgUserId(loginId); + user.setLastName(request.getParameter("last")); + user.setFirstName(request.getParameter("first")); + user.setEmail(request.getParameter("email")); + Role role = null; + HashMap additionalParams = new HashMap(); + additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request); + user.setRoles(new TreeSet<Role>()); + user.setUserApps(new TreeSet<UserApp>()); + 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)), + 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"); + } + 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); + } + } + 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. @@ -225,6 +303,16 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { } } + @RequestMapping(value = { "logout.htm" }, method = RequestMethod.GET) + public ModelAndView appLogout(HttpServletRequest request) { + try { + request.getSession().invalidate(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Logout failed", e); + } + return new ModelAndView("redirect:login.htm"); + } + /** * Discover if the portal is available by GET-ing a resource from the REST URL * specified in portal.properties, using a very short timeout. @@ -273,16 +361,14 @@ public class ECDSingleSignOnController extends UnRestrictedBaseController { return request.getSession().getId(); } - @Override public String getViewName() { return viewName; } - - @Override + public void setViewName(String viewName) { this.viewName = viewName; } - + public String getWelcomeView() { return welcomeView; } 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 5087ad1..f8fd19e 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 @@ -2,22 +2,22 @@ * =============LICENSE_START========================================================= * * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * ============LICENSE_END========================================================= * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ package org.onap.ccsdk.dashboard.controller; @@ -25,30 +25,48 @@ 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; +import org.onap.ccsdk.dashboard.rest.InventoryClient; +import org.onap.portalsdk.core.controller.FusionBaseController; import org.onap.portalsdk.core.util.SystemProperties; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; +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; +import com.fasterxml.jackson.databind.ObjectMapper; + /** * This controller responds to probes for application health, returning a JSON * body to indicate current status. */ @RestController -@Configuration -@EnableAspectJAutoProxy @RequestMapping("/") -public class HealthCheckController extends DashboardRestrictedBaseController { +public class HealthCheckController extends FusionBaseController { + @Autowired + InventoryClient inventoryClient; + + @Autowired + DeploymentHandlerClient deploymentHandlerClient; + + @Autowired + CloudifyClient cfyClient; + /** * 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 @@ -56,9 +74,13 @@ public class HealthCheckController extends DashboardRestrictedBaseController { * @param request HttpServletRequest * @return HealthStatus object always */ - @RequestMapping(value = { APP_HEALTH_CHECK_PATH }, method = RequestMethod.GET, produces = "application/json") + @RequestMapping( + value = {APP_HEALTH_CHECK_PATH}, + method = RequestMethod.GET, + produces = "application/json") public HealthStatus healthCheck(HttpServletRequest request, HttpServletResponse response) { return new HealthStatus(200, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + " health check passed "); } + } 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 4251212..3877dfc 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,44 +22,55 @@ package org.onap.ccsdk.dashboard.controller; +import java.io.PrintWriter; import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.function.Predicate; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import org.apache.http.HttpStatus; import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceAlreadyDeactivatedException; -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; import org.onap.ccsdk.dashboard.model.RestResponseError; import org.onap.ccsdk.dashboard.model.RestResponsePage; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.cloudify.ServiceRefCfyList; import org.onap.ccsdk.dashboard.model.inventory.Blueprint; -import org.onap.ccsdk.dashboard.model.inventory.Service; +import org.onap.ccsdk.dashboard.model.inventory.BlueprintResponse; 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.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.rest.CloudifyClient; +import org.onap.ccsdk.dashboard.rest.ConsulClient; import org.onap.ccsdk.dashboard.rest.InventoryClient; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.objectcache.AbstractCacheManager; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.web.support.AppUtils; -import org.onap.ccsdk.dashboard.util.DashboardProperties; - +import org.onap.portalsdk.core.web.support.UserUtils; 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.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -84,105 +95,40 @@ public class InventoryController extends DashboardRestrictedBaseController { @Autowired InventoryClient inventoryClient; + @Autowired + CloudifyClient cloudifyClient; + @Autowired + ConsulClient consulClient; + + /** + * For caching data + */ + private AbstractCacheManager cacheManager; + + @Autowired + public void setCacheManager(AbstractCacheManager cacheManager) { + this.cacheManager = cacheManager; + } + + public AbstractCacheManager getCacheManager() { + return cacheManager; + } + /** * Enum for selecting an item type. */ public enum InventoryDataItem { - SERVICES, SERVICE_TYPES, SERVICES_GROUPBY; + SERVICE_TYPES, SERVICE_TYPE_NAME, OWNER, SERVICE_TYPE_ID; } private static Date begin, end; - private static final String SERVICES_PATH = "dcae-services"; + 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"; private static final String VIEW_SERVICE_TYPE_BLUEPRINT_PATH = "dcae-service-type-blueprint"; private static final String DEP_IDS_FOR_TYPE = "dcae-services/typeIds"; - - /** - * Gets one page of objects and supporting information via the REST client. On - * success, returns a PaginatedRestResponse object as String. - * - * @param option Specifies which item list type to get - * @param pageNum Page number of results - * @param pageSize Number of items per browser page - * @return JSON block as String, see above. - * @throws Exception On any error; e.g., Network failure. - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - private String getItemListForPage(HttpServletRequest request, InventoryDataItem option, - int pageNum, int pageSize, String sortBy, String searchBy) throws Exception { - List itemList = null; - switch (option) { - case SERVICES: - itemList = inventoryClient.getServices().collect(Collectors.toList()); - if (searchBy != null) { - itemList = (List) itemList.stream() - .filter(s -> ((Service) s).contains(searchBy)).collect(Collectors.toList()); - } - for (Service bp : (List<Service>) itemList) { - bp.setCanDeploy(Optional.of(true)); - } - if (sortBy != null) { - if (sortBy.equals("deploymentRef")) { - Collections.sort(itemList, serviceDeploymentRefComparator); - } else if (sortBy.equals("serviceId")) { - Collections.sort(itemList, serviceIdComparator); - } else if (sortBy.equals("created")) { - Collections.sort(itemList, serviceCreatedComparator); - } else if (sortBy.equals("modified")) { - Collections.sort(itemList, serviceModifiedComparator); - } - } - break; - case SERVICE_TYPES: - itemList = inventoryClient.getServiceTypes().collect(Collectors.toList()); - if (searchBy != null) { - itemList = - (List) itemList.stream().filter(s -> ((ServiceType) s).contains(searchBy)) - .collect(Collectors.toList()); - } - for (ServiceType bp : (List<ServiceType>) itemList) { - bp.setCanDeploy(Optional.of(true)); - } - if (sortBy != null) { - if (sortBy.equals("owner")) { - Collections.sort(itemList, serviceTypeOwnerComparator); - } else if (sortBy.equals("typeId")) { - Collections.sort(itemList, serviceTypeIdComparator); - } else if (sortBy.equals("typeName")) { - Collections.sort(itemList, serviceTypeNameComparator); - } else if (sortBy.equals("typeVersion")) { - Collections.sort(itemList, serviceTypeVersionComparator); - } else if (sortBy.equals("created")) { - Collections.sort(itemList, serviceTypeCreatedComparator); - } else if (sortBy.equals("application")) { - Collections.sort(itemList, serviceTypeApplComparator); - } else if (sortBy.equals("component")) { - Collections.sort(itemList, serviceTypeCompComparator); - } - } - break; - default: - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Getting page of items failed!"); - throw new Exception( - "getItemListForPage failed: unimplemented case: " + option.name()); - } - - // Shrink if needed - final int totalItems = itemList.size(); - final int pageCount = (int) Math.ceil((double) totalItems / pageSize); - if (totalItems > pageSize) - itemList = getPageOfList(pageNum, pageSize, itemList); - - RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); - String outboundJson = objectMapper.writeValueAsString(model); - return outboundJson; - } + private static final String SERVICE_TYPE_ID = "service-type-id-list"; /** * version with user role auth Gets one page of objects and supporting @@ -202,171 +148,211 @@ public class InventoryController extends DashboardRestrictedBaseController { HashMap<String, Boolean> comp_deploy_tab = (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 (roleAuth == null) { + roleAuth = "READ"; + } Set<String> userApps = (Set<String>) session.getAttribute("authComponents"); if (userApps == null) { userApps = new TreeSet<String>(); } - + ReadWriteLock lock = new ReentrantReadWriteLock(); List itemList = null; - List<ServiceType> filterList = new ArrayList<ServiceType>(); - List<Service> authDepList = new ArrayList<Service>(); - switch (option) { - case SERVICES: - itemList = inventoryClient.getServices().collect(Collectors.toList()); - if (roleLevel.equals("app")) { - for (String userRole : userApps) { - logger.debug(">>>> check component type from deployment: " + userRole); - for (Service cont : (List<Service>) itemList) { - String deplRef = cont.getDeploymentRef().toLowerCase(); - logger.debug(">>>> container deployment name: " + deplRef); - if (deplRef.contains(userRole)) { - logger.debug(">>>> adding deployment item to filtered subset"); - authDepList.add(cont); - } - } - } - } + List bpItemList = null; + int totalItems = 0; + + lock.readLock().lock(); + List<ServiceTypeSummary> bpList = + (List<ServiceTypeSummary>)getCacheManager().getObject(SERVICE_TYPES_PATH); + lock.readLock().unlock(); + if (bpList == null) { + bpList = inventoryClient.getServiceTypes().collect(Collectors.toList()); + } - if (searchBy != null) { - if (!roleLevel.equals("app")) { - itemList = - (List) itemList.stream().filter(s -> ((Service) s).contains(searchBy)) - .collect(Collectors.toList()); - } else { - if (!authDepList.isEmpty()) { - authDepList = (List) authDepList.stream() - .filter(s -> ((Service) s).contains(searchBy)) - .collect(Collectors.toList()); - } - } + String svcRefFilterStr = ""; + String appFilterStr = ""; + String compFilterStr = ""; + String ownerFilterStr = ""; + 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()); + 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()); + 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()); + 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()); + 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()); + ownerFilterStr = ownerList.get(0).split(":")[1]; + } + if (!ownerFilterStr.isEmpty()) { + List<ServiceTypeSummary> ownerBpList = new ArrayList<ServiceTypeSummary>(); + lock.readLock().lock(); + Map<String, List<ServiceTypeSummary>> bpPerOwner = + (Map<String, List<ServiceTypeSummary>>) getCacheManager().getObject("owner_bp_map"); + lock.readLock().unlock(); + + 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 (roleLevel.equals("app")) { - logger.debug(">>>> update response with authorized content"); - itemList.clear(); - itemList.addAll(authDepList); + + if (bpPerOwner != null) { + 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()); + bpOwnerSet.stream().forEach(e -> ownerBpList.addAll(e.getValue())); + bpItemList = ownerBpList; } - - // check for authorization to perform delete deployed blueprints - - if (!roleLevel.equals("ops")) { - for (Service bp : (List<Service>) itemList) { - String deplRef = bp.getDeploymentRef().split("_")[0].toLowerCase(); - logger.debug(">>>> deployment reference: " + deplRef); - if (comp_deploy_tab.containsKey(deplRef)) { - boolean enableDeploy = comp_deploy_tab.get(deplRef); - logger.debug(">>>> enable deploy button: " + enableDeploy); - bp.setCanDeploy(Optional.of(enableDeploy)); - } else { - bp.setCanDeploy(Optional.of(false)); - } - } - } else { - for (Service bp : (List<Service>) itemList) { - bp.setCanDeploy(Optional.of(true)); - } - } - - if (sortBy != null) { - if (sortBy.equals("deploymentRef")) { - Collections.sort(itemList, serviceDeploymentRefComparator); - } else if (sortBy.equals("serviceId")) { - Collections.sort(itemList, serviceIdComparator); - } else if (sortBy.equals("created")) { - Collections.sort(itemList, serviceCreatedComparator); - } else if (sortBy.equals("modified")) { - Collections.sort(itemList, serviceModifiedComparator); - } + if (bpItemList == null) { + bpItemList = new ArrayList<ServiceTypeSummary>(); + bpItemList.addAll(bpList); } + } + } + if (bpItemList == null) { + bpItemList = new ArrayList<ServiceTypeSummary>(); + bpItemList.addAll(bpList); + } + // apply role based filtering + 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()); + } else if (roleLevel.equals("app_dev")) { + Predicate<ServiceTypeSummary> appFilter = + p -> p.getComponent() != null && !p.getComponent().equalsIgnoreCase("dcae") + && !p.getComponent().equalsIgnoreCase("d2a"); + 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()); + 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()); + itemList = new ArrayList<String>(); + itemList.addAll(svcTypeList); break; case SERVICE_TYPES: - ServiceTypeQueryParams serviceQueryParams = - new ServiceTypeQueryParams.Builder().onlyLatest(false).build(); - itemList = inventoryClient.getServiceTypes(serviceQueryParams) - .collect(Collectors.toList()); - if (roleLevel.equals("app")) { - for (String userApp : userApps) { - logger.debug(">>>> check component type from BP: " + userApp); - for (ServiceType bp : (List<ServiceType>) itemList) { - String bpComp = bp.getComponent(); - String bpOwner = bp.getOwner(); // for backward compatibility - logger.debug(">>>> BP component name: " + bpComp); - if ((bpComp != null && bpComp.equalsIgnoreCase(userApp)) - || bpOwner.contains(userApp)) { - logger.debug(">>>> adding item to filtered subset"); - filterList.add(bp); - } - } - } + // apply response filters + itemList = bpItemList; + String outFilter = request.getParameter("_include"); + if (outFilter != null) { + List<String> svcSummaryList = + (List) itemList.stream().map(x -> extractBpSummary((ServiceTypeSummary)x)).collect(Collectors.toList()); + return objectMapper.writeValueAsString(svcSummaryList); } - if (searchBy != null) { - if (!roleLevel.equals("app")) { - itemList = (List) itemList.stream() - .filter(s -> ((ServiceType) s).contains(searchBy)) - .collect(Collectors.toList()); - } else { - if (!filterList.isEmpty()) { - filterList = (List) filterList.stream() - .filter(s -> ((ServiceType) s).contains(searchBy)) + // apply user search filters + if (searchBy != null && !searchBy.isEmpty()) { + if (!svcRefFilterStr.isEmpty()) { + List<String> svcFilterList = + new ArrayList<String>(Arrays.asList(svcRefFilterStr.split(","))); + if (!svcFilterList.isEmpty()) { + 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(","))); + Predicate<ServiceTypeSummary> srvcAppFilter = + p -> p.getApplication() != null; + Stream<ServiceTypeSummary> svcStream = itemList.stream(); + + 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(","))); + 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()); } - } - if (roleLevel.equals("app")) { - logger.debug(">>>> update response with authorized content"); - itemList.clear(); - itemList.addAll(filterList); - } - // check for authorization to perform update/delete/deploy blueprints - if (!roleLevel.equals("ops")) { - for (ServiceType bp : (List<ServiceType>) itemList) { - String bpComp = bp.getComponent(); - if (bpComp != null && bpComp.length() > 0) { - bpComp = bpComp.toLowerCase(); - } else { - String bpOwner = bp.getOwner(); // for backward compatibility - if (bpOwner != null && bpOwner.contains(":")) { - bpComp = bp.getOwner().split(":")[0].toLowerCase(); - } - } - logger.debug(">>>> BP component name: " + bpComp); - if (comp_deploy_tab.containsKey(bpComp)) { - boolean enableDeploy = comp_deploy_tab.get(bpComp); - logger.debug(">>>> enable deploy button: " + enableDeploy); - bp.setCanDeploy(Optional.of(enableDeploy)); - } else { - bp.setCanDeploy(Optional.of(false)); - } + if (!containsFilterStr.isEmpty()) { + final String simpleSrch = containsFilterStr.split(",")[0]; + itemList = (List<ServiceTypeSummary>) itemList.stream() + .filter(s -> ((ServiceTypeSummary) s).contains(simpleSrch)).collect(Collectors.toList()); } - } else { - for (ServiceType bp : (List<ServiceType>) itemList) { - bp.setCanDeploy(Optional.of(true)); - } - } - + } if (sortBy != null) { if (sortBy.equals("owner")) { - Collections.sort(itemList, serviceTypeOwnerComparator); + ((List<ServiceTypeSummary>)itemList).sort( + (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getOwner().compareTo(o2.getOwner())); } else if (sortBy.equals("typeId")) { - Collections.sort(itemList, serviceTypeIdComparator); + ((List<ServiceTypeSummary>)itemList).sort( + (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getTypeId().get().compareTo(o2.getTypeId().get())); } else if (sortBy.equals("typeName")) { - Collections.sort(itemList, serviceTypeNameComparator); + ((List<ServiceTypeSummary>)itemList).sort( + (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getTypeName().compareTo(o2.getTypeName())); } else if (sortBy.equals("typeVersion")) { - Collections.sort(itemList, serviceTypeVersionComparator); + ((List<ServiceTypeSummary>)itemList).sort( + (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getTypeVersion().compareTo(o2.getTypeVersion())); } else if (sortBy.equals("created")) { - Collections.sort(itemList, serviceTypeCreatedComparator); + ((List<ServiceTypeSummary>)itemList).sort( + (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getCreated().get().compareTo(o2.getCreated().get())); } else if (sortBy.equals("application")) { - Collections.sort(itemList, serviceTypeApplComparator); + ((List<ServiceTypeSummary>)itemList).sort( + (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getApplication().compareTo(o2.getApplication())); } else if (sortBy.equals("component")) { - Collections.sort(itemList, serviceTypeCompComparator); + ((List<ServiceTypeSummary>)itemList).sort( + (ServiceTypeSummary o1, ServiceTypeSummary o2) -> o1.getComponent().compareTo(o2.getComponent())); } } break; @@ -380,18 +366,91 @@ public class InventoryController extends DashboardRestrictedBaseController { throw new Exception( "getItemListForPage failed: unimplemented case: " + option.name()); } - // Shrink if needed - final int totalItems = itemList.size(); + if (itemList != null) { + totalItems = itemList.size(); + } final int pageCount = (int) Math.ceil((double) totalItems / pageSize); - if (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; + for (ServiceTypeSummary bp : (List<ServiceTypeSummary>) itemList) { + bp.setCanDeploy(Optional.of(deployFlag)); + } + } else { + for (ServiceTypeSummary bp : (List<ServiceTypeSummary>) itemList) { + String bpComp = bp.getComponent(); + if (bpComp != null && bpComp.length() > 0) { + bpComp = bpComp.toLowerCase(); + } else { + String bpOwner = bp.getOwner(); // for backward compatibility + if (bpOwner != null && bpOwner.contains(":")) { + bpComp = bp.getOwner().split(":")[0].toLowerCase(); + } + } + if (comp_deploy_tab.containsKey(bpComp)) { + boolean enableDeploy = comp_deploy_tab.get(bpComp); + logger.debug(">>>> enable deploy button: " + enableDeploy); + bp.setCanDeploy(Optional.of(enableDeploy)); + } else { + bp.setCanDeploy(Optional.of(false)); + } + } + } + } else { + for (ServiceTypeSummary bp : (List<ServiceTypeSummary>) itemList) { + bp.setCanDeploy(Optional.of(true)); + } + } + // add the deployments mapping to the list + lock.readLock().lock(); + List<ServiceTypeServiceMap> cache_bp_map_arr = + (List<ServiceTypeServiceMap>) getCacheManager().getObject("bp_deploy_map"); + lock.readLock().unlock(); + if (cache_bp_map_arr != 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()); + } + } + } + } RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList); String outboundJson = objectMapper.writeValueAsString(model); return outboundJson; } - + + @SuppressWarnings("unchecked") + @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); + lock.readLock().unlock(); + if (bpList != null) { + 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. @@ -407,16 +466,8 @@ public class InventoryController extends DashboardRestrictedBaseController { try { int pageNum = getRequestPageNumber(request); int pageSize = getRequestPageSize(request); - String appEnv = "os"; - appEnv = - DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth"); - if (appEnv.equals("os")) { - outboundJson = - getItemListForPage(request, option, pageNum, pageSize, sortBy, searchBy); - } else { - outboundJson = - getItemListForPageAuth(request, option, pageNum, pageSize, sortBy, searchBy); - } + outboundJson = + getItemListForPageAuth(request, option, pageNum, pageSize, sortBy, searchBy); } catch (Exception ex) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "DCAE Inventory"); @@ -445,121 +496,24 @@ public class InventoryController extends DashboardRestrictedBaseController { } /** - * Supports sorting service types by owner - */ - private static Comparator<ServiceType> serviceTypeOwnerComparator = - new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getOwner().compareToIgnoreCase(o2.getOwner()); - } - }; - - /** - * Supports sorting service types by application - */ - private static Comparator<ServiceType> serviceTypeApplComparator = - new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getApplication().compareToIgnoreCase(o2.getApplication()); - } - }; - - /** - * Supports sorting service types by component - */ - private static Comparator<ServiceType> serviceTypeCompComparator = - new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getComponent().compareToIgnoreCase(o2.getComponent()); - } - }; - - /** - * Supports sorting service types by type id - */ - private static Comparator<ServiceType> serviceTypeIdComparator = new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getTypeId().get().compareToIgnoreCase(o2.getTypeId().get()); - } - }; - - /** - * Supports sorting service types by type name - */ - private static Comparator<ServiceType> serviceTypeNameComparator = - new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getTypeName().compareToIgnoreCase(o2.getTypeName()); - } - }; - - /** - * Supports sorting service types by type version - */ - private static Comparator<ServiceType> serviceTypeVersionComparator = - new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getTypeVersion().compareTo(o2.getTypeVersion()); - } - }; - - /** - * Supports sorting service types by created date - */ - private static Comparator<ServiceType> serviceTypeCreatedComparator = - new Comparator<ServiceType>() { - @Override - public int compare(ServiceType o1, ServiceType o2) { - return o1.getCreated().get().compareToIgnoreCase(o2.getCreated().get()); - } - }; - - /** - * Supports sorting services by deploymentRef - */ - private static Comparator<Service> serviceDeploymentRefComparator = new Comparator<Service>() { - @Override - public int compare(Service o1, Service o2) { - return o1.getDeploymentRef().compareToIgnoreCase(o2.getDeploymentRef()); - } - }; - - /** - * Supports sorting services by service id - */ - private static Comparator<Service> serviceIdComparator = new Comparator<Service>() { - @Override - public int compare(Service o1, Service o2) { - return o1.getServiceId().compareToIgnoreCase(o2.getServiceId()); - } - }; - - /** - * Supports sorting services by created date - */ - private static Comparator<Service> serviceCreatedComparator = new Comparator<Service>() { - @Override - public int compare(Service o1, Service o2) { - return o1.getCreated().compareToIgnoreCase(o2.getCreated()); - } - }; - - /** - * Supports sorting services by created date + * Serves one page of blueprint owners + * + * @param request HttpServletRequest + * @return List of ServiceTypes objects */ - private static Comparator<Service> serviceModifiedComparator = new Comparator<Service>() { - @Override - public int compare(Service o1, Service o2) { - return o1.getModified().compareToIgnoreCase(o2.getModified()); - } - }; - + @RequestMapping( + value = {OWNERS}, + method = RequestMethod.GET, + produces = "application/json") + @ResponseBody + public String getOwnersByPage(HttpServletRequest request) { + preLogAudit(request); + String json = getItemListForPageWrapper(request, InventoryDataItem.OWNER, + request.getParameter("sortBy"), request.getParameter("searchBy")); + postLogAudit(request); + return json; + } + /** * Serves one page of service types * @@ -600,27 +554,50 @@ public class InventoryController extends DashboardRestrictedBaseController { return objectMapper.writeValueAsString(result); } + /** - * Serves one page of services - * + * Serves the complete list of service type names + * * @param request HttpServletRequest - * - * @return List of Service objects + * + * @return list of service type names */ @RequestMapping( - value = {SERVICES_PATH}, + value = {SERVICE_TYPE_NAME}, method = RequestMethod.GET, produces = "application/json") @ResponseBody - public String getServicesByPage(HttpServletRequest request) { + @Cacheable + public String getAllServiceTypeNames(HttpServletRequest request) { // preLogAudit(request); String json = null; - json = getItemListForPageWrapper(request, InventoryDataItem.SERVICES, + json = getItemListForPageWrapper(request, InventoryDataItem.SERVICE_TYPE_NAME, request.getParameter("sortBy"), request.getParameter("searchBy")); postLogAudit(request); return json; - } - + } + + /** + * 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 + 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. * @@ -679,68 +656,61 @@ public class InventoryController extends DashboardRestrictedBaseController { * @throws Exception On serialization failure */ @RequestMapping( - value = {SERVICE_TYPES_PATH + "/{typeid}"}, + value = {SERVICE_TYPES_PATH + "/{typeId}"}, method = RequestMethod.DELETE, produces = "application/json") @ResponseBody - public String deleteServiceType(@PathVariable("typeid") String typeid, - HttpServletRequest request, HttpServletResponse response) throws Exception { + public String deleteServiceType(@PathVariable("typeId") String typeId, + HttpServletRequest request, + HttpServletResponse response) throws Exception { preLogAudit(request); - String json = "{\"202\": \"OK\"}"; + String json = "{\"204\": \"Blueprint deleted\"}"; + boolean allow = true; try { - inventoryClient.deleteServiceType(typeid); + // 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 (!allow) { + 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); + this.cacheOwnerToBpMap(); + } } catch (ServiceTypeNotFoundException | ServiceTypeAlreadyDeactivatedException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "DCAE Inventory"); MDC.put("TargetServiceName", "DCAE Inventory"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting service type " + typeid + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); - json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); - } catch (Exception t) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting service type " + typeid + " failed!"); - logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); - json = objectMapper - .writeValueAsString(new RestResponseError("deleteDeployment failed", t)); - } finally { - postLogAudit(request); - } - return json; - } - - /** - * Deletes the specified service i.e. deployment from inventory - * - * @param id Service ID - * @param request HttpServletRequest - * @param response HttpServletResponse - * @return status code on success; error on failure. - * @throws Exception On serialization failure - */ - @RequestMapping( - value = {SERVICES_PATH + "/{serviceId}"}, - method = RequestMethod.DELETE, - produces = "application/json") - @ResponseBody - public String deleteService(@PathVariable("serviceId") String serviceId, - HttpServletRequest request, HttpServletResponse response) throws Exception { - preLogAudit(request); - String json = "{\"202\": \"OK\"}"; - try { - inventoryClient.deleteService(serviceId); - } catch (ServiceNotFoundException | ServiceAlreadyDeactivatedException e) { - MDC.put(SystemProperties.STATUS_CODE, "ERROR"); - MDC.put("TargetEntity", "DCAE Inventory"); - MDC.put("TargetServiceName", "DCAE Inventory"); - MDC.put("ErrorCode", "300"); - MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting service " + serviceId + " failed!"); + MDC.put("ErrorDescription", "Deleting service type " + typeId + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage())); } catch (Exception t) { @@ -749,10 +719,10 @@ public class InventoryController extends DashboardRestrictedBaseController { MDC.put("TargetServiceName", "DCAE Inventory"); MDC.put("ErrorCode", "300"); MDC.put("ErrorCategory", "ERROR"); - MDC.put("ErrorDescription", "Deleting service " + serviceId + " failed!"); + MDC.put("ErrorDescription", "Deleting service type " + typeId + " failed!"); logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception"); json = objectMapper - .writeValueAsString(new RestResponseError("deleteDeployment failed", t)); + .writeValueAsString(new RestResponseError("delete blueprint failed", t)); } finally { postLogAudit(request); } @@ -778,8 +748,7 @@ public class InventoryController extends DashboardRestrictedBaseController { String json = "{\"201\": \"OK\"}"; try { // Verify that the Service Type can be parsed for inputs. - Blueprint.parse(serviceType.getBlueprintTemplate()); - // InventoryClient inventoryClient = getInventoryClient(request); + Blueprint.parse(serviceType.getBlueprintTemplate()); inventoryClient.addServiceType(serviceType); } catch (BlueprintParseException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); @@ -839,8 +808,8 @@ public class InventoryController extends DashboardRestrictedBaseController { String json = "{\"201\": \"OK\"}"; try { Blueprint.parse(serviceTypeRequest.getBlueprintTemplate()); - // InventoryClient inventoryClient = getInventoryClient(request); inventoryClient.addServiceType(serviceTypeRequest); + this.cacheOwnerToBpMap(); } catch (BlueprintParseException e) { MDC.put(SystemProperties.STATUS_CODE, "ERROR"); MDC.put("TargetEntity", "DCAE Inventory"); diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/ControllerEndpoint.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/ControllerEndpoint.java deleted file mode 100644 index 3e74ff4..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/ControllerEndpoint.java +++ /dev/null @@ -1,91 +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.domain; - -import org.onap.portalsdk.core.domain.support.DomainVo; - -/** - * Model for controller endpoint information stored in database. A single row - * for a user represents a selected endpoint. - */ -public class ControllerEndpoint extends DomainVo { - - private static final long serialVersionUID = 8785223545128054402L; - - private long userId; - private String name; - private String url; - private String inventoryUrl; - private String dhandlerUrl; - - public ControllerEndpoint() { - } - - public ControllerEndpoint(long userId, String name, String url, String inventoryUrl, String dhandlerUrl) { - this.userId = userId; - this.name = name; - this.url = url; - this.inventoryUrl = inventoryUrl; - this.dhandlerUrl = dhandlerUrl; - } - - public long getUserId() { - return userId; - } - - public void setUserId(long userId) { - this.userId = userId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getInventoryUrl() { - return inventoryUrl; - } - - public void setInventoryUrl(String inventoryUrl) { - this.inventoryUrl = inventoryUrl; - } - - public String getDhandlerUrl() { - return dhandlerUrl; - } - - public void setDhandlerUrl(String dhandlerUrl) { - this.dhandlerUrl = dhandlerUrl; - } -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/EcdComponent.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/EcdComponent.java deleted file mode 100644 index c62d7bc..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/domain/EcdComponent.java +++ /dev/null @@ -1,68 +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.domain; - -import org.apache.commons.lang3.StringUtils; -import org.onap.portalsdk.core.domain.support.DomainVo; - -public class EcdComponent extends DomainVo { - - private static final long serialVersionUID = 1L; - - private Long compId; - private String cname; // component name - private String dname; // component display name - - public Long getCompId() { - return compId; - } - - public void setCompId(Long compId) { - this.compId = compId; - } - - public String getCname() { - return cname; - } - - public void setCname(String cname) { - this.cname = cname; - } - - public String getDname() { - return dname; - } - - public void setDname(String dname) { - this.dname = dname; - } - - public boolean contains(String searchString) { - if (StringUtils.containsIgnoreCase(this.getCname(), searchString) - || StringUtils.containsIgnoreCase(this.getDname(), searchString)) { - return true; - } - return false; - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployment.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployment.java deleted file mode 100644 index 60bf229..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployment.java +++ /dev/null @@ -1,165 +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; - -import java.util.List; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Model with fields only for the top-level attributes. All complex child - * structures are represented simply as generic collections. - */ -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; - - @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; - } - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentRequest.java deleted file mode 100644 index 2110111..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentRequest.java +++ /dev/null @@ -1,64 +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; - -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Model for message POST-ed to controller to create a Cloudify Deployment: - * - * <pre> - { - "deployment_id" : "deployment-id", - "blueprint_id" : "blueprint-id", - "parameters" : - { - "p1" : "v1" - } - } - * </pre> - */ -public final class CloudifyDeploymentRequest extends ECTransportModel { - - /** A unique identifier for the deployment. */ - public final String deployment_id; - /** A unique identifier for the blueprint. */ - public final String blueprint_id; - /** - * These values are input for the deployment which can be retrieved from the GET - * /blueprint API this is :plan.input field in GET /blueprint - */ - public final Map<String, Object> parameters; - - @JsonCreator - public CloudifyDeploymentRequest(@JsonProperty("deployment_id") String deployment_id, - @JsonProperty("blueprint_id") String blueprint_id, - @JsonProperty("parameters") Map<String, Object> parameters) { - this.deployment_id = deployment_id; - this.blueprint_id = blueprint_id; - this.parameters = parameters; - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpdateRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpdateRequest.java deleted file mode 100644 index 16ac145..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpdateRequest.java +++ /dev/null @@ -1,88 +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; - -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Model for message POST-ed to controller to update a Cloudify Deployment: - * - * NOTE: THIS IS NOT HOW THE REQUEST TO CLOUDIFY'S ENDPOINT LOOKS. THE REQUEST - * IS CONSTRUCTED IN PROPER FORMAT IN THE API HANDLER - * - * <pre> - * { - "deployment_id" : "deployment-id", - "workflow_name" : "workflow-name", - "allow_custom_parameter" : "true|false", - "force" : "true|false", - "node_instance_id": "node-instance-id", - "limits_cpu": limits_cpu, - "limits_mem": limits_mem, - "image": "image", - "replicas": replicas, - "container_name": "container_name" - } - * </pre> - */ -public final class CloudifyDeploymentUpdateRequest extends ECTransportModel { - - /** A unique identifier for the deployment. */ - public final String deployment_id; - /** A unique identifier for the workflow */ - public final String workflow_name; - public final Boolean allow_custom_parameter; - public final Boolean force; - /** Parameters: retrieve using the GET /deployments */ - // public final Map<String, Object> parameters; - public final String node_instance_id; - public final String limits_cpu; - public final String limits_mem; - public final String image; - public final Number replicas; - public final String container_name; - - @JsonCreator - public CloudifyDeploymentUpdateRequest(@JsonProperty("deployment_id") String deployment_id, - @JsonProperty("workflow_name") String workflow_name, - @JsonProperty("allow_custom_parameter") Boolean allowCustomParameter, @JsonProperty("force") Boolean force, - @JsonProperty("node_instance_id") String node_instance_id, @JsonProperty("limits_cpu") String limits_cpu, - @JsonProperty("limits_mem") String limits_mem, @JsonProperty("image") String image, - @JsonProperty("replicas") Number replicas, @JsonProperty("container_name") String container_name) { - - this.deployment_id = deployment_id; - this.workflow_name = workflow_name; - this.allow_custom_parameter = allowCustomParameter; - this.force = force; - // this.parameters = parameters; - this.node_instance_id = node_instance_id; - this.limits_cpu = limits_cpu; - this.limits_mem = limits_mem; - this.image = image; - this.replicas = replicas; - this.container_name = container_name; - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpdateResponse.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpdateResponse.java deleted file mode 100644 index 65688bb..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpdateResponse.java +++ /dev/null @@ -1,87 +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; - -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Model with fields only for the top-level attributes. All complex child - * structures are represented simply as generic collections. - */ -public final class CloudifyDeploymentUpdateResponse 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 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 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; - - public final String tenant_name; - - public final String created_by; - - public final Boolean private_resource; - - public final String resource_availability; - - @JsonCreator - public CloudifyDeploymentUpdateResponse(@JsonProperty("status") String status, - @JsonProperty("created_at") String created_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("error") String error, @JsonProperty("id") String id, - @JsonProperty("parameters") Map<String, Object> parameters, @JsonProperty("tenant_name") String tenant_name, - @JsonProperty("created_by") String created_by, @JsonProperty("private_resource") Boolean private_resource, - @JsonProperty("resource_availability") String resource_availability) { - - this.status = status; - this.created_at = created_at; - this.workflow_id = workflow_id; - this.is_system_workflow = is_system_workflow; - this.blueprint_id = blueprint_id; - this.deployment_id = deployment_id; - this.error = error; - this.id = id; - this.parameters = parameters; - this.tenant_name = tenant_name; - this.created_by = created_by; - this.private_resource = private_resource; - this.resource_availability = resource_availability; - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpgradeRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpgradeRequest.java deleted file mode 100644 index 30d3d16..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentUpgradeRequest.java +++ /dev/null @@ -1,79 +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; - -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Model for message POST-ed to controller to execute upgrade workflow on a - * Cloudify Deployment: - * - * NOTE: THIS IS NOT HOW THE REQUEST TO CLOUDIFY'S ENDPOINT LOOKS. THE REQUEST - * IS CONSTRUCTED IN PROPER FORMAT IN THE API HANDLER - * - * <pre> -* { - "config_url": config_url, - "config_format": config_format, - "chartRepo": chartRepo, - "chartVersion": chartVersion - }; - * </pre> - */ -public final class CloudifyDeploymentUpgradeRequest extends ECTransportModel { - - public final String config_url; - public final String config_format; - public final String chartRepo; - public final String chartVersion; - - @JsonCreator - public CloudifyDeploymentUpgradeRequest(@JsonProperty("config_url") String config_url, - @JsonProperty("config_format") String config_format, @JsonProperty("chartRepo") String chartRepo, - @JsonProperty("chartVersion") String chartVersion) { - - this.config_url = config_url; - this.config_format = config_format; - this.chartRepo = chartRepo; - this.chartVersion = chartVersion; - } - - public String getConfig_url() { - return config_url; - } - - public String getConfig_format() { - return config_format; - } - - public String getChartRepo() { - return chartRepo; - } - - public String getChartVersion() { - return chartVersion; - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyEvent.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyEvent.java deleted file mode 100644 index d95ff24..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyEvent.java +++ /dev/null @@ -1,90 +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; - -import java.util.LinkedList; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonCreator; -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; - - @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; - } -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecution.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecution.java deleted file mode 100644 index 3fe393d..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecution.java +++ /dev/null @@ -1,83 +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; - -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Model with fields only for the top-level attributes. All complex child - * structures are represented simply as generic collections. - */ -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 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; - /** true if helm plugin is used */ - public Boolean is_helm; - /** true if helm status is enabled */ - public Boolean helm_status; - - @JsonCreator - public CloudifyExecution(@JsonProperty("status") String status, @JsonProperty("created_at") String created_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, - @JsonProperty("is_helm") Boolean is_helm, @JsonProperty("helm_status") Boolean helm_status) { - - this.status = status; - this.created_at = created_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.is_helm = is_helm; - this.helm_status = helm_status; - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionRequest.java deleted file mode 100644 index a9bad02..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionRequest.java +++ /dev/null @@ -1,106 +0,0 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * 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. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; - -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonCreator; -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; - - @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; - } - - 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; - } - - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceId.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceId.java deleted file mode 100644 index abe25fc..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceId.java +++ /dev/null @@ -1,62 +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; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Model with fields only for the top-level attributes. All complex child - * structures are represented as generic collections. - */ -public final class CloudifyNodeInstanceId extends ECTransportModel { - - /** The id of the node instance. */ - public final String id; - - /** The name of the user that created the node instance */ - // public final String created_by; - /** The id of the deployment the node instance belongs to. */ - // public final String deployment_id; - /** The Compute node instance id the node is contained within. */ - // public final String host_id; - /** The relationships the node has with other nodes. */ - // public final List relationships; - /** The runtime properties of the node instance. */ - // public final String runtime_properties; - /** The node instance state. */ - // public final String state; - /** The name of the tenant that owns the node instance. */ - - // public final String tenant_name; - /** - * A version attribute used for optimistic locking when updating the node - * instance. - */ - // public final String version; - - @JsonCreator - public CloudifyNodeInstanceId(@JsonProperty("id") String id) { - this.id = id; - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecret.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecret.java deleted file mode 100644 index 594ebfa..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecret.java +++ /dev/null @@ -1,53 +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; - -import com.fasterxml.jackson.annotation.JsonCreator; -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 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; - - @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) { - 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; - } -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecretUpload.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecretUpload.java deleted file mode 100644 index 3026a7a..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecretUpload.java +++ /dev/null @@ -1,53 +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; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class CloudifySecretUpload extends ECTransportModel { - - /** The secret's name */ - public final String name; - /** The secret’s value */ - public final String value; - /** Update value if secret already exists */ - public final boolean update_if_exists; - /** 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 boolean is_hidden_value; - /** The tenant name for this secret */ - public final String tenant; - - @JsonCreator - public CloudifySecretUpload(@JsonProperty("name") String name, @JsonProperty("value") String value, - @JsonProperty("update_if_exists") boolean update_if_exists, @JsonProperty("visibility") String visibility, - @JsonProperty("is_hidden_value") boolean is_hidden_value, @JsonProperty("tenant") String tenant) { - this.name = name; - this.value = value; - this.update_if_exists = update_if_exists; - this.visibility = visibility; - this.is_hidden_value = is_hidden_value; - this.tenant = tenant; - } -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointCredentials.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointCredentials.java deleted file mode 100644 index 03159c2..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointCredentials.java +++ /dev/null @@ -1,100 +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; - -import org.onap.portalsdk.core.onboarding.util.CipherUtil; - -/** - * Model with Controller username and password for use only within the back end; - * never serialized as JSON. - */ -public class ControllerEndpointCredentials extends ControllerEndpointTransport { - - public String username; - public String password; - public boolean isEncryptedPass; - - public ControllerEndpointCredentials(boolean selected, String name, String url, String inventoryUrl, - String dhandlerUrl, String consulUrl, String username, String password, boolean isEncryptedPass) { - super(selected, name, url, inventoryUrl, dhandlerUrl, consulUrl); - this.username = username; - this.password = password; - this.isEncryptedPass = isEncryptedPass; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public boolean getEncryptedPassword() { - return isEncryptedPass; - } - - public void setEncryptedPassword(boolean isEncryptedPass) { - this.isEncryptedPass = isEncryptedPass; - } - - /** - * Convenience method to yield a ControllerEndpointTransport object. - * - * @return ControllerEndpoint with copy of the non-privileged data - */ - public ControllerEndpointTransport toControllerEndpointTransport() { - return new ControllerEndpointTransport(getSelected(), getName(), getUrl(), getInventoryUrl(), getDhandlerUrl(), - getConsulUrl()); - } - - /** - * Accepts clear text and stores an encrypted value; as a side effect, sets the - * encrypted flag to true. - * - * @param plainText Clear-text password - * @throws Exception If encryption fails - */ - public void encryptPassword(final String plainText) throws Exception { - this.password = CipherUtil.encrypt(plainText); - this.isEncryptedPass = true; - } - - /** - * Client should call this method if {@link #getEncryptedPassword()} returns - * true. - * - * @return Clear-text password. - * @throws Exception If decryption fails - */ - public String decryptPassword() throws Exception { - return CipherUtil.decrypt(password); - } -}
\ No newline at end of file diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointTransport.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointTransport.java deleted file mode 100644 index 56019c9..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerEndpointTransport.java +++ /dev/null @@ -1,96 +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; - -/** - * Model for message passed by backend to frontend about ECOMP-C Endpoints. - */ -public class ControllerEndpointTransport extends ECTransportModel { - - private boolean selected; - private String name; - private String url; - private String inventoryUrl; - private String dhandlerUrl; - private String consulUrl; - - public ControllerEndpointTransport() { - } - - public ControllerEndpointTransport(boolean selected, String name, String url, String inventoryUrl, - String dhandlerUrl, String consulUrl) { - this.selected = selected; - this.name = name; - this.url = url; - this.inventoryUrl = inventoryUrl; - this.dhandlerUrl = dhandlerUrl; - this.consulUrl = consulUrl; - } - - public boolean getSelected() { - return selected; - } - - public void setSelected(boolean selected) { - this.selected = selected; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getInventoryUrl() { - return inventoryUrl; - } - - public void setInventoryUrl(String inventoryUrl) { - this.inventoryUrl = inventoryUrl; - } - - public String getDhandlerUrl() { - return dhandlerUrl; - } - - public void setDhandlerUrl(String dhandlerUrl) { - this.dhandlerUrl = dhandlerUrl; - } - - public String getConsulUrl() { - return consulUrl; - } - - public void setConsulUrl(String consulUrl) { - this.consulUrl = consulUrl; - } -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerOpsTools.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerOpsTools.java deleted file mode 100644 index 1bc8702..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ControllerOpsTools.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; - -/** - * Model for message passed by backend to frontend about OPS Tools URLs. - */ -public class ControllerOpsTools extends ECTransportModel { - - private String id; - private String url; - - public ControllerOpsTools() { - } - - public ControllerOpsTools(String id, String url) { - this.setId(id); - this.setUrl(url); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprint.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyBlueprint.java index d9fa528..bdb920d 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprint.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyBlueprint.java @@ -19,10 +19,12 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; import java.util.Map; +import org.onap.ccsdk.dashboard.model.ECTransportModel; + import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -32,30 +34,30 @@ 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; + /** 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; - } + @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/CloudifyBlueprintList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyBlueprintList.java index 6238e22..faee797 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyBlueprintList.java @@ -1,4 +1,3 @@ - /******************************************************************************* * =============LICENSE_START========================================================= * @@ -20,46 +19,46 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; +import org.onap.ccsdk.dashboard.model.ECTransportModel; + 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 new file mode 100644 index 0000000..a895dd0 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployedTenant.java @@ -0,0 +1,99 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * 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. + * ============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; + +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; + 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) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((created_at == null) ? 0 : created_at.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((tenant_name == null) ? 0 : tenant_name.hashCode()); + result = prime * result + ((updated_at == null) ? 0 : updated_at.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CloudifyDeployedTenant other = (CloudifyDeployedTenant) obj; + if (created_at == null) { + if (other.created_at != null) + return false; + } else if (!created_at.equals(other.created_at)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (tenant_name == null) { + if (other.tenant_name != null) + return false; + } else if (!tenant_name.equals(other.tenant_name)) + return false; + if (updated_at == null) { + if (other.updated_at != null) + return false; + } 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/CloudifyDeployedTenantList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployedTenantList.java index 155f415..96a91b6 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployedTenantList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployedTenantList.java @@ -19,44 +19,44 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; +import org.onap.ccsdk.dashboard.model.ECTransportModel; + 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 new file mode 100644 index 0000000..94ccf7d --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeployment.java @@ -0,0 +1,219 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * 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. + * ============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; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model with fields only for the top-level attributes. All complex child + * structures are represented simply as generic collections. + */ +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; + + /** internal role based setting */ + public boolean canDeploy; + + /** latest execution object */ + public CloudifyExecution lastExecution; + /** install execution workflow status */ + //public String installStatus; + /** true if helm plugin is used */ + public Boolean isHelm; + /** true if helm status is enabled */ + public Boolean helmStatus; + /** Consul service health status */ + public String healthStatus; + /** 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) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((tenant_name == null) ? 0 : tenant_name.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CloudifyDeployment other = (CloudifyDeployment) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (tenant_name == null) { + if (other.tenant_name != null) + return false; + } 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/CloudifyDeployedTenant.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentExt.java index 624c41a..3f906d1 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeployedTenant.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentExt.java @@ -19,25 +19,28 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import org.onap.ccsdk.dashboard.model.ECTransportModel; -public class CloudifyDeployedTenant extends ECTransportModel { +public class CloudifyDeploymentExt extends ECTransportModel { /** A unique identifier for the deployment. */ - public final String id; - /** tenant where the deployment was done */ - public final String tenant_name; - /** The id of the blueprint the deployment is based on. */ - public final String blueprint_id; - - @JsonCreator - public CloudifyDeployedTenant(@JsonProperty("id") String id, @JsonProperty("blueprint_id") String blueprint_id, - @JsonProperty("tenant_name") String tenant_name) { + public String id; + /** blueprint ID for the deployment */ + public String bp_id; + public String tenant; + /** latest execution object */ + public CloudifyExecution lastExecution; + /** true if helm plugin is used */ + 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; - this.blueprint_id = blueprint_id; - this.tenant_name = tenant_name; + this.bp_id = bp_id; + this.tenant = tenant; } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/EcdAppComponent.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentHelm.java index 28eb6f0..9e4d122 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/EcdAppComponent.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentHelm.java @@ -2,7 +2,7 @@ * =============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. @@ -19,25 +19,24 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; -import java.util.List; +package org.onap.ccsdk.dashboard.model.cloudify; -import org.onap.ccsdk.dashboard.domain.EcdComponent; +public class CloudifyDeploymentHelm { -public class EcdAppComponent { - - public String app; - - public List<EcdComponent> comps; - - /* - * @JsonCreator public EcdAppComponent(@JsonProperty("app") String app, - * - * @JsonProperty("comps") List<EcdComponent> comps) { this(app, comps); } - */ - public EcdAppComponent(String app, List<EcdComponent> comps) { - this.app = app; - this.comps = comps; + /** A unique identifier for the deployment. */ + public String id; + /** true if helm plugin is used */ + 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/CloudifySecretList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentList.java index 5a30163..4f83648 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifySecretList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyDeploymentList.java @@ -19,44 +19,46 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; +import org.onap.ccsdk.dashboard.model.ECTransportModel; + import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -public class CloudifySecretList extends ECTransportModel { - public final List<CloudifySecret> items; - public final Metadata metadata; +public class CloudifyDeploymentList extends ECTransportModel { + + public final List<CloudifyDeployment> items; + public final Metadata metadata; @JsonCreator - public CloudifySecretList(@JsonProperty("items") List<CloudifySecret> 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/CloudifyErrorCause.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyErrorCause.java index bca8fb3..8f6599c 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyErrorCause.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyErrorCause.java @@ -19,33 +19,37 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; + +import org.onap.ccsdk.dashboard.model.ECTransportModel; import com.fasterxml.jackson.annotation.JsonCreator; 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 new file mode 100644 index 0000000..a6593ab --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyEvent.java @@ -0,0 +1,98 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * 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. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model.cloudify; + +import java.util.LinkedList; +import java.util.List; + +import org.onap.ccsdk.dashboard.model.ECTransportModel; + +import com.fasterxml.jackson.annotation.JsonCreator; +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; + + @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; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyEventList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyEventList.java index f5d596f..dc0052b 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyEventList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyEventList.java @@ -19,45 +19,45 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; +import org.onap.ccsdk.dashboard.model.ECTransportModel; + import com.fasterxml.jackson.annotation.JsonCreator; 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 new file mode 100644 index 0000000..366a43d --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecution.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * 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. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model.cloudify; + +import java.util.Map; + +import org.onap.ccsdk.dashboard.model.ECTransportModel; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Model with fields only for the top-level attributes. All complex child + * structures are represented simply as generic collections. + */ +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; + + @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; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecutionList.java index c53b314..9592179 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyExecutionList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecutionList.java @@ -19,46 +19,46 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; +import org.onap.ccsdk.dashboard.model.ECTransportModel; + 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 new file mode 100644 index 0000000..41b034c --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyExecutionRequest.java @@ -0,0 +1,105 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * 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. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model.cloudify; + +import java.util.Map; + +import org.onap.ccsdk.dashboard.model.ECTransportModel; + +import com.fasterxml.jackson.annotation.JsonCreator; +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; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeId.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeId.java index 6352f40..da517b1 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeId.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeId.java @@ -19,18 +19,20 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; + +import org.onap.ccsdk.dashboard.model.ECTransportModel; 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/CloudifyNodeIdList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeIdList.java index f384a6f..53bde24 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeIdList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeIdList.java @@ -19,7 +19,7 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; @@ -28,36 +28,34 @@ 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/CloudifyNodeInstance.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstance.java index c89079d..2b17e77 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstance.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstance.java @@ -19,26 +19,27 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; -import java.util.List; import java.util.Map; +import org.onap.ccsdk.dashboard.model.ECTransportModel; + import com.fasterxml.jackson.annotation.JsonCreator; 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; + /** 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; - } + @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/CloudifyBlueprintContent.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceId.java index ca24849..1775b65 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintContent.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceId.java @@ -19,25 +19,25 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; + +import org.onap.ccsdk.dashboard.model.ECTransportModel; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** - * Trivial wrapper for Blueprint YAML content. + * Model with fields only for the top-level attributes. All complex child + * structures are represented as generic collections. */ -public final class CloudifyBlueprintContent extends ECTransportModel { - - /** A unique identifier for the blueprint. */ - public final String id; - /** The content of the blueprint as YAML */ - public final String content; +public final class CloudifyNodeInstanceId extends ECTransportModel { - @JsonCreator - public CloudifyBlueprintContent(@JsonProperty("id") String id, @JsonProperty("content") String content) { - this.id = id; - this.content = content; - } + /** 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/CloudifyNodeInstanceIdList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceIdList.java index 423abe2..1909bf6 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceIdList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceIdList.java @@ -1,4 +1,3 @@ - /******************************************************************************* * =============LICENSE_START========================================================= * @@ -20,46 +19,46 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; +import org.onap.ccsdk.dashboard.model.ECTransportModel; + 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/CloudifyNodeInstanceList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceList.java index 1813e5c..adf005c 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyNodeInstanceList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyNodeInstanceList.java @@ -19,45 +19,45 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; +import org.onap.ccsdk.dashboard.model.ECTransportModel; + import com.fasterxml.jackson.annotation.JsonCreator; 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/CloudifyBlueprintUpload.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyPlugin.java index a77e974..c79126c 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyBlueprintUpload.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyPlugin.java @@ -19,37 +19,40 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -/** - * Model for message POST-ed to controller to create a Cloudify Blueprint: - * - * <pre> - { - "blueprint_id" : "blueprint-id", - "blueprint_filename" : "name.yaml", - "zip_url" : "url" - } - * </pre> +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 class CloudifyBlueprintUpload extends ECTransportModel { - - /** A unique identifier for the blueprint. */ - public final String blueprint_id; - /** The blueprint’s main file name. */ - public final String blueprint_filename; - /** The zip file URL. */ - public final String zip_url; - + 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 CloudifyBlueprintUpload(@JsonProperty("blueprint_id") String blueprint_id, - @JsonProperty("blueprint_filename") String blueprint_filename, @JsonProperty("zip_url") String zip_url) { - this.blueprint_id = blueprint_id; - this.blueprint_filename = blueprint_filename; - this.zip_url = zip_url; + 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; + this.distribution = distribution; + this.uploaded_at = uploaded_at; } - } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyPluginList.java index 4dfef1e..8930fd4 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyDeploymentList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyPluginList.java @@ -19,21 +19,21 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; +import org.onap.ccsdk.dashboard.model.ECTransportModel; + import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -public class CloudifyDeploymentList extends ECTransportModel { - - public final List<CloudifyDeployment> items; +public class CloudifyPluginList extends ECTransportModel { + public final List<CloudifyPlugin> items; public final Metadata metadata; @JsonCreator - public CloudifyDeploymentList(@JsonProperty("items") List<CloudifyDeployment> items, - @JsonProperty("metadata") Metadata metadata) { + public CloudifyPluginList(@JsonProperty("items") List<CloudifyPlugin> items, @JsonProperty("metadata") Metadata metadata){ this.items = items; this.metadata = metadata; } @@ -42,23 +42,21 @@ public class CloudifyDeploymentList 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 new file mode 100644 index 0000000..d087ce3 --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifySecret.java @@ -0,0 +1,80 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * 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. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model.cloudify; + +import org.onap.ccsdk.dashboard.model.ECTransportModel; + +import com.fasterxml.jackson.annotation.JsonCreator; +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 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 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; + } + + /** + * @return the key + */ + public String getKey() { + return key; + } + + /** + * @return the value + */ + public String getValue() { + return value; + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyTenant.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyTenant.java index b885936..53f5149 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyTenant.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyTenant.java @@ -19,25 +19,29 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; + + +import org.onap.ccsdk.dashboard.model.ECTransportModel; import com.fasterxml.jackson.annotation.JsonCreator; 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/CloudifyTenantList.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyTenantList.java index c7f8530..4610b9e 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/CloudifyTenantList.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/CloudifyTenantList.java @@ -19,44 +19,44 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.cloudify; import java.util.List; +import org.onap.ccsdk.dashboard.model.ECTransportModel; + 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/inventory/ServiceGroupByResults.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/ServiceRefCfyList.java index d8e6e8b..10c9bea 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceGroupByResults.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/cloudify/ServiceRefCfyList.java @@ -19,24 +19,31 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model.inventory; +package org.onap.ccsdk.dashboard.model.cloudify; -import java.util.Set; +import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -public class ServiceGroupByResults { +public class ServiceRefCfyList { + /** Number of Service objects */ + public final Integer totalCount; + /** Collection containing all of the returned Service objects */ + public final Collection<CloudifyDeployedTenant> items; - /** Property name of the service that the group by operation was performed on */ - public String propertyName; - /** Set of Service objects that have the aforementioned propertyName */ - public Set<InventoryProperty> propertyValues; + /** + * @return the items + */ + public Collection<CloudifyDeployedTenant> getItems() { + return items; + } @JsonCreator - public ServiceGroupByResults(@JsonProperty("propertyName") String propertyName, - @JsonProperty("propertyValues") Set<InventoryProperty> propertyValues) { - this.propertyName = propertyName; - this.propertyValues = propertyValues; + 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/ConsulDatacenter.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulDatacenter.java index 1e57b12..e95cdb1 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulDatacenter.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulDatacenter.java @@ -19,7 +19,9 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +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; 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 new file mode 100644 index 0000000..6837b8d --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulDeploymentHealth.java @@ -0,0 +1,111 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * 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. + * ============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; + this.checkID = checkID; + this.name = name; + this.status = status; + this.serviceID = serviceID; + this.serviceName = serviceName; + } + + public String getNode() { + return node; + } + + public String getCheckID() { + return checkID; + } + + public String getName() { + return name; + } + + public String getStatus() { + return status; + } + + public String getServiceID() { + return serviceID; + } + + public String getServiceName() { + return serviceName; + } + + public static class Builder { + private final String node; + private final String checkID; + private final String name; + private final String status; + private final String serviceID; + private final String serviceName; + + public Builder(ConsulServiceHealth input) { + this.node = input.node; + this.checkID = input.checkID; + this.name = input.name; + this.status = input.status; + this.serviceID = input.serviceID; + this.serviceName = input.serviceName; + } + + public ConsulDeploymentHealth build() { + return new ConsulDeploymentHealth(node, checkID, name,status, serviceID, serviceName); + } + + public String getNode() { + return node; + } + + public String getCheckID() { + return checkID; + } + + public String getName() { + return name; + } + + public String getStatus() { + return status; + } + + public String getServiceID() { + return serviceID; + } + + public String getServiceName() { + return serviceName; + } + } +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulHealthServiceRegistration.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulHealthServiceRegistration.java index 5612b6d..76f9491 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulHealthServiceRegistration.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulHealthServiceRegistration.java @@ -19,10 +19,12 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +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; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulNodeInfo.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulNodeInfo.java index 7122a52..3cbf3e0 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulNodeInfo.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulNodeInfo.java @@ -19,10 +19,12 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +package org.onap.ccsdk.dashboard.model.consul; import java.util.Map; +import org.onap.ccsdk.dashboard.model.ECTransportModel; + import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; 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 new file mode 100644 index 0000000..a5bfc3d --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceCatalogItem.java @@ -0,0 +1,71 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * 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. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model.consul; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ConsulServiceCatalogItem { + + public final String node; + public final String address; + public final String datacenter; + public final String serviceName; + public final String serviceAddress; + 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 ) { + this.node = node; + this.address = address; + this.datacenter = datacenter; + this.serviceName = serviceName; + this.serviceAddress = serviceAddress; + this.servicePort = servicePort; + } + + public String getNode() { + return node; + } + + public String getAddress() { + return address; + } + + public String getDatacenter() { + return datacenter; + } + + public String getServiceName() { + return serviceName; + } + + public String getServiceAddress() { + return serviceAddress; + } + + public String getServicePort() { + return servicePort; + } + +} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceHealth.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceHealth.java index 5f3876a..1c0cb35 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceHealth.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceHealth.java @@ -19,7 +19,9 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +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; @@ -53,6 +55,8 @@ public final class ConsulServiceHealth extends ECTransportModel { public final String output; public final String serviceID; public final String serviceName; + public final String[] serviceTags; + public String tenant; public final int createIndex; public final int modifyIndex; @@ -61,7 +65,7 @@ public final class ConsulServiceHealth extends ECTransportModel { @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("CreateIndex") int createIndex, @JsonProperty("ModifyIndex") int modifyIndex) { + @JsonProperty("ServiceTags") String[] serviceTags, @JsonProperty("CreateIndex") int createIndex, @JsonProperty("ModifyIndex") int modifyIndex) { this.node = node; this.checkID = checkID; this.name = name; @@ -70,8 +74,28 @@ public final class ConsulServiceHealth extends ECTransportModel { this.output = output; this.serviceID = serviceID; this.serviceName = serviceName; + this.serviceTags = serviceTags; this.createIndex = createIndex; 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 = ""; } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceHealthHistory.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceHealthHistory.java index 42e1fd2..a3f0cf9 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceHealthHistory.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceHealthHistory.java @@ -19,7 +19,9 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +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; diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceInfo.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceInfo.java index bb04a66..7f34bdb 100644 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/ConsulServiceInfo.java +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/consul/ConsulServiceInfo.java @@ -20,10 +20,12 @@ * ECOMP is a trademark and service mark of AT&T Intellectual Property. *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; +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; 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 7e93d9c..33dfb6a 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 @@ -21,6 +21,8 @@ *******************************************************************************/ package org.onap.ccsdk.dashboard.model.deploymenthandler; +import java.util.Collection; +import java.util.LinkedList; import java.util.Map; import java.util.Optional; @@ -77,11 +79,32 @@ 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("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; @@ -89,6 +112,13 @@ public class DeploymentInput { this.blueprintId = Optional.ofNullable(blueprintId); this.inputs = inputs; this.tenant = tenant; + this.reinstall_list = (reinstallList == null) ? new LinkedList<String>() : reinstallList; + this.skip_install = skipInstall; + this.skip_uninstall = skipUninstall; + this.skip_reinstall = skipReinstall; + this.force = force; + this.ignore_failure = ignoreFailure; + this.install_first = installFirst; } public String getBlueprintName() { @@ -118,4 +148,32 @@ public class DeploymentInput { public Optional<String> getBlueprintId() { return blueprintId; } + + public Collection<String> getReinstall_list() { + return reinstall_list; + } + + public boolean isSkip_install() { + return skip_install; + } + + public boolean isSkip_uninstall() { + return skip_uninstall; + } + + public boolean isSkip_reinstall() { + return skip_reinstall; + } + + public boolean isForce() { + return force; + } + + public boolean isIgnore_failure() { + return ignore_failure; + } + + public boolean isInstall_first() { + return install_first; + } } 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 b0ac9e9..94bb064 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 @@ -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; } @@ -72,4 +72,5 @@ public class DeploymentRequest { public Map<String, Object> getInputs() { return this.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 ae229b2..0bb6f74 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 @@ -21,7 +21,11 @@ *******************************************************************************/ 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; @@ -69,15 +73,60 @@ 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("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; this.tenant = tenant; this.method = method; + this.reinstall_list = (reinstallList == null) ? new LinkedList<String>() : reinstallList; + this.skip_install = skipInstall; + this.skip_uninstall = skipUninstall; + this.skip_reinstall = skipReinstall; + this.force = force; + this.ignore_failure = ignoreFailure; + this.install_first = installFirst; + } + + public DeploymentRequestObject(String deploymentId, String serviceTypeId, String method, + Map<String, Object> inputs, String tenant) { + super(); + this.deploymentId = deploymentId; + this.method = method; + this.serviceTypeId = serviceTypeId; + this.tenant = tenant; + this.inputs = inputs; + this.reinstall_list = null; + this.skip_install = true; + this.skip_uninstall = true; + this.skip_reinstall = true; + this.force = false; + this.ignore_failure = true; + this.install_first = false; } public String getDeploymentId() { @@ -99,4 +148,32 @@ public class DeploymentRequestObject { public String getMethod() { return method; } + + public Collection<String> getReinstall_list() { + return reinstall_list; + } + + public boolean isSkip_install() { + return skip_install; + } + + public boolean isSkip_uninstall() { + return skip_uninstall; + } + + public boolean isSkip_reinstall() { + return skip_reinstall; + } + + public boolean isForce() { + return force; + } + + public boolean isIgnore_failure() { + return ignore_failure; + } + + public boolean isInstall_first() { + return install_first; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/InventoryDeploymentRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/InventoryDeploymentRequest.java deleted file mode 100644 index 173744a..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/deploymenthandler/InventoryDeploymentRequest.java +++ /dev/null @@ -1,87 +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.deploymenthandler; - -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Model for message used by the controller to create a DeploymentRequest for - * the Deployment Handler API. - * - * <pre> - { - "deploymentId" : "deploymentId", - "body" : - { - "serviceTypeId" : "serviceTypeId", - "inputs" : - { - "input1" : "parameter1" - "input2" : "parameter2" - ... - "inputn" : "parametern" - } - } - } - * </pre> - */ -public final class InventoryDeploymentRequest { - - /** Unique deployment identifier assigned by the API client. */ - private final String deploymentId; - - /** - * The service type identifier (a unique ID assigned by DCAE inventory) for the - * service to be deployed. - */ - private final String serviceTypeId; - - /** - * Object containing inputs needed by the service blueprint to create an - * instance of the service. Content of the object depends on the service being - * deployed. - */ - private final Map<String, Object> inputs; - - @JsonCreator - public InventoryDeploymentRequest(@JsonProperty("deploymentId") String deploymentId, - @JsonProperty("serviceTypeId") String serviceTypeId, @JsonProperty("inputs") Map<String, Object> inputs) { - this.deploymentId = deploymentId; - this.serviceTypeId = serviceTypeId; - this.inputs = inputs; - } - - public String getDeploymentId() { - return this.deploymentId; - } - - public String getServiceTypeId() { - return this.serviceTypeId; - } - - public Map<String, Object> getInputs() { - return this.inputs; - } -} 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 70f5fd5..184e0fb 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 @@ -32,6 +32,7 @@ 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) @@ -39,6 +40,7 @@ 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/Service.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/Service.java index 3631623..dc1daa7 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 @@ -57,7 +57,15 @@ public class Service { private Optional<Boolean> canDeploy; /** tenant name for this service */ private String tenant; - + /** install execution workflow status */ + private String installStatus; + /** true if helm plugin is used */ + public Boolean isHelm; + /** true if helm status is enabled */ + 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, @@ -165,4 +173,36 @@ public class Service { * public ServiceRef build() { return new ServiceRef(serviceId, created, * modified); } } */ + + public String getInstallStatus() { + return installStatus; + } + + public void setInstallStatus(String installStatus) { + this.installStatus = installStatus; + } + + public Boolean getIsHelm() { + return isHelm; + } + + public void setIsHelm(Boolean isHelm) { + this.isHelm = isHelm; + } + + public Boolean getHelmStatus() { + return helmStatus; + } + + public void setHelmStatus(Boolean helmStatus) { + this.helmStatus = helmStatus; + } + + public String getHealthStatus() { + return this.healthStatus; + } + + public void setHealthStatus(String healthStatus) { + this.healthStatus = healthStatus; + } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponentRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponentRequest.java deleted file mode 100644 index 123392b..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceComponentRequest.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.inventory; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class ServiceComponentRequest { - - /** Component ID of the Service Component */ - public String componentId; - /** Component Type of the Service Component */ - public String componentType; - /** - * Specifies the name of the underlying source service responsible for this - * component - */ - public String componentSource; - /** - * Used to determine if this component can be shared amongst different Services - */ - public Integer shareable; - - @JsonCreator - public ServiceComponentRequest(@JsonProperty("componentId") String componentId, - @JsonProperty("componentType") String componentType, - @JsonProperty("componentSource") String componentSource, @JsonProperty("shareable") Integer shareable) { - this.componentId = componentId; - this.componentType = componentType; - this.componentSource = componentSource; - this.shareable = shareable; - } - - public static ServiceComponentRequest from(ServiceComponent sc) { - return new ServiceComponentRequest(sc.componentId, sc.componentType, sc.componentSource, sc.shareable); - } -} 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 f338d28..7b70e1c 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 @@ -27,21 +27,25 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class ServiceRef { /** Service ID of the Service */ - private final String serviceId; + public final String id; /** Creation date of the Service */ - private final String created; + public final String created_at; /** Last modified date of the Service */ - private final String modified; - + public final String updated_at; + public final String tenant_name = ""; + @JsonCreator - public ServiceRef(@JsonProperty("serviceId") String serviceId, @JsonProperty("created") String created, - @JsonProperty("modified") String modified) { - this.serviceId = serviceId; - this.created = created; - this.modified = 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; } @@ -53,7 +57,7 @@ public class ServiceRef { 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 d9491d9..def0e0a 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 @@ -23,6 +23,8 @@ 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; @@ -30,6 +32,7 @@ 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<ServiceRef> items; @JsonCreator diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRequest.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRequest.java deleted file mode 100644 index 46b3351..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceRequest.java +++ /dev/null @@ -1,77 +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.inventory; - -import java.util.ArrayList; -import java.util.Collection; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class ServiceRequest { - - /** ID of the associated service type */ - public String typeId; - /** Id of the associated VNF that this service is monitoring */ - public String vnfId; - /** The type of the associated VNF that this service is monitoring */ - public String vnfType; - /** Location identifier of the associated VNF that this service is monitoring */ - public String vnfLocation; - /** Reference to a Cloudify deployment */ - public String deploymentRef; - /** - * Collection of ServiceComponentRequest objects that this service is composed - * of - */ - public Collection<ServiceComponentRequest> components; - - @JsonCreator - public ServiceRequest(@JsonProperty("typeId") String typeId, @JsonProperty("vnfId") String vnfId, - @JsonProperty("vnfType") String vnfType, @JsonProperty("vnfLocation") String vnfLocation, - @JsonProperty("deploymentRef") String deploymentRef, - @JsonProperty("components") Collection<ServiceComponentRequest> components) { - this.typeId = typeId; - this.vnfId = vnfId; - this.vnfType = vnfType; - this.vnfLocation = vnfLocation; - this.deploymentRef = deploymentRef; - this.components = components; - } - - public static ServiceRequest from(String typeId, Service service) { - - // Convert the Collection<ServiceComponent> in service to - // Collection<ServiceComponentRequest> for serviceRequest - final Collection<ServiceComponent> serviceComponents = service.getComponents(); - final Collection<ServiceComponentRequest> serviceComponentRequests = new ArrayList<ServiceComponentRequest>(); - - if (serviceComponents != null) { - for (ServiceComponent sc : serviceComponents) { - serviceComponentRequests.add(ServiceComponentRequest.from(sc)); - } - } - - return new ServiceRequest(typeId, service.getVnfId(), service.getVnfType(), service.getVnfLocation(), - service.getDeploymentRef(), serviceComponentRequests); - } -} 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 4af4cb1..f1351fc 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 @@ -237,8 +237,9 @@ public class ServiceType { this.blueprintInputs = bpObj.getInputs(); this.blueprintDescription = bpObj.getDescription(); } catch (BlueprintParseException e) { -/* 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); } } 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 8d98d9d..7b733ee 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 @@ -33,9 +33,10 @@ public class ServiceTypeQueryParams { private final String asdcResourceId; private final String application; private final String component; + private final String owner; // Non-instantiable - private ServiceTypeQueryParams() { + private ServiceTypeQueryParams(org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummary.Builder builder) { this.typeName = null; this.onlyLatest = null; this.onlyActive = null; @@ -46,11 +47,12 @@ public class ServiceTypeQueryParams { this.asdcResourceId = null; this.application = null; this.component = null; + 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 component, String owner) { this.typeName = typeName; this.onlyLatest = onlyLatest; this.onlyActive = onlyActive; @@ -61,6 +63,7 @@ public class ServiceTypeQueryParams { this.asdcResourceId = asdcResourceId; this.application = application; this.component = component; + this.owner = owner; } public static class Builder { @@ -74,7 +77,13 @@ public class ServiceTypeQueryParams { private String asdcResourceId; private String application; private String component; + private String owner; + public Builder owner(String owner) { + this.owner = owner; + return this; + } + public Builder typeName(String typeName) { this.typeName = typeName; return this; @@ -115,9 +124,18 @@ public class ServiceTypeQueryParams { return this; } + public Builder application(String application) { + 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); + asdcServiceId, asdcResourceId, application, component, owner); } } @@ -160,4 +178,8 @@ 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 533571b..84efcb8 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 @@ -100,6 +100,16 @@ public class ServiceTypeRequest { this.asdcResourceId = asdcResourceId; this.asdcServiceURL = asdcServiceURL; } + + public ServiceTypeRequest(String owner, String typeName, Integer typeVersion, String blueprintTemplate, + String application, String component) { + this.owner = owner; + this.typeName = typeName; + this.typeVersion = typeVersion; + this.blueprintTemplate = blueprintTemplate; + this.application = application; + this.component = component; + } public static ServiceTypeRequest from(ServiceType serviceType) { return new ServiceTypeRequest(serviceType.getOwner(), serviceType.getTypeName(), serviceType.getTypeVersion(), @@ -107,7 +117,12 @@ public class ServiceTypeRequest { 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 efcdf3b..3b2f541 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,7 +2,7 @@ * =============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. @@ -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.model.inventory; @@ -28,11 +27,11 @@ public class ServiceTypeServiceMap { private final String serviceTypeId; - private final ServiceRefList serviceRefList; + private final Object serviceRefList; @JsonCreator public ServiceTypeServiceMap(@JsonProperty("serviceTypeId") String serviceTypeId, - @JsonProperty("created") ServiceRefList serviceRefList) { + @JsonProperty("serviceRefList") Object serviceRefList) { this.serviceTypeId = serviceTypeId; this.serviceRefList = serviceRefList; } @@ -41,7 +40,7 @@ public class ServiceTypeServiceMap { return serviceTypeId; } - public ServiceRefList getServiceRefList() { + public Object getServiceRefList() { return 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 new file mode 100644 index 0000000..877a8ed --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeSummary.java @@ -0,0 +1,239 @@ +/******************************************************************************* + * =============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.inventory; + +import java.util.Optional; + +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.dashboard.model.cloudify.ServiceRefCfyList; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author rp5662 + * + */ +public class ServiceTypeSummary { + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "ServiceTypeSummary [owner=" + owner + ", typeName=" + typeName + ", typeVersion=" + + typeVersion + ", component=" + component + ", typeId=" + typeId + ", created=" + + created + "]"; + } + + /** Owner of the ServiceType */ + private final String owner; + + /** Name of the ServiceType */ + private final String typeName; + + /** Version number for this ServiceType */ + private final Integer typeVersion; + + /** 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) { + + this.owner = owner; + this.typeName = typeName; + this.typeVersion = typeVersion; + this.application = application; + this.component = component; + this.typeId = Optional.ofNullable(typeId); + this.created = Optional.ofNullable(created); + this.canDeploy = Optional.of(false); + this.expanded = Optional.of(false); + } + + private ServiceTypeSummary(Builder builder) { + this.typeName = builder.typeName; + this.owner = builder.owner; + this.typeVersion = builder.typeVersion; + this.typeId = builder.typeId; + this.application = builder.application; + this.component = builder.component; + this.created = builder.created; + this.canDeploy = builder.canDeploy; + } + + public static class Builder { + private String owner; + private String typeName; + private Integer typeVersion; + private String application; + private String component; + 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; + } + + public Builder typeName(String typeName) { + this.typeName = typeName; + return this; + } + + public Builder typeVersion(Integer typeVersion) { + 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; + } + + public String getOwner() { + return owner; + } + + public Integer getTypeVersion() { + return typeVersion; + } + + public String getApplication() { + return application; + } + + public String getComponent() { + return component; + } + + public Optional<String> getTypeId() { + return typeId; + } + + public Optional<String> getCreated() { + return created; + } + + public Optional<Boolean> getCanDeploy() { + return canDeploy; + } + + public void setCanDeploy(Optional<Boolean> canDeploy) { + this.canDeploy = canDeploy; + } + + public ServiceRefCfyList getDeployments() { + return deployments; + } + + 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)) { + return true; + } + return false; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((typeId == null) ? 0 : typeId.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ServiceTypeSummary other = (ServiceTypeSummary) obj; + if (typeId == null) { + if (other.typeId != null) + return false; + } else if (!typeId.equals(other.typeId)) + return false; + return true; + } + +} 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 new file mode 100644 index 0000000..149e75b --- /dev/null +++ b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/model/inventory/ServiceTypeSummaryList.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * 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. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ +package org.onap.ccsdk.dashboard.model.inventory; + +import java.util.Collection; + +import org.onap.ccsdk.dashboard.model.ECTransportModel; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceTypeSummaryList extends ECTransportModel { + + /** Number of ServiceType objects */ + public final Integer totalCount; + /** Collection containing all of the returned ServiceType objects */ + public final Collection<ServiceTypeSummary> items; + /** Links to the previous and next page of items */ + public final PaginationLinks paginationLinks; + + @JsonCreator + public ServiceTypeSummaryList( + @JsonProperty("items") Collection<ServiceTypeSummary> items, + @JsonProperty("totalCount") Integer totalCount, + @JsonProperty("links") PaginationLinks paginationLinks) { + this.items = items; + this.totalCount = totalCount; + this.paginationLinks = paginationLinks; + } + + /** InlineResponse200Links */ + public static final class PaginationLinks { + public final Link previousLink; + public final Link nextLink; + + @JsonCreator + public PaginationLinks(@JsonProperty("previousLink") Link previousLink, + @JsonProperty("nextLink") Link nextLink) { + this.previousLink = previousLink; + this.nextLink = nextLink; + } + } +} 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 1ffab54..04a084e 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 @@ -21,20 +21,26 @@ *******************************************************************************/ package org.onap.ccsdk.dashboard.rest; +import java.util.List; import java.util.Map; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateResponse; -import org.onap.ccsdk.dashboard.model.CloudifyEventList; -import org.onap.ccsdk.dashboard.model.CloudifyExecution; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; -import org.onap.ccsdk.dashboard.model.CloudifyTenantList; +import javax.servlet.http.HttpServletRequest; + +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyBlueprintList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployment; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentExt; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentHelm; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyEventList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionList; +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; /** * @author rp5662 @@ -51,7 +57,7 @@ public interface CloudifyClient { /** * Gets the list of Cloudify tenants. * - * @return CloudifyBlueprintList + * @return CloudifyTenantList */ public CloudifyTenantList getTenants(); @@ -85,13 +91,6 @@ public interface CloudifyClient { public CloudifyNodeInstanceIdList getNodeInstanceId(String deploymentId, String nodeId, String tenant); /** - * Gets all the deployments with include filters for tenant name - * - * @return List of CloudifyDeployedTenant objects - */ - public CloudifyDeployedTenantList getTenantInfoFromDeploy(String tenant); - - /** * Get the node-instance-id. * * @param deploymentId deployment ID @@ -102,14 +101,6 @@ public interface CloudifyClient { public CloudifyNodeInstanceIdList getNodeInstanceId(String id, String tenant); /** - * Initiate a deployment update in cloudify - * - * @param execution - * @return - */ - public CloudifyDeploymentUpdateResponse updateDeployment(CloudifyDeploymentUpdateRequest execution); - - /** * Query execution information for a deployment ID passed as input * * @param deploymentId @@ -167,7 +158,21 @@ public interface CloudifyClient { * Query deployments from cloudify * */ - public CloudifyDeploymentList getDeployments(); + 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" + * @param inputKey + * @param inputValue + * @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; /** * Query a blueprint object matching the blueprint ID in cloudify @@ -186,4 +191,70 @@ public interface CloudifyClient { * @return */ public CloudifyDeploymentList getDeploymentInputs(String id, String tenant); + + /** + * Query a cloudify secret under a tenant scope + * + * @param secretName + * @param tenant + * @return + */ + public CloudifySecret getSecret(String secretName, String tenant); + + /** + * Query install workflow execution summary for a deployment ID + * + * @param deploymentId + * @param tenant + * @return + */ + public CloudifyExecutionList getInstallExecutionSummary(String deploymentId, String tenant); + + /** + * + * Delete Blueprint + * + * @param blueprint ID + */ + public void deleteBlueprint(String bpName, String tenant); + /** + * + * Query deployment node instances + * + * @param deploymentId + * @param tenant + * @return + */ + public CloudifyNodeInstanceIdList getNodeInstances(String deploymentId, String tenant); + + public List<CloudifyDeployment> getDeployments(String tenant, int pageSize, int pageOffset, + boolean recurse); + + public List<CloudifyDeployment> getDeployments(String tenant, int pageSize, int pageOffset, + boolean recurse, boolean cache); + + public byte[] viewBlueprint(String tenant, String id); + + public void cacheDeployments(); + + public CloudifyDeployment getDeploymentResource(final String id, final String tenant); + + public List<CloudifyDeployment> getDeploymentsWithFilter(HttpServletRequest request) throws Exception; + + public CloudifyNodeInstanceList getNodeInstanceDetails(String deploymentId, String tenant); + + public List<CloudifyDeployedTenant> getDeploymentForBlueprint(final String bpId); + + public List<CloudifyDeploymentExt> updateWorkflowStatus(List<CloudifyDeployment> itemList); + + public List<CloudifyDeploymentHelm> updateHelmInfo(List<CloudifyDeployment> itemList); + + public List<String> getDeploymentNamesWithFilter(HttpServletRequest request) + throws Exception; + + public CloudifyPluginList getPlugins(); + + public CloudifyExecutionList getExecutionsSummaryPerTenant(String tenant); + + public CloudifyExecution getExecutionIdSummary(final String id, final String tenant); } 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 28bd87c..0e64ef0 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 @@ -23,32 +23,53 @@ package org.onap.ccsdk.dashboard.rest; import java.net.MalformedURLException; import java.net.URL; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; import java.util.Map; - +import java.util.Set; +import java.util.TreeSet; +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.model.CloudifyBlueprintList; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateResponse; -import org.onap.ccsdk.dashboard.model.CloudifyEventList; -import org.onap.ccsdk.dashboard.model.CloudifyExecution; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; -import org.onap.ccsdk.dashboard.model.CloudifyNodeIdList; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; -import org.onap.ccsdk.dashboard.model.CloudifyTenantList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyBlueprint; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyBlueprintList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenantList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployment; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentExt; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentHelm; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyEventList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionRequest; +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.util.DashboardProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.objectcache.AbstractCacheManager; +import org.onap.portalsdk.core.web.support.AppUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.scheduling.annotation.Scheduled; @org.springframework.stereotype.Service public class CloudifyRestClientImpl extends RestClientBase implements CloudifyClient { @@ -64,19 +85,35 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl private static final String NODE_INSTANCES = "node-instances"; private static final String UPDATE_DEPLOYMENT = "update-deployment"; private static final String EVENTS = "events"; - private static final String TENANT = "tenant_name"; + private static final String SECRETS = "secrets"; + private static final String SERVICE_ID = "service-list"; + private static final String PLUGINS = "plugins"; + + /** + * For caching data + */ + private AbstractCacheManager cacheManager; + + @Autowired + public void setCacheManager(AbstractCacheManager cacheManager) { + this.cacheManager = cacheManager; + } + public AbstractCacheManager getCacheManager() { + return cacheManager; + } + @PostConstruct public void init() { - String webapiUrl = DashboardProperties.getControllerProperty("dev", - DashboardProperties.CONTROLLER_SUBKEY_URL); + String webapiUrl = DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_URL); if (webapiUrl == null) { throw new IllegalArgumentException("Null URL not permitted"); } - String user = DashboardProperties.getControllerProperty("dev", - DashboardProperties.CONTROLLER_SUBKEY_USERNAME); - String pass = DashboardProperties.getControllerProperty("dev", - DashboardProperties.CONTROLLER_SUBKEY_PASS); + String user = DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_USERNAME); + String pass = DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_PASS); URL url = null; try { url = new URL(webapiUrl); @@ -90,6 +127,207 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl } } + @SuppressWarnings("unchecked") + public List<CloudifyDeploymentHelm> updateHelmInfo(List<CloudifyDeployment> itemList) { + boolean isHelm = false; + boolean helmStatus = false; + List<CloudifyDeploymentHelm> result = new ArrayList<>(); + for (CloudifyDeployment srvc : (List<CloudifyDeployment>) itemList) { + try { + isHelm = false; + helmStatus = false; + CloudifyBlueprintList bpList = + this.getBlueprint(srvc.blueprint_id, srvc.tenant_name); + Map<String, Object> bpPlan = bpList.items.get(0).plan; + Map<String, String> workflows = (Map<String, String>) bpPlan.get("workflows"); + Map<String, String> pluginInfo = + ((List<Map<String, String>>) bpPlan.get("deployment_plugins_to_install")) + .get(0); + if (pluginInfo.get("name").equals("helm-plugin")) { + isHelm = true; + } + if (workflows.containsKey("status")) { + helmStatus = true; + } + CloudifyDeploymentHelm cfyDeplHelm = + new CloudifyDeploymentHelm(srvc.id, isHelm, helmStatus); + result.add(cfyDeplHelm); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getBlueprint failed"); + CloudifyDeploymentHelm cfyDeplHelm = + new CloudifyDeploymentHelm(srvc.id, false, false); + result.add(cfyDeplHelm); + continue; + } + } + return result; + } + + public List<CloudifyDeploymentExt> updateWorkflowStatus(List<CloudifyDeployment> itemList) { + List<CloudifyDeploymentExt> result = new ArrayList<>(); + for (CloudifyDeployment srvc : (List<CloudifyDeployment>) itemList) { + try { + // find deployment execution info per item + 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); + result.add(cfyDeplExt); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getExecutionsSummary failed"); + srvc.lastExecution = null; + continue; + } + } + 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>() { + }); + 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"}); + 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>() { + }); + return response.getBody().items.get(0); + } + + @Scheduled(fixedRate=86400000, initialDelay=15000) + public void cacheTenants() { + logger.debug(EELFLoggerDelegate.debugLogger, "cacheTenants begin"); + CloudifyTenantList tenantsList = this.getTenants(); + ReadWriteLock lock = new ReentrantReadWriteLock(); + lock.writeLock().lock(); + getCacheManager().putObject(TENANTS, tenantsList.items); + lock.writeLock().unlock(); + logger.debug(EELFLoggerDelegate.debugLogger, "cacheTenants end"); + } + + @SuppressWarnings("unchecked") + @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>) getCacheManager().getObject(TENANTS); + lock.readLock().unlock(); + String cfyTen = ""; + if (tenantItems != null) { + for (CloudifyTenant item : tenantItems) { + cfyTen = item.name; + lock.readLock().lock(); + List<CloudifyDeployment> cfyDeplList = + (List<CloudifyDeployment>)getCacheManager(). + getObject(SERVICE_ID + ":" + cfyTen); + lock.readLock().unlock(); + if (cfyDeplList != null) { + List<CloudifyDeploymentExt> cfyDeplExecList = + this.updateWorkflowStatus(cfyDeplList); + lock.writeLock().lock(); + getCacheManager().putObject(SERVICE_ID + ":" + cfyTen + ":ext", cfyDeplExecList); + lock.writeLock().unlock(); + } + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "cacheDeploymentExecInfo end"); + } + + @SuppressWarnings("unchecked") + @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>) getCacheManager().getObject(TENANTS); + lock.readLock().unlock(); + String cfyTen = ""; + if (tenantItems != null) { + for (CloudifyTenant item : tenantItems) { + cfyTen = item.name; + lock.readLock().lock(); + List<CloudifyDeployment> cfyDeplList = + (List<CloudifyDeployment>)getCacheManager(). + getObject(SERVICE_ID + ":" + cfyTen); + lock.readLock().unlock(); + if (cfyDeplList != null) { + List<CloudifyDeploymentHelm> cfyDeplHelmList = + this.updateHelmInfo(cfyDeplList); + lock.writeLock().lock(); + getCacheManager().putObject(SERVICE_ID + ":" + cfyTen + ":helm", cfyDeplHelmList); + lock.writeLock().unlock(); + } + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "cacheDeploymentHelmInfo end"); + } + + @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>) getCacheManager().getObject(TENANTS); + lock.readLock().unlock(); + String cfyTen = "default_tenant"; + if (tenantItems != null) { + for (CloudifyTenant item : tenantItems) { + cfyTen = item.name; + 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(0).toString()}); + logger.debug(EELFLoggerDelegate.debugLogger, "cacheDeployments begin: url {}", url); + HttpEntity<String> entity = getTenantHeader(cfyTen); + ResponseEntity<CloudifyDeploymentList> response = + restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference<CloudifyDeploymentList>() {}); + List<CloudifyDeployment> cfyDeplList = new ArrayList<CloudifyDeployment>(); + cfyDeplList.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", + "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>() {}); + deplPgOffset += pageSize; + cfyDeplList.addAll(response.getBody().items); + } + lock.writeLock().lock(); + getCacheManager().putObject(SERVICE_ID + ":" + cfyTen, cfyDeplList); + lock.writeLock().unlock(); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "cacheDeployments done putting deployment data"); + } + @Override public CloudifyTenantList getTenants() { String url = buildUrl(new String[] { baseUrl, TENANTS }, null); @@ -124,6 +362,30 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl } @Override + public CloudifyNodeInstanceList getNodeInstanceDetails(String deploymentId, String tenant) { + 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>() { + }); + 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" }); + logger.debug(EELFLoggerDelegate.debugLogger, "getNodeInstanceId: url {}", url); + HttpEntity<String> entity = getTenantHeader(tenant); + 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" }); @@ -164,21 +426,20 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl } @Override - public CloudifyDeployedTenantList getTenantInfoFromDeploy(String tenant) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, - new String[] { "_include", "id,blueprint_id,tenant_name" }); - logger.debug(EELFLoggerDelegate.debugLogger, "getTenantInfoFromDeploy: url {}", url); + public CloudifyExecutionList getExecutions(final String deploymentId, final String tenant) { + 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<CloudifyDeployedTenantList> response = restTemplate.exchange(url, HttpMethod.GET, entity, - new ParameterizedTypeReference<CloudifyDeployedTenantList>() { + ResponseEntity<CloudifyExecutionList> response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference<CloudifyExecutionList>() { }); return response.getBody(); } @Override - public CloudifyExecutionList getExecutions(final String deploymentId, final String tenant) { - String url = buildUrl(new String[] { baseUrl, EXECUTIONS }, new String[] { "deployment_id", deploymentId }); + 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" }); logger.debug(EELFLoggerDelegate.debugLogger, "getExecutions: url {}", url); HttpEntity<String> entity = getTenantHeader(tenant); ResponseEntity<CloudifyExecutionList> response = restTemplate.exchange(url, HttpMethod.GET, entity, @@ -188,9 +449,32 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl } @Override - public CloudifyExecutionList getExecutionsSummary(final String deploymentId, final String tenant) { + 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" }); + logger.debug(EELFLoggerDelegate.debugLogger, "getExecutionsSummaryPerTenant: url {}", url); + HttpEntity<String> entity = getTenantHeader(tenant); + 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" }); + logger.debug(EELFLoggerDelegate.debugLogger, "getExecutionIdSummary: url {}", url); + HttpEntity<String> entity = getTenantHeader(tenant); + 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, - "_include", "deployment_id,id,status,workflow_id,tenant_name,created_at" }); + "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, @@ -198,7 +482,7 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl }); return response.getBody(); } - + @Override public CloudifyExecution startExecution(CloudifyExecutionRequest execution) { String url = buildUrl(new String[] { baseUrl, EXECUTIONS }, null); @@ -211,13 +495,6 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl } @Override - public CloudifyDeploymentUpdateResponse updateDeployment(CloudifyDeploymentUpdateRequest execution) { - String url = buildUrl(new String[] { baseUrl, UPDATE_DEPLOYMENT }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "updateDeployment: url {}", url); - return restTemplate.postForObject(url, execution, CloudifyDeploymentUpdateResponse.class); - } - - @Override public CloudifyExecution cancelExecution(final String executionId, Map<String, String> parameters, final String tenant) { String url = buildUrl(new String[] { baseUrl, EXECUTIONS, executionId }, null); @@ -246,18 +523,516 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl } @Override - public CloudifyDeploymentList getDeployments() { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, null); + public byte[] viewBlueprint(String tenant, final String id) { + 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 = + 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) { + 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) { + List<CloudifyDeployment> cfyDeplList = null; + if (cache) { + 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()}); + logger.debug(EELFLoggerDelegate.debugLogger, "getDeployments: url {}", url); + HttpEntity<String> entity = getTenantHeader(tenant); + 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 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()}); + response = restTemplate.exchange(url, HttpMethod.GET, entity, + new ParameterizedTypeReference<CloudifyDeploymentList>() { + }); + deplPgOffset += pageSize; + cfyDeplList.addAll(response.getBody().items); + } + } + } + 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()}); logger.debug(EELFLoggerDelegate.debugLogger, "getDeployments: url {}", url); - ResponseEntity<CloudifyDeploymentList> response = restTemplate.exchange(url, HttpMethod.GET, null, + HttpEntity<String> entity = getTenantHeader(tenant); + 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); + } + + @SuppressWarnings("unchecked") + @Override + 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()); + } + List<String> response = new ArrayList<String>(); + response.addAll(svcIdList); + return response; + } + + @SuppressWarnings("unchecked") + @Override + public List<CloudifyDeployment> getDeploymentsWithFilter(HttpServletRequest request) throws Exception { + String filters = request.getParameter("filters"); + List<CloudifyDeployment> deployments = new ArrayList<CloudifyDeployment>(); + if (filters != null) { + deployments = getDeploymentsWithFilter(request, filters); + } else { + List<CloudifyTenant> selectedTenants = new ArrayList<CloudifyTenant>(); + selectedTenants = getTenants().items; + List<CloudifyDeployment> itemList = null; + for (CloudifyTenant tenant : selectedTenants) { + itemList = this.getDeployments(tenant.name, 500, 0, true); + deployments.addAll(itemList); + } + // apply user role based auth + Set<String> userApps = 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"); + 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()); + } 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()); + } + } + } + } + return deployments; + } + + @Override + 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; + HttpEntity<String> entity; + String tenantFilterStr = ""; + int pageSize = 500; + + //---------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()}); + + 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"); + + 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.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))) + .collect(Collectors.<CloudifyDeployment>toList()); + } else { + 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); + 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); + } + } + 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>(); + 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"); + } + 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"); + } + 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>(); + 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"); + } + 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>(); + 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) { + CloudifyBlueprintList bpList = getBlueprint(dep.blueprint_id, dep.tenant_name); + Map<String, Object> bpPlan = bpList.items.get(0).plan; + Map<String, String> workflows = (Map<String, String>) bpPlan.get("workflows"); + Map<String, String> pluginInfo = ((List<Map<String, String>>) bpPlan + .get("deployment_plugins_to_install")).get(0); + 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; + } + return newFilteredDeployments; + } @Override public CloudifyDeploymentList getDeployment(final String id) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, new String[] { "id", id }); + 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>() { @@ -267,7 +1042,7 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl @Override public CloudifyDeploymentList getDeployment(final String id, final String tenant) { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS }, new String[] { "id", id, TENANT, tenant }); + 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, @@ -285,4 +1060,44 @@ public class CloudifyRestClientImpl extends RestClientBase implements CloudifyCl entity, new ParameterizedTypeReference<CloudifyDeploymentList>() {}); return response.getBody(); } + + /** + * Get a cloudify secret + * + * @return CloudifySecret + */ + @Override + public CloudifySecret getSecret(String secretName, String tenant) { + 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>() { + }); + return response.getBody(); + } + + /** + * Get the list of cloudify plugins + * + * @return List<CloudifyPlugin> + */ + public CloudifyPluginList getPlugins() { + 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>() { + }); + CloudifyPluginList result = response.getBody(); + return result; + } + + @Override + public void deleteBlueprint(String bpName, String tenant) { + 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>() { + }); + } } 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 c63652b..90da400 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 @@ -21,13 +21,16 @@ *******************************************************************************/ package org.onap.ccsdk.dashboard.rest; +import java.net.URL; import java.util.List; -import org.onap.ccsdk.dashboard.model.ConsulDatacenter; -import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; -import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; -import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; +import org.onap.ccsdk.dashboard.model.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; /** * Defines the interface of the Consul REST client. @@ -48,6 +51,16 @@ public interface ConsulClient { * @return List of ConsulServiceHealth */ public List<ConsulServiceHealth> getServiceHealth(String datacenter, String srvcName); + + /** + * 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 + * matches the given deployment id + * + * @param deploymentId Deployment Id + * @return List of ConsulServiceHealth + */ + public ConsulDeploymentHealth getServiceHealthByDeploymentId(String deploymentId); /** * Gets all the nodes that are monitored by Consul. @@ -71,20 +84,4 @@ public interface ConsulClient { */ public List<ConsulDatacenter> getDatacenters(); - /** - * Registers a service with Consul for health check. - * - * @param registration Details about the service to be registered. - * @return Result of registering a service - */ - public String registerService(ConsulHealthServiceRegistration registration); - - /** - * Deregisters a service with Consul for health check. - * - * @param serviceName Name of the service to be deregistered. - * @return Response code - */ - public int deregisterService(String serviceName); - } 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 2567577..911e342 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 @@ -29,15 +29,25 @@ import java.util.Map; import javax.annotation.PostConstruct; +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +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.model.ConsulDatacenter; -import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; -import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration.EndpointCheck; +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.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.ccsdk.dashboard.model.ConsulNodeInfo; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; -import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; @@ -45,6 +55,9 @@ 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; @@ -55,18 +68,27 @@ public class ConsulRestClientImpl extends RestClientBase implements ConsulClient private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulRestClientImpl.class); private String baseUrl; - private final ObjectMapper objectMapper = new ObjectMapper(); + private String consul_acl_token; + private HttpEntity<String> token_entity; private static final String API_VER = "v1"; private static final String CATALOG = "catalog"; private static final String SERVICES = "services"; private static final String HEALTH = "health"; private static final String CHECKS = "checks"; + private static final String STATE = "state"; + private static final String ANY = "any"; @PostConstruct public void init() { - String webapiUrl = DashboardProperties.getControllerProperty("dev", - DashboardProperties.CONTROLLER_SUBKEY_CONSUL_URL); + if (consul_acl_token == null || consul_acl_token.isEmpty()) { + consul_acl_token = getConsulAcl(); + } + if (consul_acl_token != null && !consul_acl_token.isEmpty()) { + token_entity = getConsulTokenHeader(consul_acl_token); + } + String webapiUrl = DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CONSUL_URL); if (webapiUrl == null) throw new IllegalArgumentException("Null URL not permitted"); URL url = null; @@ -82,136 +104,271 @@ 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", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_URL); + String cfyBaseUrl = ""; + if (webapiUrl != null) { + String user = DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_USERNAME); + String pass = DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_PASS); + URL url = null; + try { + url = new URL(webapiUrl); + cfyBaseUrl = url.toExternalForm(); + String urlScheme = webapiUrl.split(":")[0]; + if (cfyRest == null) { + cfyRest = + createCfyRestTemplate(url, user, pass, urlScheme); + } + 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(); + } catch (MalformedURLException me) { + //throw new RuntimeException("Failed to parse URL", ex); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse URL - malformed" + me.getMessage()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + acl_token = ""; + } + } + return acl_token; + } + + 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 + CloseableHttpClient httpClient = null; + + if (user != null && pass != null) { + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + 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); + 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; + } + @Override public List<ConsulServiceHealth> getServiceHealth(String dc, String srvc) { 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 = restTemplate.exchange(url, HttpMethod.GET, null, + ResponseEntity<List<ConsulServiceHealth>> response = null; + try { + response = restTemplate.exchange(url, HttpMethod.GET, token_entity, + 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>>() { + }); + } else { + throw e; + } + } + } + if (!response.getBody().isEmpty()) { + return response.getBody(); + } else { + return null; + } + } + + @Override + public ConsulDeploymentHealth getServiceHealthByDeploymentId(String deploymentId) { + 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; + try { + response = restTemplate.exchange(url, HttpMethod.GET, token_entity, new ParameterizedTypeReference<List<ConsulServiceHealth>>() { }); - return response.getBody(); + } 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>>() { + }); + } else { + throw e; + } + } + } + if (!response.getBody().isEmpty()) { + return new ConsulDeploymentHealth.Builder(response.getBody().get(0)).build(); + } else { + return null; + } } @Override public List<ConsulServiceInfo> getServices(String dc) { 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 = restTemplate.exchange(url, HttpMethod.GET, null, + ResponseEntity<Map<String, Object>> response = null; + try { + response = restTemplate.exchange(url, HttpMethod.GET, token_entity, new ParameterizedTypeReference<Map<String, Object>>() { }); - 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<?>) - addrs = (List<String>) entry.getValue(); - else - addrs = new ArrayList<>(); - list.add(new ConsulServiceInfo(entry.getKey(), addrs)); - } - return list; + } 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>>() { + }); + } else { + throw e; + } + } + } + if (!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<?>) + addrs = (List<String>) entry.getValue(); + else + addrs = new ArrayList<>(); + list.add(new ConsulServiceInfo(entry.getKey(), addrs)); + } + return list; + } else { + return null; + } } @Override public List<ConsulNodeInfo> getNodes(String dc) { 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 = restTemplate.exchange(url, HttpMethod.GET, null, + ResponseEntity<List<ConsulNodeInfo>> response = null; + try { + response = restTemplate.exchange(url, HttpMethod.GET, token_entity, new ParameterizedTypeReference<List<ConsulNodeInfo>>() { }); - return response.getBody(); + } 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>>() { + }); + } else { + throw e; + } + } + } + if (!response.getBody().isEmpty()) { + return response.getBody(); + } else { + return null; + } } @Override public List<ConsulServiceHealth> getNodeServicesHealth(String dc, String nodeId) { 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 = restTemplate.exchange(url, HttpMethod.GET, null, + ResponseEntity<List<ConsulServiceHealth>> response = null; + try { + response = restTemplate.exchange(url, HttpMethod.GET, token_entity, new ParameterizedTypeReference<List<ConsulServiceHealth>>() { }); - return response.getBody(); + } 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>>() { + }); + } else { + throw e; + } + } + } + if (!response.getBody().isEmpty()) { + return response.getBody(); + } else { + return null; + } } @Override public List<ConsulDatacenter> getDatacenters() { String url = buildUrl(new String[] { baseUrl, API_VER, CATALOG, "datacenters" }, null); logger.debug(EELFLoggerDelegate.debugLogger, "getDatacentersHealth: url {}", url); - ResponseEntity<List<String>> response = restTemplate.exchange(url, HttpMethod.GET, null, + ResponseEntity<List<String>> response = null; + try { + response = restTemplate.exchange(url, HttpMethod.GET, token_entity, new ParameterizedTypeReference<List<String>>() { }); - List<String> list = response.getBody(); - List<ConsulDatacenter> result = new ArrayList<>(); - for (String dc : list) - result.add(new ConsulDatacenter(dc)); - return result; - } - - @Override - public String registerService(ConsulHealthServiceRegistration registration) { - String url = buildUrl(new String[] { baseUrl, API_VER, "/agent/service/register" }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "registerService: url {}", url); - String resultStr = ""; - JSONObject outputJson = new JSONObject(); - JSONObject checkObject = new JSONObject(); - List<EndpointCheck> checks = registration.services.get(0).checks; - String service_name = registration.services.get(0).name; - String service_port = registration.services.get(0).port; - String service_address = registration.services.get(0).address; - List<String> tags = registration.services.get(0).tags; - - outputJson.put("Name", service_name); - outputJson.put("ID", service_name); - outputJson.put("Port", Integer.parseInt(service_port)); - outputJson.put("Address", service_address); - outputJson.put("Tags", tags); - - if (checks.size() == 1) { - checkObject.put("HTTP", checks.get(0).endpoint); - checkObject.put("Interval", checks.get(0).interval); - if (!checks.get(0).description.isEmpty()) - checkObject.put("Notes", checks.get(0).description); - checkObject.put("ServiceID", service_name); - outputJson.put("Check", checkObject); - } else { - JSONArray checks_new = new JSONArray(); - for (EndpointCheck check : checks) { - checkObject.put("HTTP", check.endpoint); - checkObject.put("Interval", check.endpoint); - if (!check.description.isEmpty()) - checkObject.put("Notes", check.description); - checkObject.put("ServiceID", service_name); - checks_new.put(checkObject); + } 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>>() { + }); + } else { + throw e; + } } - outputJson.put("Checks", checks_new); } - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(outputJson.toString(), headers); - ResponseEntity<JSONObject> result = restTemplate.exchange(url, HttpMethod.PUT, entity, - new ParameterizedTypeReference<JSONObject>() { - }); - try { - resultStr = objectMapper.writeValueAsString(result); - } catch (JsonProcessingException e) { - - } finally { - } - return resultStr; + 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; + } } - @Override - public int deregisterService(String serviceName) { - String url = buildUrl(new String[] { baseUrl, API_VER, "/agent/service/deregister", serviceName }, null); - logger.debug(EELFLoggerDelegate.debugLogger, "deregisterService: url {}", url); - - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(headers); - ResponseEntity<JSONObject> result = restTemplate.exchange(url, HttpMethod.PUT, entity, - new ParameterizedTypeReference<JSONObject>() { - }); - return result.getStatusCode().value(); - } } 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 0804e9a..012ec32 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 @@ -23,6 +23,8 @@ package org.onap.ccsdk.dashboard.rest; import java.util.stream.Stream; +import javax.servlet.http.HttpServletRequest; + import org.onap.ccsdk.dashboard.exceptions.BadRequestException; import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; import org.onap.ccsdk.dashboard.exceptions.DownstreamException; @@ -35,6 +37,11 @@ import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; public interface DeploymentHandlerClient { /** + * Run deployment handler service health check + * + */ + public String checkHealth(); + /** * Gets a list of all service deployments known to the orchestrator. * * @return Stream<String> @@ -65,17 +72,16 @@ public interface DeploymentHandlerClient { * /dcae-deployments/{deploymentId} * */ - public DeploymentResponse putDeployment(String deploymentId, String tenant, DeploymentRequest deploymentRequest) + public DeploymentResponse putDeployment(String deploymentId, String tenant, DeploymentRequest deploymentRequest, + HttpServletRequest request) throws BadRequestException, ServiceAlreadyExistsException, ServerErrorException, DownstreamException; /** - * Initiate update for a deployment + * For API use, Request deployment of a DCAE Service. * * @param deploymentId Unique deployment identifier assigned by the API * client. * - * @param tenant Cloudify tenant where the deployment should be done - * * @param deploymentRequest Deployment request object that contains the * necessary fields for service deployment. * @@ -83,7 +89,7 @@ public interface DeploymentHandlerClient { * /dcae-deployments/{deploymentId} * */ - public DeploymentResponse updateDeployment(String deploymentId, String tenant, DeploymentRequest deploymentRequest) + public DeploymentResponse putDeployment(String deploymentId, String tenant, DeploymentRequest deploymentRequest) throws BadRequestException, ServiceAlreadyExistsException, ServerErrorException, DownstreamException; /** @@ -93,6 +99,16 @@ public interface DeploymentHandlerClient { * @param deploymentId Unique deployment identifier assigned by the API client. * */ + public void deleteDeployment(String deploymentId, String tenant, HttpServletRequest request) + throws BadRequestException, ServerErrorException, DownstreamException, DeploymentNotFoundException; + + /** + * For API use, Uninstall the DCAE service and remove all associated data from the + * orchestrator. + * + * @param deploymentId Unique deployment identifier assigned by the API client. + * + */ public void deleteDeployment(String deploymentId, String tenant) throws BadRequestException, ServerErrorException, DownstreamException, DeploymentNotFoundException; } 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 6e9ecb4..803c710 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 @@ -24,21 +24,35 @@ package org.onap.ccsdk.dashboard.rest; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Stream; import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletRequest; import org.onap.ccsdk.dashboard.exceptions.BadRequestException; import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; import org.onap.ccsdk.dashboard.exceptions.DownstreamException; import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployment; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentExt; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentHelm; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentErrorResponse; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentLink; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentsListResponse; import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.onap.portalsdk.core.objectcache.AbstractCacheManager; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -48,9 +62,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; -import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; @org.springframework.stereotype.Service public class DeploymentHandlerClientImpl extends RestClientBase implements DeploymentHandlerClient { @@ -59,13 +71,28 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo 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; + + @Autowired + public void setCacheManager(AbstractCacheManager cacheManager) { + this.cacheManager = cacheManager; + } + + public AbstractCacheManager getCacheManager() { + return cacheManager; + } protected final ObjectMapper objectMapper = new ObjectMapper(); @PostConstruct public void init() { - String webapiUrl = DashboardProperties.getControllerProperty("dev", - DashboardProperties.CONTROLLER_SUBKEY_DHANDLER_URL); + String webapiUrl = DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_DHANDLER_URL); if (webapiUrl == null) throw new IllegalArgumentException("Null URL not permitted"); URL url = null; @@ -82,6 +109,14 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo } + public String checkHealth() { + String url = buildUrl(new String[] { baseUrl, HEALTH_CHECK }, null); + ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, + 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, @@ -104,48 +139,19 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo @Override public DeploymentResponse putDeployment(String deploymentId, String tenant, DeploymentRequest deploymentRequest) throws BadRequestException, ServiceAlreadyExistsException, ServerErrorException, DownstreamException { - String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS, deploymentId }, - new String[] { "cfy_tenant_name", tenant }); - try { - 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>() { - }); - return result.getBody(); - } catch (HttpServerErrorException | HttpClientErrorException e) { - DeploymentErrorResponse errBody = null; - String errMsg = ""; - try { - errBody = objectMapper.readValue(e.getResponseBodyAsString(), DeploymentErrorResponse.class); - } catch (IOException e1) { - errBody = null; - } - if (errBody != null) { - errMsg = errBody.getMessage(); - } - StringBuilder errDetails = new StringBuilder(); - errDetails.append(e.getMessage()).append(" ").append(errMsg); - if (e.getStatusCode().value() == 400 || e.getStatusCode().value() == 415 - || e.getStatusCode().value() == 404) { - throw new BadRequestException(errDetails.toString()); - } else if (e.getStatusCode().value() == 409) { - throw new ServiceAlreadyExistsException(errDetails.toString()); - } else if (e.getStatusCode().value() == 500) { - throw new ServerErrorException(errDetails.toString()); - } else if (e.getStatusCode().value() == 502 || e.getStatusCode().value() == 504) { - throw new DownstreamException(errDetails.toString()); - } - } - return null; + return putDeployment(deploymentId, tenant, deploymentRequest, null); } - + @Override - public DeploymentResponse updateDeployment(String deploymentId, String tenant, DeploymentRequest deploymentRequest) + public DeploymentResponse putDeployment(String deploymentId, String tenant, DeploymentRequest deploymentRequest, + HttpServletRequest request) throws BadRequestException, ServiceAlreadyExistsException, ServerErrorException, DownstreamException { - String url = buildUrl(new String[] { baseUrl, UPDATE_PATH, deploymentId }, + String url = buildUrl(new String[] { baseUrl, DEPLOYMENTS, deploymentId }, new String[] { "cfy_tenant_name", tenant }); + String user = ""; + if (request != null) { + user = UserUtils.getUserSession(request).getLoginId(); + } try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); @@ -153,20 +159,71 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo 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"); + lock.readLock().unlock(); + if (itemList != null) { + // add the new resource into app cache + CloudifyDeployment cfyDepl = + cloudifyClient.getDeploymentResource(deploymentId, tenant); + lock.writeLock().lock(); + itemList.add(0, cfyDepl); + lock.writeLock().unlock(); + if (itemExecList != null) { + List<CloudifyDeployment> thisDep = new ArrayList<CloudifyDeployment>(); + thisDep.add(cfyDepl); + List<CloudifyDeploymentExt> thisDepExec = + cloudifyClient.updateWorkflowStatus(thisDep); + List<CloudifyDeploymentHelm> thisDepHelm = + cloudifyClient.updateHelmInfo(thisDep); + lock.writeLock().lock(); + itemExecList.add(0, thisDepExec.get(0)); + itemHelmList.add(0, thisDepHelm.get(0)); + lock.writeLock().unlock(); + } + // handle the owner deployment map cache + if (!user.isEmpty()) { + 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"); + lock.readLock().unlock(); + if (deplPerOwner != null) { + List<CloudifyDeployedTenant> currOwnedDepls = deplPerOwner.get(user); + if (currOwnedDepls != null) { + currOwnedDepls.add(0, updDepl); + } else { + 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>(); + deplForBpAggr.add(updDepl); + deplPerOwner.put(user, deplForBpAggr); + } + } + } return result.getBody(); } catch (HttpServerErrorException | HttpClientErrorException e) { - DeploymentErrorResponse errBody = null; - String errMsg = ""; - try { - errBody = objectMapper.readValue(e.getResponseBodyAsString(), DeploymentErrorResponse.class); - } catch (IOException e1) { - errBody = null; - } - if (errBody != null) { - errMsg = errBody.getMessage(); - } + String errBody = null; + errBody = e.getResponseBodyAsString(); StringBuilder errDetails = new StringBuilder(); - errDetails.append(e.getMessage()).append(" ").append(errMsg); + errDetails.append(e.getMessage()).append(" ").append(errBody); if (e.getStatusCode().value() == 400 || e.getStatusCode().value() == 415 || e.getStatusCode().value() == 404) { throw new BadRequestException(errDetails.toString()); @@ -178,17 +235,62 @@ public class DeploymentHandlerClientImpl extends RestClientBase implements Deplo throw new DownstreamException(errDetails.toString()); } } - return null; // Perhaps this should be a proper JSON error response. + return null; } @Override public void deleteDeployment(String deploymentId, String tenant) throws BadRequestException, ServerErrorException, DownstreamException, DeploymentNotFoundException { + 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, "ignore_failure", "true" }); + 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); + // remove resource from app cache + ReadWriteLock lock = new ReentrantReadWriteLock(); + lock.readLock().lock(); + List itemList = + (List<CloudifyDeployment>)getCacheManager().getObject(SERVICE_ID + ":" + tenant); + lock.readLock().unlock(); + if (itemList != null) { + lock.writeLock().lock(); + itemList.remove(cfyDepl); + getCacheManager().removeObject(SERVICE_ID + ":" + tenant); + // 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"); + 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); + if (currOwnedDepls != null) { + currOwnedDepls.remove(updDepl); + lock.writeLock().lock(); + deplPerOwner.put(user, currOwnedDepls); + lock.writeLock().unlock(); + } + } + } } catch (HttpServerErrorException | HttpClientErrorException e) { DeploymentErrorResponse errBody = null; String errMsg = ""; 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 1b93bc7..8f19e9b 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 @@ -37,6 +37,7 @@ 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; /** * Defines the interface of the Inventory Client. @@ -44,12 +45,25 @@ import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; public interface InventoryClient { /** + * Run inventory service health check + * + */ + public String checkHealth(); + + /** + * Get and store in cache, list of all DCAE Service Type objects. + * + * @return void + */ + public void cacheServiceTypes(); + + /** * Gets a list of all DCAE Service Type objects. * * @return Collection<ServiceType> */ - public Stream<ServiceType> getServiceTypes(); - + public Stream<ServiceTypeSummary> getServiceTypes(); + /** * Gets a list of all DCAE Service Type objects that fall under a specified * filter. @@ -59,7 +73,7 @@ public interface InventoryClient { * * @return Collection<ServiceType> */ - public Stream<ServiceType> getServiceTypes(ServiceTypeQueryParams serviceTypeQueryParams); + public Stream<ServiceTypeSummary> getServiceTypes(ServiceTypeQueryParams serviceTypeQueryParams); /** * Inserts a new DCAE Service Type, or updates an existing instance associated @@ -117,7 +131,7 @@ public interface InventoryClient { * * @return Collection<Service> */ - public Stream<Service> getServices(); + //public Stream<Service> getServices(); /** * Gets a list of all DCAE Service objects that fall under a specified filter. @@ -127,7 +141,7 @@ public interface InventoryClient { * * @return Collection<Service> */ - public Stream<Service> getServices(ServiceQueryParams serviceQueryParams); + //public Stream<Service> getServices(ServiceQueryParams serviceQueryParams); /** * Gets a list of all DCAE Service References that match a service type filter. @@ -159,32 +173,8 @@ public interface InventoryClient { * @return Service */ - public Optional<Service> getService(String serviceId); - - /** - * Puts a new DCAE Service with the specified serviceId, or updates an existing - * DCAE Service corresponding to the specified serviceId. - * - * @param typeId Type ID of the associated DCAE Service Type - * - * @param service DCAE Service to be uploaded. - */ - public void putService(String typeId, Service service); - - /** - * Deletes an existing DCAE Service object corresponding to the specified - * serviceId. - * - * @param serviceId Service ID of the DCAE Service to be deleted. - * - * @exception ServiceNotFoundException Thrown if the DCAE Service is - * not found. - * - * @exception ServiceAlreadyDeactivatedException Thrown if the DCAE Service is - * already deactivated. - * - */ + //public Optional<Service> getService(String serviceId); - public void deleteService(String serviceId) throws ServiceNotFoundException, ServiceAlreadyDeactivatedException; + 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 c7c1cdf..69fca94 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 @@ -30,6 +30,7 @@ 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; @@ -43,6 +44,13 @@ import org.springframework.web.client.RestTemplate; public class RestClientBase { protected RestTemplate restTemplate = null; + /** + * @param restTemplate the restTemplate to set + */ + public void setRestTemplate(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + } + protected void createRestTemplate(URL url, String user, String pass, String urlScheme) { RestTemplate restTempl = null; final HttpHost httpHost = new HttpHost(url.getHost(), url.getPort(), urlScheme); @@ -61,7 +69,9 @@ public class RestClientBase { 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); @@ -111,4 +121,16 @@ public class RestClientBase { headers.set("Tenant", tenant); return new HttpEntity<String>("parameters", headers); } + + /** + * Create Http Entity for the consul token header + * + * @param token string + * @return + */ + protected HttpEntity<String> getConsulTokenHeader(String token) { + HttpHeaders headers = new HttpHeaders(); + headers.set("X-Consul-Token", token); + return new HttpEntity<String>("parameters", headers); + } } 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 c1296f0..100170c 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 @@ -28,51 +28,61 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.function.Predicate; import java.util.Optional; -import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.PostConstruct; -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceAlreadyDeactivatedException; -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; import org.onap.ccsdk.dashboard.model.inventory.ApiResponseMessage; -import org.onap.ccsdk.dashboard.model.inventory.InventoryProperty; import org.onap.ccsdk.dashboard.model.inventory.Link; import org.onap.ccsdk.dashboard.model.inventory.Service; -import org.onap.ccsdk.dashboard.model.inventory.ServiceGroupByResults; import org.onap.ccsdk.dashboard.model.inventory.ServiceList; import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; import org.onap.ccsdk.dashboard.model.inventory.ServiceRef; import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; -import org.onap.ccsdk.dashboard.model.inventory.ServiceRequest; 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.util.DashboardProperties; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.objectcache.AbstractCacheManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; import org.springframework.web.client.HttpClientErrorException; @org.springframework.stereotype.Service +@Component 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"; public static final String SERVICES_GROUPBY = "dcae-services-groupby"; + public static final String HEALTH_CHECK = "healthcheck"; + /** + * For caching data + */ + private AbstractCacheManager cacheManager; + @PostConstruct public void init() { - String webapiUrl = DashboardProperties.getControllerProperty("dev", - DashboardProperties.CONTROLLER_SUBKEY_INVENTORY_URL); + String webapiUrl = DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_INVENTORY_URL); if (webapiUrl == null) throw new IllegalArgumentException("Null URL not permitted"); URL url = null; @@ -90,28 +100,74 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory } - public Stream<ServiceType> getServiceTypes() { - String url = buildUrl(new String[] { baseUrl, SERVICE_TYPES }, null); - ResponseEntity<ServiceTypeList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceTypeList>() { + public String checkHealth() { + String url = buildUrl(new String[] { baseUrl, HEALTH_CHECK }, null); + ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference<String>() { }); - Collection<ServiceType> collection = response.getBody().items; - + return response.getBody(); + } + + @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>() { + }); + 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<ServiceTypeList>() { + new ParameterizedTypeReference<ServiceTypeSummaryList>() { }); collection.addAll(response.getBody().items); nextLink = response.getBody().paginationLinks.nextLink; } + ReadWriteLock lock = new ReentrantReadWriteLock(); + // put into cache + lock.writeLock().lock(); + getCacheManager().putObject(SERVICE_TYPES, collection); + lock.writeLock().unlock(); + 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>() { + }); + 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>() { + }); + collection.addAll(response.getBody().items); + nextLink = response.getBody().paginationLinks.nextLink; + } + ReadWriteLock lock = new ReentrantReadWriteLock(); + // put into cache + lock.writeLock().lock(); + getCacheManager().putObject(SERVICE_TYPES, collection); + lock.writeLock().unlock(); return collection.stream(); } + + @Autowired + public void setCacheManager(AbstractCacheManager cacheManager) { + this.cacheManager = cacheManager; + } - public Stream<ServiceType> getServiceTypes(ServiceTypeQueryParams serviceTypeQueryParams) { + public AbstractCacheManager getCacheManager() { + return cacheManager; + } + + public Stream<ServiceTypeSummary> getServiceTypes(ServiceTypeQueryParams serviceTypeQueryParams) { // Only utilize the parameters that aren't null HashMap<String, String> map = new HashMap<>(); @@ -139,6 +195,12 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory if (serviceTypeQueryParams.getAsdcResourceId() != null) { map.put("asdcResourceId", serviceTypeQueryParams.getAsdcResourceId()); } + if (serviceTypeQueryParams.getApplication() != null) { + map.put("application", serviceTypeQueryParams.getApplication()); + } + if (serviceTypeQueryParams.getComponent() != null) { + map.put("component", serviceTypeQueryParams.getComponent()); + } ArrayList<String> params = new ArrayList<>(); for (Entry<String, String> ent : map.entrySet()) { params.add(ent.getKey()); @@ -146,17 +208,17 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory } String url = buildUrl(new String[] { baseUrl, SERVICE_TYPES }, params.toArray(new String[params.size()])); - ResponseEntity<ServiceTypeList> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<ServiceTypeList>() { + ResponseEntity<ServiceTypeSummaryList> response = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference<ServiceTypeSummaryList>() { }); - Collection<ServiceType> collection = response.getBody().items; + 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<ServiceTypeList>() { + new ParameterizedTypeReference<ServiceTypeSummaryList>() { }); collection.addAll(response.getBody().items); nextLink = response.getBody().paginationLinks.nextLink; @@ -170,14 +232,31 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory // Take the ServiceType object and create a ServiceTypeRequest from it ServiceTypeRequest serviceTypeRequest = ServiceTypeRequest.from(serviceType); - - return restTemplate.postForObject(url, serviceTypeRequest, ServiceType.class); + ServiceType upldBp = restTemplate.postForObject(url, serviceTypeRequest, ServiceType.class); + List<ServiceTypeSummary> itemList = this.getServiceTypes().collect(Collectors.toList()); + ReadWriteLock lock = new ReentrantReadWriteLock(); + lock.writeLock().lock(); + getCacheManager().removeObject(SERVICE_TYPES); + // put updated collection back into cache + getCacheManager().putObject(SERVICE_TYPES, itemList); + lock.writeLock().unlock(); + return upldBp; } + @SuppressWarnings("unchecked") public ServiceType addServiceType(ServiceTypeRequest serviceTypeRequest) { String url = buildUrl(new String[] { baseUrl, SERVICE_TYPES }, null); - - return restTemplate.postForObject(url, serviceTypeRequest, ServiceType.class); + 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, + // using query params (typeName, owner, app, component) + List<ServiceTypeSummary> itemList = this.getServiceTypes().collect(Collectors.toList()); + ReadWriteLock lock = new ReentrantReadWriteLock(); + lock.writeLock().lock(); + // put updated collection back into cache + getCacheManager().putObject(SERVICE_TYPES, itemList); + lock.writeLock().unlock(); + return uplBp; } public Optional<ServiceType> getServiceType(String typeId) { @@ -188,12 +267,33 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory 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); + ReadWriteLock lock = new ReentrantReadWriteLock(); try { - restTemplate.exchange(url, HttpMethod.DELETE, null, new ParameterizedTypeReference<ApiResponseMessage>() { + ResponseEntity<ApiResponseMessage> response = + 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); + 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()); + lock.writeLock().lock(); + getCacheManager().removeObject(SERVICE_TYPES); + // put updated collection back into cache + getCacheManager().putObject(SERVICE_TYPES, itemList); + lock.writeLock().unlock(); } catch (HttpClientErrorException e) { if (e.getStatusCode().value() == 410) { throw new ServiceTypeAlreadyDeactivatedException(e.getMessage()); @@ -203,7 +303,7 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory } } - public Stream<Service> getServices() { +/* public Stream<Service> getServices() { String url = buildUrl(new String[] { baseUrl, SERVICES }, null); ResponseEntity<ServiceList> response = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<ServiceList>() { @@ -222,7 +322,7 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory return collection.stream(); } - +*/ public ServiceRefList getServicesForType(ServiceQueryParams serviceQueryParams) { // Only utilize the typeId @@ -257,7 +357,7 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory return new ServiceRefList(srvcRefList, itemCnt); } - +/* public Stream<Service> getServices(ServiceQueryParams serviceQueryParams) { // Only utilize the parameters that aren't null @@ -308,43 +408,22 @@ public class RestInventoryClientImpl extends RestClientBase implements Inventory return collection.stream(); } - /* - * public Set<InventoryProperty> getPropertiesOfServices(String propertyName) { - * String url = buildUrl(new String[] {baseUrl, SERVICES_GROUPBY, propertyName}, - * null); ResponseEntity<ServiceGroupByResults> response = - * restTemplate.exchange(url, HttpMethod.GET, null, new - * ParameterizedTypeReference<ServiceGroupByResults>() { }); return - * response.getBody().propertyValues; } - */ public Optional<Service> getService(String serviceId) { String url = buildUrl(new String[] { baseUrl, SERVICES, serviceId }, null); - ResponseEntity<Service> response = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference<Service>() { - }); - return Optional.ofNullable(response.getBody()); - } - - public void putService(String typeId, Service service) { - String url = buildUrl(new String[] { baseUrl, SERVICES, service.getServiceId() }, null); - - ServiceRequest serviceRequest = ServiceRequest.from(typeId, service); - - restTemplate.exchange(url, HttpMethod.PUT, new HttpEntity<ServiceRequest>(serviceRequest), - new ParameterizedTypeReference<Service>() { - }); - } - - public void deleteService(String serviceId) throws ServiceNotFoundException, ServiceAlreadyDeactivatedException { - String url = buildUrl(new String[] { baseUrl, SERVICES, serviceId }, null); + ResponseEntity<Service> response = null; try { - restTemplate.exchange(url, HttpMethod.DELETE, null, new ParameterizedTypeReference<ApiResponseMessage>() { - }); - } catch (HttpClientErrorException e) { - if (e.getStatusCode().value() == 410) { - throw new ServiceAlreadyDeactivatedException(e.getMessage()); - } else if (e.getStatusCode().value() == 404) { - throw new ServiceNotFoundException(e.getMessage()); - } + 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; } } diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointService.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointService.java deleted file mode 100644 index b63f972..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointService.java +++ /dev/null @@ -1,75 +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.service; - -import java.util.List; - -import org.onap.ccsdk.dashboard.domain.ControllerEndpoint; -import org.onap.ccsdk.dashboard.domain.EcdComponent; - -/** - * Provides methods for managing the user's selection of controller endpoint. - * - * No method throws a checked exception, in keeping with the Spring philosophy - * of throwing unchecked exceptions. - */ -public interface ControllerEndpointService { - - /** - * Gets the object for the specified user ID. - * - * @param userId Application user ID - * @return ControllerEndpointCredentials instance; null if none exists. - */ - ControllerEndpoint getControllerEndpointSelection(long userId); - - /** - * Creates or updates an entry for the user ID specified within the object. - * - * @param endpoint info to store. - */ - void updateControllerEndpointSelection(ControllerEndpoint endpoint); - - /** - * Deletes the object for the specified user ID. - * - * @param userId Application user ID - */ - void deleteControllerEndpointSelection(long userId); - - /** - * Gets all component names that are currently supported through ECOMPC - * dashboard - * - * @return Component instance list; - */ - public List<EcdComponent> getComponents(); - - /** - * - * Add a new component to support in ECOMPC platform - * - * @param component - */ - void insertComponent(EcdComponent component); -} diff --git a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointServiceImpl.java b/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointServiceImpl.java deleted file mode 100644 index 6eacb47..0000000 --- a/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/service/ControllerEndpointServiceImpl.java +++ /dev/null @@ -1,115 +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.service; - -import org.onap.ccsdk.dashboard.domain.ControllerEndpoint; -import org.onap.ccsdk.dashboard.domain.EcdComponent; - -import java.util.List; - -import org.onap.portalsdk.core.service.DataAccessService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -/** - * Complete controller endpoint information is in properties. The database just - * stores the user's selection. Users are not expected to enter credentials so - * this hybrid solution keeps credentials out of the database. - */ -@Service("controllerEndpointService") -@Transactional -public class ControllerEndpointServiceImpl implements ControllerEndpointService { - - @Autowired - private DataAccessService dataAccessService; - - /** - * @return Data access service - */ - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - /** - * @param dataAccessService Data access service - */ - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - /* - * (non-Javadoc) - * - * @see org.openecomp.controller.dashboard.service.ControllerEndpointService# - * getControllerEndpoint(java.lang.Integer) - */ - @Override - public ControllerEndpoint getControllerEndpointSelection(long userId) { - return (ControllerEndpoint) getDataAccessService().getDomainObject(ControllerEndpoint.class, userId, null); - } - - /* - * (non-Javadoc) - * - * @see org.openecomp.controller.dashboard.service.ControllerEndpointService# - * getComponents() - */ - @SuppressWarnings("unchecked") - @Override - public List<EcdComponent> getComponents() { - return dataAccessService.executeNamedQuery("getAllComponents", null, null); - } - - @Override - public void insertComponent(EcdComponent component) { - dataAccessService.saveDomainObject(component, null); - } - - /* - * (non-Javadoc) - * - * @see org.openecomp.controller.dashboard.service.ControllerEndpointService# - * updateControllerEndpoint(org.openecomp.controller.dashboard.domain. - * ControllerEndpoint) - */ - @Override - public void updateControllerEndpointSelection(ControllerEndpoint endpoint) { - getDataAccessService().saveDomainObject(endpoint, null); - } - - /* - * // (non-Javadoc) - * - * @see org.openecomp.controller.dashboard.service.ControllerEndpointService# - * deleteControllerEndpoint(java.lang.Integer) - */ - @Override - public void deleteControllerEndpointSelection(long userId) { - ControllerEndpoint dbEntry = (ControllerEndpoint) getDataAccessService() - .getDomainObject(ControllerEndpoint.class, userId, null); - if (dbEntry != null) - getDataAccessService().deleteDomainObject(dbEntry, null); - } - -} 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 35d5d01..d785ea5 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 @@ -3,8 +3,6 @@ * * ================================================================================= * 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. @@ -45,83 +43,61 @@ import org.springframework.core.env.Environment; public class DashboardProperties { /** - * Key for property that indicates if test data should be used - */ - public static final String CONTROLLER_MOCK_DATA = "controller.mock.data"; - /** - * Key for property with list of controllers + * Key for property with list of sites */ - public static final String CONTROLLER_KEY_LIST = "controller.key.list"; + public static final String CONTROLLER_SITE_LIST = "controller.site.list"; /** - * Subkey for property with Controller name (description) + * Subkey for property with site name */ - public static final String CONTROLLER_SUBKEY_NAME = "name"; + public static final String SITE_SUBKEY_NAME = "name"; /** - * Subkey for property with Controller URL + * Subkey for property with Cloudify URL */ - public static final String CONTROLLER_SUBKEY_URL = "url"; + public static final String SITE_SUBKEY_CLOUDIFY_URL = "cloudify.url"; /** * Subkey for property with Inventory URL */ - public static final String CONTROLLER_SUBKEY_INVENTORY_URL = "inventory.url"; + public static final String SITE_SUBKEY_INVENTORY_URL = "inventory.url"; /** * Subkey for property with Deployment Handler URL */ - public static final String CONTROLLER_SUBKEY_DHANDLER_URL = "dhandler.url"; + public static final String SITE_SUBKEY_DHANDLER_URL = "dhandler.url"; /** * Subkey for property with Consul URL */ - public static final String CONTROLLER_SUBKEY_CONSUL_URL = "consul.url"; + public static final String SITE_SUBKEY_CONSUL_URL = "consul.url"; + /** + * Subkey for property with DBCL URL + */ + public static final String SITE_SUBKEY_DBCL_URL = "dbcl.url"; + /** + * Subkey for property with DBCL URL + */ + public static final String SITE_SUBKEY_FEED_URL = "feed_m.url"; /** * Subkey for property with Controller user name for authentication */ - public static final String CONTROLLER_SUBKEY_USERNAME = "username"; + public static final String SITE_SUBKEY_CLOUDIFY_USERNAME = "cloudify.username"; /** * Subkey for property with Controller password */ - public static final String CONTROLLER_SUBKEY_PASS = "password"; + public static final String SITE_SUBKEY_CLOUDIFY_PASS = "cloudify.password"; /** * Subkey for property with Controller password encryption status */ - public static final String CONTROLLER_SUBKEY_ENCRYPTED = "is_encrypted"; + public static final String SITE_SUBKEY_CLOUDIFY_ENCRYPTED = "is_encrypted"; + /** * Key for dashboard deployment environment - dev/uat/prod */ public static final String CONTROLLER_IN_ENV = "controller.env"; /** - * Key for cloudify tenant environment - */ - public static final String CLOUDIFY_TENANT_PRIM = "cloudify.tenant.primary"; - - /** - * Key for aic tenant environment - */ - public static final String AIC_TENANT_PRIM = "aic.tenant.primary"; - - /** - * Key for controller type: ATT or OS - */ - public static final String CONTROLLER_TYPE = "controller.type"; - - /** * Key for K8s deploy permission string * */ public static final String APP_K8S_PERM = "k8s.deploy.perm"; - public static final String OPS_K8S_URL = "ops.k8s.url"; - - public static final String OPS_GRAFANA_URL = "ops.grf.url"; - - public static final String OPS_CLOUDIFY_URL = "ops.cfy.url"; - - public static final String OPS_CONSUL_URL = "ops.cnsl.url"; - - public static final String OPS_PROMETHEUS_URL = "ops.prom.url"; - - public static final String OPS_DBCL_URL = "ops.dbcl.url"; - private static Environment environment; protected Environment getEnvironment() { @@ -133,7 +109,7 @@ public class DashboardProperties { */ @Autowired public void setEnvironment(final Environment environment) { - DashboardProperties.environment = environment; + this.environment = environment; } /** @@ -180,8 +156,8 @@ public class DashboardProperties { String listVal = getProperty(key); if (listVal == null) return null; - - return listVal.split("\\s*,\\s*"); + String[] vals = listVal.split("\\s*,\\s*"); + return vals; } /** @@ -197,4 +173,16 @@ public class DashboardProperties { return getProperty(key); } + /** + * 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 + * @return Property value for key "controllerKey.propKey" + */ + public static String getControllerPropertyDef(final String controllerKey, final String propKey, String defVal) { + final String key = controllerKey + '.' + propKey; + return getPropertyDef(key, defVal); + } } |