Initial OpenECOMP SDC commit
[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 javax.inject.Singleton;
24 import javax.servlet.ServletContext;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.ws.rs.Consumes;
27 import javax.ws.rs.GET;
28 import javax.ws.rs.HeaderParam;
29 import javax.ws.rs.PUT;
30 import javax.ws.rs.Path;
31 import javax.ws.rs.PathParam;
32 import javax.ws.rs.Produces;
33 import javax.ws.rs.core.Context;
34 import javax.ws.rs.core.MediaType;
35 import javax.ws.rs.core.Response;
36
37 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
38 import org.openecomp.sdc.be.config.BeEcompErrorManager;
39 import org.openecomp.sdc.be.dao.api.ActionStatus;
40 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
41 import org.openecomp.sdc.be.info.GroupDefinitionInfo;
42 import org.openecomp.sdc.be.model.GroupDefinition;
43 import org.openecomp.sdc.be.model.Resource;
44 import org.openecomp.sdc.be.model.User;
45 import org.openecomp.sdc.common.api.Constants;
46 import org.openecomp.sdc.common.config.EcompErrorName;
47 import org.openecomp.sdc.exception.ResponseFormat;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 import com.google.gson.Gson;
52 import com.google.gson.GsonBuilder;
53 import com.jcabi.aspects.Loggable;
54 import com.wordnik.swagger.annotations.Api;
55 import com.wordnik.swagger.annotations.ApiOperation;
56 import com.wordnik.swagger.annotations.ApiParam;
57 import com.wordnik.swagger.annotations.ApiResponse;
58 import com.wordnik.swagger.annotations.ApiResponses;
59
60 import fj.data.Either;
61
62 /**
63  * Root resource (exposed at "/" path)
64  */
65 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
66 @Path("/v1/catalog")
67 @Api(value = "Resource Group Servlet", description = "Resource Group Servlet")
68 @Singleton
69 public class GroupServlet extends AbstractValidationsServlet {
70
71         private static Logger log = LoggerFactory.getLogger(GroupServlet.class.getName());
72
73         private Gson gson = new Gson();
74
75         @GET
76         @Path("/{containerComponentType}/{componentId}/groups/{groupId}")
77         @Consumes(MediaType.APPLICATION_JSON)
78         @Produces(MediaType.APPLICATION_JSON)
79         @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupId", response = Resource.class)
80         @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") })
81         public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
82                         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
83                 ServletContext context = request.getSession().getServletContext();
84                 String url = request.getMethod() + " " + request.getRequestURI();
85                 log.debug("(get) Start handle request of {}", url);
86                 Response response = null;
87
88                 try {
89
90                         GroupBusinessLogic businessLogic = this.getGroupBL(context);
91                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
92                         Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic.getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false);
93
94                         if (actionResponse.isRight()) {
95                                 log.debug("failed to get all non abstract {}", containerComponentType);
96                                 return buildErrorResponse(actionResponse.right().value());
97                         }
98
99                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
100
101                 } catch (Throwable e) {
102                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "getGroupArtifactById");
103                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
104                         log.debug("getGroupArtifactById unexpected exception", e);
105                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
106                 }
107
108         }
109
110         @PUT
111         @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/metadata")
112         @Consumes(MediaType.APPLICATION_JSON)
113         @Produces(MediaType.APPLICATION_JSON)
114         @ApiOperation(value = "Update Group Metadata", httpMethod = "PUT", notes = "Returns updated group definition", response = GroupDefinition.class)
115         @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
116         public Response updateGroupMetadata(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
117                         @ApiParam(value = "Service object to be Updated", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
118
119                 ServletContext context = request.getSession().getServletContext();
120                 String url = request.getMethod() + " " + request.getRequestURI();
121                 log.debug("Start handle request of {}", url);
122
123                 User user = new User();
124                 user.setUserId(userId);
125                 log.debug("modifier id is {}", userId);
126
127                 Response response = null;
128
129                 try {
130                         GroupBusinessLogic businessLogic = getGroupBL(context);
131
132                         Either<GroupDefinition, ResponseFormat> convertResponse = parseToGroup(data);
133                         if (convertResponse.isRight()) {
134                                 log.debug("failed to parse group");
135                                 response = buildErrorResponse(convertResponse.right().value());
136                                 return response;
137                         }
138                         GroupDefinition updatedGroup = convertResponse.left().value();
139
140                         // Update GroupDefinition
141                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
142                         Either<GroupDefinition, ResponseFormat> actionResponse = businessLogic.updateGroupMetadata(componentId, user, groupUniqueId, componentTypeEnum, updatedGroup, true);
143
144                         if (actionResponse.isRight()) {
145                                 log.debug("failed to update GroupDefinition");
146                                 response = buildErrorResponse(actionResponse.right().value());
147                                 return response;
148                         }
149
150                         GroupDefinition group = actionResponse.left().value();
151                         Object result = RepresentationUtils.toRepresentation(group);
152                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
153
154                 } catch (Exception e) {
155                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Group Metadata");
156                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Metadata");
157                         log.debug("update group metadata failed with exception", e);
158                         response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
159                         return response;
160
161                 }
162         }
163
164         /**
165          * Convert data to GroupDefinition object
166          * 
167          * @param groupJson
168          * @return
169          */
170         public Either<GroupDefinition, ResponseFormat> parseToGroup(String groupJson) {
171                 try {
172                         Gson gson = new GsonBuilder().setPrettyPrinting().create();
173                         GroupDefinition groupDefinition = gson.fromJson(groupJson, GroupDefinition.class);
174                         return Either.left(groupDefinition);
175                 } catch (Exception e) {
176                         log.debug("Failed to parse json (group data) to GroupDefinition object");
177                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
178                         return Either.right(responseFormat);
179                 }
180         }
181
182 }