aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadEndpoint.java
blob: 5847a06e2b850a5c0955411472aae52d84541c13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * 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.openecomp.sdc.be.servlets;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.openecomp.sdc.be.components.impl.CommonImportManager;
import org.openecomp.sdc.be.components.validation.AccessValidations;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
import org.openecomp.sdc.be.model.AnnotationTypeDefinition;
import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations;
import org.openecomp.sdc.be.utils.TypeUtils;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import com.google.common.annotations.VisibleForTesting;
import com.jcabi.aspects.Loggable;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
/**
 * Here new APIs for types upload written in an attempt to gradually servlet responseCode
 */
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog/uploadType")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@OpenAPIDefinition(info = @Info(title = "Catalog Types Upload"))
@Controller
public class TypesUploadEndpoint {

    private final CommonImportManager commonImportManager;
    private final AnnotationTypeOperations annotationTypeOperations;
    private final AccessValidations accessValidations;

    public TypesUploadEndpoint(CommonImportManager commonImportManager, AnnotationTypeOperations annotationTypeOperations, AccessValidations accessValidations) {
        this.commonImportManager = commonImportManager;
        this.annotationTypeOperations = annotationTypeOperations;
        this.accessValidations = accessValidations;
    }

    @POST
    @Path("/annotationtypes")
    @Operation(description = "Create AnnotationTypes from yaml", method = "POST",
            summary = "Returns created annotation types",responses = @ApiResponse(
                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "annotation types created"),
            @ApiResponse(responseCode = "403", description = "Restricted operation"),
            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
            @ApiResponse(responseCode = "409", description = "annotation types already exist")})
    
    public Response uploadAnnotationTypes(@Parameter(description = "FileInputStream") @FormDataParam("annotationTypesZip") File file,
            @HeaderParam("USER_ID") String userId) throws IOException {
        accessValidations.validateUserExists(userId, "Annotation Types Creation");
        Wrapper<String> yamlStringWrapper = new Wrapper<>();
        AbstractValidationsServlet.extractZipContents(yamlStringWrapper, file);
        List<ImmutablePair<AnnotationTypeDefinition, Boolean>> typesResults =
                commonImportManager.createElementTypes(yamlStringWrapper.getInnerElement(),
                        TypesUploadEndpoint::buildAnnotationFromFieldMap, annotationTypeOperations);
        HttpStatus status = getHttpStatus(typesResults);
        return Response.status(status.value()).entity(typesResults).build();
    }

    @VisibleForTesting
    static <T extends ToscaDataDefinition> HttpStatus getHttpStatus(List<ImmutablePair<T, Boolean>> typesResults) {
        boolean typeActionFailed = false;
        boolean typeExists = false;
        boolean typeActionSucceeded = false;
        for (ImmutablePair<T, Boolean> typeResult : typesResults) {
            Boolean result = typeResult.getRight();
            if (result==null) {
                typeExists = true;
            } else if (result) {
                typeActionSucceeded = true;
            } else {
                typeActionFailed = true;
            }
        }
        HttpStatus status = HttpStatus.OK;
        if (typeActionFailed) {
            status =  HttpStatus.BAD_REQUEST;
        } else if (typeActionSucceeded) {
            status = HttpStatus.CREATED;
        } else if (typeExists) {
            status = HttpStatus.CONFLICT;
        }
        return status;
    }

    private static <T extends ToscaDataDefinition> T buildAnnotationFromFieldMap(String typeName, Map<String, Object> toscaJson) {
        AnnotationTypeDefinition annotationType = new AnnotationTypeDefinition();
        annotationType.setVersion(TypeUtils.getFirstCertifiedVersionVersion());
        annotationType.setHighestVersion(true);
        annotationType.setType(typeName);
        TypeUtils.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, annotationType::setDescription);
        CommonImportManager.setProperties(toscaJson, annotationType::setProperties);
        return (T) annotationType;
    }


}