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.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.jcabi.aspects.Loggable;
26 import fj.data.Either;
27 import io.swagger.v3.oas.annotations.Operation;
28 import io.swagger.v3.oas.annotations.Parameter;
29 import io.swagger.v3.oas.annotations.media.ArraySchema;
30 import io.swagger.v3.oas.annotations.media.Content;
31 import io.swagger.v3.oas.annotations.media.Schema;
32 import io.swagger.v3.oas.annotations.responses.ApiResponse;
33 import io.swagger.v3.oas.annotations.servers.Server;
34 import io.swagger.v3.oas.annotations.tags.Tag;
35 import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic;
36 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
37 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
38 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
39 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
40 import org.openecomp.sdc.be.config.BeEcompErrorManager;
41 import org.openecomp.sdc.be.dao.api.ActionStatus;
42 import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
43 import org.openecomp.sdc.be.impl.ComponentsUtils;
44 import org.openecomp.sdc.be.impl.ServletUtils;
45 import org.openecomp.sdc.be.model.AttributeDefinition;
46 import org.openecomp.sdc.be.model.User;
47 import org.openecomp.sdc.be.user.UserBusinessLogic;
48 import org.openecomp.sdc.common.api.Constants;
49 import org.openecomp.sdc.common.datastructure.Wrapper;
50 import org.openecomp.sdc.common.log.wrappers.Logger;
51 import org.openecomp.sdc.exception.ResponseFormat;
52 import org.springframework.stereotype.Controller;
54 import javax.inject.Inject;
55 import javax.servlet.ServletContext;
56 import javax.servlet.http.HttpServletRequest;
57 import javax.ws.rs.Consumes;
58 import javax.ws.rs.DELETE;
59 import javax.ws.rs.HeaderParam;
60 import javax.ws.rs.POST;
61 import javax.ws.rs.PUT;
62 import javax.ws.rs.Path;
63 import javax.ws.rs.PathParam;
64 import javax.ws.rs.Produces;
65 import javax.ws.rs.core.Context;
66 import javax.ws.rs.core.MediaType;
67 import javax.ws.rs.core.Response;
68 import java.io.IOException;
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 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
126 Wrapper<AttributeDataDefinition> attributesWrapper = new Wrapper<>();
127 // convert json to AttributeDefinition
129 buildAttributeFromString(data, attributesWrapper, errorWrapper);
130 if (errorWrapper.isEmpty()) {
131 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
132 Either<AttributeDataDefinition, ResponseFormat> createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId);
133 if (createAttribute.isRight()) {
134 errorWrapper.setInnerElement(createAttribute.right().value());
136 attributesWrapper.setInnerElement(createAttribute.left().value());
141 if (!errorWrapper.isEmpty()) {
142 log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement());
143 response = buildErrorResponse(errorWrapper.getInnerElement());
145 AttributeDataDefinition createdAttDef = attributesWrapper.getInnerElement();
146 log.debug("Attribute {} created successfully with id {}", createdAttDef.getName(), createdAttDef.getUniqueId());
147 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
148 response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(createdAttDef));
153 } catch (Exception e) {
154 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute");
155 log.debug("create property failed with exception", e);
161 * Updates existing Attribute with given attributeID on a resource with given resourceID
171 @Path("resources/{resourceId}/attributes/{attributeId}")
172 @Consumes(MediaType.APPLICATION_JSON)
173 @Produces(MediaType.APPLICATION_JSON)
174 @Operation(description = "Update Resource Attribute", method = "PUT", summary = "Returns updated attribute",
175 responses = {@ApiResponse(
176 content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
177 @ApiResponse(responseCode = "200", description = "Resource attribute updated"),
178 @ApiResponse(responseCode = "403", description = "Restricted operation"),
179 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
180 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
181 public Response updateAttribute(
182 @Parameter(description = "resource id to update with new attribute",
183 required = true) @PathParam("resourceId") final String resourceId,
184 @Parameter(description = "attribute id to update",
185 required = true) @PathParam("attributeId") final String attributeId,
186 @Parameter(description = "Resource attribute to update", required = true) String data,
187 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
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 // convert json to PropertyDefinition
201 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
202 Wrapper<AttributeDataDefinition> attributesWrapper = new Wrapper<>();
203 // convert json to AttributeDefinition
205 buildAttributeFromString(data, attributesWrapper, errorWrapper);
207 if (errorWrapper.isEmpty()) {
208 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
209 Either<AttributeDataDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId);
211 if (eitherUpdateAttribute.isRight()) {
212 errorWrapper.setInnerElement(eitherUpdateAttribute.right().value());
214 attributesWrapper.setInnerElement(eitherUpdateAttribute.left().value());
219 if (!errorWrapper.isEmpty()) {
220 log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement());
221 response = buildErrorResponse(errorWrapper.getInnerElement());
223 AttributeDataDefinition updatedAttribute = attributesWrapper.getInnerElement();
224 log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId());
225 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
226 response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute));
231 } catch (Exception e) {
232 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute");
233 log.debug("update attribute failed with exception", e);
239 * Deletes existing Attribute with given attributeID on a resource with given resourceID
248 @Path("resources/{resourceId}/attributes/{attributeId}")
249 @Consumes(MediaType.APPLICATION_JSON)
250 @Produces(MediaType.APPLICATION_JSON)
251 @Operation(description = "Create Resource Attribute", method = "DELETE", summary = "Returns deleted attribute",
252 responses = {@ApiResponse(
253 content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
254 @ApiResponse(responseCode = "204", description = "deleted attribute"),
255 @ApiResponse(responseCode = "403", description = "Restricted operation"),
256 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
257 @ApiResponse(responseCode = "404", description = "Resource property not found")})
258 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
259 public Response deleteAttribute(
260 @Parameter(description = "resource id of attribute",
261 required = true) @PathParam("resourceId") final String resourceId,
262 @Parameter(description = "Attribute id to delete",
263 required = true) @PathParam("attributeId") final String attributeId,
264 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
266 ServletContext context = request.getSession().getServletContext();
268 String url = request.getMethod() + " " + request.getRequestURI();
269 log.debug("Start handle request of {}", url);
270 log.debug("modifier id is {}", userId);
273 // delete the property
274 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
275 Either<AttributeDataDefinition, ResponseFormat> eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId);
276 if (eitherAttribute.isRight()) {
277 log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value());
278 return buildErrorResponse(eitherAttribute.right().value());
280 AttributeDataDefinition attributeDefinition = eitherAttribute.left().value();
281 String name = attributeDefinition.getName();
283 log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId());
284 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
285 return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition));
287 } catch (Exception e) {
288 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute");
289 log.debug("delete attribute failed with exception", e);
294 private void buildAttributeFromString(String data, Wrapper<AttributeDataDefinition> attributesWrapper,
295 Wrapper<ResponseFormat> errorWrapper) {
297 Gson gson = new GsonBuilder().setPrettyPrinting().create();
298 final AttributeDataDefinition attribute = gson.fromJson(data, AttributeDefinition.class);
299 if (attribute == null) {
300 log.info(ATTRIBUTE_CONTENT_IS_INVALID, data);
301 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
302 errorWrapper.setInnerElement(responseFormat);
304 attributesWrapper.setInnerElement(attribute);
307 } catch (Exception e) {
308 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
309 errorWrapper.setInnerElement(responseFormat);
310 log.debug(ATTRIBUTE_CONTENT_IS_INVALID, data, e);
311 log.info(ATTRIBUTE_CONTENT_IS_INVALID, data);