Catalog alignment
[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.OpenAPIDefinition;
26 import io.swagger.v3.oas.annotations.Operation;
27 import io.swagger.v3.oas.annotations.Parameter;
28 import io.swagger.v3.oas.annotations.info.Info;
29 import io.swagger.v3.oas.annotations.media.ArraySchema;
30 import io.swagger.v3.oas.annotations.media.Content;
31 import io.swagger.v3.oas.annotations.media.Schema;
32 import io.swagger.v3.oas.annotations.responses.ApiResponse;
33 import io.swagger.v3.oas.annotations.responses.ApiResponses;
34 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
35 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
36 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
37 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
38 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
39 import org.openecomp.sdc.be.config.BeEcompErrorManager;
40 import org.openecomp.sdc.be.dao.api.ActionStatus;
41 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
42 import org.openecomp.sdc.be.impl.ComponentsUtils;
43 import org.openecomp.sdc.be.impl.ServletUtils;
44 import org.openecomp.sdc.be.info.GroupDefinitionInfo;
45 import org.openecomp.sdc.be.model.GroupDefinition;
46 import org.openecomp.sdc.be.model.Resource;
47 import org.openecomp.sdc.be.model.User;
48 import org.openecomp.sdc.be.user.UserBusinessLogic;
49 import org.openecomp.sdc.common.api.Constants;
50 import org.openecomp.sdc.common.log.wrappers.Logger;
51 import org.openecomp.sdc.exception.ResponseFormat;
52 import org.springframework.stereotype.Controller;
53
54 import javax.inject.Inject;
55 import javax.servlet.http.HttpServletRequest;
56 import javax.ws.rs.Consumes;
57 import javax.ws.rs.DELETE;
58 import javax.ws.rs.GET;
59 import javax.ws.rs.HeaderParam;
60 import javax.ws.rs.POST;
61 import javax.ws.rs.PUT;
62 import javax.ws.rs.Path;
63 import javax.ws.rs.PathParam;
64 import javax.ws.rs.Produces;
65 import javax.ws.rs.core.Context;
66 import javax.ws.rs.core.MediaType;
67 import javax.ws.rs.core.Response;
68 import java.io.IOException;
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 @OpenAPIDefinition(info = @Info(title = "Group Servlet"))
78 @Controller
79 public class GroupServlet extends AbstractValidationsServlet {
80
81     private static final Logger log = Logger.getLogger(GroupServlet.class);
82     public static final String START_HANDLE_REQUEST = "Start handle request of {}";
83     private final GroupBusinessLogic groupBL;
84
85     @Inject
86     public GroupServlet(UserBusinessLogic userBusinessLogic, GroupBusinessLogic groupBL,
87             ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
88             ServletUtils servletUtils, ResourceImportManager resourceImportManager) {
89         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
90         this.groupBL = groupBL;
91     }
92
93     @POST
94     @Path("/{containerComponentType}/{componentId}/groups/{groupType}")
95     @Operation(description = "Create group ", method = "POST",
96             summary = "Creates new group in component and returns it", responses = @ApiResponse(
97                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))))
98     @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Group created"), @ApiResponse(
99             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 = @ApiResponse(
123                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))
124     @ApiResponses(value = {@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",
159             responses = @ApiResponse(
160                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
161     @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "ResourceInstance deleted"), @ApiResponse(
162             responseCode = "400",
163             description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
164             @ApiResponse(responseCode = "403", description = "Restricted operation"),
165             @ApiResponse(responseCode = "404", description = "Component not found"),
166             @ApiResponse(responseCode = "500", description = "Internal Error")})
167     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
168     public Response deleteGroup(@PathParam("containerComponentType") final String containerComponentType,
169             @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupId,
170             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
171         String url = request.getMethod() + " " + request.getRequestURI();
172         log.debug(START_HANDLE_REQUEST, url);
173         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
174         GroupDefinition groupDefinition = groupBL
175                 .deleteGroup(componentId, componentTypeEnum, groupId, userId);
176
177         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), groupDefinition.getUniqueId());
178     }
179
180     @PUT
181     @Path("/{containerComponentType}/{componentId}/groups/{groupId}")
182     @Operation(description = "Update Group metadata", method = "PUT", summary = "Returns updated Group",
183             responses = @ApiResponse(
184                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
185     @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Group updated"),
186             @ApiResponse(responseCode = "403", description = "Restricted operation"),
187             @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
188             @ApiResponse(responseCode = "404", description = "component / group Not found")})
189     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
190     public Response updateGroup(@PathParam("containerComponentType") final String containerComponentType,
191             @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
192             @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
193             @Parameter(description = "GroupDefinition", required = true) GroupDefinition groupData,
194             @Context final HttpServletRequest request) {
195         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
196         GroupDefinition updatedGroup = groupBL.updateGroup(componentId, componentTypeEnum, groupId, userId, groupData);
197         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updatedGroup);
198     }
199
200     @PUT
201     @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/metadata")
202     @Consumes(MediaType.APPLICATION_JSON)
203     @Produces(MediaType.APPLICATION_JSON)
204     @Operation(description = "Update Group Metadata", method = "PUT", summary = "Returns updated group definition",
205             responses = @ApiResponse(
206                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))))
207     @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Group Updated"),
208             @ApiResponse(responseCode = "403", description = "Restricted operation"),
209             @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
210     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
211     public Response updateGroupMetadata(@PathParam("containerComponentType") final String containerComponentType,
212             @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
213             @Parameter(description = "Service object to be Updated", required = true) String data,
214             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
215
216         String url = request.getMethod() + " " + request.getRequestURI();
217         log.debug(START_HANDLE_REQUEST, url);
218
219         User user = new User();
220         user.setUserId(userId);
221         log.debug("modifier id is {}", userId);
222
223         Response response = null;
224
225         try {
226             Either<GroupDefinition, ResponseFormat> convertResponse = parseToObject(data, () -> GroupDefinition.class);
227             if (convertResponse.isRight()) {
228                 log.debug("failed to parse group");
229                 response = buildErrorResponse(convertResponse.right().value());
230                 return response;
231             }
232             GroupDefinition updatedGroup = convertResponse.left().value();
233
234             // Update GroupDefinition
235             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
236             Either<GroupDefinition, ResponseFormat> actionResponse = groupBL
237                     .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true ,true);
238
239             if (actionResponse.isRight()) {
240                 log.debug("failed to update GroupDefinition");
241                 response = buildErrorResponse(actionResponse.right().value());
242                 return response;
243             }
244
245             GroupDefinition group = actionResponse.left().value();
246             Object result = RepresentationUtils.toRepresentation(group);
247             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
248
249         } catch (Exception e) {
250             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Metadata");
251             log.debug("update group metadata failed with exception", e);
252             throw e;
253         }
254     }
255
256 }