Merge "[1707-OS] Updated license text according to the"
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ComponentInstanceServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.sdc.be.servlets;
22
23 import java.io.InputStream;
24 import java.lang.reflect.Type;
25 import java.util.Arrays;
26 import java.util.List;
27
28 import javax.inject.Singleton;
29 import javax.servlet.ServletContext;
30 import javax.servlet.http.HttpServletRequest;
31 import javax.ws.rs.Consumes;
32 import javax.ws.rs.DELETE;
33 import javax.ws.rs.GET;
34 import javax.ws.rs.HeaderParam;
35 import javax.ws.rs.POST;
36 import javax.ws.rs.PUT;
37 import javax.ws.rs.Path;
38 import javax.ws.rs.PathParam;
39 import javax.ws.rs.Produces;
40 import javax.ws.rs.core.Context;
41 import javax.ws.rs.core.MediaType;
42 import javax.ws.rs.core.Response;
43
44 import org.apache.commons.io.IOUtils;
45 import org.codehaus.jackson.map.ObjectMapper;
46 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
47 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
48 import org.openecomp.sdc.be.config.BeEcompErrorManager;
49 import org.openecomp.sdc.be.dao.api.ActionStatus;
50 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
51 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
52 import org.openecomp.sdc.be.info.GroupDefinitionInfo;
53 import org.openecomp.sdc.be.model.ComponentInstance;
54 import org.openecomp.sdc.be.model.ComponentInstanceInput;
55 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
56 import org.openecomp.sdc.be.model.InputDefinition;
57 import org.openecomp.sdc.be.model.PropertyConstraint;
58 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
59 import org.openecomp.sdc.be.model.Resource;
60 import org.openecomp.sdc.be.model.User;
61 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
62 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
63 import org.openecomp.sdc.common.api.Constants;
64 import org.openecomp.sdc.common.datastructure.Wrapper;
65 import org.openecomp.sdc.exception.ResponseFormat;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 import com.google.gson.Gson;
70 import com.google.gson.GsonBuilder;
71 import com.google.gson.reflect.TypeToken;
72 import com.jcabi.aspects.Loggable;
73 import io.swagger.annotations.Api;
74 import io.swagger.annotations.ApiOperation;
75 import io.swagger.annotations.ApiParam;
76 import io.swagger.annotations.ApiResponse;
77 import io.swagger.annotations.ApiResponses;
78
79 import fj.data.Either;
80
81 /**
82  * Root resource (exposed at "/" path)
83  * .json
84  */
85 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
86 @Path("/v1/catalog")
87 @Api(value = "Resource Instance Servlet", description = "Resource Instance Servlet")
88 @Singleton
89 public class ComponentInstanceServlet extends AbstractValidationsServlet {
90
91         private static Logger log = LoggerFactory.getLogger(ComponentInstanceServlet.class.getName());
92
93         Type constraintType = new TypeToken<PropertyConstraint>() {
94         }.getType();
95
96         Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
97
98         @POST
99         @Path("/{containerComponentType}/{componentId}/resourceInstance")
100         @Consumes(MediaType.APPLICATION_JSON)
101         @Produces(MediaType.APPLICATION_JSON)
102         @ApiOperation(value = "Create ComponentInstance", httpMethod = "POST", notes = "Returns created ComponentInstance", response = Response.class)
103         @ApiResponses(value = { @ApiResponse(code = 201, message = "Component created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
104                         @ApiResponse(code = 409, message = "Component instance already exist") })
105         public Response createComponentInstance(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("componentId") final String containerComponentId,
106                         @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
107                         @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) {
108                 ServletContext context = request.getSession().getServletContext();
109
110                 try {
111
112                         ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);
113                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
114                         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
115                         if (componentInstanceLogic == null) {
116                                 log.debug("Unsupported component type {}", containerComponentType);
117                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
118                         }
119                         Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance);
120
121                         if (actionResponse.isRight()) {
122                                 return buildErrorResponse(actionResponse.right().value());
123                         }
124                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
125
126                 } catch (Exception e) {
127                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance");
128                         log.debug("create component instance failed with exception", e);
129                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
130                 }
131         }
132
133         @POST
134         @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}")
135         @Consumes(MediaType.APPLICATION_JSON)
136         @Produces(MediaType.APPLICATION_JSON)
137         @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
138         @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
139         public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
140                         @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
141                                         + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
142                         @Context final HttpServletRequest request) {
143                 ServletContext context = request.getSession().getServletContext();
144
145                 String url = request.getMethod() + " " + request.getRequestURI();
146                 log.debug("Start handle request of {}", url);
147                 try {
148
149                         log.debug("Start handle request of {}", url);
150
151                         InputStream inputStream = request.getInputStream();
152
153                         byte[] bytes = IOUtils.toByteArray(inputStream);
154
155                         if (bytes == null || bytes.length == 0) {
156                                 log.info("Empty body was sent.");
157                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
158                         }
159
160                         String userId = request.getHeader(Constants.USER_ID_HEADER);
161
162                         String data = new String(bytes);
163                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
164                         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
165                         if (componentInstanceLogic == null) {
166                                 log.debug("Unsupported component type {}", containerComponentType);
167                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
168                         }
169                         Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
170
171                         if (convertResponse.isRight()) {
172                                 BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance");
173                                 log.debug("Failed to convert received data to BE format.");
174                                 return buildErrorResponse(convertResponse.right().value());
175                         }
176
177                         ComponentInstance resourceInstance = convertResponse.left().value();
178                         Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, resourceInstance);
179
180                         if (actionResponse.isRight()) {
181                                 return buildErrorResponse(actionResponse.right().value());
182                         }
183                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
184
185                 } catch (Exception e) {
186                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance");
187                         log.debug("update resource instance with exception", e);
188                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
189                 }
190
191         }
192
193         @POST
194         @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance")
195         @Consumes(MediaType.APPLICATION_JSON)
196         @Produces(MediaType.APPLICATION_JSON)
197         @ApiOperation(value = "Update resource instance multiple component", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
198         @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
199         public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId,
200                         @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
201                                         + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
202                         @Context final HttpServletRequest request, @ApiParam(value = "Component Instance JSON Array", required = true) final String componentInstanceJsonArray) {
203
204                 ServletContext context = request.getSession().getServletContext();
205                 String url = request.getMethod() + " " + request.getRequestURI();
206                 log.debug("Start handle request of {}", url);
207
208                 try {
209                         log.debug("Start handle request of {}", url);
210
211                         if (componentInstanceJsonArray == null || componentInstanceJsonArray.length() == 0) {
212                                 log.info("Empty JSON list was sent.");
213                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
214                         }
215
216                         String userId = request.getHeader(Constants.USER_ID_HEADER);
217
218                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
219                         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
220                         if (componentInstanceLogic == null) {
221                                 log.debug("Unsupported component type {}", containerComponentType);
222                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
223                         }
224
225                         Either<List<ComponentInstance>, ResponseFormat> convertResponse = convertToMultipleResourceInstance(componentInstanceJsonArray);
226
227                         if (convertResponse.isRight()) {
228                                 // Using both ECOMP error methods, show to Sofer
229                                 BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance");
230                                 /*
231                                  * BeEcompErrorManager.getInstance().processEcompError( EcompErrorName.BeSystemError, "Resource Instance - updateResourceInstance");
232                                  */
233                                 log.debug("Failed to convert received data to BE format.");
234                                 return buildErrorResponse(convertResponse.right().value());
235                         }
236
237                         List<ComponentInstance> componentInstanceList = convertResponse.left().value();
238
239                         Either<List<ComponentInstance>, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstance(containerComponentType, componentId, userId, componentInstanceList, true, true);
240
241                         if (actionResponse.isRight()) {
242                                 return buildErrorResponse(actionResponse.right().value());
243                         }
244
245                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
246
247                 } catch (Exception e) {
248                         /*
249                          * BeEcompErrorManager.getInstance().processEcompError( EcompErrorName.BeRestApiGeneralError, "Update Resource Instance" );
250                          */
251                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance");
252                         log.debug("update resource instance with exception", e);
253                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
254                 }
255
256         }
257
258         @DELETE
259         @Path("/{containerComponentType}/{componentId}/resourceInstance/{resourceInstanceId}")
260         @Consumes(MediaType.APPLICATION_JSON)
261         @Produces(MediaType.APPLICATION_JSON)
262         @ApiOperation(value = "Delete ResourceInstance", httpMethod = "DELETE", notes = "Returns delete resourceInstance", response = Response.class)
263         @ApiResponses(value = { @ApiResponse(code = 201, message = "ResourceInstance deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
264         public Response deleteResourceInstance(@PathParam("componentId") final String componentId, @PathParam("resourceInstanceId") final String resourceInstanceId,
265                         @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
266                                         + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
267                         @Context final HttpServletRequest request) {
268                 ServletContext context = request.getSession().getServletContext();
269                 String url = request.getMethod() + " " + request.getRequestURI();
270                 Response response = null;
271                 try {
272                         log.debug("Start handle request of {}", url);
273                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
274                         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
275                         if (componentInstanceLogic == null) {
276                                 log.debug("Unsupported component type {}", containerComponentType);
277                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
278                         }
279                         String userId = request.getHeader(Constants.USER_ID_HEADER);
280                         Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId);
281
282                         if (actionResponse.isRight()) {
283                                 response = buildErrorResponse(actionResponse.right().value());
284                         } else {
285                                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
286                         }
287                         return response;
288                 } catch (Exception e) {
289                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance");
290                         log.debug("delete resource instance with exception", e);
291                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
292                 }
293         }
294
295         @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true)
296         @POST
297         @Path("/{containerComponentType}/{componentId}/resourceInstance/associate")
298         @Consumes(MediaType.APPLICATION_JSON)
299         @Produces(MediaType.APPLICATION_JSON)
300         @ApiOperation(value = "Associate RI to RI", httpMethod = "POST", notes = "Returns created RelationshipInfo", response = Response.class)
301         @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship created"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
302                         @ApiResponse(code = 409, message = "Relationship already exist") })
303         public Response associateRIToRI(@ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId,
304                         @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
305                                         + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType,
306                         @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) {
307                 ServletContext context = request.getSession().getServletContext();
308
309                 String url = request.getMethod() + " " + request.getRequestURI();
310                 log.debug("Start handle request of {}", url);
311                 Response response = null;
312
313                 try {
314
315                         log.debug("Start handle request of {}", url);
316
317                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
318                         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
319                         if (componentInstanceLogic == null) {
320                                 log.debug("Unsupported component type {}", containerComponentType);
321                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
322                         }
323
324                         Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data);
325
326                         Either<RequirementCapabilityRelDef, ResponseFormat> resultOp;
327                         if (regInfoW.isRight()) {
328                                 BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - associateRIToRI");
329                                 log.debug("Failed to convert received data to BE format.");
330                                 resultOp = Either.right(regInfoW.right().value());
331                         } else {
332                                 RequirementCapabilityRelDef requirementDef = regInfoW.left().value();
333                                 resultOp = componentInstanceLogic.associateRIToRI(componentId, userId, requirementDef, componentTypeEnum);
334                         }
335
336                         Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = resultOp;
337
338                         if (actionResponse.isRight()) {
339                                 response = buildErrorResponse(actionResponse.right().value());
340                         } else {
341                                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
342                         }
343                         return response;
344
345                 } catch (Exception e) {
346                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance");
347                         log.debug("associate resource instance to another RI with exception", e);
348                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
349                 }
350         }
351
352         @PUT
353         @Path("/{containerComponentType}/{componentId}/resourceInstance/dissociate")
354         @Consumes(MediaType.APPLICATION_JSON)
355         @Produces(MediaType.APPLICATION_JSON)
356         @ApiOperation(value = "Dissociate RI from RI", httpMethod = "PUT", notes = "Returns deleted RelationshipInfo", response = Response.class)
357         @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship deleted"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
358         public Response dissociateRIFromRI(
359                         @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
360                                         + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType,
361                         @ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "RelationshipInfo", required = true) String data,
362                         @Context final HttpServletRequest request) {
363                 ServletContext context = request.getSession().getServletContext();
364
365                 String url = request.getMethod() + " " + request.getRequestURI();
366                 log.debug("Start handle request of {}", url);
367
368                 try {
369
370                         log.debug("Start handle request of {}", url);
371
372                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
373                         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
374                         if (componentInstanceLogic == null) {
375                                 log.debug("Unsupported component type {}", containerComponentType);
376                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
377                         }
378
379                         Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data);
380                         if (regInfoW.isRight()) {
381                                 BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - dissociateRIFromRI");
382                                 log.debug("Failed to convert received data to BE format.");
383                                 return buildErrorResponse(regInfoW.right().value());
384                         }
385
386                         RequirementCapabilityRelDef requirementDef = regInfoW.left().value();
387                         Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceLogic.dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum);
388
389                         if (actionResponse.isRight()) {
390                                 return buildErrorResponse(actionResponse.right().value());
391                         }
392                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
393
394                 } catch (Exception e) {
395                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance");
396                         log.debug("dissociate resource instance from service failed with exception", e);
397                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
398                 }
399         }
400
401         @POST
402         @Path("/{containerComponentType}/{componentId}/resourceInstance/createAndAssociate")
403         @Consumes(MediaType.APPLICATION_JSON)
404         @Produces(MediaType.APPLICATION_JSON)
405         @ApiOperation(value = "Create RI and associate RI to RI", httpMethod = "POST", notes = "Returns created RI and RelationshipInfo", response = Response.class)
406         @ApiResponses(value = { @ApiResponse(code = 201, message = "RI created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
407                         @ApiResponse(code = 409, message = "Relationship already exist") })
408         public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId,
409                         @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
410                         @Context final HttpServletRequest request) {
411                 ServletContext context = request.getSession().getServletContext();
412
413                 String url = request.getMethod() + " " + request.getRequestURI();
414                 log.debug("Start handle request of {}", url);
415                 try {
416
417                         log.debug("Start handle request of {}", url);
418
419                         InputStream inputStream = request.getInputStream();
420
421                         byte[] bytes = IOUtils.toByteArray(inputStream);
422
423                         if (bytes == null || bytes.length == 0) {
424                                 log.info("Empty body was sent.");
425                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
426                         }
427
428                         String userId = request.getHeader(Constants.USER_ID_HEADER);
429
430                         String data = new String(bytes);
431
432                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
433                         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
434                         if (componentInstanceLogic == null) {
435                                 log.debug("Unsupported component type {}", containerComponentType);
436                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
437                         }
438
439                         Either<CreateAndAssotiateInfo, ActionStatus> convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class);
440                         if (convertStatus.isRight()) {
441                                 BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - createAndAssociateRIToRI");
442                                 log.debug("Failed to convert received data to BE format.");
443                                 Either<Object, ResponseFormat> formattedResponse = Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));
444                                 return buildErrorResponse(formattedResponse.right().value());
445                         }
446
447                         CreateAndAssotiateInfo createAndAssotiateInfo = convertStatus.left().value();
448                         Either<CreateAndAssotiateInfo, ResponseFormat> actionResponse = componentInstanceLogic.createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo);
449
450                         if (actionResponse.isRight()) {
451                                 return buildErrorResponse(actionResponse.right().value());
452                         }
453                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
454                 } catch (Exception e) {
455                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create and Associate Resource Instance");
456                         log.debug("create and associate RI failed with exception", e);
457                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
458                 }
459         }
460
461         @POST
462         @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property")
463         @Consumes(MediaType.APPLICATION_JSON)
464         @Produces(MediaType.APPLICATION_JSON)
465         @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
466         @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
467         public Response updateResourceInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
468                         @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
469                         @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
470                         @Context final HttpServletRequest request) {
471
472                 String url = request.getMethod() + " " + request.getRequestURI();
473                 log.debug("Start handle request of {}", url);
474
475                 try {
476                         Wrapper<String> dataWrapper = new Wrapper<>();
477                         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
478                         Wrapper<ComponentInstanceProperty> propertyWrapper = new Wrapper<>();
479
480                         validateInputStream(request, dataWrapper, errorWrapper);
481
482                         if (errorWrapper.isEmpty()) {
483                                 validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
484                         }
485
486                         if (!errorWrapper.isEmpty()) {
487                                 return buildErrorResponse(errorWrapper.getInnerElement());
488                         }
489
490                         ComponentInstanceProperty property = propertyWrapper.getInnerElement();
491
492                         log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property);
493
494                         ServletContext context = request.getSession().getServletContext();
495
496                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
497                         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
498                         if (componentInstanceLogic == null) {
499                                 log.debug("Unsupported component type {}", containerComponentType);
500                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
501                         }
502
503                         Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdatePropertyValue(componentTypeEnum, componentId, componentInstanceId, property, userId);
504
505                         if (actionResponse.isRight()) {
506                                 return buildErrorResponse(actionResponse.right().value());
507                         }
508
509                         ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value();
510                         ObjectMapper mapper = new ObjectMapper();
511                         String result = mapper.writeValueAsString(resourceInstanceProperty);
512                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
513
514                 } catch (Exception e) {
515                         log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
516                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
517                 }
518
519         }
520         
521         @POST
522         @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/input")
523         @Consumes(MediaType.APPLICATION_JSON)
524         @Produces(MediaType.APPLICATION_JSON)
525         @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
526         @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
527         public Response updateResourceInstanceInput(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
528                         @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
529                         @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
530                         @Context final HttpServletRequest request) {
531
532                 String url = request.getMethod() + " " + request.getRequestURI();
533                 log.debug("Start handle request of {}", url);
534
535                 try {
536                         Wrapper<String> dataWrapper = new Wrapper<>();
537                         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
538                         Wrapper<ComponentInstanceInput> propertyWrapper = new Wrapper<>();
539                         
540                         validateInputStream(request, dataWrapper, errorWrapper);
541                         ComponentInstanceInput property = null;
542
543                         if (errorWrapper.isEmpty()) {
544                                 User modifier = new User();
545                                 modifier.setUserId(userId);
546                                 log.debug("modifier id is {}", userId);
547                                 
548                                 Either<ComponentInstanceInput, ResponseFormat> inputEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataWrapper.getInnerElement(), modifier, ComponentInstanceInput.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);;
549                                 if(inputEither.isRight()){
550                                         log.debug("Failed to convert data to input definition. Status is {}", inputEither.right().value());
551                                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
552                                 }
553                                 property = inputEither.left().value();
554                                 
555                         }
556
557                         if (property == null) {
558                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
559                         }
560
561                         
562                         log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property);
563
564                         ServletContext context = request.getSession().getServletContext();
565
566                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
567                         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
568                         if (componentInstanceLogic == null) {
569                                 log.debug("Unsupported component type {}", containerComponentType);
570                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
571                         }
572
573                         Either<ComponentInstanceInput, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdateInstanceInputValue(componentTypeEnum, componentId, componentInstanceId, property, userId);
574
575                         if (actionResponse.isRight()) {
576                                 return buildErrorResponse(actionResponse.right().value());
577                         }
578
579                         ComponentInstanceInput resourceInstanceProperty = actionResponse.left().value();
580                         ObjectMapper mapper = new ObjectMapper();
581                         String result = mapper.writeValueAsString(resourceInstanceProperty);
582                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
583
584                 } catch (Exception e) {
585                         log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
586                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
587                 }
588
589         }
590
591         /**
592          * Updates ResourceInstance Attribute
593          * 
594          * @param componentId
595          * @param containerComponentType
596          * @param componentInstanceId
597          * @param userId
598          * @param request
599          * @return
600          */
601         @POST
602         @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/attribute")
603         @Consumes(MediaType.APPLICATION_JSON)
604         @Produces(MediaType.APPLICATION_JSON)
605         @ApiOperation(value = "Update resource instance attribute", httpMethod = "POST", notes = "Returns updated resource instance attribute", response = Response.class)
606         @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
607         public Response updateResourceInstanceAttribute(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
608                         @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
609                         @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
610                         @Context final HttpServletRequest request) {
611
612                 String url = request.getMethod() + " " + request.getRequestURI();
613                 log.debug("Start handle request of {}", url);
614
615                 try {
616
617                         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
618                         Wrapper<String> dataWrapper = new Wrapper<>();
619                         Wrapper<ComponentInstanceProperty> attributeWrapper = new Wrapper<>();
620                         Wrapper<ComponentInstanceBusinessLogic> blWrapper = new Wrapper<>();
621
622                         validateInputStream(request, dataWrapper, errorWrapper);
623
624                         if (errorWrapper.isEmpty()) {
625                                 validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
626                         }
627
628                         if (errorWrapper.isEmpty()) {
629                                 validateComponentInstanceBusinessLogic(request, containerComponentType, blWrapper, errorWrapper);
630                         }
631
632                         if (errorWrapper.isEmpty()) {
633                                 ComponentInstanceBusinessLogic componentInstanceLogic = blWrapper.getInnerElement();
634                                 ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
635                                 log.debug("Start handle request of ComponentInstanceAttribute. Received attribute is {}", attributeWrapper.getInnerElement());
636                                 Either<ComponentInstanceProperty, ResponseFormat> eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId);
637                                 if (eitherAttribute.isRight()) {
638                                         errorWrapper.setInnerElement(eitherAttribute.right().value());
639                                 } else {
640                                         attributeWrapper.setInnerElement(eitherAttribute.left().value());
641                                 }
642                         }
643
644                         return buildResponseFromElement(errorWrapper, attributeWrapper);
645
646                 } catch (Exception e) {
647                         log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
648                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
649                 }
650
651         }
652
653         @DELETE
654         @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property/{propertyId}")
655         @Consumes(MediaType.APPLICATION_JSON)
656         @Produces(MediaType.APPLICATION_JSON)
657         @ApiOperation(value = "Update resource instance", httpMethod = "DELETE", notes = "Returns deleted resource instance property", response = Response.class)
658         @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
659         public Response deleteResourceInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
660                         @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
661                         @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "property id") @PathParam("propertyId") final String propertyId,
662                         @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
663
664                 ServletContext context = request.getSession().getServletContext();
665
666                 String url = request.getMethod() + " " + request.getRequestURI();
667                 log.debug("Start handle request of {}", url);
668                 try {
669
670                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
671                         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
672                         if (componentInstanceLogic == null) {
673                                 log.debug("Unsupported component type {}", containerComponentType);
674                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
675                         }
676
677                         Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId);
678                         if (actionResponse.isRight()) {
679                                 return buildErrorResponse(actionResponse.right().value());
680                         }
681                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
682                 } catch (Exception e) {
683                         log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
684                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
685                 }
686
687         }
688
689         @POST
690         @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/changeVersion")
691         @Consumes(MediaType.APPLICATION_JSON)
692         @Produces(MediaType.APPLICATION_JSON)
693         @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
694         @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
695         public Response changeResourceInstanceVersion(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
696                         @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
697                         @Context final HttpServletRequest request) {
698                 ServletContext context = request.getSession().getServletContext();
699
700                 String url = request.getMethod() + " " + request.getRequestURI();
701                 log.debug("Start handle request of {}", url);
702                 try {
703                         InputStream inputStream = request.getInputStream();
704
705                         byte[] bytes = IOUtils.toByteArray(inputStream);
706
707                         if (bytes == null || bytes.length == 0) {
708                                 log.info("Empty body was sent.");
709                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
710                         }
711
712                         String userId = request.getHeader(Constants.USER_ID_HEADER);
713
714                         String data = new String(bytes);
715
716                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
717                         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
718                         if (componentInstanceLogic == null) {
719                                 log.debug("Unsupported component type {}", containerComponentType);
720                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
721                         }
722
723                         Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
724
725                         if (convertResponse.isRight()) {
726                                 BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance");
727                                 log.debug("Failed to convert received data to BE format.");
728                                 return buildErrorResponse(convertResponse.right().value());
729                         }
730
731                         ComponentInstance newResourceInstance = convertResponse.left().value();
732                         Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance);
733
734                         if (actionResponse.isRight()) {
735                                 return buildErrorResponse(actionResponse.right().value());
736                         }
737                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
738
739                 } catch (Exception e) {
740                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance");
741                         log.debug("update resource instance with exception", e);
742                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
743                 }
744
745         }
746         
747         @POST
748         @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property")
749         @Consumes(MediaType.APPLICATION_JSON)
750         @Produces(MediaType.APPLICATION_JSON)
751         @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
752         @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
753         public Response updateGroupInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
754                         @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
755                         @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId,  @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
756                         @Context final HttpServletRequest request) {
757
758                 String url = request.getMethod() + " " + request.getRequestURI();
759                 log.debug("Start handle request of {}", url);
760
761                 try {
762                         Wrapper<String> dataWrapper = new Wrapper<>();
763                         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
764                         Wrapper<ComponentInstanceProperty> propertyWrapper = new Wrapper<>();
765
766                         validateInputStream(request, dataWrapper, errorWrapper);
767
768                         if (errorWrapper.isEmpty()) {
769                                 validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
770                         }
771
772                         if (!errorWrapper.isEmpty()) {
773                                 return buildErrorResponse(errorWrapper.getInnerElement());
774                         }
775
776                         ComponentInstanceProperty property = propertyWrapper.getInnerElement();
777
778                         log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property);
779
780                         ServletContext context = request.getSession().getServletContext();
781
782                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
783                         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
784                         if (componentInstanceLogic == null) {
785                                 log.debug("Unsupported component type {}", containerComponentType);
786                                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
787                         }
788
789                         Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId);
790
791                         if (actionResponse.isRight()) {
792                                 return buildErrorResponse(actionResponse.right().value());
793                         }
794
795                         ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value();
796                         ObjectMapper mapper = new ObjectMapper();
797                         String result = mapper.writeValueAsString(resourceInstanceProperty);
798                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
799
800                 } catch (Exception e) {
801                         log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
802                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
803                 }
804
805         }
806         
807         @GET
808         @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}")
809         @Consumes(MediaType.APPLICATION_JSON)
810         @Produces(MediaType.APPLICATION_JSON)
811         @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupInstId", response = Resource.class)
812         @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") })
813         public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("groupInstId") final String groupInstId,
814                         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
815                 ServletContext context = request.getSession().getServletContext();
816                 String url = request.getMethod() + " " + request.getRequestURI();
817                 log.debug("(GET) Start handle request of {}", url);
818
819                 try {
820
821                         GroupBusinessLogic businessLogic = this.getGroupBL(context);
822                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
823                         Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic.getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId, groupInstId, userId, false);
824
825                         if (actionResponse.isRight()) {
826                                 log.debug("failed to get all non abstract {}", containerComponentType);
827                                 return buildErrorResponse(actionResponse.right().value());
828                         }
829
830                         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
831
832                 } catch (Exception e) {
833                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
834                         log.debug("getGroupArtifactById unexpected exception", e);
835                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
836                 }
837
838         }
839         
840         //US831698
841         @GET
842         @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties")
843         @Consumes(MediaType.APPLICATION_JSON)
844         @Produces(MediaType.APPLICATION_JSON)
845         @ApiOperation(value = "Get component instance properties", httpMethod = "GET", 
846         notes = "Returns component instance properties", response = Response.class)
847         @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), 
848                         @ApiResponse(code = 403, message = "Restricted operation"), 
849                         @ApiResponse(code = 404, message = "Component/Component Instance - not found") })
850         public Response getInstancePropertiesById(@PathParam("containerComponentType") final String containerComponentType, 
851                         @PathParam("containerComponentId") final String containerComponentId, 
852                         @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
853                         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
854                 
855                 ServletContext context = request.getSession().getServletContext();
856                 String url = request.getMethod() + " " + request.getRequestURI();
857                 log.debug("(GET) Start handle request of {}", url);
858
859                 try {
860                         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
861                         ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum);
862                         
863                         Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBL
864                                         .getComponentInstancePropertiesById(containerComponentType, containerComponentId, 
865                                                         componentInstanceUniqueId, userId);
866
867                         if (componentInstancePropertiesById.isRight()) {
868                                 log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", 
869                                                 componentInstanceUniqueId, containerComponentType, containerComponentId);
870                                 return buildErrorResponse(componentInstancePropertiesById.right().value());
871                         }
872
873                         return buildOkResponse(getComponentsUtils().
874                                         getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value());
875                 } catch (Exception e) {
876                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
877                         log.debug("getGroupArtifactById unexpected exception", e);
878                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
879                 }
880
881         }
882         
883         private Either<ComponentInstance, ResponseFormat> convertToResourceInstance(String data) {
884
885                 // Either<ComponentInstance, ActionStatus> convertStatus =
886                 // convertJsonToObject(data, ComponentInstance.class);
887                 Either<ComponentInstance, ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
888                 if (convertStatus.isRight()) {
889                         return Either.right(convertStatus.right().value());
890                 }
891                 ComponentInstance resourceInstanceInfo = convertStatus.left().value();
892
893                 return Either.left(resourceInstanceInfo);
894         }
895
896         private Either<List<ComponentInstance>, ResponseFormat> convertToMultipleResourceInstance(String dataList) {
897
898                 Either<ComponentInstance[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
899                 if (convertStatus.isRight()) {
900                         return Either.right(convertStatus.right().value());
901                 }
902
903                 return Either.left(Arrays.asList(convertStatus.left().value()));
904         }
905
906         private Either<RequirementCapabilityRelDef, ResponseFormat> convertToRequirementCapabilityRelDef(String data) {
907
908                 Either<RequirementCapabilityRelDef, ActionStatus> convertStatus = convertJsonToObject(data, RequirementCapabilityRelDef.class);
909                 if (convertStatus.isRight()) {
910                         return Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));
911                 }
912                 RequirementCapabilityRelDef requirementCapabilityRelDef = convertStatus.left().value();
913                 return Either.left(requirementCapabilityRelDef);
914         }
915
916         private <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {
917                 try {
918                         log.trace("convert json to object. json=\n {}", data);
919                         T t = null;
920                         t = gson.fromJson(data, clazz);
921                         if (t == null) {
922                                 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
923                                 log.debug("object is null after converting from json");
924                                 return Either.right(ActionStatus.INVALID_CONTENT);
925                         }
926                         return Either.left(t);
927                 } catch (Exception e) {
928                         // INVALID JSON
929                         BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
930                         log.debug("failed to convert from json", e);
931                         return Either.right(ActionStatus.INVALID_CONTENT);
932                 }
933         }
934 }