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.AttributeDefinition;
62 import org.openecomp.sdc.be.model.User;
63 import org.openecomp.sdc.be.user.UserBusinessLogic;
64 import org.openecomp.sdc.common.api.Constants;
65 import org.openecomp.sdc.common.datastructure.Wrapper;
66 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
67 import org.openecomp.sdc.common.log.wrappers.Logger;
68 import org.openecomp.sdc.exception.ResponseFormat;
69 import org.springframework.stereotype.Controller;
72 * 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 {
83 private static final Logger log = Logger.getLogger(AttributeServlet.class);
84 private static final String ATTRIBUTE_CONTENT_IS_INVALID = "Attribute content is invalid - {}";
87 public AttributeServlet(UserBusinessLogic userBusinessLogic,
88 ComponentInstanceBusinessLogic componentInstanceBL,
89 ComponentsUtils componentsUtils, ServletUtils servletUtils,
90 ResourceImportManager resourceImportManager) {
91 super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
95 * Creates new Attribute on a resource with given resource ID
104 @Path("resources/{resourceId}/attributes")
105 @Consumes(MediaType.APPLICATION_JSON)
106 @Produces(MediaType.APPLICATION_JSON)
107 @Operation(description = "Create Resource Attribute", method = "POST",
108 summary = "Returns created resource attribute", responses = {
109 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
110 @ApiResponse(responseCode = "201", description = "Resource property created"),
111 @ApiResponse(responseCode = "403", description = "Restricted operation"),
112 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
113 @ApiResponse(responseCode = "409", description = "Resource attribute already exist")})
114 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
115 public Response createAttribute(
116 @Parameter(description = "resource id to update with new attribute",
117 required = true) @PathParam("resourceId") final String resourceId,
118 @Parameter(description = "Resource attribute to be created", required = true) String data,
119 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
122 ServletContext context = request.getSession().getServletContext();
124 String url = request.getMethod() + " " + request.getRequestURI();
125 log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
128 final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
129 AttributeDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper);
131 if (errorWrapper.isEmpty()) {
132 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
133 Either<AttributeDefinition, ResponseFormat> createAttribute = businessLogic.
134 createAttribute(resourceId, attributeDataDefinition, userId);
135 if (createAttribute.isRight()) {
136 errorWrapper.setInnerElement(createAttribute.right().value());
138 attributeDataDefinition = createAttribute.left().value();
142 if (!errorWrapper.isEmpty()) {
143 log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement());
144 return buildErrorResponse(errorWrapper.getInnerElement());
146 log.debug("Attribute {} created successfully with id {}", attributeDataDefinition.getName(), attributeDataDefinition.getUniqueId());
147 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
148 return 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)
188 ServletContext context = request.getSession().getServletContext();
190 String url = request.getMethod() + " " + request.getRequestURI();
191 log.debug("Start handle request of {}", url);
194 User modifier = new User();
195 modifier.setUserId(userId);
196 log.debug("modifier id is {}", userId);
199 final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
200 AttributeDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper);
201 if (errorWrapper.isEmpty()) {
202 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
203 Either<AttributeDefinition, ResponseFormat> eitherUpdateAttribute
204 = businessLogic.updateAttribute(resourceId, attributeId, attributeDataDefinition, userId);
205 if (eitherUpdateAttribute.isRight()) {
206 errorWrapper.setInnerElement(eitherUpdateAttribute.right().value());
208 attributeDataDefinition = eitherUpdateAttribute.left().value();
212 if (!errorWrapper.isEmpty()) {
213 log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement());
214 return buildErrorResponse(errorWrapper.getInnerElement());
216 log.debug("Attribute id {} updated successfully ", attributeDataDefinition.getUniqueId());
217 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
218 return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition));
221 } catch (Exception e) {
222 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute");
223 log.debug("update attribute failed with exception", e);
229 * Deletes existing Attribute with given attributeID on a resource with given resourceID
238 @Path("resources/{resourceId}/attributes/{attributeId}")
239 @Consumes(MediaType.APPLICATION_JSON)
240 @Produces(MediaType.APPLICATION_JSON)
241 @Operation(description = "Create Resource Attribute", method = "DELETE", summary = "Returns deleted attribute",
242 responses = {@ApiResponse(
243 content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
244 @ApiResponse(responseCode = "204", description = "deleted attribute"),
245 @ApiResponse(responseCode = "403", description = "Restricted operation"),
246 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
247 @ApiResponse(responseCode = "404", description = "Resource property not found")})
248 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
249 public Response deleteAttribute(
250 @Parameter(description = "resource id of attribute",
251 required = true) @PathParam("resourceId") final String resourceId,
252 @Parameter(description = "Attribute id to delete",
253 required = true) @PathParam("attributeId") final String attributeId,
254 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
257 ServletContext context = request.getSession().getServletContext();
259 String url = request.getMethod() + " " + request.getRequestURI();
260 log.debug("Start handle request of {}", url);
261 log.debug("modifier id is {}", userId);
264 // delete the property
265 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context,
266 () -> AttributeBusinessLogic.class);
267 Either<AttributeDefinition, ResponseFormat> eitherAttribute = businessLogic
268 .deleteAttribute(resourceId, attributeId, userId);
269 if (eitherAttribute.isRight()) {
270 log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value());
271 return buildErrorResponse(eitherAttribute.right().value());
273 AttributeDefinition attributeDefinition = eitherAttribute.left().value();
274 String name = attributeDefinition.getName();
276 log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId());
277 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
278 return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition));
280 } catch (Exception e) {
281 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute");
282 log.debug("delete attribute failed with exception", e);
287 private AttributeDefinition convertJsonToObject(final String data,
288 final Wrapper<ResponseFormat> errorWrapper) {
290 final ObjectMapper mapper = new ObjectMapper();
292 return mapper.readValue(data, AttributeDefinition.class);
293 } catch (final IOException e) {
294 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ATTRIBUTE_CONTENT_IS_INVALID, data);
295 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
296 errorWrapper.setInnerElement(responseFormat);