e25783204e882a4aee36a77eee0677738758bd83
[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.impl.aaf.AafPermission;
48 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
49 import org.openecomp.sdc.be.components.validation.AccessValidations;
50 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
51 import org.openecomp.sdc.be.impl.ComponentsUtils;
52 import org.openecomp.sdc.be.model.AnnotationTypeDefinition;
53 import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations;
54 import org.openecomp.sdc.be.utils.TypeUtils;
55 import org.openecomp.sdc.common.datastructure.Wrapper;
56 import org.openecomp.sdc.common.zip.exception.ZipException;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.springframework.http.HttpStatus;
60 import org.springframework.stereotype.Controller;
61
62 /**
63  * Here new APIs for types upload written in an attempt to gradually servlet code
64  */
65 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
66 @Path("/v1/catalog/uploadType")
67 @Consumes(MediaType.MULTIPART_FORM_DATA)
68 @Produces(MediaType.APPLICATION_JSON)
69 @Tags({@Tag(name = "SDCE-2 APIs")})
70 @Servers({@Server(url = "/sdc2/rest")})
71 @Controller
72 public class TypesUploadEndpoint extends BeGenericServlet {
73
74     private static final Logger LOGGER = LoggerFactory.getLogger(TypesUploadEndpoint.class);
75     private final CommonImportManager commonImportManager;
76     private final AnnotationTypeOperations annotationTypeOperations;
77     private final AccessValidations accessValidations;
78
79     public TypesUploadEndpoint(ComponentsUtils componentsUtils, CommonImportManager commonImportManager,
80                                AnnotationTypeOperations annotationTypeOperations, AccessValidations accessValidations) {
81         super(componentsUtils);
82         this.commonImportManager = commonImportManager;
83         this.annotationTypeOperations = annotationTypeOperations;
84         this.accessValidations = accessValidations;
85     }
86
87     @VisibleForTesting
88     static <T extends ToscaDataDefinition> HttpStatus getHttpStatus(List<ImmutablePair<T, Boolean>> typesResults) {
89         boolean typeActionFailed = false;
90         boolean typeExists = false;
91         boolean typeActionSucceeded = false;
92         for (ImmutablePair<T, Boolean> typeResult : typesResults) {
93             Boolean result = typeResult.getRight();
94             if (result == null) {
95                 typeExists = true;
96             } else if (result) {
97                 typeActionSucceeded = true;
98             } else {
99                 typeActionFailed = true;
100             }
101         }
102         HttpStatus status = HttpStatus.OK;
103         if (typeActionFailed) {
104             status = HttpStatus.BAD_REQUEST;
105         } else if (typeActionSucceeded) {
106             status = HttpStatus.CREATED;
107         } else if (typeExists) {
108             status = HttpStatus.CONFLICT;
109         }
110         return status;
111     }
112
113     private static <T extends ToscaDataDefinition> T buildAnnotationFromFieldMap(String typeName, Map<String, Object> toscaJson) {
114         AnnotationTypeDefinition annotationType = new AnnotationTypeDefinition();
115         annotationType.setVersion(TypeUtils.getFirstCertifiedVersionVersion());
116         annotationType.setHighestVersion(true);
117         annotationType.setType(typeName);
118         TypeUtils.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, annotationType::setDescription);
119         CommonImportManager.setProperties(toscaJson, annotationType::setProperties);
120         return (T) annotationType;
121     }
122
123     @POST
124     @Path("/annotationtypes")
125     @Operation(description = "Create AnnotationTypes from yaml", method = "POST", summary = "Returns created annotation types", responses = {
126         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
127         @ApiResponse(responseCode = "201", description = "annotation types created"),
128         @ApiResponse(responseCode = "403", description = "Restricted operation"),
129         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
130         @ApiResponse(responseCode = "409", description = "annotation types already exist")})
131     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
132     public Response uploadAnnotationTypes(@Parameter(description = "FileInputStream") @FormDataParam("annotationTypesZip") File file,
133                                           @HeaderParam("USER_ID") String userId) {
134         accessValidations.validateUserExists(userId, "Annotation Types Creation");
135         final Wrapper<String> yamlStringWrapper = new Wrapper<>();
136         try {
137             AbstractValidationsServlet.extractZipContents(yamlStringWrapper, file);
138         } catch (final ZipException e) {
139             LOGGER.error("Could not extract zip contents", e);
140         }
141         List<ImmutablePair<AnnotationTypeDefinition, Boolean>> typesResults = commonImportManager
142             .createElementTypes(yamlStringWrapper.getInnerElement(), TypesUploadEndpoint::buildAnnotationFromFieldMap, annotationTypeOperations);
143         HttpStatus status = getHttpStatus(typesResults);
144         return Response.status(status.value()).entity(typesResults).build();
145     }
146 }