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