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