Remove legacy certificate handling
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / externalapi / servlet / AbstractTemplateServlet.java
1 /*
2  * Copyright (C) 2020 CMCC, Inc. and others. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.openecomp.sdc.be.externalapi.servlet;
17
18 import com.jcabi.aspects.Loggable;
19 import fj.data.Either;
20 import io.swagger.v3.oas.annotations.Operation;
21 import io.swagger.v3.oas.annotations.Parameter;
22 import io.swagger.v3.oas.annotations.media.ArraySchema;
23 import io.swagger.v3.oas.annotations.media.Content;
24 import io.swagger.v3.oas.annotations.media.Schema;
25 import io.swagger.v3.oas.annotations.responses.ApiResponse;
26 import io.swagger.v3.oas.annotations.servers.Server;
27 import io.swagger.v3.oas.annotations.tags.Tag;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.List;
31 import javax.inject.Inject;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.ws.rs.GET;
34 import javax.ws.rs.HeaderParam;
35 import javax.ws.rs.POST;
36 import javax.ws.rs.Path;
37 import javax.ws.rs.PathParam;
38 import javax.ws.rs.Produces;
39 import javax.ws.rs.core.Context;
40 import javax.ws.rs.core.MediaType;
41 import javax.ws.rs.core.Response;
42
43 import org.apache.commons.collections.CollectionUtils;
44 import org.openecomp.sdc.be.components.impl.AbstractTemplateBusinessLogic;
45 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
46 import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
47 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
48 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
49 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
50 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
51 import org.openecomp.sdc.be.config.BeEcompErrorManager;
52 import org.openecomp.sdc.be.dao.api.ActionStatus;
53 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
54 import org.openecomp.sdc.be.externalapi.servlet.representation.AbstractTemplateInfo;
55 import org.openecomp.sdc.be.externalapi.servlet.representation.CopyServiceInfo;
56 import org.openecomp.sdc.be.impl.ComponentsUtils;
57 import org.openecomp.sdc.be.impl.ServletUtils;
58 import org.openecomp.sdc.be.model.Component;
59 import org.openecomp.sdc.be.model.Service;
60 import org.openecomp.sdc.be.model.User;
61 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
62 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
63 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
64 import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
65 import org.openecomp.sdc.be.servlets.RepresentationUtils;
66 import org.openecomp.sdc.common.api.Constants;
67 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
68 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
69 import org.openecomp.sdc.common.log.enums.StatusCode;
70 import org.openecomp.sdc.common.log.wrappers.Logger;
71 import org.openecomp.sdc.exception.ResponseFormat;
72 import org.springframework.stereotype.Controller;
73
74 /**
75  * This servlet provides external interfaces related to abstract templates.
76  *
77  * @author hekeguang
78  */
79 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
80 @Path("/v1/catalog")
81 @Tag(name = "SDCE-7 APIs")
82 @Server(url = "/sdc")
83 @Controller
84 public class AbstractTemplateServlet extends AbstractValidationsServlet {
85
86     private static final Logger log = Logger.getLogger(AbstractTemplateServlet.class);
87     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(AbstractTemplateServlet.class.getName());
88     private final ElementBusinessLogic elementBusinessLogic;
89     private final AbstractTemplateBusinessLogic abstractTemplateBusinessLogic;
90     private final ServiceBusinessLogic serviceBusinessLogic;
91     private final ResourceBusinessLogic resourceBusinessLogic;
92     @Context
93     private HttpServletRequest request;
94
95     @Inject
96     public AbstractTemplateServlet(ComponentInstanceBusinessLogic componentInstanceBL,
97                                    ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
98                                    ElementBusinessLogic elementBusinessLogic, AbstractTemplateBusinessLogic abstractTemplateBusinessLogic,
99                                    ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) {
100         super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
101         this.elementBusinessLogic = elementBusinessLogic;
102         this.abstractTemplateBusinessLogic = abstractTemplateBusinessLogic;
103         this.serviceBusinessLogic = serviceBusinessLogic;
104         this.resourceBusinessLogic = resourceBusinessLogic;
105     }
106
107     /**
108      * @param requestId
109      * @param instanceIdHeader
110      * @param accept
111      * @param authorization
112      * @param uuid
113      * @return
114      */
115     @GET
116     @Path("/abstract/service/serviceUUID/{uuid}/status")
117     @Produces(MediaType.APPLICATION_JSON)
118     @Operation(description = "Fetch abstract status of service", method = "GET", summary = "Return whether the service is a virtual service", responses = {
119         @ApiResponse(responseCode = "200", description = "The check result of whether the service is an abstract service is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))),
120         @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
121         @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
122         @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
123         @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
124         @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
125         @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
126     public Response getServiceAbstractStatus(
127         @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
128         @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
129         @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
130         @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
131         @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) throws IOException {
132         ResponseFormat responseFormat = null;
133         AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TEMPLATE_ABSTRACT_STATUS;
134         String requestURI = request.getRequestURI();
135         String url = request.getMethod() + " " + requestURI;
136         log.debug("getServiceAbstractStatus: Start handle request of {}", url);
137         String assetType = "services";
138         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
139         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
140         DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
141         // Mandatory
142         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
143             log.debug("getServiceAbstractStatus: Missing X-ECOMP-InstanceID header");
144             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
145             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
146             return buildErrorResponse(responseFormat);
147         }
148         try {
149             Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
150                 .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
151             if (assetTypeData.isRight()) {
152                 log.debug("getServiceAbstractStatus: Service Fetching Failed");
153                 responseFormat = assetTypeData.right().value();
154                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
155                 return buildErrorResponse(responseFormat);
156             }
157             resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());
158             log.debug("getServiceAbstractStatus: Service Fetching Success");
159             Either<AbstractTemplateInfo, ResponseFormat> resMetadata = abstractTemplateBusinessLogic
160                 .getServiceAbstractStatus(assetTypeData.left().value());
161             if (resMetadata.isRight()) {
162                 log.debug("getServiceAbstractStatus: Service abstract status get Failed");
163                 responseFormat = resMetadata.right().value();
164                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
165                 return buildErrorResponse(responseFormat);
166             }
167             Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
168             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
169             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
170             return buildOkResponse(responseFormat, result);
171         } catch (Exception e) {
172             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch abstract status of service");
173             log.debug("getServiceAbstractStatus: Fetch abstract status of service with exception", e);
174             throw e;
175         }
176     }
177
178     /**
179      * @param requestId
180      * @param instanceIdHeader
181      * @param accept
182      * @param authorization
183      * @param uuid
184      * @return
185      */
186     @POST
187     @Path("/abstract/service/serviceUUID/{uuid}/copy")
188     @Produces(MediaType.APPLICATION_JSON)
189     @Operation(description = "Copy a new service based on the existing service", method = "POST", summary = "Return whether the copy service is successful", responses = {
190         @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))),
191         @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
192         @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
193         @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
194         @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
195         @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
196         @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
197         @ApiResponse(responseCode = "409", description = "Service already exist")})
198     public Response copyExistService(
199         @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
200         @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
201         @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
202         @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
203         @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
204         @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid,
205         @Parameter(hidden = true) String data) throws IOException {
206         String url = request.getMethod() + " " + request.getRequestURI();
207         log.debug("copyExistService: Start handle request of {}", url);
208         User modifier = new User();
209         modifier.setUserId(userId);
210         log.debug("modifier id is {}", userId);
211         loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, StatusCode.STARTED, "Starting to create a service by user {} ", userId);
212         validateNotEmptyBody(data);
213         Either<CopyServiceInfo, ResponseFormat> convertResponse = parseToCopyServiceInfo(data, modifier);
214         if (convertResponse.isRight()) {
215             throw new ByResponseFormatComponentException(convertResponse.right().value());
216         }
217         String assetType = "services";
218         CopyServiceInfo copyServiceInfo = convertResponse.left().value();
219         Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
220             .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
221         if (assetTypeData.isRight() || assetTypeData.left().value().size() != 1) {
222             log.debug("getServiceAbstractStatus: Service Fetching Failed");
223             throw new ByResponseFormatComponentException(assetTypeData.right().value());
224         }
225         log.debug("getServiceAbstractStatus: Service Fetching Success");
226         Service service = (Service) assetTypeData.left().value().get(0);
227         List<String> tags = service.getTags();
228         if (CollectionUtils.isNotEmpty(tags)) {
229
230             for (int i = tags.size() - 1; i >= 0; i--) {
231                 String tag = tags.get(i);
232                 if (service.getName().equals(tag)) {
233                     tags.remove(tag);
234                 }
235             }
236         } else {
237             tags = new ArrayList<>();
238         }
239         service.setName(copyServiceInfo.getNewServiceName());
240         tags.add(copyServiceInfo.getNewServiceName());
241         Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.createService(service, modifier);
242         if (actionResponse.isRight()) {
243             log.debug("Failed to create service");
244             throw new ByResponseFormatComponentException(actionResponse.right().value());
245         }
246         loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, service.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
247             "Service {} has been copyied by user {} ", service.getName(), userId);
248         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
249     }
250
251     public Either<CopyServiceInfo, ResponseFormat> parseToCopyServiceInfo(String serviceJson, User user) {
252         return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, CopyServiceInfo.class, AuditingActionEnum.CREATE_RESOURCE,
253             ComponentTypeEnum.SERVICE);
254     }
255 }