Reformat catalog-be
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / GroupServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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.jcabi.aspects.Loggable;
23 import fj.data.Either;
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.IOException;
35 import javax.inject.Inject;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.ws.rs.Consumes;
38 import javax.ws.rs.DELETE;
39 import javax.ws.rs.GET;
40 import javax.ws.rs.HeaderParam;
41 import javax.ws.rs.POST;
42 import javax.ws.rs.PUT;
43 import javax.ws.rs.Path;
44 import javax.ws.rs.PathParam;
45 import javax.ws.rs.Produces;
46 import javax.ws.rs.core.Context;
47 import javax.ws.rs.core.MediaType;
48 import javax.ws.rs.core.Response;
49 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
50 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
51 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
52 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
53 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
54 import org.openecomp.sdc.be.config.BeEcompErrorManager;
55 import org.openecomp.sdc.be.dao.api.ActionStatus;
56 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
57 import org.openecomp.sdc.be.impl.ComponentsUtils;
58 import org.openecomp.sdc.be.impl.ServletUtils;
59 import org.openecomp.sdc.be.info.GroupDefinitionInfo;
60 import org.openecomp.sdc.be.model.GroupDefinition;
61 import org.openecomp.sdc.be.model.Resource;
62 import org.openecomp.sdc.be.model.User;
63 import org.openecomp.sdc.be.user.UserBusinessLogic;
64 import org.openecomp.sdc.common.api.Constants;
65 import org.openecomp.sdc.common.log.wrappers.Logger;
66 import org.openecomp.sdc.exception.ResponseFormat;
67 import org.springframework.stereotype.Controller;
68
69 /**
70  * Root resource (exposed at "/" path)
71  */
72 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
73 @Consumes(MediaType.APPLICATION_JSON)
74 @Produces(MediaType.APPLICATION_JSON)
75 @Path("/v1/catalog")
76 @Tags({@Tag(name = "SDC Internal APIs")})
77 @Servers({@Server(url = "/sdc2/rest")})
78 @Controller
79 public class GroupServlet extends AbstractValidationsServlet {
80
81     public static final String START_HANDLE_REQUEST = "Start handle request of {}";
82     private static final Logger log = Logger.getLogger(GroupServlet.class);
83     private final GroupBusinessLogic groupBL;
84
85     @Inject
86     public GroupServlet(UserBusinessLogic userBusinessLogic, GroupBusinessLogic groupBL, ComponentInstanceBusinessLogic componentInstanceBL,
87                         ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager) {
88         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
89         this.groupBL = groupBL;
90     }
91
92     @POST
93     @Path("/{containerComponentType}/{componentId}/groups/{groupType}")
94     @Operation(description = "Create group ", method = "POST", summary = "Creates new group in component and returns it", responses = {
95         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))),
96         @ApiResponse(responseCode = "201", description = "Group created"),
97         @ApiResponse(responseCode = "400", description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
98         @ApiResponse(responseCode = "403", description = "Restricted operation"),
99         @ApiResponse(responseCode = "404", description = "Component not found"), @ApiResponse(responseCode = "500", description = "Internal Error")})
100     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
101     public Response createGroup(@PathParam("containerComponentType") final String containerComponentType,
102                                 @PathParam("componentId") final String componentId, @PathParam("groupType") final String type,
103                                 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
104         String url = request.getMethod() + " " + request.getRequestURI();
105         log.debug("(post) Start handle request of {}", url);
106         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
107         GroupDefinition groupDefinition = groupBL.createGroup(componentId, componentTypeEnum, type, userId);
108         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), groupDefinition);
109     }
110
111     @GET
112     @Path("/{containerComponentType}/{componentId}/groups/{groupId}")
113     @Operation(description = "Get group artifacts ", method = "GET", summary = "Returns artifacts metadata according to groupId", responses = {
114         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
115         @ApiResponse(responseCode = "200", description = "group found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
116         @ApiResponse(responseCode = "404", description = "Group not found")})
117     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
118     public Response getGroupById(@PathParam("containerComponentType") final String containerComponentType,
119                                  @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
120                                  @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
121         String url = request.getMethod() + " " + request.getRequestURI();
122         log.debug("(get) Start handle request of {}", url);
123         try {
124             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
125             Either<GroupDefinitionInfo, ResponseFormat> actionResponse = groupBL
126                 .getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false);
127             if (actionResponse.isRight()) {
128                 log.debug("failed to get all non abstract {}", containerComponentType);
129                 return buildErrorResponse(actionResponse.right().value());
130             }
131             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
132         } catch (Exception e) {
133             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
134             log.debug("getGroupArtifactById unexpected exception", e);
135             throw e;
136         }
137     }
138
139     @DELETE
140     @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}")
141     @Operation(description = "Delete Group", method = "DELETE", summary = "Returns deleted group id", responses = {
142         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
143         @ApiResponse(responseCode = "201", description = "ResourceInstance deleted"),
144         @ApiResponse(responseCode = "400", description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
145         @ApiResponse(responseCode = "403", description = "Restricted operation"),
146         @ApiResponse(responseCode = "404", description = "Component not found"), @ApiResponse(responseCode = "500", description = "Internal Error")})
147     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
148     public Response deleteGroup(@PathParam("containerComponentType") final String containerComponentType,
149                                 @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupId,
150                                 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
151         String url = request.getMethod() + " " + request.getRequestURI();
152         log.debug(START_HANDLE_REQUEST, url);
153         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
154         GroupDefinition groupDefinition = groupBL.deleteGroup(componentId, componentTypeEnum, groupId, userId);
155         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), groupDefinition.getUniqueId());
156     }
157
158     @PUT
159     @Path("/{containerComponentType}/{componentId}/groups/{groupId}")
160     @Operation(description = "Update Group metadata", method = "PUT", summary = "Returns updated Group", responses = {
161         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
162         @ApiResponse(responseCode = "200", description = "Group updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
163         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
164         @ApiResponse(responseCode = "404", description = "component / group Not found")})
165     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
166     public Response updateGroup(@PathParam("containerComponentType") final String containerComponentType,
167                                 @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
168                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
169                                 @Parameter(description = "GroupDefinition", required = true) GroupDefinition groupData,
170                                 @Context final HttpServletRequest request) {
171         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
172         GroupDefinition updatedGroup = groupBL.updateGroup(componentId, componentTypeEnum, groupId, userId, groupData);
173         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updatedGroup);
174     }
175
176     @PUT
177     @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/metadata")
178     @Consumes(MediaType.APPLICATION_JSON)
179     @Produces(MediaType.APPLICATION_JSON)
180     @Operation(description = "Update Group Metadata", method = "PUT", summary = "Returns updated group definition", responses = {
181         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))),
182         @ApiResponse(responseCode = "200", description = "Group Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
183         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
184     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
185     public Response updateGroupMetadata(@PathParam("containerComponentType") final String containerComponentType,
186                                         @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
187                                         @Parameter(description = "Service object to be Updated", required = true) String data,
188                                         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
189         throws IOException {
190         String url = request.getMethod() + " " + request.getRequestURI();
191         log.debug(START_HANDLE_REQUEST, url);
192         User user = new User();
193         user.setUserId(userId);
194         log.debug("modifier id is {}", userId);
195         try {
196             Either<GroupDefinition, ResponseFormat> convertResponse = parseToObject(data, () -> GroupDefinition.class);
197             if (convertResponse.isRight()) {
198                 log.debug("failed to parse group");
199                 return buildErrorResponse(convertResponse.right().value());
200             }
201             GroupDefinition updatedGroup = convertResponse.left().value();
202             // Update GroupDefinition
203             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
204             Either<GroupDefinition, ResponseFormat> actionResponse = groupBL
205                 .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true, true);
206             if (actionResponse.isRight()) {
207                 log.debug("failed to update GroupDefinition");
208                 return buildErrorResponse(actionResponse.right().value());
209             }
210             GroupDefinition group = actionResponse.left().value();
211             Object result = RepresentationUtils.toRepresentation(group);
212             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
213         } catch (Exception e) {
214             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Metadata");
215             log.debug("update group metadata failed with exception", e);
216             throw e;
217         }
218     }
219 }