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 com.fasterxml.jackson.databind.ObjectMapper;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.jcabi.aspects.Loggable;
27 import fj.data.Either;
28 import io.swagger.v3.oas.annotations.Operation;
29 import io.swagger.v3.oas.annotations.Parameter;
30 import io.swagger.v3.oas.annotations.media.ArraySchema;
31 import io.swagger.v3.oas.annotations.media.Content;
32 import io.swagger.v3.oas.annotations.media.Schema;
33 import io.swagger.v3.oas.annotations.responses.ApiResponse;
34 import io.swagger.v3.oas.annotations.servers.Server;
35 import io.swagger.v3.oas.annotations.tags.Tag;
36 import java.io.IOException;
37 import javax.inject.Inject;
38 import javax.servlet.ServletContext;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.ws.rs.Consumes;
41 import javax.ws.rs.DELETE;
42 import javax.ws.rs.HeaderParam;
43 import javax.ws.rs.POST;
44 import javax.ws.rs.PUT;
45 import javax.ws.rs.Path;
46 import javax.ws.rs.PathParam;
47 import javax.ws.rs.Produces;
48 import javax.ws.rs.core.Context;
49 import javax.ws.rs.core.MediaType;
50 import javax.ws.rs.core.Response;
51 import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic;
52 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
53 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
54 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
55 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
56 import org.openecomp.sdc.be.config.BeEcompErrorManager;
57 import org.openecomp.sdc.be.dao.api.ActionStatus;
58 import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
59 import org.openecomp.sdc.be.impl.ComponentsUtils;
60 import org.openecomp.sdc.be.impl.ServletUtils;
61 import org.openecomp.sdc.be.model.User;
62 import org.openecomp.sdc.be.user.UserBusinessLogic;
63 import org.openecomp.sdc.common.api.Constants;
64 import org.openecomp.sdc.common.datastructure.Wrapper;
65 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
66 import org.openecomp.sdc.common.log.wrappers.Logger;
67 import org.openecomp.sdc.exception.ResponseFormat;
68 import org.springframework.stereotype.Controller;
71 * Web Servlet for actions on Attributes
76 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
78 @Tag(name = "SDC Internal APIs")
79 @Server(url = "/sdc2/rest")
81 public class AttributeServlet extends AbstractValidationsServlet {
82 private static final Logger log = Logger.getLogger(AttributeServlet.class);
83 private static final String ATTRIBUTE_CONTENT_IS_INVALID = "Attribute content is invalid - {}";
85 public AttributeServlet(UserBusinessLogic userBusinessLogic,
86 ComponentInstanceBusinessLogic componentInstanceBL,
87 ComponentsUtils componentsUtils, ServletUtils servletUtils,
88 ResourceImportManager resourceImportManager) {
89 super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
93 * Creates new Attribute on a resource with given resource ID
102 @Path("resources/{resourceId}/attributes")
103 @Consumes(MediaType.APPLICATION_JSON)
104 @Produces(MediaType.APPLICATION_JSON)
105 @Operation(description = "Create Resource Attribute", method = "POST",
106 summary = "Returns created resource attribute", responses = {
107 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
108 @ApiResponse(responseCode = "201", description = "Resource property created"),
109 @ApiResponse(responseCode = "403", description = "Restricted operation"),
110 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
111 @ApiResponse(responseCode = "409", description = "Resource attribute already exist")})
112 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
113 public Response createAttribute(
114 @Parameter(description = "resource id to update with new attribute",
115 required = true) @PathParam("resourceId") final String resourceId,
116 @Parameter(description = "Resource attribute to be created", required = true) String data,
117 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
119 ServletContext context = request.getSession().getServletContext();
121 String url = request.getMethod() + " " + request.getRequestURI();
122 log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
125 final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
126 AttributeDataDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper);
128 if (errorWrapper.isEmpty()) {
129 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
130 Either<AttributeDataDefinition, ResponseFormat> createAttribute = businessLogic
131 .createAttribute(resourceId, attributeDataDefinition, userId);
132 if (createAttribute.isRight()) {
133 errorWrapper.setInnerElement(createAttribute.right().value());
135 attributeDataDefinition = createAttribute.left().value();
140 if (!errorWrapper.isEmpty()) {
141 log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement());
142 response = buildErrorResponse(errorWrapper.getInnerElement());
144 log.debug("Attribute {} created successfully with id {}", attributeDataDefinition.getName(), attributeDataDefinition.getUniqueId());
145 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
146 response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition));
151 } catch (Exception e) {
152 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute");
153 log.debug("create property failed with exception", e);
159 * Updates existing Attribute with given attributeID on a resource with given resourceID
169 @Path("resources/{resourceId}/attributes/{attributeId}")
170 @Consumes(MediaType.APPLICATION_JSON)
171 @Produces(MediaType.APPLICATION_JSON)
172 @Operation(description = "Update Resource Attribute", method = "PUT", summary = "Returns updated attribute",
173 responses = {@ApiResponse(
174 content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
175 @ApiResponse(responseCode = "200", description = "Resource attribute updated"),
176 @ApiResponse(responseCode = "403", description = "Restricted operation"),
177 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
178 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
179 public Response updateAttribute(
180 @Parameter(description = "resource id to update with new attribute",
181 required = true) @PathParam("resourceId") final String resourceId,
182 @Parameter(description = "attribute id to update",
183 required = true) @PathParam("attributeId") final String attributeId,
184 @Parameter(description = "Resource attribute to update", required = true) String data,
185 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
187 ServletContext context = request.getSession().getServletContext();
189 String url = request.getMethod() + " " + request.getRequestURI();
190 log.debug("Start handle request of {}", url);
193 User modifier = new User();
194 modifier.setUserId(userId);
195 log.debug("modifier id is {}", userId);
198 final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
199 AttributeDataDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper);
200 if (errorWrapper.isEmpty()) {
201 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
202 Either<AttributeDataDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic
203 .updateAttribute(resourceId, attributeId, attributeDataDefinition, userId);
204 if (eitherUpdateAttribute.isRight()) {
205 errorWrapper.setInnerElement(eitherUpdateAttribute.right().value());
207 attributeDataDefinition = eitherUpdateAttribute.left().value();
212 if (!errorWrapper.isEmpty()) {
213 log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement());
214 response = buildErrorResponse(errorWrapper.getInnerElement());
216 log.debug("Attribute id {} updated successfully ", attributeDataDefinition.getUniqueId());
217 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
218 response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition));
223 } catch (Exception e) {
224 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute");
225 log.debug("update attribute failed with exception", e);
231 * Deletes existing Attribute with given attributeID on a resource with given resourceID
240 @Path("resources/{resourceId}/attributes/{attributeId}")
241 @Consumes(MediaType.APPLICATION_JSON)
242 @Produces(MediaType.APPLICATION_JSON)
243 @Operation(description = "Create Resource Attribute", method = "DELETE", summary = "Returns deleted attribute",
244 responses = {@ApiResponse(
245 content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
246 @ApiResponse(responseCode = "204", description = "deleted attribute"),
247 @ApiResponse(responseCode = "403", description = "Restricted operation"),
248 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
249 @ApiResponse(responseCode = "404", description = "Resource property not found")})
250 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
251 public Response deleteAttribute(
252 @Parameter(description = "resource id of attribute",
253 required = true) @PathParam("resourceId") final String resourceId,
254 @Parameter(description = "Attribute id to delete",
255 required = true) @PathParam("attributeId") final String attributeId,
256 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
258 ServletContext context = request.getSession().getServletContext();
260 String url = request.getMethod() + " " + request.getRequestURI();
261 log.debug("Start handle request of {}", url);
262 log.debug("modifier id is {}", userId);
265 // delete the property
266 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
267 Either<AttributeDataDefinition, ResponseFormat> eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId);
268 if (eitherAttribute.isRight()) {
269 log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value());
270 return buildErrorResponse(eitherAttribute.right().value());
272 AttributeDataDefinition attributeDefinition = eitherAttribute.left().value();
273 String name = attributeDefinition.getName();
275 log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId());
276 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
277 return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition));
279 } catch (Exception e) {
280 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute");
281 log.debug("delete attribute failed with exception", e);
286 private void buildAttributeFromString(String data, Wrapper<AttributeDataDefinition> attributesWrapper,
287 Wrapper<ResponseFormat> errorWrapper) {
289 Gson gson = new GsonBuilder().setPrettyPrinting().create();
290 final AttributeDataDefinition attribute = gson.fromJson(data, AttributeDataDefinition.class);
291 if (attribute == null) {
292 log.info(ATTRIBUTE_CONTENT_IS_INVALID, data);
293 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
294 errorWrapper.setInnerElement(responseFormat);
296 attributesWrapper.setInnerElement(attribute);
299 } catch (Exception e) {
300 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
301 errorWrapper.setInnerElement(responseFormat);
302 log.debug(ATTRIBUTE_CONTENT_IS_INVALID, data, e);
303 log.info(ATTRIBUTE_CONTENT_IS_INVALID, data);
307 private AttributeDataDefinition convertJsonToObject(final String data,
308 final Wrapper<ResponseFormat> errorWrapper) {
310 final ObjectMapper mapper = new ObjectMapper();
312 return mapper.readValue(data, AttributeDataDefinition.class);
313 } catch (final IOException e) {
314 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ATTRIBUTE_CONTENT_IS_INVALID, data);
315 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
316 errorWrapper.setInnerElement(responseFormat);