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