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