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