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 io.swagger.v3.oas.annotations.tags.Tags;
37 import java.io.IOException;
38 import javax.inject.Inject;
39 import javax.servlet.ServletContext;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.ws.rs.Consumes;
42 import javax.ws.rs.DELETE;
43 import javax.ws.rs.HeaderParam;
44 import javax.ws.rs.POST;
45 import javax.ws.rs.PUT;
46 import javax.ws.rs.Path;
47 import javax.ws.rs.PathParam;
48 import javax.ws.rs.Produces;
49 import javax.ws.rs.core.Context;
50 import javax.ws.rs.core.MediaType;
51 import javax.ws.rs.core.Response;
52 import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic;
53 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
54 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
55 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
56 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
57 import org.openecomp.sdc.be.config.BeEcompErrorManager;
58 import org.openecomp.sdc.be.dao.api.ActionStatus;
59 import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
60 import org.openecomp.sdc.be.impl.ComponentsUtils;
61 import org.openecomp.sdc.be.impl.ServletUtils;
62 import org.openecomp.sdc.be.model.AttributeDefinition;
63 import org.openecomp.sdc.be.model.User;
64 import org.openecomp.sdc.be.user.UserBusinessLogic;
65 import org.openecomp.sdc.common.api.Constants;
66 import org.openecomp.sdc.common.datastructure.Wrapper;
67 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
68 import org.openecomp.sdc.common.log.wrappers.Logger;
69 import org.openecomp.sdc.exception.ResponseFormat;
70 import org.springframework.stereotype.Controller;
73 * Web Servlet for actions on Attributes
77 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
79 @Tags({@Tag(name = "SDCE-2 APIs")})
80 @Server(url = "/sdc2/rest")
82 public class AttributeServlet extends AbstractValidationsServlet {
84 private static final Logger log = Logger.getLogger(AttributeServlet.class);
85 private static final String ATTRIBUTE_CONTENT_IS_INVALID = "Attribute content is invalid - {}";
88 public AttributeServlet(UserBusinessLogic userBusinessLogic,
89 ComponentInstanceBusinessLogic componentInstanceBL,
90 ComponentsUtils componentsUtils, ServletUtils servletUtils,
91 ResourceImportManager resourceImportManager) {
92 super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
96 * Creates new Attribute on a resource with given resource ID
105 @Path("resources/{resourceId}/attributes")
106 @Consumes(MediaType.APPLICATION_JSON)
107 @Produces(MediaType.APPLICATION_JSON)
108 @Operation(description = "Create Resource Attribute", method = "POST",
109 summary = "Returns created resource attribute", responses = {
110 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
111 @ApiResponse(responseCode = "201", description = "Resource property created"),
112 @ApiResponse(responseCode = "403", description = "Restricted operation"),
113 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
114 @ApiResponse(responseCode = "409", description = "Resource attribute already exist")})
115 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
116 public Response createAttribute(
117 @Parameter(description = "resource id to update with new attribute",
118 required = true) @PathParam("resourceId") final String resourceId,
119 @Parameter(description = "Resource attribute to be created", required = true) String data,
120 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
123 ServletContext context = request.getSession().getServletContext();
125 String url = request.getMethod() + " " + request.getRequestURI();
126 log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
129 final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
130 AttributeDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper);
132 if (errorWrapper.isEmpty()) {
133 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
134 Either<AttributeDefinition, ResponseFormat> createAttribute = businessLogic.
135 createAttribute(resourceId, attributeDataDefinition, userId);
136 if (createAttribute.isRight()) {
137 errorWrapper.setInnerElement(createAttribute.right().value());
139 attributeDataDefinition = createAttribute.left().value();
143 if (!errorWrapper.isEmpty()) {
144 log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement());
145 return buildErrorResponse(errorWrapper.getInnerElement());
147 log.debug("Attribute {} created successfully with id {}", attributeDataDefinition.getName(), attributeDataDefinition.getUniqueId());
148 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
149 return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition));
152 } catch (Exception e) {
153 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute");
154 log.debug("create property failed with exception", e);
160 * Updates existing Attribute with given attributeID on a resource with given resourceID
170 @Path("resources/{resourceId}/attributes/{attributeId}")
171 @Consumes(MediaType.APPLICATION_JSON)
172 @Produces(MediaType.APPLICATION_JSON)
173 @Operation(description = "Update Resource Attribute", method = "PUT", summary = "Returns updated attribute",
174 responses = {@ApiResponse(
175 content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
176 @ApiResponse(responseCode = "200", description = "Resource attribute updated"),
177 @ApiResponse(responseCode = "403", description = "Restricted operation"),
178 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
179 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
180 public Response updateAttribute(
181 @Parameter(description = "resource id to update with new attribute",
182 required = true) @PathParam("resourceId") final String resourceId,
183 @Parameter(description = "attribute id to update",
184 required = true) @PathParam("attributeId") final String attributeId,
185 @Parameter(description = "Resource attribute to update", required = true) String data,
186 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
189 ServletContext context = request.getSession().getServletContext();
191 String url = request.getMethod() + " " + request.getRequestURI();
192 log.debug("Start handle request of {}", url);
195 User modifier = new User();
196 modifier.setUserId(userId);
197 log.debug("modifier id is {}", userId);
200 final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
201 AttributeDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper);
202 if (errorWrapper.isEmpty()) {
203 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
204 Either<AttributeDefinition, ResponseFormat> eitherUpdateAttribute
205 = businessLogic.updateAttribute(resourceId, attributeId, attributeDataDefinition, userId);
206 if (eitherUpdateAttribute.isRight()) {
207 errorWrapper.setInnerElement(eitherUpdateAttribute.right().value());
209 attributeDataDefinition = eitherUpdateAttribute.left().value();
213 if (!errorWrapper.isEmpty()) {
214 log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement());
215 return buildErrorResponse(errorWrapper.getInnerElement());
217 log.debug("Attribute id {} updated successfully ", attributeDataDefinition.getUniqueId());
218 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
219 return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition));
222 } catch (Exception e) {
223 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute");
224 log.debug("update attribute failed with exception", e);
230 * Deletes existing Attribute with given attributeID on a resource with given resourceID
239 @Path("resources/{resourceId}/attributes/{attributeId}")
240 @Consumes(MediaType.APPLICATION_JSON)
241 @Produces(MediaType.APPLICATION_JSON)
242 @Operation(description = "Create Resource Attribute", method = "DELETE", summary = "Returns deleted attribute",
243 responses = {@ApiResponse(
244 content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
245 @ApiResponse(responseCode = "204", description = "deleted attribute"),
246 @ApiResponse(responseCode = "403", description = "Restricted operation"),
247 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
248 @ApiResponse(responseCode = "404", description = "Resource property not found")})
249 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
250 public Response deleteAttribute(
251 @Parameter(description = "resource id of attribute",
252 required = true) @PathParam("resourceId") final String resourceId,
253 @Parameter(description = "Attribute id to delete",
254 required = true) @PathParam("attributeId") final String attributeId,
255 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
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,
267 () -> AttributeBusinessLogic.class);
268 Either<AttributeDefinition, ResponseFormat> eitherAttribute = businessLogic
269 .deleteAttribute(resourceId, attributeId, userId);
270 if (eitherAttribute.isRight()) {
271 log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value());
272 return buildErrorResponse(eitherAttribute.right().value());
274 AttributeDefinition attributeDefinition = eitherAttribute.left().value();
275 String name = attributeDefinition.getName();
277 log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId());
278 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
279 return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition));
281 } catch (Exception e) {
282 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute");
283 log.debug("delete attribute failed with exception", e);
288 private AttributeDefinition convertJsonToObject(final String data,
289 final Wrapper<ResponseFormat> errorWrapper) {
291 final ObjectMapper mapper = new ObjectMapper();
293 return mapper.readValue(data, AttributeDefinition.class);
294 } catch (final IOException e) {
295 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ATTRIBUTE_CONTENT_IS_INVALID, data);
296 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
297 errorWrapper.setInnerElement(responseFormat);