Remove legacy certificate handling
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / TypesUploadEndpoint.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.sdc.be.servlets;
21
22 import com.google.common.annotations.VisibleForTesting;
23 import com.jcabi.aspects.Loggable;
24 import io.swagger.v3.oas.annotations.Operation;
25 import io.swagger.v3.oas.annotations.Parameter;
26 import io.swagger.v3.oas.annotations.media.ArraySchema;
27 import io.swagger.v3.oas.annotations.media.Content;
28 import io.swagger.v3.oas.annotations.media.Schema;
29 import io.swagger.v3.oas.annotations.responses.ApiResponse;
30 import io.swagger.v3.oas.annotations.servers.Server;
31 import io.swagger.v3.oas.annotations.servers.Servers;
32 import io.swagger.v3.oas.annotations.tags.Tag;
33 import io.swagger.v3.oas.annotations.tags.Tags;
34 import java.io.File;
35 import java.util.List;
36 import java.util.Map;
37 import javax.ws.rs.Consumes;
38 import javax.ws.rs.HeaderParam;
39 import javax.ws.rs.POST;
40 import javax.ws.rs.Path;
41 import javax.ws.rs.Produces;
42 import javax.ws.rs.core.MediaType;
43 import javax.ws.rs.core.Response;
44 import org.apache.commons.lang3.tuple.ImmutablePair;
45 import org.glassfish.jersey.media.multipart.FormDataParam;
46 import org.openecomp.sdc.be.components.impl.CommonImportManager;
47 import org.openecomp.sdc.be.components.validation.AccessValidations;
48 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
49 import org.openecomp.sdc.be.impl.ComponentsUtils;
50 import org.openecomp.sdc.be.model.AnnotationTypeDefinition;
51 import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations;
52 import org.openecomp.sdc.be.utils.TypeUtils;
53 import org.openecomp.sdc.common.datastructure.Wrapper;
54 import org.openecomp.sdc.common.zip.exception.ZipException;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.springframework.http.HttpStatus;
58 import org.springframework.stereotype.Controller;
59
60 /**
61  * Here new APIs for types upload written in an attempt to gradually servlet code
62  */
63 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
64 @Path("/v1/catalog/uploadType")
65 @Consumes(MediaType.MULTIPART_FORM_DATA)
66 @Produces(MediaType.APPLICATION_JSON)
67 @Tags({@Tag(name = "SDCE-2 APIs")})
68 @Servers({@Server(url = "/sdc2/rest")})
69 @Controller
70 public class TypesUploadEndpoint extends BeGenericServlet {
71
72     private static final Logger LOGGER = LoggerFactory.getLogger(TypesUploadEndpoint.class);
73     private final CommonImportManager commonImportManager;
74     private final AnnotationTypeOperations annotationTypeOperations;
75     private final AccessValidations accessValidations;
76
77     public TypesUploadEndpoint(ComponentsUtils componentsUtils, CommonImportManager commonImportManager,
78                                AnnotationTypeOperations annotationTypeOperations, AccessValidations accessValidations) {
79         super(componentsUtils);
80         this.commonImportManager = commonImportManager;
81         this.annotationTypeOperations = annotationTypeOperations;
82         this.accessValidations = accessValidations;
83     }
84
85     @VisibleForTesting
86     static <T extends ToscaDataDefinition> HttpStatus getHttpStatus(List<ImmutablePair<T, Boolean>> typesResults) {
87         boolean typeActionFailed = false;
88         boolean typeExists = false;
89         boolean typeActionSucceeded = false;
90         for (ImmutablePair<T, Boolean> typeResult : typesResults) {
91             Boolean result = typeResult.getRight();
92             if (result == null) {
93                 typeExists = true;
94             } else if (result) {
95                 typeActionSucceeded = true;
96             } else {
97                 typeActionFailed = true;
98             }
99         }
100         HttpStatus status = HttpStatus.OK;
101         if (typeActionFailed) {
102             status = HttpStatus.BAD_REQUEST;
103         } else if (typeActionSucceeded) {
104             status = HttpStatus.CREATED;
105         } else if (typeExists) {
106             status = HttpStatus.CONFLICT;
107         }
108         return status;
109     }
110
111     private static <T extends ToscaDataDefinition> T buildAnnotationFromFieldMap(String typeName, Map<String, Object> toscaJson) {
112         AnnotationTypeDefinition annotationType = new AnnotationTypeDefinition();
113         annotationType.setVersion(TypeUtils.getFirstCertifiedVersionVersion());
114         annotationType.setHighestVersion(true);
115         annotationType.setType(typeName);
116         TypeUtils.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, annotationType::setDescription);
117         CommonImportManager.setProperties(toscaJson, annotationType::setProperties);
118         return (T) annotationType;
119     }
120
121     @POST
122     @Path("/annotationtypes")
123     @Operation(description = "Create AnnotationTypes from yaml", method = "POST", summary = "Returns created annotation types", responses = {
124         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
125         @ApiResponse(responseCode = "201", description = "annotation types created"),
126         @ApiResponse(responseCode = "403", description = "Restricted operation"),
127         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
128         @ApiResponse(responseCode = "409", description = "annotation types already exist")})
129     public Response uploadAnnotationTypes(@Parameter(description = "FileInputStream") @FormDataParam("annotationTypesZip") File file,
130                                           @HeaderParam("USER_ID") String userId) {
131         accessValidations.validateUserExists(userId, "Annotation Types Creation");
132         final Wrapper<String> yamlStringWrapper = new Wrapper<>();
133         try {
134             AbstractValidationsServlet.extractZipContents(yamlStringWrapper, file);
135         } catch (final ZipException e) {
136             LOGGER.error("Could not extract zip contents", e);
137         }
138         List<ImmutablePair<AnnotationTypeDefinition, Boolean>> typesResults = commonImportManager
139             .createElementTypes(yamlStringWrapper.getInnerElement(), TypesUploadEndpoint::buildAnnotationFromFieldMap, annotationTypeOperations);
140         HttpStatus status = getHttpStatus(typesResults);
141         return Response.status(status.value()).entity(typesResults).build();
142     }
143 }