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