[SDC-29] rebase continue work to align source
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / AttributeServlet.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.DELETE;
28 import javax.ws.rs.HeaderParam;
29 import javax.ws.rs.POST;
30 import javax.ws.rs.PUT;
31 import javax.ws.rs.Path;
32 import javax.ws.rs.PathParam;
33 import javax.ws.rs.Produces;
34 import javax.ws.rs.core.Context;
35 import javax.ws.rs.core.MediaType;
36 import javax.ws.rs.core.Response;
37
38 import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic;
39 import org.openecomp.sdc.be.config.BeEcompErrorManager;
40 import org.openecomp.sdc.be.dao.api.ActionStatus;
41 import org.openecomp.sdc.be.model.PropertyDefinition;
42 import org.openecomp.sdc.be.model.User;
43 import org.openecomp.sdc.common.api.Constants;
44 import org.openecomp.sdc.common.datastructure.Wrapper;
45 import org.openecomp.sdc.exception.ResponseFormat;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 import com.google.gson.Gson;
50 import com.google.gson.GsonBuilder;
51 import com.jcabi.aspects.Loggable;
52 import com.wordnik.swagger.annotations.Api;
53 import com.wordnik.swagger.annotations.ApiOperation;
54 import com.wordnik.swagger.annotations.ApiParam;
55 import com.wordnik.swagger.annotations.ApiResponse;
56 import com.wordnik.swagger.annotations.ApiResponses;
57
58 import fj.data.Either;
59
60 /**
61  * Web Servlet for actions on Attributes
62  * 
63  * @author mshitrit
64  *
65  */
66 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
67 @Path("/v1/catalog")
68 @Api(value = "Resource Attribute Servlet", description = "Resource Attribute Servlet")
69 @Singleton
70 public class AttributeServlet extends AbstractValidationsServlet {
71         private static Logger log = LoggerFactory.getLogger(AttributeServlet.class.getName());
72
73         /**
74          * Creates new Attribute on a resource with given resource ID
75          * 
76          * @param resourceId
77          * @param data
78          * @param request
79          * @param userId
80          * @return
81          */
82         @POST
83         @Path("resources/{resourceId}/attributes")
84         @Consumes(MediaType.APPLICATION_JSON)
85         @Produces(MediaType.APPLICATION_JSON)
86         @ApiOperation(value = "Create Resource Attribute", httpMethod = "POST", notes = "Returns created resource attribute", response = Response.class)
87         @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
88                         @ApiResponse(code = 409, message = "Resource attribute already exist") })
89         public Response createAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource attribute to be created", required = true) String data,
90                         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
91
92                 ServletContext context = request.getSession().getServletContext();
93
94                 String url = request.getMethod() + " " + request.getRequestURI();
95                 log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
96
97                 try {
98                         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
99                         Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>();
100                         // convert json to AttributeDefinition
101
102                         buildAttributeFromString(data, attributesWrapper, errorWrapper);
103                         if (errorWrapper.isEmpty()) {
104                                 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
105                                 Either<PropertyDefinition, ResponseFormat> createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId);
106                                 if (createAttribute.isRight()) {
107                                         errorWrapper.setInnerElement(createAttribute.right().value());
108                                 } else {
109                                         attributesWrapper.setInnerElement(createAttribute.left().value());
110                                 }
111                         }
112
113                         Response response;
114                         if (!errorWrapper.isEmpty()) {
115                                 log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement());
116                                 response = buildErrorResponse(errorWrapper.getInnerElement());
117                         } else {
118                                 PropertyDefinition createdAttDef = attributesWrapper.getInnerElement();
119                                 log.debug("Attribute {} created successfully with id {}", createdAttDef.getName(), createdAttDef.getUniqueId());
120                                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
121                                 response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(createdAttDef));
122                         }
123
124                         return response;
125
126                 } catch (Exception e) {
127                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute");
128                         log.debug("create property failed with exception", e);
129                         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
130                         return buildErrorResponse(responseFormat);
131
132                 }
133         }
134
135         /**
136          * Updates existing Attribute with given attributeID on a resource with given resourceID
137          * 
138          * @param resourceId
139          * @param attributeId
140          * @param data
141          * @param request
142          * @param userId
143          * @return
144          */
145         @PUT
146         @Path("resources/{resourceId}/attributes/{attributeId}")
147         @Consumes(MediaType.APPLICATION_JSON)
148         @Produces(MediaType.APPLICATION_JSON)
149         @ApiOperation(value = "Update Resource Attribute", httpMethod = "PUT", notes = "Returns updated attribute", response = Response.class)
150         @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource attribute updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
151         public Response updateAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId,
152                         @ApiParam(value = "attribute id to update", required = true) @PathParam("attributeId") final String attributeId, @ApiParam(value = "Resource attribute to update", required = true) String data, @Context final HttpServletRequest request,
153                         @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
154
155                 ServletContext context = request.getSession().getServletContext();
156
157                 String url = request.getMethod() + " " + request.getRequestURI();
158                 log.debug("Start handle request of {}", url);
159
160                 // get modifier id
161                 User modifier = new User();
162                 modifier.setUserId(userId);
163                 log.debug("modifier id is {}", userId);
164
165                 try {
166                         // convert json to PropertyDefinition
167                         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
168                         Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>();
169                         // convert json to AttributeDefinition
170
171                         buildAttributeFromString(data, attributesWrapper, errorWrapper);
172
173                         if (errorWrapper.isEmpty()) {
174                                 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
175                                 Either<PropertyDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId);
176                                 // update property
177                                 if (eitherUpdateAttribute.isRight()) {
178                                         errorWrapper.setInnerElement(eitherUpdateAttribute.right().value());
179                                 } else {
180                                         attributesWrapper.setInnerElement(eitherUpdateAttribute.left().value());
181                                 }
182                         }
183
184                         Response response;
185                         if (!errorWrapper.isEmpty()) {
186                                 log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement());
187                                 response = buildErrorResponse(errorWrapper.getInnerElement());
188                         } else {
189                                 PropertyDefinition updatedAttribute = attributesWrapper.getInnerElement();
190                                 log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId());
191                                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
192                                 response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute));
193                         }
194
195                         return response;
196
197                 } catch (Exception e) {
198                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute");
199                         log.debug("update attribute failed with exception", e);
200                         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
201                         return buildErrorResponse(responseFormat);
202
203                 }
204         }
205
206         /**
207          * Deletes existing Attribute with given attributeID on a resource with given resourceID
208          * 
209          * @param resourceId
210          * @param attributeId
211          * @param request
212          * @param userId
213          * @return
214          */
215         @DELETE
216         @Path("resources/{resourceId}/attributes/{attributeId}")
217         @Consumes(MediaType.APPLICATION_JSON)
218         @Produces(MediaType.APPLICATION_JSON)
219         @ApiOperation(value = "Create Resource Attribute", httpMethod = "DELETE", notes = "Returns deleted attribute", response = Response.class)
220         @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted attribute"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
221                         @ApiResponse(code = 404, message = "Resource property not found") })
222         public Response deleteAttribute(@ApiParam(value = "resource id of attribute", required = true) @PathParam("resourceId") final String resourceId,
223                         @ApiParam(value = "Attribute id to delete", required = true) @PathParam("attributeId") final String attributeId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
224
225                 ServletContext context = request.getSession().getServletContext();
226
227                 String url = request.getMethod() + " " + request.getRequestURI();
228                 log.debug("Start handle request of {}", url);
229                 log.debug("modifier id is {}", userId);
230
231                 try {
232
233                         // delete the property
234                         AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
235                         Either<PropertyDefinition, ResponseFormat> eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId);
236                         if (eitherAttribute.isRight()) {
237                                 log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value());
238                                 return buildErrorResponse(eitherAttribute.right().value());
239                         }
240                         PropertyDefinition attributeDefinition = eitherAttribute.left().value();
241                         String name = attributeDefinition.getName();
242
243                         log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId());
244                         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
245                         return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition));
246
247                 } catch (Exception e) {
248                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute");
249                         log.debug("delete attribute failed with exception", e);
250                         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
251                         return buildErrorResponse(responseFormat);
252
253                 }
254         }
255
256         private void buildAttributeFromString(String data, Wrapper<PropertyDefinition> attributesWrapper, Wrapper<ResponseFormat> errorWrapper) {
257
258                 try {
259                         Gson gson = new GsonBuilder().setPrettyPrinting().create();
260                         final PropertyDefinition attribute = gson.fromJson(data, PropertyDefinition.class);
261                         if (attribute == null) {
262                                 log.info("Attribute content is invalid - {}", data);
263                                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
264                                 errorWrapper.setInnerElement(responseFormat);
265                         } else {
266                                 attributesWrapper.setInnerElement(attribute);
267                         }
268
269                 } catch (Exception e) {
270                         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
271                         errorWrapper.setInnerElement(responseFormat);
272                         log.debug("Attribute content is invalid - {}", data, e);
273                         log.info("Attribute content is invalid - {}", data);
274                 }
275         }
276 }