2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.servlets;
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;
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;
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;
58 import fj.data.Either;
61 * Web Servlet for actions on Attributes
66 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
68 @Api(value = "Resource Attribute Servlet", description = "Resource Attribute Servlet")
70 public class AttributeServlet extends AbstractValidationsServlet {
71 private static Logger log = LoggerFactory.getLogger(AttributeServlet.class.getName());
74 * Creates new Attribute on a resource with given resource ID
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) {
92 ServletContext context = request.getSession().getServletContext();
94 String url = request.getMethod() + " " + request.getRequestURI();
95 log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
98 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
99 Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>();
100 // convert json to AttributeDefinition
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());
109 attributesWrapper.setInnerElement(createAttribute.left().value());
114 if (!errorWrapper.isEmpty()) {
115 log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement());
116 response = buildErrorResponse(errorWrapper.getInnerElement());
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));
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);
136 * Updates existing Attribute with given attributeID on a resource with given resourceID
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) {
155 ServletContext context = request.getSession().getServletContext();
157 String url = request.getMethod() + " " + request.getRequestURI();
158 log.debug("Start handle request of {}", url);
161 User modifier = new User();
162 modifier.setUserId(userId);
163 log.debug("modifier id is {}", userId);
166 // convert json to PropertyDefinition
167 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
168 Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>();
169 // convert json to AttributeDefinition
171 buildAttributeFromString(data, attributesWrapper, errorWrapper);
173 if (errorWrapper.isEmpty()) {
174 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
175 Either<PropertyDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId);
177 if (eitherUpdateAttribute.isRight()) {
178 errorWrapper.setInnerElement(eitherUpdateAttribute.right().value());
180 attributesWrapper.setInnerElement(eitherUpdateAttribute.left().value());
185 if (!errorWrapper.isEmpty()) {
186 log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement());
187 response = buildErrorResponse(errorWrapper.getInnerElement());
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));
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);
207 * Deletes existing Attribute with given attributeID on a resource with given resourceID
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) {
225 ServletContext context = request.getSession().getServletContext();
227 String url = request.getMethod() + " " + request.getRequestURI();
228 log.debug("Start handle request of {}", url);
229 log.debug("modifier id is {}", userId);
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());
240 PropertyDefinition attributeDefinition = eitherAttribute.left().value();
241 String name = attributeDefinition.getName();
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));
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);
256 private void buildAttributeFromString(String data, Wrapper<PropertyDefinition> attributesWrapper, Wrapper<ResponseFormat> errorWrapper) {
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);
266 attributesWrapper.setInnerElement(attribute);
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);