Remove dead code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / BeGenericServlet.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 com.fasterxml.jackson.databind.DeserializationFeature;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import com.fasterxml.jackson.databind.module.SimpleModule;
26 import com.google.common.annotations.VisibleForTesting;
27 import com.google.gson.Gson;
28 import com.google.gson.GsonBuilder;
29 import com.google.gson.reflect.TypeToken;
30 import fj.data.Either;
31 import io.swagger.v3.oas.annotations.OpenAPIDefinition;
32 import io.swagger.v3.oas.annotations.info.Info;
33 import io.swagger.v3.oas.annotations.servers.Server;
34 import org.json.simple.JSONArray;
35 import org.json.simple.JSONObject;
36 import org.json.simple.parser.JSONParser;
37 import org.json.simple.parser.ParseException;
38 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
39 import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
40 import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic;
41 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
42 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
43 import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
44 import org.openecomp.sdc.be.components.impl.GenericArtifactBrowserBusinessLogic;
45 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
46 import org.openecomp.sdc.be.components.impl.InputsBusinessLogic;
47 import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;
48 import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;
49 import org.openecomp.sdc.be.components.impl.ProductBusinessLogic;
50 import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;
51 import org.openecomp.sdc.be.components.impl.RelationshipTypeBusinessLogic;
52 import org.openecomp.sdc.be.components.impl.RequirementBusinessLogic;
53 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
54 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
55 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
56 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
57 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
58 import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic;
59 import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic;
60 import org.openecomp.sdc.be.config.BeEcompErrorManager;
61 import org.openecomp.sdc.be.dao.api.ActionStatus;
62 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
63 import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum;
64 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
65 import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter;
66 import org.openecomp.sdc.be.impl.ComponentsUtils;
67 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
68 import org.openecomp.sdc.be.model.ComponentInstInputsMap;
69 import org.openecomp.sdc.be.model.PropertyConstraint;
70 import org.openecomp.sdc.be.model.PropertyDefinition;
71 import org.openecomp.sdc.be.model.InputDefinition;
72 import org.openecomp.sdc.be.model.User;
73 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
74 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer;
75 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
76 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
77 import org.openecomp.sdc.be.user.UserBusinessLogic;
78 import org.openecomp.sdc.common.api.Constants;
79 import org.openecomp.sdc.common.log.wrappers.Logger;
80 import org.openecomp.sdc.common.servlets.BasicServlet;
81 import org.openecomp.sdc.exception.ResponseFormat;
82 import org.springframework.web.context.WebApplicationContext;
83
84 import javax.servlet.ServletContext;
85 import javax.servlet.http.HttpServletRequest;
86 import javax.ws.rs.core.Context;
87 import javax.ws.rs.core.Response;
88 import javax.ws.rs.core.Response.ResponseBuilder;
89 import java.io.IOException;
90 import java.lang.reflect.Type;
91 import java.util.HashMap;
92 import java.util.Iterator;
93 import java.util.List;
94 import java.util.Map;
95 import java.util.Map.Entry;
96 import java.util.Objects;
97 import java.util.Set;
98 import java.util.function.Supplier;
99
100 @OpenAPIDefinition(info = @Info(title = "SDC API", description = "SDC External, Distribution and Internal APIs"),
101         servers = {@Server(url = "/sdc", description = "SDC External and Distribution APIs"),
102                 @Server(url = "/sdc2/rest", description = "SDC Internal APIs")})
103 public class BeGenericServlet extends BasicServlet {
104
105     public BeGenericServlet(UserBusinessLogic userAdminManager,
106         ComponentsUtils componentsUtils) {
107         this.userAdminManager = userAdminManager;
108         this.componentsUtils = componentsUtils;
109     }
110
111     @Context
112     protected HttpServletRequest servletRequest;
113
114     private static final Logger log = Logger.getLogger(BeGenericServlet.class);
115
116     private static final String PROPERTY_NAME_REGEX = "[\\w,\\d,_]+";
117
118     private UserBusinessLogic userAdminManager;
119     protected ComponentsUtils componentsUtils;
120
121     /******************** New error response mechanism
122      * @param requestErrorWrapper **************/
123
124     protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
125         return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
126     }
127
128     protected Response buildGeneralErrorResponse() {
129         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
130     }
131
132     protected Response buildOkResponse(Object entity) {
133         return buildOkResponseStatic(entity);
134     }
135
136     private static Response buildOkResponseStatic(Object entity) {
137         return Response.status(Response.Status.OK)
138             .entity(entity)
139             .build();
140     }
141
142     public HttpServletRequest getServletRequest() {
143         return servletRequest;
144     }
145
146     @VisibleForTesting
147     public void setRequestServlet(HttpServletRequest request) {this.servletRequest = request;}
148
149     protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) {
150         return buildOkResponse(errorResponseWrapper, entity, null);
151     }
152
153     protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity, Map<String, String> additionalHeaders) {
154         int status = errorResponseWrapper.getStatus();
155         ResponseBuilder responseBuilder = Response.status(status);
156         if (entity != null) {
157             if (log.isTraceEnabled())
158                 log.trace("returned entity is {}", entity.toString());
159             responseBuilder = responseBuilder.entity(entity);
160         }
161         if (additionalHeaders != null) {
162             for (Entry<String, String> additionalHeader : additionalHeaders.entrySet()) {
163                 String headerName = additionalHeader.getKey();
164                 String headerValue = additionalHeader.getValue();
165                 if (log.isTraceEnabled())
166                     log.trace("Adding header {} with value {} to the response", headerName, headerValue);
167                 responseBuilder.header(headerName, headerValue);
168             }
169         }
170         return responseBuilder.build();
171     }
172
173     /*******************************************************************************************************/
174     protected Either<User, ResponseFormat> getUser(final HttpServletRequest request, String userId) {
175         User user;
176         try {
177             user = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false);
178             return Either.left(user);
179         } catch (ComponentException ce) {
180             log.info("createResource method - user is not listed. userId= {}", userId);
181             ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ce);
182             user = new User("", "", userId, "", null, null);
183             getComponentsUtils().auditResource(errorResponse, user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
184             return Either.right(errorResponse);
185         }
186     }
187
188     UserBusinessLogic getUserAdminManager(ServletContext context) {
189         return getClassFromWebAppContext(context, () -> UserBusinessLogic.class);
190     }
191
192     protected GenericArtifactBrowserBusinessLogic getGenericArtifactBrowserBL(ServletContext context) {
193         return getClassFromWebAppContext(context, () -> GenericArtifactBrowserBusinessLogic.class);
194     }
195
196     protected ResourceBusinessLogic getResourceBL(ServletContext context) {
197         return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class);
198     }
199
200     InterfaceOperationBusinessLogic getInterfaceOperationBL(ServletContext context) {
201         return getClassFromWebAppContext(context, () -> InterfaceOperationBusinessLogic.class);
202     }
203
204     protected CapabilitiesBusinessLogic getCapabilitiesBL(ServletContext context) {
205         return getClassFromWebAppContext(context, () -> CapabilitiesBusinessLogic.class);
206     }
207
208     protected RelationshipTypeBusinessLogic getRelationshipTypeBL(ServletContext context) {
209         return getClassFromWebAppContext(context, () -> RelationshipTypeBusinessLogic.class);
210     }
211     protected RequirementBusinessLogic getRequirementBL(ServletContext context) {
212         return getClassFromWebAppContext(context, () -> RequirementBusinessLogic.class);
213     }
214     ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) {
215         return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class);
216     }
217
218     protected ServiceBusinessLogic getServiceBL(ServletContext context) {
219         return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class);
220     }
221
222     ProductBusinessLogic getProductBL(ServletContext context) {
223         return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class);
224     }
225
226     protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) {
227         return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class);
228     }
229     protected UpgradeBusinessLogic getUpgradeBL(ServletContext context) {
230         return getClassFromWebAppContext(context, () -> UpgradeBusinessLogic.class);
231     }
232
233     protected ElementBusinessLogic getElementBL(ServletContext context) {
234         return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class);
235     }
236
237     protected AssetMetadataConverter getAssetUtils(ServletContext context) {
238         return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class);
239     }
240
241     protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) {
242         return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class);
243     }
244
245     <T> T getClassFromWebAppContext(ServletContext context, Supplier<Class<T>> businessLogicClassGen) {
246         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
247         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
248         return webApplicationContext.getBean(businessLogicClassGen.get());
249     }
250
251     GroupBusinessLogic getGroupBL(ServletContext context) {
252
253         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
254         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
255         return webApplicationContext.getBean(GroupBusinessLogic.class);
256     }
257
258     protected ComponentInstanceBusinessLogic getComponentInstanceBL(ServletContext context) {
259         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
260         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
261         return webApplicationContext.getBean(ComponentInstanceBusinessLogic.class);
262     }
263
264     protected ComponentsUtils getComponentsUtils() {
265         ServletContext context = this.servletRequest.getSession().getServletContext();
266
267         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
268         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
269         return webApplicationContext.getBean(ComponentsUtils.class);
270     }
271
272     /**
273      * Used to support Unit Test.<br>
274      * Header Params are not supported in Unit Tests
275      *
276      * @return
277      */
278     String initHeaderParam(String headerValue, HttpServletRequest request, String headerName) {
279         String retValue;
280         if (headerValue != null) {
281             retValue = headerValue;
282         } else {
283             retValue = request.getHeader(headerName);
284         }
285         return retValue;
286     }
287
288     protected String getContentDispositionValue(String artifactFileName) {
289         return new StringBuilder().append("attachment; filename=\"").append(artifactFileName).append("\"").toString();
290     }
291
292
293
294     protected ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum, ServletContext context) {
295         ComponentBusinessLogic businessLogic;
296         switch (componentTypeEnum) {
297             case RESOURCE:
298                 businessLogic = getResourceBL(context);
299                 break;
300             case SERVICE:
301                 businessLogic = getServiceBL(context);
302                 break;
303             case PRODUCT:
304                 businessLogic = getProductBL(context);
305                 break;
306             case RESOURCE_INSTANCE:
307                 businessLogic = getResourceBL(context);
308                 break;
309             default:
310                 BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL");
311                 throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue());
312         }
313         return businessLogic;
314     }
315
316     <T> T convertJsonToObjectOfClass(String json, Class<T> clazz) {
317         T object = null;
318         ObjectMapper mapper = new ObjectMapper()
319             .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
320             .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
321         try {
322             log.trace("Starting to convert json to object. Json=\n{}", json);
323
324             SimpleModule module = new SimpleModule("customDeserializationModule");
325             module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer());
326             mapper.registerModule(module);
327
328             object = mapper.readValue(json, clazz);
329             if (object != null) {
330                 return object;
331             } else {
332                 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
333                 log.debug("The object of class {} is null after converting from json. ", clazz);
334                 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
335             }
336         } catch (IOException e) {
337             BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
338             log.debug("The exception {} occurred upon json to object convertation. Json=\n{}", e, json);
339             throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
340         }
341     }
342
343     protected Either<Map<String, PropertyDefinition>, ActionStatus> getPropertyModel(String componentId, String data) {
344         JSONParser parser = new JSONParser();
345         JSONObject root;
346         try {
347             Map<String, PropertyDefinition> properties = new HashMap<>();
348             root = (JSONObject) parser.parse(data);
349
350             Set entrySet = root.entrySet();
351             Iterator iterator = entrySet.iterator();
352             while (iterator.hasNext()) {
353                 Entry next = (Entry) iterator.next();
354                 String propertyName = (String) next.getKey();
355
356                 if(!isPropertyNameValid(propertyName)) {
357                     return Either.right(ActionStatus.INVALID_PROPERTY_NAME);
358                 }
359
360                 JSONObject value = (JSONObject) next.getValue();
361                 Either<PropertyDefinition, ActionStatus> propertyDefinitionEither =
362                         getPropertyDefinitionFromJson(componentId, propertyName, value);
363
364                 if(propertyDefinitionEither.isRight()) {
365                     return Either.right(propertyDefinitionEither.right().value());
366                 }
367
368                 properties.put(propertyName, propertyDefinitionEither.left().value());
369             }
370
371             return Either.left(properties);
372         } catch (ParseException e) {
373             log.info("Property conetnt is invalid - {}", data);
374             return Either.right(ActionStatus.INVALID_CONTENT);
375         }
376     }
377
378     protected boolean isPropertyNameValid(String propertyName) {
379         return Objects.nonNull(propertyName)
380                        && propertyName.matches(PROPERTY_NAME_REGEX);
381
382     }
383
384     private Either<PropertyDefinition, ActionStatus> getPropertyDefinitionFromJson(String componentId, String propertyName, JSONObject value) {
385         String jsonString = value.toJSONString();
386         Either<PropertyDefinition, ActionStatus> convertJsonToObject = convertJsonToObject(jsonString, PropertyDefinition.class);
387         if (convertJsonToObject.isRight()) {
388             return Either.right(convertJsonToObject.right().value());
389         }
390         PropertyDefinition propertyDefinition = convertJsonToObject.left().value();
391         String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName);
392         propertyDefinition.setUniqueId(uniqueId);
393
394         return Either.left(propertyDefinition);
395     }
396
397     private Either<InputDefinition, ActionStatus> getInputDefinitionFromJson(String componentId, String inputName, JSONObject value) {
398         String jsonString = value.toJSONString();
399         Either<InputDefinition, ActionStatus> convertJsonToObject = convertJsonToObject(jsonString, InputDefinition.class);
400         if (convertJsonToObject.isRight()) {
401             return Either.right(convertJsonToObject.right().value());
402         }
403         InputDefinition inputDefinition = convertJsonToObject.left().value();
404         String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, inputName);
405         inputDefinition.setUniqueId(uniqueId);
406
407         return Either.left(inputDefinition);
408     }
409
410     protected Either<Map<String, PropertyDefinition>, ActionStatus> getPropertiesListForUpdate(String data) {
411
412         Map<String, PropertyDefinition> properties = new HashMap<>();
413         JSONParser parser = new JSONParser();
414         JSONArray jsonArray;
415
416         try {
417             jsonArray = (JSONArray) parser.parse(data);
418             for (Object jsonElement : jsonArray) {
419                 String propertyAsString = jsonElement.toString();
420                 Either<PropertyDefinition, ActionStatus> convertJsonToObject = convertJsonToObject(propertyAsString, PropertyDefinition.class);
421
422                 if (convertJsonToObject.isRight()) {
423                     return Either.right(convertJsonToObject.right().value());
424                 }
425
426                 PropertyDefinition propertyDefinition = convertJsonToObject.left().value();
427                 properties.put(propertyDefinition.getName(), propertyDefinition);
428             }
429
430             return Either.left(properties);
431         } catch (Exception e) {
432             log.info("Property content is invalid - {}", data);
433             return Either.right(ActionStatus.INVALID_CONTENT);
434         }
435
436     }
437
438     protected String propertyToJson(Map.Entry<String, PropertyDefinition> property) {
439         JSONObject root = new JSONObject();
440         String propertyName = property.getKey();
441         PropertyDefinition propertyDefinition = property.getValue();
442         JSONObject propertyDefinitionO = getPropertyDefinitionJSONObject(propertyDefinition);
443         root.put(propertyName, propertyDefinitionO);
444         propertyDefinition.getType();
445         return root.toString();
446     }
447
448     private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition propertyDefinition) {
449
450         Either<String, ActionStatus> either = convertObjectToJson(propertyDefinition);
451         if (either.isRight()) {
452             return new JSONObject();
453         }
454         String value = either.left().value();
455         try {
456             JSONObject root = (JSONObject) new JSONParser().parse(value);
457             return root;
458         } catch (ParseException e) {
459             log.info("failed to convert input to json");
460             log.error("failed to convert to json", e);
461             return new JSONObject();
462         }
463
464     }
465
466     protected  <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {
467         T t = null;
468         Type constraintType = new TypeToken<PropertyConstraint>() {
469         }.getType();
470         Gson
471             gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyOperation.PropertyConstraintDeserialiser()).create();
472         try {
473             log.trace("convert json to object. json=\n {}", data);
474             t = gson.fromJson(data, clazz);
475             if (t == null) {
476                 log.info("object is null after converting from json");
477                 return Either.right(ActionStatus.INVALID_CONTENT);
478             }
479         } catch (Exception e) {
480             // INVALID JSON
481             log.info("failed to convert from json");
482             log.error("failed to convert from json", e);
483             return Either.right(ActionStatus.INVALID_CONTENT);
484         }
485         return Either.left(t);
486     }
487
488     private Either<String, ActionStatus> convertObjectToJson(PropertyDefinition propertyDefinition) {
489         Type constraintType = new TypeToken<PropertyConstraint>() {
490         }.getType();
491         Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyOperation.PropertyConstraintSerialiser()).create();
492         try {
493             log.trace("convert object to json. propertyDefinition= {}", propertyDefinition);
494             String json = gson.toJson(propertyDefinition);
495             if (json == null) {
496                 log.info("object is null after converting to json");
497                 return Either.right(ActionStatus.INVALID_CONTENT);
498             }
499             return Either.left(json);
500         } catch (Exception e) {
501             // INVALID JSON
502             log.info("failed to convert to json");
503             log.debug("failed to convert fto json", e);
504             return Either.right(ActionStatus.INVALID_CONTENT);
505         }
506
507     }
508
509     protected PropertyBusinessLogic getPropertyBL(ServletContext context) {
510         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
511         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
512         PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class);
513         return propertytBl;
514     }
515
516     protected InputsBusinessLogic getInputBL(ServletContext context) {
517         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
518         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
519         return webApplicationContext.getBean(InputsBusinessLogic.class);
520     }
521
522     protected PolicyBusinessLogic getPolicyBL(ServletContext context) {
523         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
524         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
525         return webApplicationContext.getBean(PolicyBusinessLogic.class);
526     }
527
528     protected Either<ComponentInstInputsMap, ResponseFormat> parseToComponentInstanceMap(String componentJson, User user, ComponentTypeEnum componentType) {
529         return getComponentsUtils().convertJsonToObjectUsingObjectMapper(componentJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, componentType);
530     }
531
532     protected Response declareProperties(String userId, String componentId, String componentType,
533             String componentInstInputsMapObj, DeclarationTypeEnum typeEnum, HttpServletRequest request) {
534         ServletContext context = request.getSession().getServletContext();
535         String url = request.getMethod() + " " + request.getRequestURI();
536         log.debug("(get) Start handle request of {}", url);
537
538         try {
539             BaseBusinessLogic businessLogic = getBlForPropertyDeclaration(typeEnum, context);
540
541             // get modifier id
542             User modifier = new User();
543             modifier.setUserId(userId);
544             log.debug("modifier id is {}", userId);
545             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
546             Either<ComponentInstInputsMap, ResponseFormat> componentInstInputsMapRes = parseToComponentInstanceMap(componentInstInputsMapObj, modifier, componentTypeEnum);
547             if (componentInstInputsMapRes.isRight()) {
548                 log.debug("failed to parse componentInstInputsMap");
549                 return buildErrorResponse(componentInstInputsMapRes.right().value());
550             }
551
552             Either<List<ToscaDataDefinition>, ResponseFormat> propertiesAfterDeclaration = businessLogic
553                                                                                .declareProperties(userId, componentId,
554                                                                                        componentTypeEnum,
555                                                                                        componentInstInputsMapRes.left().value());
556             if (propertiesAfterDeclaration.isRight()) {
557                 log.debug("failed to create inputs  for service: {}", componentId);
558                 return buildErrorResponse(propertiesAfterDeclaration.right().value());
559             }
560             Object properties = RepresentationUtils.toRepresentation(propertiesAfterDeclaration.left().value());
561             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
562
563         } catch (Exception e) {
564             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create inputs for service with id: " + componentId);
565             log.debug("Properties declaration failed with exception", e);
566             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
567         }
568     }
569
570     public BaseBusinessLogic getBlForPropertyDeclaration(DeclarationTypeEnum typeEnum,
571                                                           ServletContext context) {
572         if(typeEnum.equals(DeclarationTypeEnum.POLICY)) {
573             return getPolicyBL(context);
574         }
575
576         return getInputBL(context);
577     }
578
579     protected Either<Map<String, InputDefinition>, ActionStatus> getInputModel(String componentId, String data) {
580         JSONParser parser = new JSONParser();
581         JSONObject root;
582         try {
583             Map<String, InputDefinition> inputs = new HashMap<>();
584             root = (JSONObject) parser.parse(data);
585
586             Set entrySet = root.entrySet();
587             Iterator iterator = entrySet.iterator();
588             while (iterator.hasNext()) {
589                 Entry next = (Entry) iterator.next();
590                 String inputName = (String) next.getKey();
591
592                 if(!isInputNameValid(inputName)) {
593                     return Either.right(ActionStatus.INVALID_INPUT_NAME);
594                 }
595
596                 JSONObject value = (JSONObject) next.getValue();
597                 Either<InputDefinition, ActionStatus> inputDefinitionEither =
598                         getInputDefinitionFromJson(componentId, inputName, value);
599
600                 if(inputDefinitionEither.isRight()) {
601                     return Either.right(inputDefinitionEither.right().value());
602                 }
603
604                 inputs.put(inputName, inputDefinitionEither.left().value());
605             }
606
607             return Either.left(inputs);
608         } catch (ParseException e) {
609             log.warn("Input content is invalid - {}", data, e);
610             return Either.right(ActionStatus.INVALID_CONTENT);
611         }
612     }
613
614     protected boolean isInputNameValid(String inputName) {
615         return Objects.nonNull(inputName)
616                 && inputName.matches(PROPERTY_NAME_REGEX);
617
618     }
619 }