Upgrade swagger 70/94170/7
authorArindam Mondal <arind.mondal@samsung.com>
Fri, 23 Aug 2019 03:13:33 +0000 (12:13 +0900)
committerOfir Sonsino <ofir.sonsino@intl.att.com>
Mon, 26 Aug 2019 12:13:53 +0000 (12:13 +0000)
Issue-ID: SDC-2154
Change-Id: I95f6326a088f9a29c4ccb3b7a741d57ecf27ae7a
Signed-off-by: arindamm <arind.mondal@samsung.com>
44 files changed:
catalog-be/pom.xml
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArchiveEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CapabilityServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GenericArtifactBrowserServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InterfaceOperationServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceConsumptionServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceFilterServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java

index 4fd0da7..497bdcb 100644 (file)
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-    <modelVersion>4.0.0</modelVersion>
-
-    <artifactId>catalog-be</artifactId>
-    <packaging>war</packaging>
-
-    <parent>
-        <groupId>org.openecomp.sdc</groupId>
-        <artifactId>sdc-main</artifactId>
-        <version>1.5.1-SNAPSHOT</version>
-    </parent>
-
-    <properties>
-        <java-hamcrest.version>2.0.0.0</java-hamcrest.version>
-    </properties>
-
-    <dependencies>
-        <!--JSON and YAML Parsing-->
-        <dependency>
-            <groupId>com.fasterxml.jackson.dataformat</groupId>
-            <artifactId>jackson-dataformat-yaml</artifactId>
-            <version>${jackson.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>com.fasterxml.jackson.core</groupId>
-            <artifactId>jackson-databind</artifactId>
-            <version>${jackson.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.openecomp.sdc</groupId>
-            <artifactId>security-utils</artifactId>
-            <version>${project.version}</version>
-            <scope>compile</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.onap.sdc.common</groupId>
-            <artifactId>onap-tosca-datatype</artifactId>
-            <version>${project.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.onap.sdc.common</groupId>
-            <artifactId>onap-generic-artifact-browser-service</artifactId>
-            <version>${project.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <!-- Swagger Dependencies Start -->
-        <dependency>
-            <groupId>io.swagger</groupId>
-            <artifactId>swagger-jersey2-jaxrs</artifactId>
-            <scope>compile</scope>
-            <version>1.5.15</version>
-        </dependency>
-        <!-- Swagger Dependencies End -->
-
-        <dependency>
-            <groupId>org.openecomp.sdc</groupId>
-            <artifactId>common-app-api</artifactId>
-            <version>${project.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.openecomp.sdc.be</groupId>
-            <artifactId>common-be</artifactId>
-            <version>${project.version}</version>
-            <scope>compile</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.openecomp.sdc.be</groupId>
-            <artifactId>catalog-dao</artifactId>
-            <version>${project.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.openecomp.sdc.be</groupId>
-            <artifactId>catalog-model</artifactId>
-            <version>${project.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>ch.qos.logback</groupId>
-            <artifactId>logback-classic</artifactId>
-            <version>${logback.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <!-- Snake Yaml -->
-        <dependency>
-            <groupId>org.yaml</groupId>
-            <artifactId>snakeyaml</artifactId>
-            <version>${snakeyaml.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <!-- File changes listener -->
-        <dependency>
-            <groupId>org.apache.commons</groupId>
-            <artifactId>commons-jci-core</artifactId>
-            <version>${commons-jci-core.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <!-- Gson -->
-        <dependency>
-            <groupId>com.google.code.gson</groupId>
-            <artifactId>gson</artifactId>
-            <version>${gson.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <!-- jersey -->
-        <dependency>
-            <groupId>org.glassfish.jersey.media</groupId>
-            <artifactId>jersey-media-json-jackson</artifactId>
-            <version>${jersey-bom.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.glassfish.jersey.containers</groupId>
-            <artifactId>jersey-container-servlet-core</artifactId>
-            <version>${jersey-bom.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.glassfish.jersey.media</groupId>
-            <artifactId>jersey-media-multipart</artifactId>
-            <version>${jersey-bom.version}</version>
-            <scope>compile</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.glassfish.jersey.ext</groupId>
-            <artifactId>jersey-spring4</artifactId>
-            <version>${jersey-bom.version}</version>
-            <exclusions>
-                <exclusion>
-                    <groupId>org.springframework</groupId>
-                    <artifactId>spring-web</artifactId>
-                </exclusion>
-                <exclusion>
-                    <groupId>org.springframework</groupId>
-                    <artifactId>spring-beans</artifactId>
-                </exclusion>
-                <exclusion>
-                    <groupId>org.springframework</groupId>
-                    <artifactId>spring-core</artifactId>
-                </exclusion>
-                <exclusion>
-                    <groupId>org.springframework</groupId>
-                    <artifactId>spring-aop</artifactId>
-                </exclusion>
-                <!-- Transitive dependency of spring-bridge -->
-                <exclusion>
-                    <groupId>org.springframework</groupId>
-                    <artifactId>spring-context</artifactId>
-                </exclusion>
-            </exclusions>
-
-        </dependency>
-
-        <!--asm-all-repackaged is a jersey dependency. in current version jersey depends on a version that was compiled using java 9 compiler
-            currently our jetty (v9.3.6) does not support java 9. as soon as jetty gets upgraded we will remove this dependency-->
-        <dependency>
-            <groupId>org.glassfish.hk2.external</groupId>
-            <artifactId>asm-all-repackaged</artifactId>
-        </dependency>
-
-        <dependency>
-            <groupId>org.glassfish.jersey.ext</groupId>
-            <artifactId>jersey-bean-validation</artifactId>
-        </dependency>
-
-        <!-- http client -->
-        <dependency>
-            <groupId>org.apache.httpcomponents</groupId>
-            <artifactId>httpclient</artifactId>
-            <version>${httpclient.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.apache.httpcomponents</groupId>
-            <artifactId>httpcore</artifactId>
-            <version>${httpcore.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>commons-logging</groupId>
-            <artifactId>commons-logging</artifactId>
-            <version>${commons-logging}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>commons-codec</groupId>
-            <artifactId>commons-codec</artifactId>
-            <version>${commons-codec}</version>
-            <scope>compile</scope>
-        </dependency>
-        <!-- http client END -->
-
-        <dependency>
-            <groupId>javax.servlet</groupId>
-            <artifactId>javax.servlet-api</artifactId>
-            <version>${servlet-api.version}</version>
-            <scope>provided</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.eclipse.jgit</groupId>
-            <artifactId>org.eclipse.jgit</artifactId>
-            <version>3.4.1.201406201815-r</version>
-        </dependency>
-
-        <!-- spring - used by A4C -->
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-core</artifactId>
-            <version>${spring.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-context</artifactId>
-            <version>${spring.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-web</artifactId>
-            <version>${spring.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-webmvc</artifactId>
-            <version>${spring.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-aop</artifactId>
-            <version>${spring.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-beans</artifactId>
-            <version>${spring.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-expression</artifactId>
-            <version>${spring.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.codehaus.groovy</groupId>
-            <artifactId>groovy</artifactId>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.codehaus.janino</groupId>
-            <artifactId>janino</artifactId>
-            <version>${janino.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.codehaus.janino</groupId>
-            <artifactId>commons-compiler</artifactId>
-            <version>${janino.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>com.google.guava</groupId>
-            <artifactId>guava</artifactId>
-            <version>${guava.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.janusgraph</groupId>
-            <artifactId>janusgraph-core</artifactId>
-            <version>${janusgraph.version}</version>
-            <scope>compile</scope>
-            <exclusions>
-                <exclusion>
-                    <groupId>org.json</groupId>
-                    <artifactId>json</artifactId>
-                </exclusion>
-                <exclusion>
-                    <artifactId>slf4j-log4j12</artifactId>
-                    <groupId>org.slf4j</groupId>
-                </exclusion>
-                <exclusion>
-                    <artifactId>commons-collections</artifactId>
-                    <groupId>commons-collections</groupId>
-                </exclusion>
-                <exclusion>
-                    <groupId>org.apache.thrift</groupId>
-                    <artifactId>libthrift</artifactId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-
-        <dependency>
-            <groupId>org.janusgraph</groupId>
-            <artifactId>janusgraph-cassandra</artifactId>
-            <version>${janusgraph.version}</version>
-            <scope>compile</scope>
-            <exclusions>
-                <exclusion>
-                    <groupId>org.slf4j</groupId>
-                    <artifactId>slf4j-log4j12</artifactId>
-                </exclusion>
-                <exclusion>
-                    <groupId>io.netty</groupId>
-                    <artifactId>netty-all</artifactId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-
-        <dependency>
-            <groupId>org.apache.commons</groupId>
-            <artifactId>commons-lang3</artifactId>
-            <version>${lang3.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>com.googlecode.json-simple</groupId>
-            <artifactId>json-simple</artifactId>
-            <version>${json-simple.version}</version>
-            <scope>compile</scope>
-
-        </dependency>
-
-        <dependency>
-            <groupId>org.elasticsearch</groupId>
-            <artifactId>elasticsearch</artifactId>
-            <version>${elastic-search.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <!-- functional java -->
-        <dependency>
-            <groupId>org.functionaljava</groupId>
-            <artifactId>functionaljava</artifactId>
-            <version>${functionaljava.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <!-- Aspects -->
-        <dependency>
-            <groupId>com.jcabi</groupId>
-            <artifactId>jcabi-aspects</artifactId>
-            <version>${jcabi.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.aspectj</groupId>
-            <artifactId>aspectjrt</artifactId>
-            <version>${aspectjrt.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-
-        <!-- CAMBRIA CLIENT for U-EB -->
-        <dependency>
-            <groupId>com.att.nsa</groupId>
-            <artifactId>cambriaClient</artifactId>
-            <version>1.2.1-oss</version>
-            <scope>compile</scope>
-            <exclusions>
-                <exclusion>
-                    <groupId>com.att.nsa</groupId>
-                    <artifactId>saClientLibrary</artifactId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-
-        <dependency>
-            <groupId>org.json</groupId>
-            <artifactId>json</artifactId>
-            <version>20131018</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <!-- CASSANDRA -->
-        <dependency>
-            <groupId>com.datastax.cassandra</groupId>
-            <artifactId>cassandra-driver-core</artifactId>
-            <version>${cassandra.driver.version}</version>
-            <scope>compile</scope>
-        </dependency>
-        <dependency>
-            <groupId>com.datastax.cassandra</groupId>
-            <artifactId>cassandra-driver-mapping</artifactId>
-            <version>${cassandra.driver.version}</version>
-            <scope>compile</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.thrift</groupId>
-            <artifactId>libthrift</artifactId>
-            <version>${libthrift.version}</version>
-        </dependency>
-        <!-- CASSANDRA END -->
-
-        <!-- Inserted for ECOMP Portal Integration -->
-        <dependency>
-            <groupId>org.onap.portal.sdk</groupId>
-            <artifactId>epsdk-fw</artifactId>
-            <version>${ecomp.version}</version>
-            <scope>compile</scope>
-            <exclusions>
-                <exclusion>
-                    <groupId>com.att.nsa</groupId>
-                    <artifactId>cambriaClient</artifactId>
-                </exclusion>
-                <exclusion>
-                    <artifactId>slf4j-log4j12</artifactId>
-                    <groupId>org.slf4j</groupId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-
-        <!--Jetty Proxy-->
-        <dependency>
-            <groupId>org.eclipse.jetty</groupId>
-            <artifactId>jetty-proxy</artifactId>
-            <version>${jetty.version}</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.eclipse.jetty</groupId>
-            <artifactId>jetty-servlets</artifactId>
-            <version>${jetty.version}</version>
-            <scope>compile</scope>
-        </dependency>
-        <!-- System metrics -->
-        <dependency>
-            <groupId>org.fusesource</groupId>
-            <artifactId>sigar</artifactId>
-            <version>${sigar.version}</version>
-            <scope>compile</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.onap.dmaap.messagerouter.dmaapclient</groupId>
-            <artifactId>dmaapClient</artifactId>
-            <version>1.1.3</version>
-            <scope>compile</scope>
-            <exclusions>
-                <exclusion>
-                    <groupId>com.att.aft</groupId>
-                    <artifactId>dme2</artifactId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-        <dependency>
-            <groupId>com.att.aft</groupId>
-            <artifactId>dme2</artifactId>
-            <version>3.1.200-oss</version>
-        </dependency>
-
-        <dependency>
-            <groupId>javax.jms</groupId>
-            <artifactId>jms</artifactId>
-            <version>1.1</version>
-            <scope>provided</scope>
-        </dependency>
-
-        <!-- TEST -->
-        <dependency>
-            <groupId>org.assertj</groupId>
-            <artifactId>assertj-core</artifactId>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.glassfish.jersey.test-framework.providers</groupId>
-            <artifactId>jersey-test-framework-provider-bundle</artifactId>
-            <version>${jersey-bom.version}</version>
-            <type>pom</type>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.glassfish.jersey.core</groupId>
-            <artifactId>jersey-client</artifactId>
-            <version>${jersey-bom.version}</version>
-        </dependency>
-
-        <dependency>
-            <groupId>com.github.tomakehurst</groupId>
-            <artifactId>wiremock-standalone</artifactId>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.eclipse.jetty</groupId>
-            <artifactId>jetty-webapp</artifactId>
-            <version>${jetty.version}</version>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>junit</groupId>
-            <artifactId>junit</artifactId>
-            <version>${junit.version}</version>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.mockito</groupId>
-            <artifactId>mockito-core</artifactId>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-test</artifactId>
-            <version>${spring.version}</version>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-tx</artifactId>
-            <version>${spring.version}</version>
-        </dependency>
-
-        <dependency>
-            <groupId>io.cucumber</groupId>
-            <artifactId>cucumber-java</artifactId>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>io.cucumber</groupId>
-            <artifactId>cucumber-junit</artifactId>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.jmockit</groupId>
-            <artifactId>jmockit</artifactId>
-            <version>${jmockit.version}</version>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>com.google.code.bean-matchers</groupId>
-            <artifactId>bean-matchers</artifactId>
-            <version>0.11</version>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.hamcrest</groupId>
-            <artifactId>java-hamcrest</artifactId>
-            <version>${java-hamcrest.version}</version>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.codehaus.groovy</groupId>
-            <artifactId>groovy</artifactId>
-            <version>2.4.8</version>
-        </dependency>
-
-        <dependency>
-            <groupId>io.netty</groupId>
-            <artifactId>netty-handler</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.onap.sdc.common</groupId>
-            <artifactId>onap-tosca-datatype</artifactId>
-            <version>${project.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.commons</groupId>
-            <artifactId>commons-collections4</artifactId>
-            <version>${commons.collections.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.codehaus.jackson</groupId>
-            <artifactId>jackson-mapper-asl</artifactId>
-            <version>${jackson.mapper.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.commons</groupId>
-            <artifactId>commons-collections4</artifactId>
-            <version>${commons.collections.version}</version>
-        </dependency>
-    </dependencies>
-
-    <build>
-
-        <finalName>${project.artifactId}-${project.version}</finalName>
-
-        <plugins>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-war-plugin</artifactId>
-                <configuration>
-                    <packagingExcludes>WEB-INF\lib\slf4j-log4j*.jar,
-                        WEB-INF/classes/elasticsearch.yml,
-                        WEB-INF/classes/portal.properties
-                    </packagingExcludes>
-                    <archive>
-                        <manifestEntries>
-                            <SDC-Version>${project.version}</SDC-Version>
-                        </manifestEntries>
-                        <manifest>
-                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
-                            <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
-                        </manifest>
-                    </archive>
-
-                    <webResources>
-                        <resource>
-                            <directory>src/main/resources</directory>
-                            <directory>src/main/resources/swagger</directory>
-                        </resource>
-                    </webResources>
-                    <attachClasses>true</attachClasses>
-                </configuration>
-            </plugin>
-            <plugin>
-                <groupId>com.github.sylvainlaurent.maven</groupId>
-                <artifactId>yaml-json-validator-maven-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>validate</id>
-                        <phase>validate</phase>
-                        <goals>
-                            <goal>validate</goal>
-                        </goals>
-                        <configuration>
-                            <validationSets>
-                                <validationSet>
-                                    <includes>
-                                        <include>src/main/resources/**/*.y*ml</include>
-                                        <include>src/test/resources/**/*.y*ml</include>
-                                    </includes>
-                                </validationSet>
-                                <validationSet>
-                                    <includes>
-                                        <include>src/main/resources/**/*.json</include>
-                                        <include>src/test/resources/**/*.json</include>
-                                    </includes>
-                                </validationSet>
-                            </validationSets>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-            <plugin>
-                <groupId>com.jcabi</groupId>
-                <artifactId>jcabi-maven-plugin</artifactId>
-                <version>${jcabi.maven.plugin.version}</version>
-                <executions>
-                    <execution>
-                        <goals>
-                            <goal>ajc</goal>
-                        </goals>
-                    </execution>
-                </executions>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-assembly-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>normatives</id>
-                        <phase>package</phase>
-                        <goals>
-                            <goal>single</goal>
-                        </goals>
-                        <configuration>
-                            <finalName>normatives</finalName>
-                            <appendAssemblyId>false</appendAssemblyId>
-                            <descriptors>
-                                <descriptor>${project.basedir}/normatives.xml</descriptor>
-                            </descriptors>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-clean-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>clean.sdc.backend.folder</id>
-                        <phase>clean</phase>
-                        <goals>
-                            <goal>clean</goal>
-                        </goals>
-                        <configuration>
-                            <filesets>
-                                <!-- static configuration files -->
-                                <fileset>
-                                    <directory>
-                                        ${project.parent.basedir}/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default
-                                    </directory>
-                                    <followSymlinks>false</followSymlinks>
-                                    <includes>
-                                        <include>error-configuration.yaml</include>
-                                        <include>ecomp-error-configuration.yaml</include>
-                                        <include>logback.xml</include>
-                                    </includes>
-                                </fileset>
-                                <!-- BE WAR's -->
-                                <fileset>
-                                    <directory>${project.parent.basedir}/catalog-be/sdc-backend</directory>
-                                    <followSymlinks>false</followSymlinks>
-                                    <includes>
-                                        <include>*.war</include>
-                                    </includes>
-                                </fileset>
-                                <fileset>
-                                    <directory>
-                                        ${project.basedir}/sdc-backend-init/chef-repo/cookbooks/sdc-normatives/files/default
-                                    </directory>
-                                    <followSymlinks>false</followSymlinks>
-                                    <includes>
-                                        <include>normatives.tar.gz</include>
-                                    </includes>
-                                </fileset>
-
-
-                            </filesets>
-                        </configuration>
-                    </execution>
-
-                    <execution>
-                        <id>clean-static-files</id>
-                        <phase>clean</phase>
-                        <goals>
-                            <goal>clean</goal>
-                        </goals>
-                        <configuration>
-                            <filesets>
-                                <!-- tosca files -->
-                                <fileset>
-                                    <directory>${project.parent.basedir}/asdctool/tosca</directory>
-                                    <followSymlinks>false</followSymlinks>
-                                </fileset>
-                            </filesets>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-resources-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>copy-static-configuration-files</id>
-                        <phase>verify</phase>
-                        <goals>
-                            <goal>copy-resources</goal>
-                        </goals>
-                        <configuration>
-                            <outputDirectory>
-                                ${project.parent.basedir}/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default
-                            </outputDirectory>
-                            <resources>
-                                <resource>
-                                    <directory>${project.parent.basedir}/catalog-be/src/main/resources/config
-                                    </directory>
-                                    <includes>
-                                        <include>error-configuration.yaml</include>
-                                        <include>ecomp-error-configuration.yaml</include>
-                                        <include>logback.xml</include>
-                                    </includes>
-                                </resource>
-                            </resources>
-                        </configuration>
-                    </execution>
-                    <execution>
-                        <id>copy-tosca-folder</id>
-                        <!-- here the phase you need -->
-                        <phase>install</phase>
-                        <goals>
-                            <goal>copy-resources</goal>
-                        </goals>
-                        <configuration>
-                            <outputDirectory>${project.parent.basedir}/asdctool/tosca</outputDirectory>
-                            <resources>
-                                <resource>
-                                    <directory>${project.parent.basedir}/catalog-be/src/main/resources/import/tosca
-                                    </directory>
-                                    <filtering>true</filtering>
-                                </resource>
-                            </resources>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-            <plugin>
-                <groupId>com.github.kongchen</groupId>
-                <artifactId>swagger-maven-plugin</artifactId>
-                <version>3.1.0</version>
-                <configuration>
-                    <apiSources>
-                        <apiSource>
-                            <springmvc>false</springmvc>
-                            <schemes>http</schemes>
-                            <basePath>/sdc</basePath>
-                            <locations>io.swagger.jaxrs.json;org.openecomp.sdc.be.externalapi.servlet;org.openecomp.sdc.be.distribution.servlet;org.openecomp.normative.api</locations>
-                            <info>
-                                <title>External Rest API</title>
-                                <version>v1.0</version>
-                                <description>External Rest API Documentation</description>
-                                <termsOfService>
-                                    http://www.github.com/kongchen/swagger-maven-plugin
-                                </termsOfService>
-                            </info>
-                            <templatePath>${basedir}/templates/strapdown.html.hbs</templatePath>
-                            <outputPath>${basedir}/target/generated/swagger-ui/api.html</outputPath>
-                            <swaggerDirectory>${basedir}/target/generated/swagger-ui
-                            </swaggerDirectory>
-                            <swaggerApiReader>io.swagger.jaxrs.config.DefaultJaxrsConfig</swaggerApiReader>
-                        </apiSource>
-                    </apiSources>
-                </configuration>
-                <executions>
-                    <execution>
-                        <phase>compile</phase>
-                        <goals>
-                            <goal>generate</goal>
-                        </goals>
-                    </execution>
-                </executions>
-            </plugin>
-        </plugins>
-
-        <pluginManagement>
-            <plugins>
-                <!--This plugin's configuration is used to store Eclipse m2e settings
-                    only. It has no influence on the Maven build itself. -->
-                <plugin>
-                    <groupId>org.eclipse.m2e</groupId>
-                    <artifactId>lifecycle-mapping</artifactId>
-                    <version>1.0.0</version>
-                    <configuration>
-                        <lifecycleMappingMetadata>
-                            <pluginExecutions>
-                                <pluginExecution>
-                                    <pluginExecutionFilter>
-                                        <groupId>com.googlecode.maven-download-plugin</groupId>
-                                        <artifactId>download-maven-plugin</artifactId>
-                                        <versionRange>[1.2.1,)</versionRange>
-                                        <goals>
-                                            <goal>wget</goal>
-                                        </goals>
-                                    </pluginExecutionFilter>
-                                    <action>
-                                        <ignore></ignore>
-                                    </action>
-                                </pluginExecution>
-
-                                <pluginExecution>
-                                    <pluginExecutionFilter>
-                                        <groupId>com.jcabi</groupId>
-                                        <artifactId>jcabi-maven-plugin</artifactId>
-                                        <versionRange>[0.0,)</versionRange>
-                                        <goals>
-                                            <goal>ajc</goal>
-                                        </goals>
-                                    </pluginExecutionFilter>
-                                    <action>
-                                        <execute/>
-                                    </action>
-                                </pluginExecution>
-
-                            </pluginExecutions>
-                        </lifecycleMappingMetadata>
-                    </configuration>
-                </plugin>
-            </plugins>
-        </pluginManagement>
-        <!-- Swagger Plugins End -->
-    </build>
-
-    <profiles>
-        <profile>
-            <id>docker-staging</id>
-            <properties>
-                <docker.tag>${project.version}-STAGING-${maven.build.timestamp}</docker.tag>
-                <docker.latest.tag>${project.version}-STAGING-latest</docker.latest.tag>
-            </properties>
-        </profile>
-
-        <profile>
-            <id>docker</id>
-            <activation>
-                <activeByDefault>false</activeByDefault>
-            </activation>
-            <build>
-                <plugins>
-                    <plugin>
-                        <groupId>org.apache.maven.plugins</groupId>
-                        <artifactId>maven-resources-plugin</artifactId>
-                        <executions>
-                            <execution>
-                                <id>copy-resources-apidocs</id>
-                                <phase>verify</phase>
-                                <goals>
-                                    <goal>copy-resources</goal>
-                                </goals>
-                                <configuration>
-                                    <outputDirectory>${basedir}/sdc-backend</outputDirectory>
-                                    <resources>
-                                        <resource>
-                                            <directory>
-                                                ${project.parent.basedir}/openecomp-be/tools/swagger-ui/target/api-docs
-                                            </directory>
-                                            <includes>
-                                                <include>api-docs.war</include>
-                                            </includes>
-                                        </resource>
-                                    </resources>
-                                </configuration>
-                            </execution>
-
-                            <execution>
-                                <id>copy-resources-be</id>
-                                <phase>verify</phase>
-                                <goals>
-                                    <goal>copy-resources</goal>
-                                </goals>
-                                <configuration>
-                                    <outputDirectory>${basedir}/sdc-backend</outputDirectory>
-                                    <resources>
-                                        <resource>
-                                            <directory>${project.parent.basedir}/catalog-be/target</directory>
-                                            <includes>
-                                                <include>catalog-be-${project.version}.war</include>
-                                            </includes>
-                                        </resource>
-                                        <resource>
-                                            <directory>
-                                                ${project.parent.basedir}/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/target
-                                            </directory>
-                                            <includes>
-                                                <include>onboarding-be-${project.version}.war</include>
-                                            </includes>
-                                        </resource>
-                                    </resources>
-                                </configuration>
-                            </execution>
-                            <execution>
-                                <id>copy-normatives</id>
-                                <phase>verify</phase>
-                                <goals>
-                                    <goal>copy-resources</goal>
-                                </goals>
-                                <configuration>
-                                    <outputDirectory>
-                                        sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default
-                                    </outputDirectory>
-                                    <resources>
-                                        <resource>
-                                            <directory>${project.parent.basedir}/catalog-be/target</directory>
-                                            <includes>
-                                                <include>normatives.tar.gz</include>
-                                            </includes>
-                                        </resource>
-                                    </resources>
-                                </configuration>
-                            </execution>
-                        </executions>
-                    </plugin>
-                    <plugin>
-                        <groupId>io.fabric8</groupId>
-                        <artifactId>docker-maven-plugin</artifactId>
-                        <configuration>
-                            <apiVersion>1.23</apiVersion>
-                            <registry>nexus3.onap.org:10001</registry>
-                            <authConfig>
-                                <pull>
-                                    <username>docker</username>
-                                    <password>docker</password>
-                                </pull>
-                            </authConfig>
-                            <images>
-
-                                <!-- Build backend image -->
-                                <image>
-                                    <name>onap/sdc-backend</name>
-                                    <alias>sdc-backend</alias>
-                                    <build>
-                                        <cleanup>try</cleanup>
-                                        <dockerFileDir>${project.basedir}/sdc-backend</dockerFileDir>
-                                        <tags>
-                                            <tag>${docker.tag}</tag>
-                                            <tag>
-                                                ${parsedVersion.majorVersion}.${parsedVersion.minorVersion}-STAGING-latest
-                                            </tag>
-                                        </tags>
-                                    </build>
-                                </image>
-                                <!-- Build backend-init image -->
-                                <image>
-                                    <name>onap/sdc-backend-init</name>
-                                    <alias>sdc-backend-init</alias>
-                                    <build>
-                                        <cleanup>try</cleanup>
-                                        <dockerFileDir>${project.basedir}/sdc-backend-init</dockerFileDir>
-                                        <tags>
-                                            <tag>${docker.tag}</tag>
-                                            <tag>
-                                                ${parsedVersion.majorVersion}.${parsedVersion.minorVersion}-STAGING-latest
-                                            </tag>
-                                        </tags>
-                                    </build>
-                                </image>
-                            </images>
-                        </configuration>
-                        <executions>
-                            <execution>
-                                <id>clean-images</id>
-                                <phase>pre-clean</phase>
-                                <goals>
-                                    <goal>remove</goal>
-                                </goals>
-                                <configuration>
-                                    <removeAll>true</removeAll>
-                                    <image>onap/sdc-backend,onap/sdc-backend-init</image>
-                                </configuration>
-                            </execution>
-
-                            <execution>
-                                <id>generate-images</id>
-                                <phase>install</phase>
-                                <goals>
-                                    <goal>build</goal>
-                                </goals>
-                            </execution>
-
-                            <execution>
-                                <id>push-images</id>
-                                <phase>deploy</phase>
-                                <goals>
-                                    <goal>push</goal>
-                                </goals>
-                                <configuration>
-                                    <image>onap/sdc-backend,onap/sdc-backend-init</image>
-                                </configuration>
-                            </execution>
-                        </executions>
-                    </plugin>
-                </plugins>
-            </build>
-        </profile>
-    </profiles>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">\r
+    <modelVersion>4.0.0</modelVersion>\r
+\r
+    <artifactId>catalog-be</artifactId>\r
+    <packaging>war</packaging>\r
+\r
+    <parent>\r
+        <groupId>org.openecomp.sdc</groupId>\r
+        <artifactId>sdc-main</artifactId>\r
+        <version>1.5.1-SNAPSHOT</version>\r
+    </parent>\r
+\r
+    <properties>\r
+        <java-hamcrest.version>2.0.0.0</java-hamcrest.version>\r
+        <swagger.version>2.0.8</swagger.version>\r
+    </properties>\r
+\r
+    <dependencies>\r
+        <!--JSON and YAML Parsing-->\r
+        <dependency>\r
+            <groupId>com.fasterxml.jackson.dataformat</groupId>\r
+            <artifactId>jackson-dataformat-yaml</artifactId>\r
+            <version>${jackson.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>com.fasterxml.jackson.core</groupId>\r
+            <artifactId>jackson-databind</artifactId>\r
+            <version>${jackson.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.openecomp.sdc</groupId>\r
+            <artifactId>security-utils</artifactId>\r
+            <version>${project.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+        <dependency>\r
+            <groupId>org.onap.sdc.common</groupId>\r
+            <artifactId>onap-tosca-datatype</artifactId>\r
+            <version>${project.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.onap.sdc.common</groupId>\r
+            <artifactId>onap-generic-artifact-browser-service</artifactId>\r
+            <version>${project.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <!-- Swagger Dependencies Start -->\r
+        <dependency>\r
+                <groupId>io.swagger.core.v3</groupId>\r
+                <artifactId>swagger-annotations</artifactId>\r
+                <version>${swagger.version}</version>\r
+            </dependency>\r
+        <!-- Swagger Dependencies End -->\r
+\r
+        <dependency>\r
+            <groupId>org.openecomp.sdc</groupId>\r
+            <artifactId>common-app-api</artifactId>\r
+            <version>${project.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.openecomp.sdc.be</groupId>\r
+            <artifactId>common-be</artifactId>\r
+            <version>${project.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+        <dependency>\r
+            <groupId>org.openecomp.sdc.be</groupId>\r
+            <artifactId>catalog-dao</artifactId>\r
+            <version>${project.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.openecomp.sdc.be</groupId>\r
+            <artifactId>catalog-model</artifactId>\r
+            <version>${project.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>ch.qos.logback</groupId>\r
+            <artifactId>logback-classic</artifactId>\r
+            <version>${logback.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <!-- Snake Yaml -->\r
+        <dependency>\r
+            <groupId>org.yaml</groupId>\r
+            <artifactId>snakeyaml</artifactId>\r
+            <version>${snakeyaml.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <!-- File changes listener -->\r
+        <dependency>\r
+            <groupId>org.apache.commons</groupId>\r
+            <artifactId>commons-jci-core</artifactId>\r
+            <version>${commons-jci-core.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <!-- Gson -->\r
+        <dependency>\r
+            <groupId>com.google.code.gson</groupId>\r
+            <artifactId>gson</artifactId>\r
+            <version>${gson.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <!-- jersey -->\r
+        <dependency>\r
+            <groupId>org.glassfish.jersey.media</groupId>\r
+            <artifactId>jersey-media-json-jackson</artifactId>\r
+            <version>${jersey-bom.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.glassfish.jersey.containers</groupId>\r
+            <artifactId>jersey-container-servlet-core</artifactId>\r
+            <version>${jersey-bom.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.glassfish.jersey.media</groupId>\r
+            <artifactId>jersey-media-multipart</artifactId>\r
+            <version>${jersey-bom.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+        <dependency>\r
+            <groupId>org.glassfish.jersey.ext</groupId>\r
+            <artifactId>jersey-spring4</artifactId>\r
+            <version>${jersey-bom.version}</version>\r
+            <exclusions>\r
+                <exclusion>\r
+                    <groupId>org.springframework</groupId>\r
+                    <artifactId>spring-web</artifactId>\r
+                </exclusion>\r
+                <exclusion>\r
+                    <groupId>org.springframework</groupId>\r
+                    <artifactId>spring-beans</artifactId>\r
+                </exclusion>\r
+                <exclusion>\r
+                    <groupId>org.springframework</groupId>\r
+                    <artifactId>spring-core</artifactId>\r
+                </exclusion>\r
+                <exclusion>\r
+                    <groupId>org.springframework</groupId>\r
+                    <artifactId>spring-aop</artifactId>\r
+                </exclusion>\r
+                <!-- Transitive dependency of spring-bridge -->\r
+                <exclusion>\r
+                    <groupId>org.springframework</groupId>\r
+                    <artifactId>spring-context</artifactId>\r
+                </exclusion>\r
+            </exclusions>\r
+\r
+        </dependency>\r
+\r
+        <!--asm-all-repackaged is a jersey dependency. in current version jersey depends on a version that was compiled using java 9 compiler\r
+            currently our jetty (v9.3.6) does not support java 9. as soon as jetty gets upgraded we will remove this dependency-->\r
+        <dependency>\r
+            <groupId>org.glassfish.hk2.external</groupId>\r
+            <artifactId>asm-all-repackaged</artifactId>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.glassfish.jersey.ext</groupId>\r
+            <artifactId>jersey-bean-validation</artifactId>\r
+        </dependency>\r
+\r
+        <!-- http client -->\r
+        <dependency>\r
+            <groupId>org.apache.httpcomponents</groupId>\r
+            <artifactId>httpclient</artifactId>\r
+            <version>${httpclient.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.apache.httpcomponents</groupId>\r
+            <artifactId>httpcore</artifactId>\r
+            <version>${httpcore.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>commons-logging</groupId>\r
+            <artifactId>commons-logging</artifactId>\r
+            <version>${commons-logging}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>commons-codec</groupId>\r
+            <artifactId>commons-codec</artifactId>\r
+            <version>${commons-codec}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+        <!-- http client END -->\r
+\r
+        <dependency>\r
+            <groupId>javax.servlet</groupId>\r
+            <artifactId>javax.servlet-api</artifactId>\r
+            <version>${servlet-api.version}</version>\r
+            <scope>provided</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.eclipse.jgit</groupId>\r
+            <artifactId>org.eclipse.jgit</artifactId>\r
+            <version>3.4.1.201406201815-r</version>\r
+        </dependency>\r
+\r
+        <!-- spring - used by A4C -->\r
+        <dependency>\r
+            <groupId>org.springframework</groupId>\r
+            <artifactId>spring-core</artifactId>\r
+            <version>${spring.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.springframework</groupId>\r
+            <artifactId>spring-context</artifactId>\r
+            <version>${spring.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.springframework</groupId>\r
+            <artifactId>spring-web</artifactId>\r
+            <version>${spring.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.springframework</groupId>\r
+            <artifactId>spring-webmvc</artifactId>\r
+            <version>${spring.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.springframework</groupId>\r
+            <artifactId>spring-aop</artifactId>\r
+            <version>${spring.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.springframework</groupId>\r
+            <artifactId>spring-beans</artifactId>\r
+            <version>${spring.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.springframework</groupId>\r
+            <artifactId>spring-expression</artifactId>\r
+            <version>${spring.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.codehaus.groovy</groupId>\r
+            <artifactId>groovy</artifactId>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.codehaus.janino</groupId>\r
+            <artifactId>janino</artifactId>\r
+            <version>${janino.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.codehaus.janino</groupId>\r
+            <artifactId>commons-compiler</artifactId>\r
+            <version>${janino.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>com.google.guava</groupId>\r
+            <artifactId>guava</artifactId>\r
+            <version>${guava.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.janusgraph</groupId>\r
+            <artifactId>janusgraph-core</artifactId>\r
+            <version>${janusgraph.version}</version>\r
+            <scope>compile</scope>\r
+            <exclusions>\r
+                <exclusion>\r
+                    <groupId>org.json</groupId>\r
+                    <artifactId>json</artifactId>\r
+                </exclusion>\r
+                <exclusion>\r
+                    <artifactId>slf4j-log4j12</artifactId>\r
+                    <groupId>org.slf4j</groupId>\r
+                </exclusion>\r
+                <exclusion>\r
+                    <artifactId>commons-collections</artifactId>\r
+                    <groupId>commons-collections</groupId>\r
+                </exclusion>\r
+                <exclusion>\r
+                    <groupId>org.apache.thrift</groupId>\r
+                    <artifactId>libthrift</artifactId>\r
+                </exclusion>\r
+            </exclusions>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.janusgraph</groupId>\r
+            <artifactId>janusgraph-cassandra</artifactId>\r
+            <version>${janusgraph.version}</version>\r
+            <scope>compile</scope>\r
+            <exclusions>\r
+                <exclusion>\r
+                    <groupId>org.slf4j</groupId>\r
+                    <artifactId>slf4j-log4j12</artifactId>\r
+                </exclusion>\r
+                <exclusion>\r
+                    <groupId>io.netty</groupId>\r
+                    <artifactId>netty-all</artifactId>\r
+                </exclusion>\r
+            </exclusions>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.apache.commons</groupId>\r
+            <artifactId>commons-lang3</artifactId>\r
+            <version>${lang3.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>com.googlecode.json-simple</groupId>\r
+            <artifactId>json-simple</artifactId>\r
+            <version>${json-simple.version}</version>\r
+            <scope>compile</scope>\r
+\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.elasticsearch</groupId>\r
+            <artifactId>elasticsearch</artifactId>\r
+            <version>${elastic-search.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <!-- functional java -->\r
+        <dependency>\r
+            <groupId>org.functionaljava</groupId>\r
+            <artifactId>functionaljava</artifactId>\r
+            <version>${functionaljava.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <!-- Aspects -->\r
+        <dependency>\r
+            <groupId>com.jcabi</groupId>\r
+            <artifactId>jcabi-aspects</artifactId>\r
+            <version>${jcabi.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.aspectj</groupId>\r
+            <artifactId>aspectjrt</artifactId>\r
+            <version>${aspectjrt.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+\r
+        <!-- CAMBRIA CLIENT for U-EB -->\r
+        <dependency>\r
+            <groupId>com.att.nsa</groupId>\r
+            <artifactId>cambriaClient</artifactId>\r
+            <version>1.2.1-oss</version>\r
+            <scope>compile</scope>\r
+            <exclusions>\r
+                <exclusion>\r
+                    <groupId>com.att.nsa</groupId>\r
+                    <artifactId>saClientLibrary</artifactId>\r
+                </exclusion>\r
+            </exclusions>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.json</groupId>\r
+            <artifactId>json</artifactId>\r
+            <version>20131018</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <!-- CASSANDRA -->\r
+        <dependency>\r
+            <groupId>com.datastax.cassandra</groupId>\r
+            <artifactId>cassandra-driver-core</artifactId>\r
+            <version>${cassandra.driver.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+        <dependency>\r
+            <groupId>com.datastax.cassandra</groupId>\r
+            <artifactId>cassandra-driver-mapping</artifactId>\r
+            <version>${cassandra.driver.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+        <dependency>\r
+            <groupId>org.apache.thrift</groupId>\r
+            <artifactId>libthrift</artifactId>\r
+            <version>${libthrift.version}</version>\r
+        </dependency>\r
+        <!-- CASSANDRA END -->\r
+\r
+        <!-- Inserted for ECOMP Portal Integration -->\r
+        <dependency>\r
+            <groupId>org.onap.portal.sdk</groupId>\r
+            <artifactId>epsdk-fw</artifactId>\r
+            <version>${ecomp.version}</version>\r
+            <scope>compile</scope>\r
+            <exclusions>\r
+                <exclusion>\r
+                    <groupId>com.att.nsa</groupId>\r
+                    <artifactId>cambriaClient</artifactId>\r
+                </exclusion>\r
+                <exclusion>\r
+                    <artifactId>slf4j-log4j12</artifactId>\r
+                    <groupId>org.slf4j</groupId>\r
+                </exclusion>\r
+            </exclusions>\r
+        </dependency>\r
+\r
+        <!--Jetty Proxy-->\r
+        <dependency>\r
+            <groupId>org.eclipse.jetty</groupId>\r
+            <artifactId>jetty-proxy</artifactId>\r
+            <version>${jetty.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.eclipse.jetty</groupId>\r
+            <artifactId>jetty-servlets</artifactId>\r
+            <version>${jetty.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+        <!-- System metrics -->\r
+        <dependency>\r
+            <groupId>org.fusesource</groupId>\r
+            <artifactId>sigar</artifactId>\r
+            <version>${sigar.version}</version>\r
+            <scope>compile</scope>\r
+        </dependency>\r
+        <dependency>\r
+            <groupId>org.onap.dmaap.messagerouter.dmaapclient</groupId>\r
+            <artifactId>dmaapClient</artifactId>\r
+            <version>1.1.3</version>\r
+            <scope>compile</scope>\r
+            <exclusions>\r
+                <exclusion>\r
+                    <groupId>com.att.aft</groupId>\r
+                    <artifactId>dme2</artifactId>\r
+                </exclusion>\r
+            </exclusions>\r
+        </dependency>\r
+        <dependency>\r
+            <groupId>com.att.aft</groupId>\r
+            <artifactId>dme2</artifactId>\r
+            <version>3.1.200-oss</version>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>javax.jms</groupId>\r
+            <artifactId>jms</artifactId>\r
+            <version>1.1</version>\r
+            <scope>provided</scope>\r
+        </dependency>\r
+\r
+        <!-- TEST -->\r
+        <dependency>\r
+            <groupId>org.assertj</groupId>\r
+            <artifactId>assertj-core</artifactId>\r
+            <scope>test</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.glassfish.jersey.test-framework.providers</groupId>\r
+            <artifactId>jersey-test-framework-provider-bundle</artifactId>\r
+            <version>${jersey-bom.version}</version>\r
+            <type>pom</type>\r
+            <scope>test</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.glassfish.jersey.core</groupId>\r
+            <artifactId>jersey-client</artifactId>\r
+            <version>${jersey-bom.version}</version>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>com.github.tomakehurst</groupId>\r
+            <artifactId>wiremock-standalone</artifactId>\r
+            <scope>test</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.eclipse.jetty</groupId>\r
+            <artifactId>jetty-webapp</artifactId>\r
+            <version>${jetty.version}</version>\r
+            <scope>test</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>junit</groupId>\r
+            <artifactId>junit</artifactId>\r
+            <version>${junit.version}</version>\r
+            <scope>test</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.mockito</groupId>\r
+            <artifactId>mockito-core</artifactId>\r
+            <scope>test</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.springframework</groupId>\r
+            <artifactId>spring-test</artifactId>\r
+            <version>${spring.version}</version>\r
+            <scope>test</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.springframework</groupId>\r
+            <artifactId>spring-tx</artifactId>\r
+            <version>${spring.version}</version>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>io.cucumber</groupId>\r
+            <artifactId>cucumber-java</artifactId>\r
+            <scope>test</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>io.cucumber</groupId>\r
+            <artifactId>cucumber-junit</artifactId>\r
+            <scope>test</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.jmockit</groupId>\r
+            <artifactId>jmockit</artifactId>\r
+            <version>${jmockit.version}</version>\r
+            <scope>test</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>com.google.code.bean-matchers</groupId>\r
+            <artifactId>bean-matchers</artifactId>\r
+            <version>0.11</version>\r
+            <scope>test</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.hamcrest</groupId>\r
+            <artifactId>java-hamcrest</artifactId>\r
+            <version>${java-hamcrest.version}</version>\r
+            <scope>test</scope>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>org.codehaus.groovy</groupId>\r
+            <artifactId>groovy</artifactId>\r
+            <version>2.4.8</version>\r
+        </dependency>\r
+\r
+        <dependency>\r
+            <groupId>io.netty</groupId>\r
+            <artifactId>netty-handler</artifactId>\r
+        </dependency>\r
+        <dependency>\r
+            <groupId>org.onap.sdc.common</groupId>\r
+            <artifactId>onap-tosca-datatype</artifactId>\r
+            <version>${project.version}</version>\r
+        </dependency>\r
+        <dependency>\r
+            <groupId>org.apache.commons</groupId>\r
+            <artifactId>commons-collections4</artifactId>\r
+            <version>${commons.collections.version}</version>\r
+        </dependency>\r
+        <dependency>\r
+            <groupId>org.codehaus.jackson</groupId>\r
+            <artifactId>jackson-mapper-asl</artifactId>\r
+            <version>${jackson.mapper.version}</version>\r
+        </dependency>\r
+        <dependency>\r
+            <groupId>org.apache.commons</groupId>\r
+            <artifactId>commons-collections4</artifactId>\r
+            <version>${commons.collections.version}</version>\r
+        </dependency>\r
+    </dependencies>\r
+\r
+    <build>\r
+\r
+        <finalName>${project.artifactId}-${project.version}</finalName>\r
+\r
+        <plugins>\r
+            <plugin>\r
+                <groupId>org.apache.maven.plugins</groupId>\r
+                <artifactId>maven-war-plugin</artifactId>\r
+                <configuration>\r
+                    <packagingExcludes>WEB-INF\lib\slf4j-log4j*.jar,\r
+                        WEB-INF/classes/elasticsearch.yml,\r
+                        WEB-INF/classes/portal.properties\r
+                    </packagingExcludes>\r
+                    <archive>\r
+                        <manifestEntries>\r
+                            <SDC-Version>${project.version}</SDC-Version>\r
+                        </manifestEntries>\r
+                        <manifest>\r
+                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>\r
+                            <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>\r
+                        </manifest>\r
+                    </archive>\r
+\r
+                    <webResources>\r
+                        <resource>\r
+                            <directory>src/main/resources</directory>\r
+                            <directory>src/main/resources/swagger</directory>\r
+                        </resource>\r
+                    </webResources>\r
+                    <attachClasses>true</attachClasses>\r
+                </configuration>\r
+            </plugin>\r
+            <plugin>\r
+                <groupId>com.github.sylvainlaurent.maven</groupId>\r
+                <artifactId>yaml-json-validator-maven-plugin</artifactId>\r
+                <executions>\r
+                    <execution>\r
+                        <id>validate</id>\r
+                        <phase>validate</phase>\r
+                        <goals>\r
+                            <goal>validate</goal>\r
+                        </goals>\r
+                        <configuration>\r
+                            <validationSets>\r
+                                <validationSet>\r
+                                    <includes>\r
+                                        <include>src/main/resources/**/*.y*ml</include>\r
+                                        <include>src/test/resources/**/*.y*ml</include>\r
+                                    </includes>\r
+                                </validationSet>\r
+                                <validationSet>\r
+                                    <includes>\r
+                                        <include>src/main/resources/**/*.json</include>\r
+                                        <include>src/test/resources/**/*.json</include>\r
+                                    </includes>\r
+                                </validationSet>\r
+                            </validationSets>\r
+                        </configuration>\r
+                    </execution>\r
+                </executions>\r
+            </plugin>\r
+            <plugin>\r
+                <groupId>com.jcabi</groupId>\r
+                <artifactId>jcabi-maven-plugin</artifactId>\r
+                <version>${jcabi.maven.plugin.version}</version>\r
+                <executions>\r
+                    <execution>\r
+                        <goals>\r
+                            <goal>ajc</goal>\r
+                        </goals>\r
+                    </execution>\r
+                </executions>\r
+            </plugin>\r
+            <plugin>\r
+                <groupId>org.apache.maven.plugins</groupId>\r
+                <artifactId>maven-assembly-plugin</artifactId>\r
+                <executions>\r
+                    <execution>\r
+                        <id>normatives</id>\r
+                        <phase>package</phase>\r
+                        <goals>\r
+                            <goal>single</goal>\r
+                        </goals>\r
+                        <configuration>\r
+                            <finalName>normatives</finalName>\r
+                            <appendAssemblyId>false</appendAssemblyId>\r
+                            <descriptors>\r
+                                <descriptor>${project.basedir}/normatives.xml</descriptor>\r
+                            </descriptors>\r
+                        </configuration>\r
+                    </execution>\r
+                </executions>\r
+            </plugin>\r
+            <plugin>\r
+                <groupId>org.apache.maven.plugins</groupId>\r
+                <artifactId>maven-clean-plugin</artifactId>\r
+                <executions>\r
+                    <execution>\r
+                        <id>clean.sdc.backend.folder</id>\r
+                        <phase>clean</phase>\r
+                        <goals>\r
+                            <goal>clean</goal>\r
+                        </goals>\r
+                        <configuration>\r
+                            <filesets>\r
+                                <!-- static configuration files -->\r
+                                <fileset>\r
+                                    <directory>\r
+                                        ${project.parent.basedir}/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default\r
+                                    </directory>\r
+                                    <followSymlinks>false</followSymlinks>\r
+                                    <includes>\r
+                                        <include>error-configuration.yaml</include>\r
+                                        <include>ecomp-error-configuration.yaml</include>\r
+                                        <include>logback.xml</include>\r
+                                    </includes>\r
+                                </fileset>\r
+                                <!-- BE WAR's -->\r
+                                <fileset>\r
+                                    <directory>${project.parent.basedir}/catalog-be/sdc-backend</directory>\r
+                                    <followSymlinks>false</followSymlinks>\r
+                                    <includes>\r
+                                        <include>*.war</include>\r
+                                    </includes>\r
+                                </fileset>\r
+                                <fileset>\r
+                                    <directory>\r
+                                        ${project.basedir}/sdc-backend-init/chef-repo/cookbooks/sdc-normatives/files/default\r
+                                    </directory>\r
+                                    <followSymlinks>false</followSymlinks>\r
+                                    <includes>\r
+                                        <include>normatives.tar.gz</include>\r
+                                    </includes>\r
+                                </fileset>\r
+\r
+\r
+                            </filesets>\r
+                        </configuration>\r
+                    </execution>\r
+\r
+                    <execution>\r
+                        <id>clean-static-files</id>\r
+                        <phase>clean</phase>\r
+                        <goals>\r
+                            <goal>clean</goal>\r
+                        </goals>\r
+                        <configuration>\r
+                            <filesets>\r
+                                <!-- tosca files -->\r
+                                <fileset>\r
+                                    <directory>${project.parent.basedir}/asdctool/tosca</directory>\r
+                                    <followSymlinks>false</followSymlinks>\r
+                                </fileset>\r
+                            </filesets>\r
+                        </configuration>\r
+                    </execution>\r
+                </executions>\r
+            </plugin>\r
+            <plugin>\r
+                <groupId>org.apache.maven.plugins</groupId>\r
+                <artifactId>maven-resources-plugin</artifactId>\r
+                <executions>\r
+                    <execution>\r
+                        <id>copy-static-configuration-files</id>\r
+                        <phase>verify</phase>\r
+                        <goals>\r
+                            <goal>copy-resources</goal>\r
+                        </goals>\r
+                        <configuration>\r
+                            <outputDirectory>\r
+                                ${project.parent.basedir}/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default\r
+                            </outputDirectory>\r
+                            <resources>\r
+                                <resource>\r
+                                    <directory>${project.parent.basedir}/catalog-be/src/main/resources/config\r
+                                    </directory>\r
+                                    <includes>\r
+                                        <include>error-configuration.yaml</include>\r
+                                        <include>ecomp-error-configuration.yaml</include>\r
+                                        <include>logback.xml</include>\r
+                                    </includes>\r
+                                </resource>\r
+                            </resources>\r
+                        </configuration>\r
+                    </execution>\r
+                    <execution>\r
+                        <id>copy-tosca-folder</id>\r
+                        <!-- here the phase you need -->\r
+                        <phase>install</phase>\r
+                        <goals>\r
+                            <goal>copy-resources</goal>\r
+                        </goals>\r
+                        <configuration>\r
+                            <outputDirectory>${project.parent.basedir}/asdctool/tosca</outputDirectory>\r
+                            <resources>\r
+                                <resource>\r
+                                    <directory>${project.parent.basedir}/catalog-be/src/main/resources/import/tosca\r
+                                    </directory>\r
+                                    <filtering>true</filtering>\r
+                                </resource>\r
+                            </resources>\r
+                        </configuration>\r
+                    </execution>\r
+                </executions>\r
+            </plugin>\r
+            <plugin>\r
+                <groupId>com.github.kongchen</groupId>\r
+                <artifactId>swagger-maven-plugin</artifactId>\r
+                <version>3.1.0</version>\r
+                <configuration>\r
+                    <apiSources>\r
+                        <apiSource>\r
+                            <springmvc>false</springmvc>\r
+                            <schemes>http</schemes>\r
+                            <basePath>/sdc</basePath>\r
+                            <locations>io.swagger.jaxrs.json;org.openecomp.sdc.be.externalapi.servlet;org.openecomp.sdc.be.distribution.servlet;org.openecomp.normative.api</locations>\r
+                            <info>\r
+                                <title>External Rest API</title>\r
+                                <version>v1.0</version>\r
+                                <description>External Rest API Documentation</description>\r
+                                <termsOfService>\r
+                                    http://www.github.com/kongchen/swagger-maven-plugin\r
+                                </termsOfService>\r
+                            </info>\r
+                            <templatePath>${basedir}/templates/strapdown.html.hbs</templatePath>\r
+                            <outputPath>${basedir}/target/generated/swagger-ui/api.html</outputPath>\r
+                            <swaggerDirectory>${basedir}/target/generated/swagger-ui\r
+                            </swaggerDirectory>\r
+                            <swaggerApiReader>io.swagger.jaxrs.config.DefaultJaxrsConfig</swaggerApiReader>\r
+                        </apiSource>\r
+                    </apiSources>\r
+                </configuration>\r
+                <executions>\r
+                    <execution>\r
+                        <phase>compile</phase>\r
+                        <goals>\r
+                            <goal>generate</goal>\r
+                        </goals>\r
+                    </execution>\r
+                </executions>\r
+            </plugin>\r
+        </plugins>\r
+\r
+        <pluginManagement>\r
+            <plugins>\r
+                <!--This plugin's configuration is used to store Eclipse m2e settings\r
+                    only. It has no influence on the Maven build itself. -->\r
+                <plugin>\r
+                    <groupId>org.eclipse.m2e</groupId>\r
+                    <artifactId>lifecycle-mapping</artifactId>\r
+                    <version>1.0.0</version>\r
+                    <configuration>\r
+                        <lifecycleMappingMetadata>\r
+                            <pluginExecutions>\r
+                                <pluginExecution>\r
+                                    <pluginExecutionFilter>\r
+                                        <groupId>com.googlecode.maven-download-plugin</groupId>\r
+                                        <artifactId>download-maven-plugin</artifactId>\r
+                                        <versionRange>[1.2.1,)</versionRange>\r
+                                        <goals>\r
+                                            <goal>wget</goal>\r
+                                        </goals>\r
+                                    </pluginExecutionFilter>\r
+                                    <action>\r
+                                        <ignore></ignore>\r
+                                    </action>\r
+                                </pluginExecution>\r
+\r
+                                <pluginExecution>\r
+                                    <pluginExecutionFilter>\r
+                                        <groupId>com.jcabi</groupId>\r
+                                        <artifactId>jcabi-maven-plugin</artifactId>\r
+                                        <versionRange>[0.0,)</versionRange>\r
+                                        <goals>\r
+                                            <goal>ajc</goal>\r
+                                        </goals>\r
+                                    </pluginExecutionFilter>\r
+                                    <action>\r
+                                        <execute/>\r
+                                    </action>\r
+                                </pluginExecution>\r
+\r
+                            </pluginExecutions>\r
+                        </lifecycleMappingMetadata>\r
+                    </configuration>\r
+                </plugin>\r
+            </plugins>\r
+        </pluginManagement>\r
+        <!-- Swagger Plugins End -->\r
+    </build>\r
+\r
+    <profiles>\r
+        <profile>\r
+            <id>docker-staging</id>\r
+            <properties>\r
+                <docker.tag>${project.version}-STAGING-${maven.build.timestamp}</docker.tag>\r
+                <docker.latest.tag>${project.version}-STAGING-latest</docker.latest.tag>\r
+            </properties>\r
+        </profile>\r
+\r
+        <profile>\r
+            <id>docker</id>\r
+            <activation>\r
+                <activeByDefault>false</activeByDefault>\r
+            </activation>\r
+            <build>\r
+                <plugins>\r
+                    <plugin>\r
+                        <groupId>org.apache.maven.plugins</groupId>\r
+                        <artifactId>maven-resources-plugin</artifactId>\r
+                        <executions>\r
+                            <execution>\r
+                                <id>copy-resources-apidocs</id>\r
+                                <phase>verify</phase>\r
+                                <goals>\r
+                                    <goal>copy-resources</goal>\r
+                                </goals>\r
+                                <configuration>\r
+                                    <outputDirectory>${basedir}/sdc-backend</outputDirectory>\r
+                                    <resources>\r
+                                        <resource>\r
+                                            <directory>\r
+                                                ${project.parent.basedir}/openecomp-be/tools/swagger-ui/target/api-docs\r
+                                            </directory>\r
+                                            <includes>\r
+                                                <include>api-docs.war</include>\r
+                                            </includes>\r
+                                        </resource>\r
+                                    </resources>\r
+                                </configuration>\r
+                            </execution>\r
+\r
+                            <execution>\r
+                                <id>copy-resources-be</id>\r
+                                <phase>verify</phase>\r
+                                <goals>\r
+                                    <goal>copy-resources</goal>\r
+                                </goals>\r
+                                <configuration>\r
+                                    <outputDirectory>${basedir}/sdc-backend</outputDirectory>\r
+                                    <resources>\r
+                                        <resource>\r
+                                            <directory>${project.parent.basedir}/catalog-be/target</directory>\r
+                                            <includes>\r
+                                                <include>catalog-be-${project.version}.war</include>\r
+                                            </includes>\r
+                                        </resource>\r
+                                        <resource>\r
+                                            <directory>\r
+                                                ${project.parent.basedir}/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/target\r
+                                            </directory>\r
+                                            <includes>\r
+                                                <include>onboarding-be-${project.version}.war</include>\r
+                                            </includes>\r
+                                        </resource>\r
+                                    </resources>\r
+                                </configuration>\r
+                            </execution>\r
+                            <execution>\r
+                                <id>copy-normatives</id>\r
+                                <phase>verify</phase>\r
+                                <goals>\r
+                                    <goal>copy-resources</goal>\r
+                                </goals>\r
+                                <configuration>\r
+                                    <outputDirectory>\r
+                                        sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default\r
+                                    </outputDirectory>\r
+                                    <resources>\r
+                                        <resource>\r
+                                            <directory>${project.parent.basedir}/catalog-be/target</directory>\r
+                                            <includes>\r
+                                                <include>normatives.tar.gz</include>\r
+                                            </includes>\r
+                                        </resource>\r
+                                    </resources>\r
+                                </configuration>\r
+                            </execution>\r
+                        </executions>\r
+                    </plugin>\r
+                    <plugin>\r
+                        <groupId>io.fabric8</groupId>\r
+                        <artifactId>docker-maven-plugin</artifactId>\r
+                        <configuration>\r
+                            <apiVersion>1.23</apiVersion>\r
+                            <registry>nexus3.onap.org:10001</registry>\r
+                            <authConfig>\r
+                                <pull>\r
+                                    <username>docker</username>\r
+                                    <password>docker</password>\r
+                                </pull>\r
+                            </authConfig>\r
+                            <images>\r
+\r
+                                <!-- Build backend image -->\r
+                                <image>\r
+                                    <name>onap/sdc-backend</name>\r
+                                    <alias>sdc-backend</alias>\r
+                                    <build>\r
+                                        <cleanup>try</cleanup>\r
+                                        <dockerFileDir>${project.basedir}/sdc-backend</dockerFileDir>\r
+                                        <tags>\r
+                                            <tag>${docker.tag}</tag>\r
+                                            <tag>\r
+                                                ${parsedVersion.majorVersion}.${parsedVersion.minorVersion}-STAGING-latest\r
+                                            </tag>\r
+                                        </tags>\r
+                                    </build>\r
+                                </image>\r
+                                <!-- Build backend-init image -->\r
+                                <image>\r
+                                    <name>onap/sdc-backend-init</name>\r
+                                    <alias>sdc-backend-init</alias>\r
+                                    <build>\r
+                                        <cleanup>try</cleanup>\r
+                                        <dockerFileDir>${project.basedir}/sdc-backend-init</dockerFileDir>\r
+                                        <tags>\r
+                                            <tag>${docker.tag}</tag>\r
+                                            <tag>\r
+                                                ${parsedVersion.majorVersion}.${parsedVersion.minorVersion}-STAGING-latest\r
+                                            </tag>\r
+                                        </tags>\r
+                                    </build>\r
+                                </image>\r
+                            </images>\r
+                        </configuration>\r
+                        <executions>\r
+                            <execution>\r
+                                <id>clean-images</id>\r
+                                <phase>pre-clean</phase>\r
+                                <goals>\r
+                                    <goal>remove</goal>\r
+                                </goals>\r
+                                <configuration>\r
+                                    <removeAll>true</removeAll>\r
+                                    <image>onap/sdc-backend,onap/sdc-backend-init</image>\r
+                                </configuration>\r
+                            </execution>\r
+\r
+                            <execution>\r
+                                <id>generate-images</id>\r
+                                <phase>install</phase>\r
+                                <goals>\r
+                                    <goal>build</goal>\r
+                                </goals>\r
+                            </execution>\r
+\r
+                            <execution>\r
+                                <id>push-images</id>\r
+                                <phase>deploy</phase>\r
+                                <goals>\r
+                                    <goal>push</goal>\r
+                                </goals>\r
+                                <configuration>\r
+                                    <image>onap/sdc-backend,onap/sdc-backend-init</image>\r
+                                </configuration>\r
+                            </execution>\r
+                        </executions>\r
+                    </plugin>\r
+                </plugins>\r
+            </build>\r
+        </profile>\r
+    </profiles>\r
 </project>
\ No newline at end of file
index c7e145b..801f530 100644 (file)
@@ -1,61 +1,61 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.distribution;
-
-import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse;
-import org.openecomp.sdc.be.components.distribution.engine.SubscriberTypeEnum;
-import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData;
-
-public class AuditHandler {
-    ComponentsUtils componentsUtils;
-    String instanceID;
-    private RegistrationRequest registrationRequest;
-
-    public AuditHandler(ComponentsUtils componentsUtils, String instanceID, RegistrationRequest registrationRequest) {
-        super();
-        this.componentsUtils = componentsUtils;
-        this.instanceID = instanceID;
-        this.registrationRequest = registrationRequest;
-    }
-
-
-    public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole , DistributionTopicData distributionTopicData) {
-        componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), distributionTopicData, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode()));
-    }
-
-    public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole, DistributionTopicData distributionTopicData) {
-        componentsUtils.auditDistributionEngine(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), distributionTopicData, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode()));
-    }
-
-    public void auditRegisterRequest(CambriaErrorResponse registerResponse) {
-        componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()),
-                registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()));
-
-    }
-
-    public void auditUnRegisterRequest(CambriaErrorResponse registerResponse) {
-        componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()),
-                registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()));
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.distribution;\r
+\r
+import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse;\r
+import org.openecomp.sdc.be.components.distribution.engine.SubscriberTypeEnum;\r
+import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData;\r
+\r
+public class AuditHandler {\r
+    ComponentsUtils componentsUtils;\r
+    String instanceID;\r
+    private RegistrationRequest registrationRequest;\r
+\r
+    public AuditHandler(ComponentsUtils componentsUtils, String instanceID, RegistrationRequest registrationRequest) {\r
+        super();\r
+        this.componentsUtils = componentsUtils;\r
+        this.instanceID = instanceID;\r
+        this.registrationRequest = registrationRequest;\r
+    }\r
+\r
+\r
+    public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole , DistributionTopicData distributionTopicData) {\r
+        componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), distributionTopicData, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode()));\r
+    }\r
+\r
+    public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole, DistributionTopicData distributionTopicData) {\r
+        componentsUtils.auditDistributionEngine(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), distributionTopicData, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode()));\r
+    }\r
+\r
+    public void auditRegisterRequest(CambriaErrorResponse registerResponse) {\r
+        componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()),\r
+                registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()));\r
+\r
+    }\r
+\r
+    public void auditUnRegisterRequest(CambriaErrorResponse registerResponse) {\r
+        componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()),\r
+                registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()));\r
+    }\r
+}\r
index afad7d0..1589b93 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.distribution;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import fj.data.Either;
-import org.apache.http.HttpStatus;
-import org.openecomp.sdc.be.components.distribution.engine.*;
-import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.distribution.api.client.*;
-import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.Resource;
-import javax.ws.rs.core.Response;
-import java.util.List;
-
-import static org.apache.commons.lang.BooleanUtils.isTrue;
-import static org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask.buildTopicName;
-import static org.openecomp.sdc.be.config.ConfigurationManager.getConfigurationManager;
-
-@Component("distributionBusinessLogic")
-public class DistributionBusinessLogic {
-    public static final String REGISTER_IN_DISTRIBUTION_ENGINE = "registerInDistributionEngine";
-    public static final String UN_REGISTER_IN_DISTRIBUTION_ENGINE = "unregisterInDistributionEngine";
-    private Gson gson = new GsonBuilder().setPrettyPrinting().create();
-    private static final Logger log = Logger.getLogger(DistributionBusinessLogic.class);
-    @Resource
-    private IDistributionEngine distributionEngine;
-
-    private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance();
-    private CambriaHandler cambriaHandler;
-
-    private void initRequestEnvEndPoints(RegistrationRequest registrationRequest, DistributionEngineConfiguration config) {
-        if(registrationRequest.getDistEnvEndPoints() == null || registrationRequest.getDistEnvEndPoints().isEmpty()){
-            registrationRequest.setDistEnvEndPoints(config.getUebServers());
-        }
-    }
-    public Either<ServerListResponse, ResponseFormat> getUebServerList() {
-
-        DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager()
-                .getDistributionEngineConfiguration();
-
-        List<String> serverList = distributionEngineConfiguration.getUebServers();
-
-        if (serverList != null && !serverList.isEmpty()) {
-
-            ServerListResponse serverListResponse = new ServerListResponse();
-
-            serverListResponse.setUebServerList(serverList);
-
-            return Either.left(serverListResponse);
-        } else {
-            ResponseFormat errorResponseWrapper = getResponseFormatManager()
-                    .getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return Either.right(errorResponseWrapper);
-        }
-
-    }
-
-    public void handleRegistration(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest,
-            AuditHandler auditHandler) {
-        CambriaErrorResponse registerResponse = null;
-        try {
-            DistributionEngineConfiguration config = getConfigurationManager().getDistributionEngineConfiguration();
-            String statusTopicName = buildTopicName(config.getDistributionStatusTopicName(),
-                    registrationRequest.getDistrEnvName());
-            registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,
-                    SubscriberTypeEnum.PRODUCER, statusTopicName);
-
-            auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER,
-                    DistributionTopicData.newBuilder()
-                        .statusTopic(statusTopicName)
-                        .build());
-            boolean isRegisteredAsProducerOnStatusSuccess = responseWrapper.isEmpty();
-
-            // Story [347698] Distribution Client Get Indication from
-            // component whether to register as consumer and producer on
-            // status topic
-            boolean registeredAsConsumerOnStatus = false;
-            if (isRegisteredAsProducerOnStatusSuccess && isTrue(registrationRequest.getIsConsumerToSdcDistrStatusTopic())) {
-                registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,
-                        SubscriberTypeEnum.CONSUMER, statusTopicName);
-                auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER,
-                        DistributionTopicData.newBuilder()
-                                .statusTopic(statusTopicName)
-                                .build());
-                registeredAsConsumerOnStatus = responseWrapper.isEmpty();
-
-            }
-
-            if (responseWrapper.isEmpty()) {
-                String notificationTopicName = buildTopicName(config.getDistributionNotifTopicName(),
-                        registrationRequest.getDistrEnvName());
-                registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,
-                        SubscriberTypeEnum.CONSUMER, notificationTopicName);
-                auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER,
-                        DistributionTopicData.newBuilder()
-                            .notificationTopic(notificationTopicName)
-                            .build());
-            }
-            // Unregister Rollback
-            if (!responseWrapper.isEmpty()) {
-                if (isRegisteredAsProducerOnStatusSuccess) {
-                    CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest,
-                            SubscriberTypeEnum.PRODUCER, statusTopicName);
-                    auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER,
-                            DistributionTopicData.newBuilder()
-                                    .statusTopic(statusTopicName)
-                                    .build());
-                }
-                if (registeredAsConsumerOnStatus) {
-                    CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest,
-                            SubscriberTypeEnum.CONSUMER, statusTopicName);
-                    auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.CONSUMER,
-                            DistributionTopicData.newBuilder()
-                            .statusTopic(statusTopicName)
-                            .build());
-                }
-            }
-
-            if (responseWrapper.isEmpty()) {
-                TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest);
-                responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build());
-            }
-
-        } catch (Exception e) {
-            log.error("registration to topic failed", e);
-            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE,
-                    "registration of subscriber to topic");
-            Response errorResponse = buildErrorResponse(
-                    getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            responseWrapper.setInnerElement(errorResponse);
-        } finally {
-            auditHandler.auditRegisterRequest(registerResponse);
-        }
-    }
-
-    public void handleUnRegistration(Wrapper<Response> responseWrapper, RegistrationRequest unRegistrationRequest,
-            AuditHandler auditHandler) {
-        Wrapper<CambriaErrorResponse> cambriaResponseWrapper = new Wrapper<>();
-        try {
-            String statusTopicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName());
-            CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic(
-                    unRegistrationRequest, SubscriberTypeEnum.PRODUCER, statusTopicName);
-            auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER,
-                    DistributionTopicData.newBuilder()
-                            .statusTopic(statusTopicName)
-                            .build());
-            updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse);
-
-            String notificationTopicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName());
-            CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic(
-                    unRegistrationRequest, SubscriberTypeEnum.CONSUMER, notificationTopicName);
-            auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER,
-                    DistributionTopicData.newBuilder()
-                            .notificationTopic(notificationTopicName)
-                            .build());
-            updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse);
-
-            // Success unregister both topics
-            TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse(
-                    getNotificationTopicName(unRegistrationRequest.getDistrEnvName()),
-                    getStatusTopicName(unRegistrationRequest.getDistrEnvName()),
-                    unregisterClientConsumerTopicResponse.getOperationStatus(),
-                    unregisterClientProducerTopicResponse.getOperationStatus());
-
-            if (cambriaResponseWrapper.getInnerElement().getOperationStatus() == CambriaOperationStatus.OK) {
-                responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(unregisterResponse).build());
-            } else {
-                BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE,
-                        "unregistration failed");
-                responseWrapper.setInnerElement(
-                        Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build());
-            }
-        } catch (Exception e) {
-            log.error("unregistered to topic failed", e);
-            Response errorResponse = buildErrorResponse(
-                    getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            responseWrapper.setInnerElement(errorResponse);
-
-        } finally {
-            auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement());
-        }
-    }
-
-    private void updateResponseWrapper(Wrapper<CambriaErrorResponse> cambriaResponseWrapper,
-            CambriaErrorResponse currentResponse) {
-        if (cambriaResponseWrapper.isEmpty()) {
-            cambriaResponseWrapper.setInnerElement(currentResponse);
-        } else if (currentResponse.getOperationStatus() != CambriaOperationStatus.OK) {
-            cambriaResponseWrapper.setInnerElement(currentResponse);
-
-        }
-
-    }
-
-    public static String getNotificationTopicName(String envName) {
-        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
-                .getDistributionEngineConfiguration();
-        return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName);
-
-    }
-
-    public static String getStatusTopicName(String envName) {
-        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
-                .getDistributionEngineConfiguration();
-        return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName);
-
-    }
-
-    protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest,
-            SubscriberTypeEnum subscriberType, String topicName) {
-        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
-                .getDistributionEngineConfiguration();
-        initRequestEnvEndPoints(unRegistrationRequest, config);
-
-        log.debug("unregistering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, unRegistrationRequest.getDistEnvEndPoints());
-        return getCambriaHandler().unRegisterFromTopic(unRegistrationRequest.getDistEnvEndPoints(), config.getUebPublicKey(),
-                config.getUebSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType, topicName);
-    }
-
-    private TopicRegistrationResponse buildTopicResponse(RegistrationRequest registrationRequest) {
-        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
-                .getDistributionEngineConfiguration();
-        String statusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(),
-                registrationRequest.getDistrEnvName());
-        String notificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(),
-                registrationRequest.getDistrEnvName());
-
-        TopicRegistrationResponse topicResponse = new TopicRegistrationResponse();
-        topicResponse.setDistrNotificationTopicName(notificationTopicName);
-        topicResponse.setDistrStatusTopicName(statusTopicName);
-        return topicResponse;
-    }
-
-    protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper<Response> responseWrapper,
-            RegistrationRequest registrationRequest, SubscriberTypeEnum subscriberType, String topicName) {
-        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
-                .getDistributionEngineConfiguration();
-        initRequestEnvEndPoints(registrationRequest, config);
-        String errorMsg;
-
-        // Register for notifications as consumer
-        if (subscriberType == SubscriberTypeEnum.CONSUMER) {
-            errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed";
-        }
-        // Register for status as producer
-        else {
-            errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed";
-        }
-        log.debug("registering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, registrationRequest.getDistEnvEndPoints());
-        CambriaErrorResponse registerToTopic = getCambriaHandler().registerToTopic(registrationRequest.getDistEnvEndPoints(),
-                config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
-                subscriberType, topicName);
-
-        if (registerToTopic.getOperationStatus() != CambriaOperationStatus.OK) {
-            Response failedRegistrationResponse = buildErrorResponse(
-                    getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE,
-                    errorMsg);
-            responseWrapper.setInnerElement(failedRegistrationResponse);
-        }
-        return registerToTopic;
-    }
-
-    protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
-        return Response.status(requestErrorWrapper.getStatus())
-                .entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
-    }
-
-    public ResponseFormatManager getResponseFormatManager() {
-        return responseFormatManager;
-    }
-
-    public IDistributionEngine getDistributionEngine() {
-        return distributionEngine;
-    }
-
-    public CambriaHandler getCambriaHandler() {
-        if (cambriaHandler == null) {
-            cambriaHandler = new CambriaHandler();
-        }
-        return cambriaHandler;
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.distribution;\r
+\r
+import com.google.gson.Gson;\r
+import com.google.gson.GsonBuilder;\r
+import fj.data.Either;\r
+import org.apache.http.HttpStatus;\r
+import org.openecomp.sdc.be.components.distribution.engine.*;\r
+import org.openecomp.sdc.be.components.impl.ResponseFormatManager;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.config.ConfigurationManager;\r
+import org.openecomp.sdc.be.config.DistributionEngineConfiguration;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.distribution.api.client.*;\r
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import org.springframework.stereotype.Component;\r
+\r
+import javax.annotation.Resource;\r
+import javax.ws.rs.core.Response;\r
+import java.util.List;\r
+\r
+import static org.apache.commons.lang.BooleanUtils.isTrue;\r
+import static org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask.buildTopicName;\r
+import static org.openecomp.sdc.be.config.ConfigurationManager.getConfigurationManager;\r
+\r
+@Component("distributionBusinessLogic")\r
+public class DistributionBusinessLogic {\r
+    public static final String REGISTER_IN_DISTRIBUTION_ENGINE = "registerInDistributionEngine";\r
+    public static final String UN_REGISTER_IN_DISTRIBUTION_ENGINE = "unregisterInDistributionEngine";\r
+    private Gson gson = new GsonBuilder().setPrettyPrinting().create();\r
+    private static final Logger log = Logger.getLogger(DistributionBusinessLogic.class);\r
+    @Resource\r
+    private IDistributionEngine distributionEngine;\r
+\r
+    private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance();\r
+    private CambriaHandler cambriaHandler;\r
+\r
+    private void initRequestEnvEndPoints(RegistrationRequest registrationRequest, DistributionEngineConfiguration config) {\r
+        if(registrationRequest.getDistEnvEndPoints() == null || registrationRequest.getDistEnvEndPoints().isEmpty()){\r
+            registrationRequest.setDistEnvEndPoints(config.getUebServers());\r
+        }\r
+    }\r
+    public Either<ServerListResponse, ResponseFormat> getUebServerList() {\r
+\r
+        DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager()\r
+                .getDistributionEngineConfiguration();\r
+\r
+        List<String> serverList = distributionEngineConfiguration.getUebServers();\r
+\r
+        if (serverList != null && !serverList.isEmpty()) {\r
+\r
+            ServerListResponse serverListResponse = new ServerListResponse();\r
+\r
+            serverListResponse.setUebServerList(serverList);\r
+\r
+            return Either.left(serverListResponse);\r
+        } else {\r
+            ResponseFormat errorResponseWrapper = getResponseFormatManager()\r
+                    .getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return Either.right(errorResponseWrapper);\r
+        }\r
+\r
+    }\r
+\r
+    public void handleRegistration(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest,\r
+            AuditHandler auditHandler) {\r
+        CambriaErrorResponse registerResponse = null;\r
+        try {\r
+            DistributionEngineConfiguration config = getConfigurationManager().getDistributionEngineConfiguration();\r
+            String statusTopicName = buildTopicName(config.getDistributionStatusTopicName(),\r
+                    registrationRequest.getDistrEnvName());\r
+            registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,\r
+                    SubscriberTypeEnum.PRODUCER, statusTopicName);\r
+\r
+            auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER,\r
+                    DistributionTopicData.newBuilder()\r
+                        .statusTopic(statusTopicName)\r
+                        .build());\r
+            boolean isRegisteredAsProducerOnStatusSuccess = responseWrapper.isEmpty();\r
+\r
+            // Story [347698] Distribution Client Get Indication from\r
+            // component whether to register as consumer and producer on\r
+            // status topic\r
+            boolean registeredAsConsumerOnStatus = false;\r
+            if (isRegisteredAsProducerOnStatusSuccess && isTrue(registrationRequest.getIsConsumerToSdcDistrStatusTopic())) {\r
+                registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,\r
+                        SubscriberTypeEnum.CONSUMER, statusTopicName);\r
+                auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER,\r
+                        DistributionTopicData.newBuilder()\r
+                                .statusTopic(statusTopicName)\r
+                                .build());\r
+                registeredAsConsumerOnStatus = responseWrapper.isEmpty();\r
+\r
+            }\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                String notificationTopicName = buildTopicName(config.getDistributionNotifTopicName(),\r
+                        registrationRequest.getDistrEnvName());\r
+                registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,\r
+                        SubscriberTypeEnum.CONSUMER, notificationTopicName);\r
+                auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER,\r
+                        DistributionTopicData.newBuilder()\r
+                            .notificationTopic(notificationTopicName)\r
+                            .build());\r
+            }\r
+            // Unregister Rollback\r
+            if (!responseWrapper.isEmpty()) {\r
+                if (isRegisteredAsProducerOnStatusSuccess) {\r
+                    CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest,\r
+                            SubscriberTypeEnum.PRODUCER, statusTopicName);\r
+                    auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER,\r
+                            DistributionTopicData.newBuilder()\r
+                                    .statusTopic(statusTopicName)\r
+                                    .build());\r
+                }\r
+                if (registeredAsConsumerOnStatus) {\r
+                    CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest,\r
+                            SubscriberTypeEnum.CONSUMER, statusTopicName);\r
+                    auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.CONSUMER,\r
+                            DistributionTopicData.newBuilder()\r
+                            .statusTopic(statusTopicName)\r
+                            .build());\r
+                }\r
+            }\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest);\r
+                responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build());\r
+            }\r
+\r
+        } catch (Exception e) {\r
+            log.error("registration to topic failed", e);\r
+            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE,\r
+                    "registration of subscriber to topic");\r
+            Response errorResponse = buildErrorResponse(\r
+                    getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            responseWrapper.setInnerElement(errorResponse);\r
+        } finally {\r
+            auditHandler.auditRegisterRequest(registerResponse);\r
+        }\r
+    }\r
+\r
+    public void handleUnRegistration(Wrapper<Response> responseWrapper, RegistrationRequest unRegistrationRequest,\r
+            AuditHandler auditHandler) {\r
+        Wrapper<CambriaErrorResponse> cambriaResponseWrapper = new Wrapper<>();\r
+        try {\r
+            String statusTopicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName());\r
+            CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic(\r
+                    unRegistrationRequest, SubscriberTypeEnum.PRODUCER, statusTopicName);\r
+            auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER,\r
+                    DistributionTopicData.newBuilder()\r
+                            .statusTopic(statusTopicName)\r
+                            .build());\r
+            updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse);\r
+\r
+            String notificationTopicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName());\r
+            CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic(\r
+                    unRegistrationRequest, SubscriberTypeEnum.CONSUMER, notificationTopicName);\r
+            auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER,\r
+                    DistributionTopicData.newBuilder()\r
+                            .notificationTopic(notificationTopicName)\r
+                            .build());\r
+            updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse);\r
+\r
+            // Success unregister both topics\r
+            TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse(\r
+                    getNotificationTopicName(unRegistrationRequest.getDistrEnvName()),\r
+                    getStatusTopicName(unRegistrationRequest.getDistrEnvName()),\r
+                    unregisterClientConsumerTopicResponse.getOperationStatus(),\r
+                    unregisterClientProducerTopicResponse.getOperationStatus());\r
+\r
+            if (cambriaResponseWrapper.getInnerElement().getOperationStatus() == CambriaOperationStatus.OK) {\r
+                responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(unregisterResponse).build());\r
+            } else {\r
+                BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE,\r
+                        "unregistration failed");\r
+                responseWrapper.setInnerElement(\r
+                        Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build());\r
+            }\r
+        } catch (Exception e) {\r
+            log.error("unregistered to topic failed", e);\r
+            Response errorResponse = buildErrorResponse(\r
+                    getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            responseWrapper.setInnerElement(errorResponse);\r
+\r
+        } finally {\r
+            auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement());\r
+        }\r
+    }\r
+\r
+    private void updateResponseWrapper(Wrapper<CambriaErrorResponse> cambriaResponseWrapper,\r
+            CambriaErrorResponse currentResponse) {\r
+        if (cambriaResponseWrapper.isEmpty()) {\r
+            cambriaResponseWrapper.setInnerElement(currentResponse);\r
+        } else if (currentResponse.getOperationStatus() != CambriaOperationStatus.OK) {\r
+            cambriaResponseWrapper.setInnerElement(currentResponse);\r
+\r
+        }\r
+\r
+    }\r
+\r
+    public static String getNotificationTopicName(String envName) {\r
+        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()\r
+                .getDistributionEngineConfiguration();\r
+        return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName);\r
+\r
+    }\r
+\r
+    public static String getStatusTopicName(String envName) {\r
+        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()\r
+                .getDistributionEngineConfiguration();\r
+        return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName);\r
+\r
+    }\r
+\r
+    protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest,\r
+            SubscriberTypeEnum subscriberType, String topicName) {\r
+        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()\r
+                .getDistributionEngineConfiguration();\r
+        initRequestEnvEndPoints(unRegistrationRequest, config);\r
+\r
+        log.debug("unregistering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, unRegistrationRequest.getDistEnvEndPoints());\r
+        return getCambriaHandler().unRegisterFromTopic(unRegistrationRequest.getDistEnvEndPoints(), config.getUebPublicKey(),\r
+                config.getUebSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType, topicName);\r
+    }\r
+\r
+    private TopicRegistrationResponse buildTopicResponse(RegistrationRequest registrationRequest) {\r
+        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()\r
+                .getDistributionEngineConfiguration();\r
+        String statusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(),\r
+                registrationRequest.getDistrEnvName());\r
+        String notificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(),\r
+                registrationRequest.getDistrEnvName());\r
+\r
+        TopicRegistrationResponse topicResponse = new TopicRegistrationResponse();\r
+        topicResponse.setDistrNotificationTopicName(notificationTopicName);\r
+        topicResponse.setDistrStatusTopicName(statusTopicName);\r
+        return topicResponse;\r
+    }\r
+\r
+    protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper<Response> responseWrapper,\r
+            RegistrationRequest registrationRequest, SubscriberTypeEnum subscriberType, String topicName) {\r
+        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()\r
+                .getDistributionEngineConfiguration();\r
+        initRequestEnvEndPoints(registrationRequest, config);\r
+        String errorMsg;\r
+\r
+        // Register for notifications as consumer\r
+        if (subscriberType == SubscriberTypeEnum.CONSUMER) {\r
+            errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed";\r
+        }\r
+        // Register for status as producer\r
+        else {\r
+            errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed";\r
+        }\r
+        log.debug("registering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, registrationRequest.getDistEnvEndPoints());\r
+        CambriaErrorResponse registerToTopic = getCambriaHandler().registerToTopic(registrationRequest.getDistEnvEndPoints(),\r
+                config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),\r
+                subscriberType, topicName);\r
+\r
+        if (registerToTopic.getOperationStatus() != CambriaOperationStatus.OK) {\r
+            Response failedRegistrationResponse = buildErrorResponse(\r
+                    getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE,\r
+                    errorMsg);\r
+            responseWrapper.setInnerElement(failedRegistrationResponse);\r
+        }\r
+        return registerToTopic;\r
+    }\r
+\r
+    protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {\r
+        return Response.status(requestErrorWrapper.getStatus())\r
+                .entity(gson.toJson(requestErrorWrapper.getRequestError())).build();\r
+    }\r
+\r
+    public ResponseFormatManager getResponseFormatManager() {\r
+        return responseFormatManager;\r
+    }\r
+\r
+    public IDistributionEngine getDistributionEngine() {\r
+        return distributionEngine;\r
+    }\r
+\r
+    public CambriaHandler getCambriaHandler() {\r
+        if (cambriaHandler == null) {\r
+            cambriaHandler = new CambriaHandler();\r
+        }\r
+        return cambriaHandler;\r
+    }\r
+\r
+}\r
index 0da23ed..bd644e3 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.distribution.servlet;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
-import org.openecomp.sdc.be.servlets.BeGenericServlet;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Map;
-import org.springframework.beans.factory.annotation.Autowired;
-
-/**
- * This Servlet serves external users to download artifacts.
- * 
- * @author tgitelman
- *
- */
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Distribution Catalog Servlet", description = "This Servlet serves external users to download artifacts.")
-@Singleton
-public class DistributionCatalogServlet extends BeGenericServlet {
-
-    private static final String DOWNLOAD_ARTIFACT_FAILED_WITH_EXCEPTION = "download artifact failed with exception";
-       private static final String MISSING_X_ECOMP_INSTANCE_ID_HEADER = "Missing X-ECOMP-InstanceID header";
-       private static final Logger log = Logger.getLogger(DistributionCatalogServlet.class);
-       private final ArtifactsBusinessLogic artifactsBusinessLogic;
-
-         @Autowired
-    public DistributionCatalogServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        ArtifactsBusinessLogic artifactsBusinessLogic) {
-        super(userBusinessLogic, componentsUtils);
-        this.artifactsBusinessLogic = artifactsBusinessLogic;
-    }
-
-    @Context
-    private HttpServletRequest request;
-
-    // *******************************************************
-    // Download (GET) artifacts
-    // **********************************************************/
-    /**
-     *
-     * @param requestId
-     * @param instanceIdHeader
-     * @param accept
-     * @param authorization
-     * @param serviceName
-     * @param serviceVersion
-     * @param artifactName
-     * @return
-     */
-    @GET
-    @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_OCTET_STREAM)
-    @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"),
-            @ApiResponse(code = 404, message = "Specified Service Version is  not  found - SVC4504"),
-            @ApiResponse(code = 404, message = "Specified artifact is  not found - SVC4505"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
-    public Response downloadServiceArtifact(
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @PathParam("serviceName") final String serviceName,
-            @PathParam("serviceVersion") final String serviceVersion,
-            @PathParam("artifactName") final String artifactName) {
-
-        Response response = null;
-        String requestURI = request.getRequestURI();
-        if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
-            log.debug(MISSING_X_ECOMP_INSTANCE_ID_HEADER);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
-            return buildErrorResponse(responseFormat);
-        }
-
-        try {
-            Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsBusinessLogic
-                .downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName);
-            if (downloadRsrcArtifactEither.isRight()) {
-                ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();
-                getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
-                response = buildErrorResponse(responseFormat);
-            } else {
-                byte[] value = downloadRsrcArtifactEither.left().value();
-                InputStream is = new ByteArrayInputStream(value);
-
-                Map<String, String> headers = new HashMap<>();
-                headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
-                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
-                response = buildOkResponse(responseFormat, is, headers);
-            }
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API");
-            log.debug(DOWNLOAD_ARTIFACT_FAILED_WITH_EXCEPTION, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    /**
-     *
-     * @param requestId
-     * @param instanceIdHeader
-     * @param accept
-     * @param authorization
-     * @param serviceName
-     * @param serviceVersion
-     * @param resourceName
-     * @param resourceVersion
-     * @param artifactName
-     * @return
-     */
-    @GET
-    @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_OCTET_STREAM)
-    @ApiOperation(value = "Download resource artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"),
-            @ApiResponse(code = 404, message = "Specified Resource Instance  is not found - SVC4526"),
-            @ApiResponse(code = 404, message = "Specified Service Version is  not  found - SVC4504"),
-            @ApiResponse(code = 404, message = "Specified artifact is  not found - SVC4505"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
-    public Response downloadResourceArtifact(
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @PathParam("serviceName") final String serviceName,
-            @PathParam("serviceVersion") final String serviceVersion,
-            @PathParam("resourceName") final String resourceName,
-            @PathParam("resourceVersion") final String resourceVersion,
-            @PathParam("artifactName") final String artifactName) {
-
-        Response response = null;
-        String requestURI = request.getRequestURI();
-
-        if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
-            log.debug(MISSING_X_ECOMP_INSTANCE_ID_HEADER);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
-            return buildErrorResponse(responseFormat);
-        }
-
-        try {
-            Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsBusinessLogic
-                .downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName);
-            if (downloadRsrcArtifactEither.isRight()) {
-                ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();
-                getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
-                response = buildErrorResponse(responseFormat);
-            } else {
-                byte[] value = downloadRsrcArtifactEither.left().value();
-                // Returning 64-encoded as it was received during upload
-                InputStream is = new ByteArrayInputStream(value);
-                Map<String, String> headers = new HashMap<>();
-                headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
-                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
-                response = buildOkResponse(responseFormat, is, headers);
-            }
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API");
-            log.debug(DOWNLOAD_ARTIFACT_FAILED_WITH_EXCEPTION, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    /**
-     *
-     * @param requestId
-     * @param instanceIdHeader
-     * @param accept
-     * @param authorization
-     * @param serviceName
-     * @param serviceVersion
-     * @param resourceInstanceName
-     * @param artifactName
-     * @return
-     */
-    @GET
-    @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_OCTET_STREAM)
-    @ApiOperation(value = "Download resource instance artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"),
-            @ApiResponse(code = 404, message = "Specified Resource Instance  is not found - SVC4526"),
-            @ApiResponse(code = 404, message = "Specified Service Version is  not  found - SVC4504"),
-            @ApiResponse(code = 404, message = "Specified artifact is  not found - SVC4505"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
-    public Response downloadResourceInstanceArtifactByName(
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @PathParam("serviceName") final String serviceName,
-            @PathParam("serviceVersion") final String serviceVersion,
-            @PathParam("resourceInstanceName") final String resourceInstanceName,
-            @PathParam("artifactName") final String artifactName) {
-
-        Response response = null;
-        String requestURI = request.getRequestURI();
-
-        if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
-            log.debug(MISSING_X_ECOMP_INSTANCE_ID_HEADER);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
-            return buildErrorResponse(responseFormat);
-        }
-
-        try {
-            Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsBusinessLogic
-                .downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName);
-            if (downloadRsrcArtifactEither.isRight()) {
-                ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();
-                getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
-                response = buildErrorResponse(responseFormat);
-            } else {
-                byte[] value = downloadRsrcArtifactEither.left().value();
-                // Returning 64-encoded as it was received during upload
-                InputStream is = new ByteArrayInputStream(value);
-                Map<String, String> headers = new HashMap<>();
-                headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
-                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
-                response = buildOkResponse(responseFormat, is, headers);
-            }
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API");
-            log.debug(DOWNLOAD_ARTIFACT_FAILED_WITH_EXCEPTION, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.distribution.servlet;\r
+\r
+import java.io.ByteArrayInputStream;\r
+import java.io.InputStream;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;\r
+import org.openecomp.sdc.be.servlets.BeGenericServlet;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import org.springframework.beans.factory.annotation.Autowired;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+/**\r
+ * This Servlet serves external users to download artifacts.\r
+ * \r
+ * @author tgitelman\r
+ *\r
+ */\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info =  @Info(title = "Distribution Catalog Servlet",description = "This Servlet serves external users to download artifacts."))\r
+@Singleton\r
+public class DistributionCatalogServlet extends BeGenericServlet {\r
+\r
+    private static final String DOWNLOAD_ARTIFACT_FAILED_WITH_EXCEPTION = "download artifact failed with exception";\r
+       private static final String MISSING_X_ECOMP_INSTANCE_ID_HEADER = "Missing X-ECOMP-InstanceID header";\r
+       private static final Logger log = Logger.getLogger(DistributionCatalogServlet.class);\r
+       private final ArtifactsBusinessLogic artifactsBusinessLogic;\r
+\r
+         @Autowired\r
+    public DistributionCatalogServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils,\r
+        ArtifactsBusinessLogic artifactsBusinessLogic) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.artifactsBusinessLogic = artifactsBusinessLogic;\r
+    }\r
+\r
+    @Context\r
+    private HttpServletRequest request;\r
+\r
+    // *******************************************************\r
+    // Download (GET) artifacts\r
+    // **********************************************************/\r
+    /**\r
+     *\r
+     * @param requestId\r
+     * @param instanceIdHeader\r
+     * @param accept\r
+     * @param authorization\r
+     * @param serviceName\r
+     * @param serviceVersion\r
+     * @param artifactName\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_OCTET_STREAM)\r
+    @Operation(description = "Download service artifact", method = "GET", summary = "Returns downloaded artifact",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.",\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"),\r
+            @ApiResponse(responseCode = "404", description = "Specified Service Version is  not  found - SVC4504"),\r
+            @ApiResponse(responseCode = "404", description = "Specified artifact is  not found - SVC4505"),\r
+            @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})\r
+    public Response downloadServiceArtifact(\r
+            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @PathParam("serviceName") final String serviceName,\r
+            @PathParam("serviceVersion") final String serviceVersion,\r
+            @PathParam("artifactName") final String artifactName) {\r
+\r
+        Response response = null;\r
+        String requestURI = request.getRequestURI();\r
+        if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {\r
+            log.debug(MISSING_X_ECOMP_INSTANCE_ID_HEADER);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+        try {\r
+            Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsBusinessLogic\r
+                .downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName);\r
+            if (downloadRsrcArtifactEither.isRight()) {\r
+                ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();\r
+                getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));\r
+                response = buildErrorResponse(responseFormat);\r
+            } else {\r
+                byte[] value = downloadRsrcArtifactEither.left().value();\r
+                InputStream is = new ByteArrayInputStream(value);\r
+\r
+                Map<String, String> headers = new HashMap<>();\r
+                headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));\r
+                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));\r
+                response = buildOkResponse(responseFormat, is, headers);\r
+            }\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API");\r
+            log.debug(DOWNLOAD_ARTIFACT_FAILED_WITH_EXCEPTION, e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param requestId\r
+     * @param instanceIdHeader\r
+     * @param accept\r
+     * @param authorization\r
+     * @param serviceName\r
+     * @param serviceVersion\r
+     * @param resourceName\r
+     * @param resourceVersion\r
+     * @param artifactName\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_OCTET_STREAM)\r
+    @Operation(description = "Download resource artifact", method  = "GET", summary = "Returns downloaded artifact", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.", \r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"),\r
+            @ApiResponse(responseCode = "404", description = "Specified Resource Instance  is not found - SVC4526"),\r
+            @ApiResponse(responseCode = "404", description = "Specified Service Version is  not  found - SVC4504"),\r
+            @ApiResponse(responseCode = "404", description = "Specified artifact is  not found - SVC4505"),\r
+            @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})\r
+    public Response downloadResourceArtifact(\r
+            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @PathParam("serviceName") final String serviceName,\r
+            @PathParam("serviceVersion") final String serviceVersion,\r
+            @PathParam("resourceName") final String resourceName,\r
+            @PathParam("resourceVersion") final String resourceVersion,\r
+            @PathParam("artifactName") final String artifactName) {\r
+\r
+        Response response = null;\r
+        String requestURI = request.getRequestURI();\r
+\r
+        if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {\r
+            log.debug(MISSING_X_ECOMP_INSTANCE_ID_HEADER);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+        try {\r
+            Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsBusinessLogic\r
+                .downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName);\r
+            if (downloadRsrcArtifactEither.isRight()) {\r
+                ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();\r
+                getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));\r
+                response = buildErrorResponse(responseFormat);\r
+            } else {\r
+                byte[] value = downloadRsrcArtifactEither.left().value();\r
+                // Returning 64-encoded as it was received during upload\r
+                InputStream is = new ByteArrayInputStream(value);\r
+                Map<String, String> headers = new HashMap<>();\r
+                headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));\r
+                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));\r
+                response = buildOkResponse(responseFormat, is, headers);\r
+            }\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API");\r
+            log.debug(DOWNLOAD_ARTIFACT_FAILED_WITH_EXCEPTION, e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param requestId\r
+     * @param instanceIdHeader\r
+     * @param accept\r
+     * @param authorization\r
+     * @param serviceName\r
+     * @param serviceVersion\r
+     * @param resourceInstanceName\r
+     * @param artifactName\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_OCTET_STREAM)\r
+    @Operation(description = "Download resource instance artifact", method = "GET", summary = "Returns downloaded artifact", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.", \r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"),\r
+            @ApiResponse(responseCode = "404", description = "Specified Resource Instance  is not found - SVC4526"),\r
+            @ApiResponse(responseCode = "404", description = "Specified Service Version is  not  found - SVC4504"),\r
+            @ApiResponse(responseCode = "404", description = "Specified artifact is  not found - SVC4505"),\r
+            @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})\r
+    public Response downloadResourceInstanceArtifactByName(\r
+            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @PathParam("serviceName") final String serviceName,\r
+            @PathParam("serviceVersion") final String serviceVersion,\r
+            @PathParam("resourceInstanceName") final String resourceInstanceName,\r
+            @PathParam("artifactName") final String artifactName) {\r
+\r
+        Response response = null;\r
+        String requestURI = request.getRequestURI();\r
+\r
+        if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {\r
+            log.debug(MISSING_X_ECOMP_INSTANCE_ID_HEADER);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+        try {\r
+            Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsBusinessLogic\r
+                .downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName);\r
+            if (downloadRsrcArtifactEither.isRight()) {\r
+                ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();\r
+                getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));\r
+                response = buildErrorResponse(responseFormat);\r
+            } else {\r
+                byte[] value = downloadRsrcArtifactEither.left().value();\r
+                // Returning 64-encoded as it was received during upload\r
+                InputStream is = new ByteArrayInputStream(value);\r
+                Map<String, String> headers = new HashMap<>();\r
+                headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));\r
+                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));\r
+                response = buildOkResponse(responseFormat, is, headers);\r
+            }\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API");\r
+            log.debug(DOWNLOAD_ARTIFACT_FAILED_WITH_EXCEPTION, e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+}\r
index c660b3b..70556d6 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.distribution.servlet;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.distribution.AuditHandler;
-import org.openecomp.sdc.be.distribution.DistributionBusinessLogic;
-import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest;
-import org.openecomp.sdc.be.distribution.api.client.ServerListResponse;
-import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse;
-import org.openecomp.sdc.be.distribution.api.client.TopicUnregistrationResponse;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.servlets.BeGenericServlet;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.util.HttpUtil;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-/**
- * This Servlet serves external users for distribution purposes.
- * 
- * @author tgitelman
- *
- */
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1")
-@Api(value = "Distribution Servlet", description = "This Servlet serves external users for distribution purposes.")
-@Singleton
-public class DistributionServlet extends BeGenericServlet {
-
-    private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
-       private static final Logger log = Logger.getLogger(DistributionServlet.class);
-    private final DistributionBusinessLogic distributionLogic;
-    @Context
-    private HttpServletRequest request;
-
-    @Inject
-    public DistributionServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils, DistributionBusinessLogic distributionLogic) {
-        super(userBusinessLogic, componentsUtils);
-        this.distributionLogic = distributionLogic;
-    }
-
-    /**
-     *
-     * @param requestId
-     * @param instanceId
-     * @param accept
-     * @param authorization
-     * @return
-     */
-    @GET
-    @Path("/distributionUebCluster")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "UEB Server List", httpMethod = "GET", notes = "return the available UEB Server List",
-    //TODO Tal G fix response headers
-    responseHeaders = {
-            @ResponseHeader(name = Constants.CONTENT_TYPE_HEADER, description = "Determines the format of the response body", response = String.class),
-            @ResponseHeader(name = "Content-Length", description = "Length of  the response body", response = String.class)})
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", response = ServerListResponse.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its credentials  for  Basic Authentication - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
-    public Response getUebServerList(
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-        Response response = null;
-        ResponseFormat responseFormat = null;
-
-        if (instanceId == null) {
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            response = buildErrorResponse(responseFormat);
-            getComponentsUtils().auditGetUebCluster(null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
-            return response;
-        }
-
-        try {
-            Either<ServerListResponse, ResponseFormat> actionResponse = distributionLogic.getUebServerList();
-
-            if (actionResponse.isRight()) {
-                responseFormat = actionResponse.right().value();
-                response = buildErrorResponse(responseFormat);
-            } else {
-                responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                response = buildOkResponse(responseFormat, actionResponse.left().value());
-            }
-
-            getComponentsUtils().auditGetUebCluster(instanceId, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("failed to get ueb serbver list from cofiguration");
-            log.debug("failed to get ueb serbver list from cofiguration", e);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            getComponentsUtils().auditGetUebCluster(instanceId, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
-            response = buildErrorResponse(responseFormat);
-            return response;
-        }
-
-    }
-
-    /**
-     *
-     * @param requestId
-     * @param instanceId
-     * @param accept
-     * @param contentType
-     * @param contenLength
-     * @param authorization
-     * @param requestJson
-     * @return
-     */
-    @POST
-    @Path("/registerForDistribution")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Subscribes for distribution notifications")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "ECOMP component is successfully registered for distribution", response = TopicRegistrationResponse.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 400, message = "Missing  Body - POL4500"),
-            @ApiResponse(code = 400, message = "Invalid  Body  : missing mandatory parameter 'apiPublicKey' - POL4501"),
-            @ApiResponse(code = 400, message = "Invalid  Body  : missing mandatory parameter 'distrEnvName' - POL4502"),
-            @ApiResponse(code = 400, message = "Invalid Body :  Specified 'distrEnvName' doesn’t exist - POL4137"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( PUT,DELETE,GET  will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})
-    @ApiImplicitParams({@ApiImplicitParam(name = "requestJson", required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")})
-    public Response registerForDistribution(
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @ApiParam(value = "Length  of  the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam( hidden = true) String requestJson) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        Wrapper<RegistrationRequest> registrationRequestWrapper = new Wrapper<>();
-
-        validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL);
-
-        if (responseWrapper.isEmpty()) {
-            validateJson(responseWrapper, registrationRequestWrapper, requestJson);
-        }
-        if (responseWrapper.isEmpty()) {
-            validateEnv(responseWrapper);
-        }
-
-        if (responseWrapper.isEmpty()) {
-            distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement()));
-        } else {
-            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed");
-        }
-
-        return responseWrapper.getInnerElement();
-    }
-
-    /**
-     * Returns list of valid artifact types for validation done in the distribution client.<br>
-     * The list is the representation of the values of the enum ArtifactTypeEnum.
-     *
-     * @param requestId
-     * @param instanceId
-     * @param authorization
-     * @param accept
-     * @return
-     */
-    @GET
-    @Path("/artifactTypes")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Artifact types list", httpMethod = "GET", notes = "Fetches available artifact types list")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Artifact types list fetched successfully", response = String.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( POST,PUT,DELETE  will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})
-    public Response getValidArtifactTypes(
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-        Response response = null;
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-
-        //TODO check if in use
-        validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES);
-        if (responseWrapper.isEmpty()) {
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ArtifactTypeEnum.values());
-        } else {
-            response = responseWrapper.getInnerElement();
-        }
-        return response;
-    }
-
-    /**
-     * Removes from subscription for distribution notifications
-     *
-     * @param requestId
-     * @param instanceId
-     * @param accept
-     * @param contentType
-     * @param contenLength
-     * @param authorization
-     * @param requestJson
-     * @return
-     */
-    @POST
-    @Path("/unRegisterForDistribution")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Removes from subscription for distribution notifications")
-    //TODO Edit the responses
-    @ApiResponses(value = {
-            @ApiResponse(code = 204, message = "ECOMP component is successfully unregistered", response = TopicUnregistrationResponse.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 400, message = "Missing  Body - POL4500"),
-            @ApiResponse(code = 400, message = "Invalid  Body  : missing mandatory parameter 'apiPublicKey' - POL4501"),
-            @ApiResponse(code = 400, message = "Invalid  Body  : missing mandatory parameter 'distrEnvName' - SVC4506"),
-            @ApiResponse(code = 400, message = "Invalid Body :  Specified 'distrEnvName' doesn’t exist - POL4137"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( PUT,DELETE,GET will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})
-    @ApiImplicitParams({@ApiImplicitParam(name = "requestJson", required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")})
-    public Response unRegisterForDistribution(
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @ApiParam(value = "Length  of  the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam( hidden = true) String requestJson) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        Wrapper<RegistrationRequest> unRegistrationRequestWrapper = new Wrapper<>();
-
-        validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL);
-
-        if (responseWrapper.isEmpty()) {
-            validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson);
-        }
-        if (responseWrapper.isEmpty()) {
-            validateEnv(responseWrapper);
-        }
-        if (responseWrapper.isEmpty()) {
-            distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement()));
-        } else {
-            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed");
-        }
-
-        return responseWrapper.getInnerElement();
-    }
-
-    private void validateEnv(Wrapper<Response> responseWrapper) {
-
-        // DE194021
-        StorageOperationStatus environmentStatus = distributionLogic.getDistributionEngine().isEnvironmentAvailable();
-        if (environmentStatus != StorageOperationStatus.OK) {
-            if (environmentStatus == StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND) {
-                Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST));
-                responseWrapper.setInnerElement(missingHeaderResponse);
-            } else {
-                Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
-                responseWrapper.setInnerElement(missingHeaderResponse);
-            }
-        }
-
-    }
-
-    private void validateHeaders(Wrapper<Response> responseWrapper, HttpServletRequest request, AuditingActionEnum auditingAction) {
-        if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null) {
-            Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID));
-            responseWrapper.setInnerElement(missingHeaderResponse);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            getComponentsUtils().auditMissingInstanceIdAsDistributionEngineEvent(auditingAction, responseFormat.getStatus().toString());
-
-        }
-
-    }
-
-    private void validateJson(Wrapper<Response> responseWrapper, Wrapper<RegistrationRequest> registrationRequestWrapper, String requestJson) {
-        if (requestJson == null || requestJson.isEmpty()) {
-            Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
-            responseWrapper.setInnerElement(missingBodyResponse);
-        } else {
-            Either<RegistrationRequest, Exception> eitherRegistration = HttpUtil.convertJsonStringToObject(requestJson, RegistrationRequest.class);
-            if (eitherRegistration.isLeft()) {
-                RegistrationRequest registrationRequest = eitherRegistration.left().value();
-                if (registrationRequest.getApiPublicKey() == null) {
-                    Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY));
-                    responseWrapper.setInnerElement(missingBodyResponse);
-
-                } else if (registrationRequest.getDistrEnvName() == null) {
-                    Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME));
-                    responseWrapper.setInnerElement(missingBodyResponse);
-                } else {
-                    registrationRequestWrapper.setInnerElement(registrationRequest);
-                }
-            } else {
-                Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
-                responseWrapper.setInnerElement(missingBodyResponse);
-            }
-        }
-
-    }
-
-    private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) {
-        return new AuditHandler(getComponentsUtils(), request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), registrationRequest);
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.distribution.servlet;\r
+\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.distribution.AuditHandler;\r
+import org.openecomp.sdc.be.distribution.DistributionBusinessLogic;\r
+import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest;\r
+import org.openecomp.sdc.be.distribution.api.client.ServerListResponse;\r
+import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse;\r
+import org.openecomp.sdc.be.distribution.api.client.TopicUnregistrationResponse;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.servlets.BeGenericServlet;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.common.util.HttpUtil;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+/**\r
+ * This Servlet serves external users for distribution purposes.\r
+ * \r
+ * @author tgitelman\r
+ *\r
+ */\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1")\r
+@OpenAPIDefinition(info =  @Info(title = "Distribution Servlet",description = "This Servlet serves external users for distribution purposes."))\r
+\r
+@Singleton\r
+public class DistributionServlet extends BeGenericServlet {\r
+\r
+    private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";\r
+       private static final Logger log = Logger.getLogger(DistributionServlet.class);\r
+    private final DistributionBusinessLogic distributionLogic;\r
+    @Context\r
+    private HttpServletRequest request;\r
+\r
+    @Inject\r
+    public DistributionServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils, DistributionBusinessLogic distributionLogic) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.distributionLogic = distributionLogic;\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param requestId\r
+     * @param instanceId\r
+     * @param accept\r
+     * @param authorization\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/distributionUebCluster")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "UEB Server List", method = "GET", summary = "return the available UEB Server List")\r
+    //TODO Tal G fix response headers\r
+    /*responseHeaders = {\r
+            @ResponseHeader(name = Constants.CONTENT_TYPE_HEADER, description = "Determines the format of the response body", response = String.class),\r
+            @ResponseHeader(name = "Content-Length", description = "Length of  the response body", response = String.class)})*/\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned",\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServerListResponse.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its credentials  for  Basic Authentication - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})\r
+    public Response getUebServerList(\r
+            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,\r
+            @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+        Response response = null;\r
+        ResponseFormat responseFormat = null;\r
+\r
+        if (instanceId == null) {\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            response = buildErrorResponse(responseFormat);\r
+            getComponentsUtils().auditGetUebCluster(null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());\r
+            return response;\r
+        }\r
+\r
+        try {\r
+            Either<ServerListResponse, ResponseFormat> actionResponse = distributionLogic.getUebServerList();\r
+\r
+            if (actionResponse.isRight()) {\r
+                responseFormat = actionResponse.right().value();\r
+                response = buildErrorResponse(responseFormat);\r
+            } else {\r
+                responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                response = buildOkResponse(responseFormat, actionResponse.left().value());\r
+            }\r
+\r
+            getComponentsUtils().auditGetUebCluster(instanceId, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("failed to get ueb serbver list from cofiguration");\r
+            log.debug("failed to get ueb serbver list from cofiguration", e);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            getComponentsUtils().auditGetUebCluster(instanceId, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());\r
+            response = buildErrorResponse(responseFormat);\r
+            return response;\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param requestId\r
+     * @param instanceId\r
+     * @param accept\r
+     * @param contentType\r
+     * @param contenLength\r
+     * @param authorization\r
+     * @param requestJson\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("/registerForDistribution")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(parameters = @Parameter(name = "requestJson", required = true ), description = "Subscription status", method = "POST", summary = "Subscribes for distribution notifications")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "ECOMP component is successfully registered for distribution",content = @Content(array = @ArraySchema(schema = @Schema(implementation = TopicRegistrationResponse.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "400", description = "Missing  Body - POL4500"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid  Body  : missing mandatory parameter 'apiPublicKey' - POL4501"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid  Body  : missing mandatory parameter 'distrEnvName' - POL4502"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid Body :  Specified 'distrEnvName' doesn’t exist - POL4137"),\r
+            @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( PUT,DELETE,GET  will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500", description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})\r
+    \r
+    //@ApiImplicitParams({@ApiImplicitParam(name = "requestJson", required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")})\r
+    \r
+    public Response registerForDistribution(\r
+            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,\r
+            @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,\r
+            @Parameter(description = "Length  of  the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,\r
+            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter( hidden = true) String requestJson) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        Wrapper<RegistrationRequest> registrationRequestWrapper = new Wrapper<>();\r
+\r
+        validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL);\r
+\r
+        if (responseWrapper.isEmpty()) {\r
+            validateJson(responseWrapper, registrationRequestWrapper, requestJson);\r
+        }\r
+        if (responseWrapper.isEmpty()) {\r
+            validateEnv(responseWrapper);\r
+        }\r
+\r
+        if (responseWrapper.isEmpty()) {\r
+            distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement()));\r
+        } else {\r
+            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed");\r
+        }\r
+\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    /**\r
+     * Returns list of valid artifact types for validation done in the distribution client.<br>\r
+     * The list is the representation of the values of the enum ArtifactTypeEnum.\r
+     *\r
+     * @param requestId\r
+     * @param instanceId\r
+     * @param authorization\r
+     * @param accept\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/artifactTypes")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Artifact types list", method = "GET", summary = "Fetches available artifact types list")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Artifact types list fetched successfully", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( POST,PUT,DELETE  will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500", description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})\r
+    public Response getValidArtifactTypes(\r
+            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,\r
+            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+        Response response = null;\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+\r
+        //TODO check if in use\r
+        validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES);\r
+        if (responseWrapper.isEmpty()) {\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ArtifactTypeEnum.values());\r
+        } else {\r
+            response = responseWrapper.getInnerElement();\r
+        }\r
+        return response;\r
+    }\r
+\r
+    /**\r
+     * Removes from subscription for distribution notifications\r
+     *\r
+     * @param requestId\r
+     * @param instanceId\r
+     * @param accept\r
+     * @param contentType\r
+     * @param contenLength\r
+     * @param authorization\r
+     * @param requestJson\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("/unRegisterForDistribution")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(parameters = @Parameter(name = "requestJson", required = true ),description = "Subscription status", method = "POST", summary = "Removes from subscription for distribution notifications")\r
+    //TODO Edit the responses\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "204", description = "ECOMP component is successfully unregistered", \r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = TopicUnregistrationResponse.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "400", description = "Missing  Body - POL4500"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid  Body  : missing mandatory parameter 'apiPublicKey' - POL4501"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid  Body  : missing mandatory parameter 'distrEnvName' - SVC4506"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid Body :  Specified 'distrEnvName' doesn’t exist - POL4137"),\r
+            @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( PUT,DELETE,GET will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500", description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})\r
+    //@ApiImplicitParams({@ApiImplicitParam(name = "requestJson", required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")})\r
+    public Response unRegisterForDistribution(\r
+            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,\r
+            @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,\r
+            @Parameter(description = "Length  of  the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,\r
+            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter( hidden = true) String requestJson) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        Wrapper<RegistrationRequest> unRegistrationRequestWrapper = new Wrapper<>();\r
+\r
+        validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL);\r
+\r
+        if (responseWrapper.isEmpty()) {\r
+            validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson);\r
+        }\r
+        if (responseWrapper.isEmpty()) {\r
+            validateEnv(responseWrapper);\r
+        }\r
+        if (responseWrapper.isEmpty()) {\r
+            distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement()));\r
+        } else {\r
+            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed");\r
+        }\r
+\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    private void validateEnv(Wrapper<Response> responseWrapper) {\r
+\r
+        // DE194021\r
+        StorageOperationStatus environmentStatus = distributionLogic.getDistributionEngine().isEnvironmentAvailable();\r
+        if (environmentStatus != StorageOperationStatus.OK) {\r
+            if (environmentStatus == StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND) {\r
+                Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST));\r
+                responseWrapper.setInnerElement(missingHeaderResponse);\r
+            } else {\r
+                Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+                responseWrapper.setInnerElement(missingHeaderResponse);\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+    private void validateHeaders(Wrapper<Response> responseWrapper, HttpServletRequest request, AuditingActionEnum auditingAction) {\r
+        if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null) {\r
+            Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID));\r
+            responseWrapper.setInnerElement(missingHeaderResponse);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            getComponentsUtils().auditMissingInstanceIdAsDistributionEngineEvent(auditingAction, responseFormat.getStatus().toString());\r
+\r
+        }\r
+\r
+    }\r
+\r
+    private void validateJson(Wrapper<Response> responseWrapper, Wrapper<RegistrationRequest> registrationRequestWrapper, String requestJson) {\r
+        if (requestJson == null || requestJson.isEmpty()) {\r
+            Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));\r
+            responseWrapper.setInnerElement(missingBodyResponse);\r
+        } else {\r
+            Either<RegistrationRequest, Exception> eitherRegistration = HttpUtil.convertJsonStringToObject(requestJson, RegistrationRequest.class);\r
+            if (eitherRegistration.isLeft()) {\r
+                RegistrationRequest registrationRequest = eitherRegistration.left().value();\r
+                if (registrationRequest.getApiPublicKey() == null) {\r
+                    Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY));\r
+                    responseWrapper.setInnerElement(missingBodyResponse);\r
+\r
+                } else if (registrationRequest.getDistrEnvName() == null) {\r
+                    Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME));\r
+                    responseWrapper.setInnerElement(missingBodyResponse);\r
+                } else {\r
+                    registrationRequestWrapper.setInnerElement(registrationRequest);\r
+                }\r
+            } else {\r
+                Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));\r
+                responseWrapper.setInnerElement(missingBodyResponse);\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+    private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) {\r
+        return new AuditHandler(getComponentsUtils(), request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), registrationRequest);\r
+    }\r
+}\r
index bed28f5..a4e465e 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.externalapi.servlet;
-
-import com.jcabi.aspects.Loggable;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Map;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
-import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
-import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
-import org.openecomp.sdc.be.servlets.RepresentationUtils;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.util.GeneralUtility;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-/**
- * This Servlet serves external users operations on artifacts.
- *
- * @author mshitrit
- *
- */
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Artifact External Servlet", description = "Servlet serves external users operations on artifacts.")
-@Singleton
-public class ArtifactExternalServlet extends AbstractValidationsServlet {
-
-    private static final String FAILED_TO_UPDATE_ARTIFACT = "failed to update artifact";
-
-    @Context
-    private HttpServletRequest request;
-
-    private final ArtifactsBusinessLogic artifactsBusinessLogic;
-
-    private static final Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class);
-
-    private static String startLog = "Start handle request of ";
-
-    @Inject
-    public ArtifactExternalServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        ArtifactsBusinessLogic artifactsBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.artifactsBusinessLogic = artifactsBusinessLogic;
-    }
-
-
-    @POST
-    @Path("/{assetType}/{uuid}/interfaces/{interfaceUUID}/operations/{operationUUID}/artifacts/{artifactUUID}")
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "uploads of artifact to VF operation workflow", httpMethod = "POST", notes = "uploads of artifact to VF operation workflow")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"),
-            @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(code = 400, message = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
-    @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
-    public Response uploadInterfaceOperationArtifact(
-            @ApiParam(value = "Determines the format of the body of the request", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
-            @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,
-            @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "Asset type") @PathParam("assetType") String assetType,
-            @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
-            @ApiParam(value = "The uuid of the interface", required = true)@PathParam("interfaceUUID") final String interfaceUUID,
-            @ApiParam(value = "The uuid of the operation", required = true)@PathParam("operationUUID") final String operationUUID,
-            @ApiParam(value = "The uuid of the artifact", required = true)@PathParam("artifactUUID") final String artifactUUID,
-            @ApiParam( hidden = true) String data) {
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        ResponseFormat responseFormat = null;
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("{} {}", startLog, url);
-        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(assetType);
-        ArtifactDefinition artifactDefinition = null;
-
-        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
-            log.debug("updateArtifact: Missing X-ECOMP-InstanceID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
-            log.debug("updateArtifact: Missing USER_ID");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        try {
-            if (responseWrapper.isEmpty()) {
-                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsBusinessLogic
-                        .updateArtifactOnInterfaceOperationByResourceUUID(data, request, ComponentTypeEnum
-                                        .findByParamName(assetType), uuid, interfaceUUID, operationUUID, artifactUUID,
-                        resourceCommonInfo, artifactsBusinessLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
-                if (uploadArtifactEither.isRight()) {
-                    log.debug(FAILED_TO_UPDATE_ARTIFACT);
-                    responseFormat = uploadArtifactEither.right().value();
-                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-                } else {
-                    artifactDefinition=uploadArtifactEither.left().value();
-                    Object representation = RepresentationUtils.toRepresentation(artifactDefinition);
-                    Map<String, String> headers = new HashMap<>();
-                    headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
-                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                    responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
-                }
-            }
-        } catch (Exception e) {
-            final String message = "failed to update artifact on a resource or service";
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
-            log.debug(message, e);
-            responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
-        } finally {
-            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API,
-                    resourceCommonInfo, request, artifactDefinition, null);
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    /**
-     * Uploads an artifact to resource or service
-     *
-     * @param contentType
-     * @param checksum
-     * @param userId
-     * @param requestId
-     * @param instanceIdHeader
-     * @param accept
-     * @param authorization
-     * @param assetType
-     * @param uuid
-     * @param data
-     * @return
-     */
-    @POST
-    @Path("/{assetType}/{uuid}/artifacts")
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "uploads of artifact to a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"),
-            @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(code = 400, message = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
-    @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
-    public Response uploadArtifact(
-            @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
-            @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
-            @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
-            @ApiParam( hidden = true) String data) {
-
-        init();
-
-        Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("{} {}", startLog, url);
-        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
-        String componentTypeValue = componentType == null ? null : componentType.getValue();
-        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);
-
-        if (componentType == null) {
-            log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
-            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-        }
-        if (responseWrapper.isEmpty()) {
-            validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
-        }
-        if (responseWrapper.isEmpty() ) {
-            validateHttpCspUserIdHeader(userId, responseWrapper);
-        }
-        Response response = null;
-        ArtifactDefinition artifactDefinition = null;
-        try {
-            if (responseWrapper.isEmpty()) {
-                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsBusinessLogic
-                    .uploadArtifactToComponentByUUID(data, request, componentType, uuid,
-                        resourceCommonInfo, artifactsBusinessLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE));
-                if (uploadArtifactEither.isRight()) {
-                    log.debug("failed to upload artifact");
-                    responseWrapper.setInnerElement(uploadArtifactEither.right().value());
-                } else {
-                    artifactDefinition = uploadArtifactEither.left().value();
-                    Object representation = RepresentationUtils.toRepresentation(artifactDefinition);
-                    Map<String, String> headers = new HashMap<>();
-                    headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
-                    responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK));
-                    response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers);
-                }
-            }
-        } catch (IOException e) {
-            final String message = "failed to upload artifact to a resource or service";
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
-            log.debug(message, e);
-            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            response = buildErrorResponse(responseWrapper.getInnerElement());
-        }   catch (ComponentException e){
-            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(e));
-        }finally {
-            if( response == null ){
-                response = buildErrorResponse(responseWrapper.getInnerElement());
-            }
-            getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), AuditingActionEnum.ARTIFACT_UPLOAD_BY_API,
-                    resourceCommonInfo, request, artifactDefinition, null);
-        }
-        return response;
-    }
-
-    /**
-     * Uploads an artifact to resource instance
-     *
-     * @param assetType
-     * @param uuid
-     * @param resourceInstanceName
-     * @return
-     */
-    @POST
-    @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts")
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "uploads an artifact to a resource instance", httpMethod = "POST", notes = "uploads an artifact to a resource instance")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"),
-            @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(code = 400, message = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
-    @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
-    public Response uploadArtifactToInstance(
-            @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
-            @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
-            @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
-            @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName,
-            @ApiParam( hidden = true) String data) {
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        ResponseFormat responseFormat = null;
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("{} {}", startLog, url);
-        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
-        String componentTypeValue = componentType == null ? null : componentType.getValue();
-        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue);
-        ArtifactDefinition artifactDefinition = null;
-
-        if (componentType == null) {
-            log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
-            log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
-            log.debug("uploadArtifact: Missing USER_ID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        try {
-            if (responseWrapper.isEmpty()) {
-                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsBusinessLogic
-                    .uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName,
-                    artifactsBusinessLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE));
-                if (uploadArtifactEither.isRight()) {
-                    log.debug("failed to upload artifact");
-                    responseFormat = uploadArtifactEither.right().value();
-                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-                } else {
-                    Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
-                    Map<String, String> headers = new HashMap<>();
-                    headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
-                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                    responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
-                }
-            }
-        }catch (IOException e) {
-            final String message = "failed to upload artifact to a resource instance";
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
-            log.debug(message, e);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }catch (ComponentException e){
-            responseFormat = getComponentsUtils().getResponseFormat(e);
-        }finally {
-            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API,
-                    resourceCommonInfo, request, artifactDefinition, null);
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    /**
-     *
-     * @param contentType
-     * @param checksum
-     * @param userId
-     * @param requestId
-     * @param instanceIdHeader
-     * @param accept
-     * @param authorization
-     * @param assetType
-     * @param uuid
-     * @param artifactUUID
-     * @param data
-     * @return
-     */
-    @POST
-    @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "updates an artifact on a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(code = 409, message = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
-    @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
-    public Response updateArtifact(
-            @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
-            @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
-            @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
-            @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
-            @ApiParam(hidden = true) String data) {
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        ResponseFormat responseFormat = null;
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("{} {}", startLog, url);
-        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
-        String componentTypeValue = componentType == null ? null : componentType.getValue();
-        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);
-        if (componentType == null) {
-            log.debug("updateArtifact: assetType parameter {} is not valid", assetType);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
-            log.debug("updateArtifact: Missing X-ECOMP-InstanceID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
-            log.debug("updateArtifact: Missing USER_ID");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        ArtifactDefinition artifactDefinition = null;
-        try {
-            if (responseWrapper.isEmpty()) {
-                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsBusinessLogic
-                    .updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID,
-                        resourceCommonInfo, artifactsBusinessLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
-                if (uploadArtifactEither.isRight()) {
-                    log.debug(FAILED_TO_UPDATE_ARTIFACT);
-                    responseFormat = uploadArtifactEither.right().value();
-                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-                } else {
-                    Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
-                    Map<String, String> headers = new HashMap<>();
-                    headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
-                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                    responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
-                }
-            }
-        } catch (IOException e) {
-            final String message = "failed to update artifact on a resource or service";
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
-            log.debug(message, e);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }  catch (ComponentException e){
-            responseFormat = getComponentsUtils().getResponseFormat(e);
-        }
-        finally{
-            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API, resourceCommonInfo,
-                    request, artifactDefinition, artifactUUID);
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    /**
-     * updates an artifact on a resource instance
-     *
-     * @param assetType
-     * @param uuid
-     * @param resourceInstanceName
-     * @param artifactUUID
-     * @return
-     */
-    @POST
-    @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "updates an artifact on a resource instance", httpMethod = "POST", notes = "uploads of artifact to a resource or service")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(code = 409, message = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
-    @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
-    public Response updateArtifactOnResourceInstance(
-            @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
-            @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
-            @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
-            @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
-            @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName,
-            @ApiParam( hidden = true) String data) {
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        ResponseFormat responseFormat = null;
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("{} {}", startLog, url);
-        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
-        String componentTypeValue = componentType == null ? null : componentType.getValue();
-        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue);
-        if (componentType == null) {
-            log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
-            log.debug("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
-            log.debug("updateArtifactOnResourceInstance: Missing USER_ID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        ArtifactDefinition artifactDefinition = null;
-        try {
-            if (responseWrapper.isEmpty()) {
-                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsBusinessLogic
-                    .updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID,
-                    artifactsBusinessLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
-                if (uploadArtifactEither.isRight()) {
-                    log.debug(FAILED_TO_UPDATE_ARTIFACT);
-                    responseFormat = uploadArtifactEither.right().value();
-                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-                } else {
-                    Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
-                    Map<String, String> headers = new HashMap<>();
-                    headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
-                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                    responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
-                }
-            }
-        } catch (IOException e) {
-            final String message = "failed to update artifact on resource instance";
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
-            log.debug(message, e);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }  catch (ComponentException e){
-            responseFormat = getComponentsUtils().getResponseFormat(e);
-        }
-        finally{
-            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API, resourceCommonInfo,
-                    request, artifactDefinition, artifactUUID);
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    /**
-     * deletes an artifact of a resource or service
-     *
-     * @param assetType
-     * @param uuid
-     * @param artifactUUID
-     * @return
-     */
-    @DELETE
-    @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "deletes an artifact of a resource or service", httpMethod = "DELETE", notes = "deletes an artifact of a resource or service", response = Response.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(code = 409, message = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
-    public Response deleteArtifact(
-            @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
-            @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
-            @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) {
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        ResponseFormat responseFormat = null;
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("{} {}", startLog, url);
-        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
-        String componentTypeValue = componentType == null ? null : componentType.getValue();
-        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);
-        ArtifactDefinition artifactDefinition = null;
-        if (componentType == null) {
-            log.debug("deleteArtifact: assetType parameter {} is not valid", assetType);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
-            log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
-            log.debug("deleteArtifact: Missing USER_ID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        try {
-            if (responseWrapper.isEmpty()) {
-                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsBusinessLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID,
-                        resourceCommonInfo, artifactsBusinessLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE));
-                if (uploadArtifactEither.isRight()) {
-                    log.debug("failed to delete artifact");
-                    responseFormat = uploadArtifactEither.right().value();
-                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-                } else {
-                    Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
-                    Map<String, String> headers = new HashMap<>();
-                    headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
-                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                    responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
-                }
-            }
-        } catch (IOException e) {
-            final String message = "failed to delete an artifact of a resource or service";
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
-            log.debug(message, e);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }  catch (ComponentException e){
-            responseFormat = getComponentsUtils().getResponseFormat(e);
-        }
-        finally{
-            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API, resourceCommonInfo,
-                    request, artifactDefinition, artifactUUID);
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    /**
-     * deletes an artifact of a resource instance
-     *
-     * @param assetType
-     * @param uuid
-     * @param resourceInstanceName
-     * @return
-     */
-    @DELETE
-    @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "deletes an artifact of a resource insatnce", httpMethod = "DELETE", notes = "deletes an artifact of a resource insatnce", response = Response.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(code = 409, message = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
-    public Response deleteArtifactOnResourceInstance(
-            @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
-            @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
-            @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
-            @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) {
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        ResponseFormat responseFormat = null;
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("{} {}", startLog, url);
-        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
-        String componentTypeValue = componentType == null ? null : componentType.getValue();
-        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue);
-        if (componentType == null) {
-            log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
-            log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
-            log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        ArtifactDefinition artifactDefinition = null;
-        try {
-            if (responseWrapper.isEmpty()) {
-                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsBusinessLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID,
-                    artifactsBusinessLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE));
-                if (uploadArtifactEither.isRight()) {
-                    log.debug("failed to delete artifact");
-                    responseFormat = uploadArtifactEither.right().value();
-                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-                } else {
-                    Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
-                    Map<String, String> headers = new HashMap<>();
-                    headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
-                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                    responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
-                }
-            }
-        } catch (IOException e) {
-            final String message = "failed to delete an artifact of a resource instance";
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
-            log.debug(message, e);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }  catch (ComponentException e){
-            responseFormat = getComponentsUtils().getResponseFormat(e);
-        }
-        finally{
-            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API, resourceCommonInfo,
-                    request, artifactDefinition, artifactUUID);
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    /**
-     * downloads an artifact of a component (either a service or a resource) by artifactUUID
-     *
-     * @param assetType
-     * @param uuid
-     * @param artifactUUID
-     * @return
-     */
-    @GET
-    @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
-    @Produces(MediaType.APPLICATION_OCTET_STREAM)
-    @ApiOperation(value = "Download component artifact", httpMethod = "GET", notes = "Returns downloaded artifact")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")})
-    public Response downloadComponentArtifact(
-            @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
-            @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
-            @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) {
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        ResponseFormat responseFormat = null;
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("{} {}", startLog, url);
-        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
-        String componentTypeValue = componentType == null ? null : componentType.getValue();
-        if (componentType == null) {
-            log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
-            log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);
-        try {
-            if (responseWrapper.isEmpty()) {
-                Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsBusinessLogic
-                    .downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, resourceCommonInfo);
-                if (downloadComponentArtifactEither.isRight()) {
-                    responseFormat = downloadComponentArtifactEither.right().value();
-                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-                } else {
-                    byte[] value = downloadComponentArtifactEither.left().value();
-                    InputStream is = new ByteArrayInputStream(value);
-                    Map<String, String> headers = new HashMap<>();
-                    headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));
-                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                    responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
-                }
-            }
-        }  catch (ComponentException e){
-            responseFormat = getComponentsUtils().getResponseFormat(e);
-        }
-        finally{
-            getComponentsUtils().auditExternalDownloadArtifact(responseFormat, resourceCommonInfo,
-                    new DistributionData(instanceIdHeader, requestURI), requestId, artifactUUID, userId);
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    /**
-     * downloads an artifact of a resource instance of a component (either a service or a resource) by artifactUUID
-     *
-     * @param assetType
-     * @param uuid
-     * @param resourceInstanceName
-     * @param artifactUUID
-     * @return
-     */
-    @GET
-    @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
-    @Produces(MediaType.APPLICATION_OCTET_STREAM)
-    @ApiOperation(value = "Download resource instance artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")})
-    public Response downloadResourceInstanceArtifact(
-            @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
-            @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
-            @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
-            @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) {
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        ResponseFormat responseFormat = null;
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("{} {}", startLog, url);
-        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
-        String componentTypeValue = componentType == null ? null : componentType.getValue();
-        if (componentType == null) {
-            log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
-            log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }
-        try {
-            if (responseWrapper.isEmpty()) {
-                Either<byte[], ResponseFormat> downloadResourceArtifactEither = artifactsBusinessLogic
-                    .downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID);
-                if (downloadResourceArtifactEither.isRight()) {
-                    responseFormat = downloadResourceArtifactEither.right().value();
-                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-                } else {
-                    byte[] value = downloadResourceArtifactEither.left().value();
-                    InputStream is = new ByteArrayInputStream(value);
-                    Map<String, String> headers = new HashMap<>();
-                    headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));
-                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                    responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
-                }
-            }
-        }  catch (ComponentException e){
-            responseFormat = getComponentsUtils().getResponseFormat(e);
-        }
-        finally{
-            getComponentsUtils().auditExternalDownloadArtifact(responseFormat, new ResourceCommonInfo(resourceInstanceName, componentTypeValue),
-                    new DistributionData(instanceIdHeader, requestURI), requestId, artifactUUID, userId);
-        }
-        return responseWrapper.getInnerElement();
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.externalapi.servlet;\r
+\r
+import java.io.ByteArrayInputStream;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.HttpHeaders;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.ArtifactDefinition;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;\r
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;\r
+import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;\r
+import org.openecomp.sdc.be.servlets.RepresentationUtils;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.util.GeneralUtility;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+/**\r
+ * This Servlet serves external users operations on artifacts.\r
+ *\r
+ * @author mshitrit\r
+ *\r
+ */\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+\r
+@OpenAPIDefinition(info = @Info(title = "Artifact External Servlet",\r
+        description = "Servlet serves external users operations on artifacts."))\r
+@Singleton\r
+public class ArtifactExternalServlet extends AbstractValidationsServlet {\r
+\r
+    private static final String FAILED_TO_UPDATE_ARTIFACT = "failed to update artifact";\r
+\r
+    @Context\r
+    private HttpServletRequest request;\r
+\r
+    private final ArtifactsBusinessLogic artifactsBusinessLogic;\r
+\r
+    private static final Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class);\r
+\r
+    private static String startLog = "Start handle request of ";\r
+\r
+    @Inject\r
+    public ArtifactExternalServlet(UserBusinessLogic userBusinessLogic,\r
+            ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,\r
+            ServletUtils servletUtils, ResourceImportManager resourceImportManager,\r
+            ArtifactsBusinessLogic artifactsBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.artifactsBusinessLogic = artifactsBusinessLogic;\r
+    }\r
+\r
+\r
+    @POST\r
+    @Path("/{assetType}/{uuid}/interfaces/{interfaceUUID}/operations/{operationUUID}/artifacts/{artifactUUID}")\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(parameters = @Parameter(required = true ),description = "uploads of artifact to VF operation workflow", method = "POST",\r
+            summary = "uploads of artifact to VF operation workflow")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Artifact uploaded",\r
+                    content = @Content(\r
+                            array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Artifact name given in input already exists in the context of the asset - SVC4125"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),\r
+            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})\r
+    // @ApiImplicitParams({@ApiImplicitParam(required = true, dataType =\r
+    // "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the\r
+    // artifact")})\r
+    public Response uploadInterfaceOperationArtifact(\r
+            @Parameter(description = "Determines the format of the body of the request",\r
+                    required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,\r
+            @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body",\r
+                    required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,\r
+            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(description = "Asset type") @PathParam("assetType") String assetType,\r
+            @Parameter(description = "The uuid of the asset as published in the metadata",\r
+                    required = true) @PathParam("uuid") final String uuid,\r
+            @Parameter(description = "The uuid of the interface",\r
+                    required = true) @PathParam("interfaceUUID") final String interfaceUUID,\r
+            @Parameter(description = "The uuid of the operation",\r
+                    required = true) @PathParam("operationUUID") final String operationUUID,\r
+            @Parameter(description = "The uuid of the artifact",\r
+                    required = true) @PathParam("artifactUUID") final String artifactUUID,\r
+            @Parameter(hidden = true) String data) {\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        ResponseFormat responseFormat = null;\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("{} {}", startLog, url);\r
+        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(assetType);\r
+        ArtifactDefinition artifactDefinition = null;\r
+\r
+        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {\r
+            log.debug("updateArtifact: Missing X-ECOMP-InstanceID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {\r
+            log.debug("updateArtifact: Missing USER_ID");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        try {\r
+            if (responseWrapper.isEmpty()) {\r
+                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither =\r
+                        artifactsBusinessLogic.updateArtifactOnInterfaceOperationByResourceUUID(data, request,\r
+                                ComponentTypeEnum.findByParamName(assetType), uuid, interfaceUUID, operationUUID,\r
+                                artifactUUID, resourceCommonInfo, artifactsBusinessLogic.new ArtifactOperationInfo(true,\r
+                                        false, ArtifactOperationEnum.UPDATE));\r
+                if (uploadArtifactEither.isRight()) {\r
+                    log.debug(FAILED_TO_UPDATE_ARTIFACT);\r
+                    responseFormat = uploadArtifactEither.right().value();\r
+                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+                } else {\r
+                    artifactDefinition = uploadArtifactEither.left().value();\r
+                    Object representation = RepresentationUtils.toRepresentation(artifactDefinition);\r
+                    Map<String, String> headers = new HashMap<>();\r
+                    headers.put(Constants.MD5_HEADER,\r
+                            GeneralUtility.calculateMD5Base64EncodedByString((String) representation));\r
+                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                    responseWrapper.setInnerElement(buildOkResponse(\r
+                            getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));\r
+                }\r
+            }\r
+        } catch (Exception e) {\r
+            final String message = "failed to update artifact on a resource or service";\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);\r
+            log.debug(message, e);\r
+            responseWrapper.setInnerElement(\r
+                    buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));\r
+        } finally {\r
+            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API,\r
+                    resourceCommonInfo, request, artifactDefinition, null);\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    /**\r
+     * Uploads an artifact to resource or service\r
+     *\r
+     * @param contentType\r
+     * @param checksum\r
+     * @param userId\r
+     * @param requestId\r
+     * @param instanceIdHeader\r
+     * @param accept\r
+     * @param authorization\r
+     * @param assetType\r
+     * @param uuid\r
+     * @param data\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("/{assetType}/{uuid}/artifacts")\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "uploads of artifact to a resource or service", method = "POST",\r
+            summary = "uploads of artifact to a resource or service")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Artifact uploaded",\r
+                    content = @Content(\r
+                            array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Artifact name given in input already exists in the context of the asset - SVC4125"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),\r
+            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})\r
+    // @ApiImplicitParams({@ApiImplicitParam(required = true, dataType =\r
+    // "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the\r
+    // artifact")})\r
+    public Response uploadArtifact(\r
+            @Parameter(description = "Determines the format of the body of the request",\r
+                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,\r
+            @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body",\r
+                    required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,\r
+            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",\r
+                    required = true) @PathParam("assetType") final String assetType,\r
+            @Parameter(description = "The uuid of the asset as published in the metadata",\r
+                    required = true) @PathParam("uuid") final String uuid,\r
+            @Parameter(hidden = true) String data) {\r
+\r
+        init();\r
+\r
+        Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("{} {}", startLog, url);\r
+        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);\r
+        String componentTypeValue = componentType == null ? null : componentType.getValue();\r
+        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);\r
+\r
+        if (componentType == null) {\r
+            log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);\r
+            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+        }\r
+        if (responseWrapper.isEmpty()) {\r
+            validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);\r
+        }\r
+        if (responseWrapper.isEmpty()) {\r
+            validateHttpCspUserIdHeader(userId, responseWrapper);\r
+        }\r
+        Response response = null;\r
+        ArtifactDefinition artifactDefinition = null;\r
+        try {\r
+            if (responseWrapper.isEmpty()) {\r
+                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither =\r
+                        artifactsBusinessLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid,\r
+                                resourceCommonInfo, artifactsBusinessLogic.new ArtifactOperationInfo(true, false,\r
+                                        ArtifactOperationEnum.CREATE));\r
+                if (uploadArtifactEither.isRight()) {\r
+                    log.debug("failed to upload artifact");\r
+                    responseWrapper.setInnerElement(uploadArtifactEither.right().value());\r
+                } else {\r
+                    artifactDefinition = uploadArtifactEither.left().value();\r
+                    Object representation = RepresentationUtils.toRepresentation(artifactDefinition);\r
+                    Map<String, String> headers = new HashMap<>();\r
+                    headers.put(Constants.MD5_HEADER,\r
+                            GeneralUtility.calculateMD5Base64EncodedByString((String) representation));\r
+                    responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK));\r
+                    response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation,\r
+                            headers);\r
+                }\r
+            }\r
+        } catch (IOException e) {\r
+            final String message = "failed to upload artifact to a resource or service";\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);\r
+            log.debug(message, e);\r
+            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            response = buildErrorResponse(responseWrapper.getInnerElement());\r
+        } catch (ComponentException e) {\r
+            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(e));\r
+        } finally {\r
+            if (response == null) {\r
+                response = buildErrorResponse(responseWrapper.getInnerElement());\r
+            }\r
+            getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(),\r
+                    AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, resourceCommonInfo, request, artifactDefinition, null);\r
+        }\r
+        return response;\r
+    }\r
+\r
+    /**\r
+     * Uploads an artifact to resource instance\r
+     *\r
+     * @param assetType\r
+     * @param uuid\r
+     * @param resourceInstanceName\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts")\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "uploads an artifact to a resource instance", method = "POST",\r
+            summary = "uploads an artifact to a resource instance")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Artifact uploaded",\r
+                    content = @Content(\r
+                            array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Artifact name given in input already exists in the context of the asset - SVC4125"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),\r
+            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})\r
+    // @ApiImplicitParams({@ApiImplicitParam(required = true, dataType =\r
+    // "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the\r
+    // artifact")})\r
+    public Response uploadArtifactToInstance(\r
+            @Parameter(description = "Determines the format of the body of the request",\r
+                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,\r
+            @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body",\r
+                    required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,\r
+            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",\r
+                    required = true) @PathParam("assetType") final String assetType,\r
+            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The uuid of the asset as published in the metadata",\r
+                    required = true) @PathParam("uuid") final String uuid,\r
+            @Parameter(description = "The component instance name (as publishedin the response of the detailed query)",\r
+                    required = true) @PathParam("resourceInstanceName") final String resourceInstanceName,\r
+            @Parameter(hidden = true) String data) {\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        ResponseFormat responseFormat = null;\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("{} {}", startLog, url);\r
+        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);\r
+        String componentTypeValue = componentType == null ? null : componentType.getValue();\r
+        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue);\r
+        ArtifactDefinition artifactDefinition = null;\r
+\r
+        if (componentType == null) {\r
+            log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {\r
+            log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {\r
+            log.debug("uploadArtifact: Missing USER_ID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        try {\r
+            if (responseWrapper.isEmpty()) {\r
+                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither =\r
+                        artifactsBusinessLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid,\r
+                                resourceInstanceName, artifactsBusinessLogic.new ArtifactOperationInfo(true, false,\r
+                                        ArtifactOperationEnum.CREATE));\r
+                if (uploadArtifactEither.isRight()) {\r
+                    log.debug("failed to upload artifact");\r
+                    responseFormat = uploadArtifactEither.right().value();\r
+                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+                } else {\r
+                    Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());\r
+                    Map<String, String> headers = new HashMap<>();\r
+                    headers.put(Constants.MD5_HEADER,\r
+                            GeneralUtility.calculateMD5Base64EncodedByString((String) representation));\r
+                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                    responseWrapper.setInnerElement(buildOkResponse(\r
+                            getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));\r
+                }\r
+            }\r
+        } catch (IOException e) {\r
+            final String message = "failed to upload artifact to a resource instance";\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);\r
+            log.debug(message, e);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        } catch (ComponentException e) {\r
+            responseFormat = getComponentsUtils().getResponseFormat(e);\r
+        } finally {\r
+            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API,\r
+                    resourceCommonInfo, request, artifactDefinition, null);\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param contentType\r
+     * @param checksum\r
+     * @param userId\r
+     * @param requestId\r
+     * @param instanceIdHeader\r
+     * @param accept\r
+     * @param authorization\r
+     * @param assetType\r
+     * @param uuid\r
+     * @param artifactUUID\r
+     * @param data\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "updates an artifact on a resource or service", method = "POST",\r
+            summary = "uploads of artifact to a resource or service")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Artifact updated",\r
+                    content = @Content(\r
+                            array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),\r
+            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),\r
+            @ApiResponse(responseCode = "403",\r
+                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),\r
+            @ApiResponse(responseCode = "409",\r
+                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})\r
+    // @ApiImplicitParams({@ApiImplicitParam(required = true, dataType =\r
+    // "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the\r
+    // artifact")})\r
+    public Response updateArtifact(\r
+            @Parameter(description = "Determines the format of the body of the request",\r
+                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,\r
+            @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body",\r
+                    required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,\r
+            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",\r
+                    required = true) @PathParam("assetType") final String assetType,\r
+            @Parameter(description = "The uuid of the asset as published in the metadata",\r
+                    required = true) @PathParam("uuid") final String uuid,\r
+            @Parameter(\r
+                    description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation",\r
+                    required = true) @PathParam("artifactUUID") final String artifactUUID,\r
+            @Parameter(hidden = true) String data) {\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        ResponseFormat responseFormat = null;\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("{} {}", startLog, url);\r
+        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);\r
+        String componentTypeValue = componentType == null ? null : componentType.getValue();\r
+        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);\r
+        if (componentType == null) {\r
+            log.debug("updateArtifact: assetType parameter {} is not valid", assetType);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {\r
+            log.debug("updateArtifact: Missing X-ECOMP-InstanceID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {\r
+            log.debug("updateArtifact: Missing USER_ID");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        ArtifactDefinition artifactDefinition = null;\r
+        try {\r
+            if (responseWrapper.isEmpty()) {\r
+                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither =\r
+                        artifactsBusinessLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid,\r
+                                artifactUUID, resourceCommonInfo, artifactsBusinessLogic.new ArtifactOperationInfo(true,\r
+                                        false, ArtifactOperationEnum.UPDATE));\r
+                if (uploadArtifactEither.isRight()) {\r
+                    log.debug(FAILED_TO_UPDATE_ARTIFACT);\r
+                    responseFormat = uploadArtifactEither.right().value();\r
+                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+                } else {\r
+                    Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());\r
+                    Map<String, String> headers = new HashMap<>();\r
+                    headers.put(Constants.MD5_HEADER,\r
+                            GeneralUtility.calculateMD5Base64EncodedByString((String) representation));\r
+                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                    responseWrapper.setInnerElement(buildOkResponse(\r
+                            getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));\r
+                }\r
+            }\r
+        } catch (IOException e) {\r
+            final String message = "failed to update artifact on a resource or service";\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);\r
+            log.debug(message, e);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        } catch (ComponentException e) {\r
+            responseFormat = getComponentsUtils().getResponseFormat(e);\r
+        } finally {\r
+            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API,\r
+                    resourceCommonInfo, request, artifactDefinition, artifactUUID);\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    /**\r
+     * updates an artifact on a resource instance\r
+     *\r
+     * @param assetType\r
+     * @param uuid\r
+     * @param resourceInstanceName\r
+     * @param artifactUUID\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "updates an artifact on a resource instance", method = "POST",\r
+            summary = "uploads of artifact to a resource or service")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Artifact updated",\r
+                    content = @Content(\r
+                            array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),\r
+            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),\r
+            @ApiResponse(responseCode = "403",\r
+                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),\r
+            @ApiResponse(responseCode = "409",\r
+                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})\r
+    // @ApiImplicitParams({@ApiImplicitParam(required = true, dataType =\r
+    // "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the\r
+    // artifact")})\r
+    public Response updateArtifactOnResourceInstance(\r
+            @Parameter(description = "Determines the format of the body of the request",\r
+                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,\r
+            @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body",\r
+                    required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,\r
+            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",\r
+                    required = true) @PathParam("assetType") final String assetType,\r
+            @Parameter(description = "The uuid of the asset as published in the metadata",\r
+                    required = true) @PathParam("uuid") final String uuid,\r
+            @Parameter(\r
+                    description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation",\r
+                    required = true) @PathParam("artifactUUID") final String artifactUUID,\r
+            @Parameter(description = "The component instance name (as publishedin the response of the detailed query)",\r
+                    required = true) @PathParam("resourceInstanceName") final String resourceInstanceName,\r
+            @Parameter(hidden = true) String data) {\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        ResponseFormat responseFormat = null;\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("{} {}", startLog, url);\r
+        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);\r
+        String componentTypeValue = componentType == null ? null : componentType.getValue();\r
+        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue);\r
+        if (componentType == null) {\r
+            log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {\r
+            log.debug("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {\r
+            log.debug("updateArtifactOnResourceInstance: Missing USER_ID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        ArtifactDefinition artifactDefinition = null;\r
+        try {\r
+            if (responseWrapper.isEmpty()) {\r
+                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither =\r
+                        artifactsBusinessLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid,\r
+                                resourceInstanceName, artifactUUID, artifactsBusinessLogic.new ArtifactOperationInfo(\r
+                                        true, false, ArtifactOperationEnum.UPDATE));\r
+                if (uploadArtifactEither.isRight()) {\r
+                    log.debug(FAILED_TO_UPDATE_ARTIFACT);\r
+                    responseFormat = uploadArtifactEither.right().value();\r
+                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+                } else {\r
+                    Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());\r
+                    Map<String, String> headers = new HashMap<>();\r
+                    headers.put(Constants.MD5_HEADER,\r
+                            GeneralUtility.calculateMD5Base64EncodedByString((String) representation));\r
+                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                    responseWrapper.setInnerElement(buildOkResponse(\r
+                            getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));\r
+                }\r
+            }\r
+        } catch (IOException e) {\r
+            final String message = "failed to update artifact on resource instance";\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);\r
+            log.debug(message, e);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        } catch (ComponentException e) {\r
+            responseFormat = getComponentsUtils().getResponseFormat(e);\r
+        } finally {\r
+            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API,\r
+                    resourceCommonInfo, request, artifactDefinition, artifactUUID);\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    /**\r
+     * deletes an artifact of a resource or service\r
+     *\r
+     * @param assetType\r
+     * @param uuid\r
+     * @param artifactUUID\r
+     * @return\r
+     */\r
+    @DELETE\r
+    @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "deletes an artifact of a resource or service", method = "DELETE",\r
+            summary = "deletes an artifact of a resource or service", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Artifact deleted",\r
+                    content = @Content(\r
+                            array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),\r
+            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),\r
+            @ApiResponse(responseCode = "403",\r
+                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),\r
+            @ApiResponse(responseCode = "409",\r
+                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})\r
+    public Response deleteArtifact(\r
+            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",\r
+                    required = true) @PathParam("assetType") final String assetType,\r
+            @Parameter(description = "The uuid of the asset as published in the metadata",\r
+                    required = true) @PathParam("uuid") final String uuid,\r
+            @Parameter(\r
+                    description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation",\r
+                    required = true) @PathParam("artifactUUID") final String artifactUUID) {\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        ResponseFormat responseFormat = null;\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("{} {}", startLog, url);\r
+        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);\r
+        String componentTypeValue = componentType == null ? null : componentType.getValue();\r
+        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);\r
+        ArtifactDefinition artifactDefinition = null;\r
+        if (componentType == null) {\r
+            log.debug("deleteArtifact: assetType parameter {} is not valid", assetType);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {\r
+            log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {\r
+            log.debug("deleteArtifact: Missing USER_ID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        try {\r
+            if (responseWrapper.isEmpty()) {\r
+                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither =\r
+                        artifactsBusinessLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid,\r
+                                artifactUUID, resourceCommonInfo, artifactsBusinessLogic.new ArtifactOperationInfo(true,\r
+                                        false, ArtifactOperationEnum.DELETE));\r
+                if (uploadArtifactEither.isRight()) {\r
+                    log.debug("failed to delete artifact");\r
+                    responseFormat = uploadArtifactEither.right().value();\r
+                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+                } else {\r
+                    Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());\r
+                    Map<String, String> headers = new HashMap<>();\r
+                    headers.put(Constants.MD5_HEADER,\r
+                            GeneralUtility.calculateMD5Base64EncodedByString((String) representation));\r
+                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                    responseWrapper.setInnerElement(buildOkResponse(\r
+                            getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));\r
+                }\r
+            }\r
+        } catch (IOException e) {\r
+            final String message = "failed to delete an artifact of a resource or service";\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);\r
+            log.debug(message, e);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        } catch (ComponentException e) {\r
+            responseFormat = getComponentsUtils().getResponseFormat(e);\r
+        } finally {\r
+            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API,\r
+                    resourceCommonInfo, request, artifactDefinition, artifactUUID);\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    /**\r
+     * deletes an artifact of a resource instance\r
+     *\r
+     * @param assetType\r
+     * @param uuid\r
+     * @param resourceInstanceName\r
+     * @return\r
+     */\r
+    @DELETE\r
+    @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "deletes an artifact of a resource insatnce", method = "DELETE",\r
+            summary = "deletes an artifact of a resource insatnce", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Artifact deleted",\r
+                    content = @Content(\r
+                            array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),\r
+            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),\r
+            @ApiResponse(responseCode = "403",\r
+                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),\r
+            @ApiResponse(responseCode = "409",\r
+                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})\r
+    public Response deleteArtifactOnResourceInstance(\r
+            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",\r
+                    required = true) @PathParam("assetType") final String assetType,\r
+            @Parameter(description = "The uuid of the asset as published in the metadata",\r
+                    required = true) @PathParam("uuid") final String uuid,\r
+            @Parameter(\r
+                    description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation",\r
+                    required = true) @PathParam("artifactUUID") final String artifactUUID,\r
+            @Parameter(description = "The component instance name (as publishedin the response of the detailed query)",\r
+                    required = true) @PathParam("resourceInstanceName") final String resourceInstanceName) {\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        ResponseFormat responseFormat = null;\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("{} {}", startLog, url);\r
+        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);\r
+        String componentTypeValue = componentType == null ? null : componentType.getValue();\r
+        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue);\r
+        if (componentType == null) {\r
+            log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {\r
+            log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {\r
+            log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        ArtifactDefinition artifactDefinition = null;\r
+        try {\r
+            if (responseWrapper.isEmpty()) {\r
+                Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither =\r
+                        artifactsBusinessLogic.deleteArtifactOnRiByUUID(request, componentType, uuid,\r
+                                resourceInstanceName, artifactUUID, artifactsBusinessLogic.new ArtifactOperationInfo(\r
+                                        true, false, ArtifactOperationEnum.DELETE));\r
+                if (uploadArtifactEither.isRight()) {\r
+                    log.debug("failed to delete artifact");\r
+                    responseFormat = uploadArtifactEither.right().value();\r
+                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+                } else {\r
+                    Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());\r
+                    Map<String, String> headers = new HashMap<>();\r
+                    headers.put(Constants.MD5_HEADER,\r
+                            GeneralUtility.calculateMD5Base64EncodedByString((String) representation));\r
+                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                    responseWrapper.setInnerElement(buildOkResponse(\r
+                            getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));\r
+                }\r
+            }\r
+        } catch (IOException e) {\r
+            final String message = "failed to delete an artifact of a resource instance";\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);\r
+            log.debug(message, e);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        } catch (ComponentException e) {\r
+            responseFormat = getComponentsUtils().getResponseFormat(e);\r
+        } finally {\r
+            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API,\r
+                    resourceCommonInfo, request, artifactDefinition, artifactUUID);\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    /**\r
+     * downloads an artifact of a component (either a service or a resource) by artifactUUID\r
+     *\r
+     * @param assetType\r
+     * @param uuid\r
+     * @param artifactUUID\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")\r
+    @Produces(MediaType.APPLICATION_OCTET_STREAM)\r
+    @Operation(description = "Download component artifact", method = "GET", summary = "Returns downloaded artifact")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Artifact downloaded",\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),\r
+            @ApiResponse(responseCode = "404", description = "Artifact was not found - SVC4505")})\r
+    public Response downloadComponentArtifact(\r
+            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",\r
+                    required = true) @PathParam("assetType") final String assetType,\r
+            @Parameter(description = "The uuid of the asset as published in the metadata",\r
+                    required = true) @PathParam("uuid") final String uuid,\r
+            @Parameter(\r
+                    description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation",\r
+                    required = true) @PathParam("artifactUUID") final String artifactUUID) {\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        ResponseFormat responseFormat = null;\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("{} {}", startLog, url);\r
+        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);\r
+        String componentTypeValue = componentType == null ? null : componentType.getValue();\r
+        if (componentType == null) {\r
+            log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {\r
+            log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);\r
+        try {\r
+            if (responseWrapper.isEmpty()) {\r
+                Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsBusinessLogic\r
+                        .downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, resourceCommonInfo);\r
+                if (downloadComponentArtifactEither.isRight()) {\r
+                    responseFormat = downloadComponentArtifactEither.right().value();\r
+                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+                } else {\r
+                    byte[] value = downloadComponentArtifactEither.left().value();\r
+                    InputStream is = new ByteArrayInputStream(value);\r
+                    Map<String, String> headers = new HashMap<>();\r
+                    headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));\r
+                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                    responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));\r
+                }\r
+            }\r
+        } catch (ComponentException e) {\r
+            responseFormat = getComponentsUtils().getResponseFormat(e);\r
+        } finally {\r
+            getComponentsUtils().auditExternalDownloadArtifact(responseFormat, resourceCommonInfo,\r
+                    new DistributionData(instanceIdHeader, requestURI), requestId, artifactUUID, userId);\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    /**\r
+     * downloads an artifact of a resource instance of a component (either a service or a resource) by\r
+     * artifactUUID\r
+     *\r
+     * @param assetType\r
+     * @param uuid\r
+     * @param resourceInstanceName\r
+     * @param artifactUUID\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")\r
+    @Produces(MediaType.APPLICATION_OCTET_STREAM)\r
+    @Operation(description = "Download resource instance artifact", method = "GET",\r
+            summary = "Returns downloaded artifact", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Artifact downloaded",\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),\r
+            @ApiResponse(responseCode = "404", description = "Artifact was not found - SVC4505")})\r
+    public Response downloadResourceInstanceArtifact(\r
+            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(description = "The requested asset type",\r
+                    required = true) @PathParam("assetType") final String assetType,\r
+            @Parameter(description = "The uuid of the asset as published in the metadata",\r
+                    required = true) @PathParam("uuid") final String uuid,\r
+            @Parameter(\r
+                    description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation",\r
+                    required = true) @PathParam("artifactUUID") final String artifactUUID,\r
+            @Parameter(description = "The component instance name (as publishedin the response of the detailed query)",\r
+                    required = true) @PathParam("resourceInstanceName") final String resourceInstanceName) {\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        ResponseFormat responseFormat = null;\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("{} {}", startLog, url);\r
+        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);\r
+        String componentTypeValue = componentType == null ? null : componentType.getValue();\r
+        if (componentType == null) {\r
+            log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {\r
+            log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+        }\r
+        try {\r
+            if (responseWrapper.isEmpty()) {\r
+                Either<byte[], ResponseFormat> downloadResourceArtifactEither =\r
+                        artifactsBusinessLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid,\r
+                                resourceInstanceName, artifactUUID);\r
+                if (downloadResourceArtifactEither.isRight()) {\r
+                    responseFormat = downloadResourceArtifactEither.right().value();\r
+                    responseWrapper.setInnerElement(buildErrorResponse(responseFormat));\r
+                } else {\r
+                    byte[] value = downloadResourceArtifactEither.left().value();\r
+                    InputStream is = new ByteArrayInputStream(value);\r
+                    Map<String, String> headers = new HashMap<>();\r
+                    headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));\r
+                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                    responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));\r
+                }\r
+            }\r
+        } catch (ComponentException e) {\r
+            responseFormat = getComponentsUtils().getResponseFormat(e);\r
+        } finally {\r
+            getComponentsUtils().auditExternalDownloadArtifact(responseFormat,\r
+                    new ResourceCommonInfo(resourceInstanceName, componentTypeValue),\r
+                    new DistributionData(instanceIdHeader, requestURI), requestId, artifactUUID, userId);\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+}\r
index ebc0e62..4c91ab4 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.externalapi.servlet;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import javax.inject.Inject;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter;
-import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
-import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
-import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
-import org.openecomp.sdc.be.servlets.RepresentationUtils;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.util.GeneralUtility;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * This Servlet serves external users for retrieving component metadata.
- * 
- * @author tgitelman
- *
- */
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Asset Metadata External Servlet", description = "This Servlet serves external users for retrieving component metadata.")
-@Singleton
-public class AssetsDataServlet extends AbstractValidationsServlet {
-
-    @Context
-    private HttpServletRequest request;
-
-    private static final Logger log = Logger.getLogger(AssetsDataServlet.class);
-    private final ElementBusinessLogic elementBusinessLogic;
-    private final AssetMetadataConverter assetMetadataConverter;
-    private final ComponentBusinessLogicProvider componentBusinessLogicProvider;
-
-    @Inject
-    public AssetsDataServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        ElementBusinessLogic elementBusinessLogic,
-        AssetMetadataConverter assetMetadataConverter,
-        ComponentBusinessLogicProvider componentBusinessLogicProvider) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.elementBusinessLogic = elementBusinessLogic;
-        this.assetMetadataConverter = assetMetadataConverter;
-        this.componentBusinessLogicProvider = componentBusinessLogicProvider;
-    }
-
-    /**
-     *
-     * @param requestId
-     * @param instanceIdHeader
-     * @param accept
-     * @param authorization
-     * @param assetType
-     * @param category
-     * @param subCategory
-     * @param distributionStatus
-     * @param resourceType
-     * @return
-     */
-    @GET
-    @Path("/{assetType}")
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Fetch list of assets", httpMethod = "GET", notes = "Returns list of assets")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
-    public Response getAssetListExternal(
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
-            @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("category") String category,
-            @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("subCategory") String subCategory,
-            @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("distributionStatus") String distributionStatus,
-            @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("resourceType") String resourceType) {
-
-        Response response = null;
-        ResponseFormat responseFormat = null;
-        String query = request.getQueryString();
-        String requestURI = request.getRequestURI().endsWith("/")?
-                removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("Start handle request of {}", url);
-
-        AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
-
-        String resourceUrl = query == null ? requestURI : requestURI + "?" + query;
-        DistributionData distributionData = new DistributionData(instanceIdHeader, resourceUrl);
-
-        // Mandatory
-        if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
-            log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
-            return buildErrorResponse(responseFormat);
-        }
-
-        try {
-            Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);
-
-            if (category != null) {
-                filters.put(FilterKeyEnum.CATEGORY, category);
-            }
-            if (subCategory != null) {
-                filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
-            }
-            if (distributionStatus != null) {
-                filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
-            }
-            if (resourceType != null) {
-                ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
-                if (resourceTypeEnum == null) {
-                    log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");
-                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-                    getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
-                    return buildErrorResponse(responseFormat);
-                }
-                filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
-            }
-
-            Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getFilteredCatalogComponents(assetType, filters, query);
-
-            if (assetTypeData.isRight()) {
-                log.debug("getAssetList: Asset Fetching Failed");
-                responseFormat = assetTypeData.right().value();
-                getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
-                return buildErrorResponse(responseFormat);
-            } else {
-                log.debug("getAssetList: Asset Fetching Success");
-                Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter
-                    .convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);
-                if (resMetadata.isRight()) {
-                    log.debug("getAssetList: Asset conversion Failed");
-                    responseFormat = resMetadata.right().value();
-                    getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
-                    return buildErrorResponse(responseFormat);
-                }
-                Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
-                responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
-
-                response = buildOkResponse(responseFormat, result);
-                return response;
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
-            log.debug("getAssetList: Fetch list of assets failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    /**
-     *
-     * @param requestId
-     * @param instanceIdHeader
-     * @param accept
-     * @param authorization
-     * @param assetType
-     * @param uuid
-     * @return
-     */
-    @GET
-    @Path("/{assetType}/{uuid}/metadata")
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Detailed metadata of asset by uuid", httpMethod = "GET", notes = "Returns detailed metadata of an asset by uuid")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
-    public Response getAssetSpecificMetadataByUuidExternal(
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
-            @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) {
-
-        Response response = null;
-        ResponseFormat responseFormat = null;
-        AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("Start handle request of {}", url);
-
-        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
-        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
-        DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
-        // Mandatory
-        if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
-            log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, uuid);
-            return buildErrorResponse(responseFormat);
-        }
-
-        try {
-            Either<List<? extends Component>, ResponseFormat> assetTypeData =
-                elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
-
-            if (assetTypeData.isRight()) {
-                log.debug("getAssetList: Asset Fetching Failed");
-                responseFormat = assetTypeData.right().value();
-                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                        resourceCommonInfo, requestId, uuid);
-
-                return buildErrorResponse(responseFormat);
-            }
-            resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());
-            log.debug("getAssetList: Asset Fetching Success");
-            Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter
-                .convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
-            if (resMetadata.isRight()) {
-                log.debug("getAssetList: Asset conversion Failed");
-                responseFormat = resMetadata.right().value();
-
-                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                        resourceCommonInfo, requestId, uuid);
-                return buildErrorResponse(responseFormat);
-            }
-            Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, uuid);
-
-            response = buildOkResponse(responseFormat, result);
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
-            log.debug("getAssetList: Fetch list of assets failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    /**
-     *
-     * @param requestId
-     * @param instanceIdHeader
-     * @param accept
-     * @param authorization
-     * @param assetType
-     * @param uuid
-     * @return
-     */
-    @GET
-    @Path("/{assetType}/{uuid}/toscaModel")
-    @Produces(MediaType.APPLICATION_OCTET_STREAM)
-    @ApiOperation(value = "Fetch assets CSAR", httpMethod = "GET", notes = "Returns asset csar", response = String.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = String.class),
-            @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
-    public Response getToscaModelExternal(
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
-            @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) {
-
-        String url = request.getRequestURI();
-        log.debug("Start handle request of {} {}", request.getMethod(), url);
-        Response response = null;
-        ResponseFormat responseFormat = null;
-        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
-        AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;
-
-        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
-        DistributionData distributionData = new DistributionData(instanceIdHeader, url);
-
-        if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
-            log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, uuid);
-            return buildErrorResponse(responseFormat);
-        }
-
-        try {
-            ComponentBusinessLogic componentBL = componentBusinessLogicProvider.getInstance(componentType);
-
-
-            Either<ImmutablePair<String, byte[]>, ResponseFormat> csarArtifact = componentBL.getToscaModelByComponentUuid(componentType, uuid, resourceCommonInfo);
-            if (csarArtifact.isRight()) {
-                responseFormat = csarArtifact.right().value();
-                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                        resourceCommonInfo, requestId, uuid);
-                response = buildErrorResponse(responseFormat);
-            } else {
-                byte[] value = csarArtifact.left().value().getRight();
-                InputStream is = new ByteArrayInputStream(value);
-                String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);
-                Map<String, String> headers = new HashMap<>();
-                headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.left().value().getLeft()));
-                headers.put(Constants.MD5_HEADER, contenetMD5);
-                responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                        resourceCommonInfo, requestId, uuid);
-                response = buildOkResponse(responseFormat, is, headers);
-            }
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
-            log.debug("falied to get asset tosca model", e);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            response = buildErrorResponse(responseFormat);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, uuid);
-            return response;
-        }
-    }
-
-
-    private String removeDuplicateSlashSeparator(String requestUri) {
-        return requestUri.substring(0, requestUri.length()-1);
-    }
-
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.externalapi.servlet;\r
+\r
+import java.io.ByteArrayInputStream;\r
+import java.io.InputStream;\r
+import java.util.EnumMap;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.QueryParam;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.lang3.tuple.ImmutablePair;\r
+import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;\r
+import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter;\r
+import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.Component;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;\r
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;\r
+import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;\r
+import org.openecomp.sdc.be.servlets.RepresentationUtils;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.common.util.GeneralUtility;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+/**\r
+ * This Servlet serves external users for retrieving component metadata.\r
+ * \r
+ * @author tgitelman\r
+ *\r
+ */\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+// for retrieving component metadata.")\r
+@OpenAPIDefinition(info = @Info(title = "Asset Metadata External Servlet",\r
+        description = "This Servlet serves external users for retrieving component metadata."))\r
+@Singleton\r
+public class AssetsDataServlet extends AbstractValidationsServlet {\r
+\r
+    @Context\r
+    private HttpServletRequest request;\r
+\r
+    private static final Logger log = Logger.getLogger(AssetsDataServlet.class);\r
+    private final ElementBusinessLogic elementBusinessLogic;\r
+    private final AssetMetadataConverter assetMetadataConverter;\r
+    private final ComponentBusinessLogicProvider componentBusinessLogicProvider;\r
+\r
+    @Inject\r
+    public AssetsDataServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,\r
+            ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,\r
+            ElementBusinessLogic elementBusinessLogic, AssetMetadataConverter assetMetadataConverter,\r
+            ComponentBusinessLogicProvider componentBusinessLogicProvider) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.elementBusinessLogic = elementBusinessLogic;\r
+        this.assetMetadataConverter = assetMetadataConverter;\r
+        this.componentBusinessLogicProvider = componentBusinessLogicProvider;\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param requestId\r
+     * @param instanceIdHeader\r
+     * @param accept\r
+     * @param authorization\r
+     * @param assetType\r
+     * @param category\r
+     * @param subCategory\r
+     * @param distributionStatus\r
+     * @param resourceType\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/{assetType}")\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Fetch list of assets", method = "GET", summary = "Returns list of assets")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200",\r
+                    description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})\r
+    public Response getAssetListExternal(\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}),\r
+                    required = true) @PathParam("assetType") final String assetType,\r
+            @Parameter(description = "The filter key (resourceType only for resources)",\r
+                    required = false) @QueryParam("category") String category,\r
+            @Parameter(description = "The filter key (resourceType only for resources)",\r
+                    required = false) @QueryParam("subCategory") String subCategory,\r
+            @Parameter(description = "The filter key (resourceType only for resources)",\r
+                    required = false) @QueryParam("distributionStatus") String distributionStatus,\r
+            @Parameter(description = "The filter key (resourceType only for resources)",\r
+                    required = false) @QueryParam("resourceType") String resourceType) {\r
+\r
+        Response response = null;\r
+        ResponseFormat responseFormat = null;\r
+        String query = request.getQueryString();\r
+        String requestURI =\r
+                request.getRequestURI().endsWith("/") ? removeDuplicateSlashSeparator(request.getRequestURI())\r
+                        : request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        AuditingActionEnum auditingActionEnum =\r
+                query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;\r
+\r
+        String resourceUrl = query == null ? requestURI : requestURI + "?" + query;\r
+        DistributionData distributionData = new DistributionData(instanceIdHeader, resourceUrl);\r
+\r
+        // Mandatory\r
+        if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {\r
+            log.debug("getAssetList: Missing X-ECOMP-InstanceID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData,\r
+                    requestId);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+        try {\r
+            Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);\r
+\r
+            if (category != null) {\r
+                filters.put(FilterKeyEnum.CATEGORY, category);\r
+            }\r
+            if (subCategory != null) {\r
+                filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);\r
+            }\r
+            if (distributionStatus != null) {\r
+                filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);\r
+            }\r
+            if (resourceType != null) {\r
+                ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);\r
+                if (resourceTypeEnum == null) {\r
+                    log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");\r
+                    responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);\r
+                    getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData,\r
+                            requestId);\r
+                    return buildErrorResponse(responseFormat);\r
+                }\r
+                filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());\r
+            }\r
+\r
+            Either<List<? extends Component>, ResponseFormat> assetTypeData =\r
+                    elementBusinessLogic.getFilteredCatalogComponents(assetType, filters, query);\r
+\r
+            if (assetTypeData.isRight()) {\r
+                log.debug("getAssetList: Asset Fetching Failed");\r
+                responseFormat = assetTypeData.right().value();\r
+                getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData,\r
+                        requestId);\r
+                return buildErrorResponse(responseFormat);\r
+            } else {\r
+                log.debug("getAssetList: Asset Fetching Success");\r
+                Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata =\r
+                        assetMetadataConverter.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);\r
+                if (resMetadata.isRight()) {\r
+                    log.debug("getAssetList: Asset conversion Failed");\r
+                    responseFormat = resMetadata.right().value();\r
+                    getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData,\r
+                            requestId);\r
+                    return buildErrorResponse(responseFormat);\r
+                }\r
+                Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());\r
+                responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData,\r
+                        requestId);\r
+\r
+                response = buildOkResponse(responseFormat, result);\r
+                return response;\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");\r
+            log.debug("getAssetList: Fetch list of assets failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param requestId\r
+     * @param instanceIdHeader\r
+     * @param accept\r
+     * @param authorization\r
+     * @param assetType\r
+     * @param uuid\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/{assetType}/{uuid}/metadata")\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Detailed metadata of asset by uuid", method = "GET",\r
+            summary = "Returns detailed metadata of an asset by uuid")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200",\r
+                    description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404",\r
+                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})\r
+    public Response getAssetSpecificMetadataByUuidExternal(\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}),\r
+                    required = true) @PathParam("assetType") final String assetType,\r
+            @Parameter(description = "The requested asset uuid",\r
+                    required = true) @PathParam("uuid") final String uuid) {\r
+\r
+        Response response = null;\r
+        ResponseFormat responseFormat = null;\r
+        AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);\r
+        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());\r
+        DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);\r
+        // Mandatory\r
+        if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {\r
+            log.debug("getAssetList: Missing X-ECOMP-InstanceID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,\r
+                    resourceCommonInfo, requestId, uuid);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+        try {\r
+            Either<List<? extends Component>, ResponseFormat> assetTypeData =\r
+                    elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);\r
+\r
+            if (assetTypeData.isRight()) {\r
+                log.debug("getAssetList: Asset Fetching Failed");\r
+                responseFormat = assetTypeData.right().value();\r
+                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,\r
+                        resourceCommonInfo, requestId, uuid);\r
+\r
+                return buildErrorResponse(responseFormat);\r
+            }\r
+            resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());\r
+            log.debug("getAssetList: Asset Fetching Success");\r
+            Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata =\r
+                    assetMetadataConverter.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);\r
+            if (resMetadata.isRight()) {\r
+                log.debug("getAssetList: Asset conversion Failed");\r
+                responseFormat = resMetadata.right().value();\r
+\r
+                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,\r
+                        resourceCommonInfo, requestId, uuid);\r
+                return buildErrorResponse(responseFormat);\r
+            }\r
+            Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,\r
+                    resourceCommonInfo, requestId, uuid);\r
+\r
+            response = buildOkResponse(responseFormat, result);\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");\r
+            log.debug("getAssetList: Fetch list of assets failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param requestId\r
+     * @param instanceIdHeader\r
+     * @param accept\r
+     * @param authorization\r
+     * @param assetType\r
+     * @param uuid\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/{assetType}/{uuid}/toscaModel")\r
+    @Produces(MediaType.APPLICATION_OCTET_STREAM)\r
+    @Operation(description = "Fetch assets CSAR", method = "GET", summary = "Returns asset csar",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200",\r
+                    description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404",\r
+                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})\r
+    public Response getToscaModelExternal(\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}),\r
+                    required = true) @PathParam("assetType") final String assetType,\r
+            @Parameter(description = "The requested asset uuid",\r
+                    required = true) @PathParam("uuid") final String uuid) {\r
+\r
+        String url = request.getRequestURI();\r
+        log.debug("Start handle request of {} {}", request.getMethod(), url);\r
+        Response response = null;\r
+        ResponseFormat responseFormat = null;\r
+        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);\r
+        AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;\r
+\r
+        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());\r
+        DistributionData distributionData = new DistributionData(instanceIdHeader, url);\r
+\r
+        if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {\r
+            log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);\r
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,\r
+                    resourceCommonInfo, requestId, uuid);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+        try {\r
+            ComponentBusinessLogic componentBL = componentBusinessLogicProvider.getInstance(componentType);\r
+\r
+\r
+            Either<ImmutablePair<String, byte[]>, ResponseFormat> csarArtifact =\r
+                    componentBL.getToscaModelByComponentUuid(componentType, uuid, resourceCommonInfo);\r
+            if (csarArtifact.isRight()) {\r
+                responseFormat = csarArtifact.right().value();\r
+                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,\r
+                        resourceCommonInfo, requestId, uuid);\r
+                response = buildErrorResponse(responseFormat);\r
+            } else {\r
+                byte[] value = csarArtifact.left().value().getRight();\r
+                InputStream is = new ByteArrayInputStream(value);\r
+                String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);\r
+                Map<String, String> headers = new HashMap<>();\r
+                headers.put(Constants.CONTENT_DISPOSITION_HEADER,\r
+                        getContentDispositionValue(csarArtifact.left().value().getLeft()));\r
+                headers.put(Constants.MD5_HEADER, contenetMD5);\r
+                responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,\r
+                        resourceCommonInfo, requestId, uuid);\r
+                response = buildOkResponse(responseFormat, is, headers);\r
+            }\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");\r
+            log.debug("falied to get asset tosca model", e);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            response = buildErrorResponse(responseFormat);\r
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,\r
+                    resourceCommonInfo, requestId, uuid);\r
+            return response;\r
+        }\r
+    }\r
+\r
+\r
+    private String removeDuplicateSlashSeparator(String requestUri) {\r
+        return requestUri.substring(0, requestUri.length() - 1);\r
+    }\r
+\r
+\r
+}\r
index 26b91a3..b4c9c42 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.externalapi.servlet;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.apache.commons.lang3.StringUtils;
-import org.elasticsearch.common.Strings;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
-import org.json.simple.parser.ParseException;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
-import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
-import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase;
-import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter;
-import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
-import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
-import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
-import org.openecomp.sdc.be.servlets.RepresentationUtils;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.be.utils.CommonBeUtils;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.util.ValidationUtils;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "CRUD External Servlet", description = "This Servlet serves external users for creating assets and changing their lifecycle state")
-@Singleton
-public class CrudExternalServlet extends AbstractValidationsServlet {
-
-    @Context
-    private HttpServletRequest request;
-
-    private static final Logger log = Logger.getLogger(CrudExternalServlet.class);
-    private final ElementBusinessLogic elementBusinessLogic;
-    private final AssetMetadataConverter assetMetadataUtils;
-    private final LifecycleBusinessLogic lifecycleBusinessLogic;
-    private final ResourceBusinessLogic resourceBusinessLogic;
-
-    @Inject
-    public CrudExternalServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        ElementBusinessLogic elementBusinessLogic,
-        AssetMetadataConverter assetMetadataUtils,
-        LifecycleBusinessLogic lifecycleBusinessLogic,
-        ResourceBusinessLogic resourceBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.elementBusinessLogic = elementBusinessLogic;
-        this.assetMetadataUtils = assetMetadataUtils;
-        this.lifecycleBusinessLogic = lifecycleBusinessLogic;
-        this.resourceBusinessLogic = resourceBusinessLogic;
-    }
-
-    /**
-     * Creates a new Resource
-     *
-     * @param assetType
-     * @param data
-     * @param userId
-     * @param instanceIdHeader
-     * @return
-     */
-    @POST
-    @Path("/{assetType}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "creates a resource", httpMethod = "POST", notes = "Creates a resource")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "ECOMP component is authenticated and Asset created", response = Resource.class),
-            @ApiResponse(code = 400, message = "Missing  X-ECOMP-InstanceID  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(code = 400, message = "The name provided for the newly created resource is already in use for another resource in SDC - SVC4050"),
-            @ApiResponse(code = 400, message = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),
-            @ApiResponse(code = 400, message = "Missing request body. The post request did not contain the expected body - SVC4500"),
-            @ApiResponse(code = 400, message = "The resource name is missing in the request body - SVC4062"),
-            @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format - SVC4064"),
-            @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format (exceeds limit) - SVC4065"),
-            @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT tags exceeds character limit - SVC4066"),
-            @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name exceeds character limit - SVC4067"),
-            @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release exceeds character limit - SVC4068"),
-            @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT ATT Contact has wrong format - SVC4069"),
-            @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name has wrong format - SVC4070"),
-            @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name has wrong format - SVC4071"),
-            @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release has wrong format - SVC4072"),
-            @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name exceeds character limit - SVC4073")})
-    @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.Resource", paramType = "body", value = "json describe the created resource")})
-    public Response createResourceExternal(
-            @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
-            @ApiParam( hidden = true) String data) {
-
-        init();
-
-        Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("Start handle request of {}", url);
-        Resource resource = null;
-        User modifier = null;
-        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(ComponentTypeEnum.RESOURCE.getValue());
-
-        ServletContext context = request.getSession().getServletContext();
-        try {
-            // Validate X-ECOMP-InstanceID Header
-            if (responseWrapper.isEmpty()) {
-                validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
-            }
-            // Validate USER_ID Header
-            if (responseWrapper.isEmpty()) {
-                validateHttpCspUserIdHeader(userId, responseWrapper);
-            }
-            // Validate assetType
-            if (responseWrapper.isEmpty()) {
-                if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) ){
-                    responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
-                }
-            }
-            //Validate resource type
-            if(responseWrapper.isEmpty()){
-                JSONParser parser = new JSONParser();
-                JSONObject jsonObj = (JSONObject) parser.parse(data);
-                String resourceType = (String) jsonObj.get(FilterKeyEnum.RESOURCE_TYPE.getName());
-                if( StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType) ){
-                    resourceCommonInfo.setResourceName((String) jsonObj.get("name"));
-                    responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-                }
-            }
-            // Convert the user json to a resource
-            if (responseWrapper.isEmpty()) {
-                modifier = new User();
-                modifier.setUserId(userId);
-                Either<Resource, ResponseFormat> eitherResource = getComponentsUtils()
-                        .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class,
-                                null, ComponentTypeEnum.RESOURCE);
-                if( eitherResource.isRight() ){
-                    responseWrapper.setInnerElement(eitherResource.right().value());
-                }
-                else{
-                    resource = eitherResource.left().value();
-                }
-
-            }
-            //validate name exist
-            if(responseWrapper.isEmpty()){
-                if( Strings.isEmpty(resource.getName())){
-                    responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                            ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()));
-
-                }
-            }
-
-            if(responseWrapper.isEmpty()){
-                resource.setDerivedFrom(Arrays.asList("tosca.nodes.Root"));
-                resource.setSystemName(ValidationUtils.convertToSystemName(resource.getName()));
-                resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(),
-                        resource.getSystemName()));
-                handleCategories(context, data, resource, responseWrapper);
-            }
-            // Create the resource in the dataModel
-            if (responseWrapper.isEmpty()) {
-                resource = resourceBusinessLogic.createResource(resource, null,
-                        modifier, null, null);
-                return buildCreatedResourceResponse(resource, context, responseWrapper);
-            } else {
-                return buildErrorResponse(responseWrapper.getInnerElement());
-            }
-        } catch (IOException|ParseException e) {
-            final String message = "failed to create vfc monitoring template resource";
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
-            log.debug(message, e);
-            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return buildErrorResponse(responseWrapper.getInnerElement());
-        } catch (ComponentException e){
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(e);
-            responseWrapper.setInnerElement(responseFormat);
-            return buildErrorResponse(responseFormat);
-        }
-        finally{
-            getComponentsUtils().auditCreateResourceExternalApi(responseWrapper.getInnerElement(), resourceCommonInfo, request, resource);
-        }
-    }
-
-    /**
-     * Changing the lifecycle of an asset
-     * @param jsonChangeInfo    The description - request body
-     * @param assetType The requested asset type.Valid values are: resources / services (for VFCMT â€“ use "resources")
-     * @param uuid The uuid of the desired resource to be changed
-     * @param lifecycleTransition The lifecycle operation to be performed on the asset.Valid values are:Checkin / Checkout /  CERTIFICATION_REQUEST
-     * @param userId
-     * @return
-     */
-    @POST
-    @Path("/{assetType}/{uuid}/lifecycleState/{lifecycleOperation}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Resource state changed", response = AssetMetadata.class),
-            @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(code = 403, message = "Asset is already checked-out by another user - SVC4085"),
-            @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4080")})
-    @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction", paramType = "body", value = "userRemarks - Short description (free text) about the asset version being changed")})
-    public Response changeResourceStateExternal(
-            @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(allowableValues = "checkout, checkin", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
-            @ApiParam(value = "id of component to be changed") @PathParam(value = "uuid") final String uuid,
-            @ApiParam(value = "validValues: resources / services ", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam(value = "assetType") final String assetType,
-            @ApiParam( hidden = true) String jsonChangeInfo) {
-
-        Response response = null;
-
-        init();
-
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("Start handle request of {}", url);
-
-        //get the business logic
-        ServletContext context = request.getSession().getServletContext();
-
-        Wrapper<ResponseFormat> responseWrapper = runValidations(assetType);
-        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
-        Component component = null;
-        Component responseObject = null;
-        User modifier = null;
-
-        try{
-            // Validate X-ECOMP-InstanceID Header
-            if (responseWrapper.isEmpty()) {
-                validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
-            }
-
-            if (responseWrapper.isEmpty()) {
-                //get user
-                Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
-                if (eitherGetUser.isRight()) {
-                    ResponseFormat responseFormat = eitherGetUser.right().value();
-                    responseWrapper.setInnerElement(responseFormat);
-                    return buildErrorResponse(responseFormat);
-                }
-                modifier = eitherGetUser.left().value();
-
-                //get the component id from the uuid
-                Either<Component, ResponseFormat> latestVersion = lifecycleBusinessLogic.getLatestComponentByUuid(componentType, uuid);
-                if (latestVersion.isRight()) {
-                    ResponseFormat responseFormat = latestVersion.right().value();
-                    responseWrapper.setInnerElement(responseFormat);
-                    return buildErrorResponse(responseFormat);
-                }
-                component = latestVersion.left().value();
-                String componentId = component.getUniqueId();
-
-                //validate the transition is valid
-                Either<LifeCycleTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(lifecycleTransition, modifier);
-                if (validateEnum.isRight()) {
-                    ResponseFormat responseFormat = validateEnum.right().value();
-                    responseWrapper.setInnerElement(responseFormat);
-                    return buildErrorResponse(responseFormat);
-                }
-                LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
-
-                //create changeInfo
-                LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
-                try {
-                    if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
-                        ObjectMapper mapper = new ObjectMapper();
-                        changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
-                    }
-                }
-                catch (IOException e) {
-                    BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
-                    log.debug("failed to convert from json {}", jsonChangeInfo, e);
-                    ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(modifier, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
-                    responseWrapper.setInnerElement(responseFormat);
-                    return buildErrorResponse(responseFormat);
-                }
-
-                //execute business logic
-                Either<? extends Component, ResponseFormat> actionResponse = lifecycleBusinessLogic
-                    .changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true);
-                if (actionResponse.isRight()) {
-                    log.info("failed to change resource state");
-                    ResponseFormat responseFormat = actionResponse.right().value();
-                    responseWrapper.setInnerElement(responseFormat);
-                    return buildErrorResponse(responseFormat);
-                }
-
-                log.debug("change state successful !!!");
-                responseObject = actionResponse.left().value();
-                response = buildCreatedResourceResponse(responseObject, context, responseWrapper);
-            } else {
-                response = buildErrorResponse(responseWrapper.getInnerElement());
-            }
-
-            return response;
-        } catch (IOException e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");
-            log.debug("change lifecycle state failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            responseWrapper.setInnerElement(responseFormat);
-            return buildErrorResponse(responseFormat);
-        } catch (ComponentException e){
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(e);
-            responseWrapper.setInnerElement(responseFormat);
-            return buildErrorResponse(responseFormat);
-        }
-        finally{
-            getComponentsUtils().auditChangeLifecycleAction(responseWrapper.getInnerElement(), componentType, requestId,
-                    component, responseObject, new DistributionData(instanceIdHeader, requestURI), modifier);
-        }
-    }
-
-    private Response buildCreatedResourceResponse(Component resource, ServletContext context,
-            Wrapper<ResponseFormat> responseWrapper) throws IOException {
-        ResponseFormat responseFormat;
-        Response response;
-        Either<? extends AssetMetadata, ResponseFormat> resMetadata = assetMetadataUtils
-                .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(),
-                        true);
-        if (resMetadata.isRight()) {
-            log.debug("Asset conversion Failed");
-            responseFormat = resMetadata.right().value();
-            responseWrapper.setInnerElement(responseFormat);
-            response = buildErrorResponse(responseFormat);
-        }else{
-            final AssetMetadata assetData = resMetadata.left().value();
-            assetData.setToscaModelURL(null);
-
-            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED));
-            Object representation = RepresentationUtils.toRepresentation(assetData);
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation);
-        }
-        return response;
-    }
-
-    private void handleCategories(ServletContext context, String data, Resource resource,
-            Wrapper<ResponseFormat> responseWrapper) {
-        try {
-            JSONParser parser = new JSONParser();
-            JSONObject jsonObj = (JSONObject) parser.parse(data);
-            String category = (String) jsonObj.get(CategoryTypeEnum.CATEGORY.getValue());
-            String subcategory = (String) jsonObj.get(CategoryTypeEnum.SUBCATEGORY.getValue());
-            if (Strings.isEmpty(category)) {
-                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                        ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
-            }
-            else if (Strings.isEmpty(subcategory)) {
-                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                        ActionStatus.COMPONENT_MISSING_SUBCATEGORY));
-            }
-            if (responseWrapper.isEmpty()) {
-                // get All Categories
-                Either<List<CategoryDefinition>, ActionStatus> allResourceCategories = elementBusinessLogic
-                        .getAllResourceCategories();
-                // Error fetching categories
-                if (allResourceCategories.isRight()) {
-                    responseWrapper.setInnerElement(
-                            getComponentsUtils().getResponseFormat(allResourceCategories.right().value()));
-                } else {
-                    addCategories(resource, category, subcategory, allResourceCategories, responseWrapper);
-                }
-            }
-        } catch (ParseException e) {
-            log.debug("Exception occured in addCategories: {}", e.getMessage(), e);
-            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    private void addCategories(Resource resource, String category, String subcategory,
-            Either<List<CategoryDefinition>, ActionStatus> allResourceCategories,
-            Wrapper<ResponseFormat> responseWrapper) {
-        Optional<CategoryDefinition> optionalCategory =
-                // Stream of all the categories
-                allResourceCategories.left().value().stream()
-                        // filter in only relevant category
-                        .filter(e -> e.getName().equals(category))
-                        // get the result
-                        .findAny();
-        if (!optionalCategory.isPresent()) {
-            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                    ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
-        } else {
-            CategoryDefinition categoryDefinition = optionalCategory.get();
-
-            List<SubCategoryDefinition> subCaregories =
-                    // Stream of all sub-categories of the relevant
-                    // category
-                    categoryDefinition.getSubcategories().stream()
-                            // filter in only relevant sub-category
-                            .filter(e -> e.getName().equals(subcategory))
-                            // get the result
-                            .collect(Collectors.toList());
-
-            if( subCaregories.isEmpty() ){
-                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                        ActionStatus.COMPONENT_INVALID_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
-            }
-            else{
-                categoryDefinition.setSubcategories(subCaregories);
-                resource.setCategories(Arrays.asList(categoryDefinition));
-            }
-
-        }
-    }
-
-
-
-
-
-
-    private Wrapper<ResponseFormat> runValidations(final String assetType) {
-        Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
-
-        // Validate X-ECOMP-InstanceID Header
-        if (responseWrapper.isEmpty()) {
-            String instanceId = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
-            validateXECOMPInstanceIDHeader(instanceId,responseWrapper);
-        }
-        // Validate USER_ID Header
-        if (responseWrapper.isEmpty()) {
-            validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER),responseWrapper);
-        }
-        // Validate assetType
-        if (responseWrapper.isEmpty()) {
-            if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) &&  !AssetTypeEnum.SERVICES.getValue().equals(assetType)){
-                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
-            }
-        }
-
-        return responseWrapper;
-    }
-
-    private Either<LifeCycleTransitionEnum, ResponseFormat> validateTransitionEnum(final String lifecycleTransition, User user) {
-        LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT;
-        try {
-            transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
-        } catch (IllegalArgumentException e) {
-            log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e);
-            ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
-            return Either.right(error);
-        }
-        return Either.left(transitionEnum);
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.externalapi.servlet;\r
+\r
+import java.io.IOException;\r
+import java.util.Arrays;\r
+import java.util.List;\r
+import java.util.Optional;\r
+import java.util.stream.Collectors;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.lang3.StringUtils;\r
+import org.elasticsearch.common.Strings;\r
+import org.json.simple.JSONObject;\r
+import org.json.simple.parser.JSONParser;\r
+import org.json.simple.parser.ParseException;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;\r
+import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;\r
+import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase;\r
+import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;\r
+import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter;\r
+import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.Component;\r
+import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;\r
+import org.openecomp.sdc.be.model.Resource;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.model.category.CategoryDefinition;\r
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;\r
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;\r
+import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;\r
+import org.openecomp.sdc.be.servlets.RepresentationUtils;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.be.utils.CommonBeUtils;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.common.util.ValidationUtils;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.fasterxml.jackson.databind.ObjectMapper;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "CRUD External Servlet",\r
+        description = "This Servlet serves external users for creating assets and changing their lifecycle state"))\r
+\r
+@Singleton\r
+public class CrudExternalServlet extends AbstractValidationsServlet {\r
+\r
+    @Context\r
+    private HttpServletRequest request;\r
+\r
+    private static final Logger log = Logger.getLogger(CrudExternalServlet.class);\r
+    private final ElementBusinessLogic elementBusinessLogic;\r
+    private final AssetMetadataConverter assetMetadataUtils;\r
+    private final LifecycleBusinessLogic lifecycleBusinessLogic;\r
+    private final ResourceBusinessLogic resourceBusinessLogic;\r
+\r
+    @Inject\r
+    public CrudExternalServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        ElementBusinessLogic elementBusinessLogic,\r
+        AssetMetadataConverter assetMetadataUtils,\r
+        LifecycleBusinessLogic lifecycleBusinessLogic,\r
+        ResourceBusinessLogic resourceBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.elementBusinessLogic = elementBusinessLogic;\r
+        this.assetMetadataUtils = assetMetadataUtils;\r
+        this.lifecycleBusinessLogic = lifecycleBusinessLogic;\r
+        this.resourceBusinessLogic = resourceBusinessLogic;\r
+    }\r
+\r
+    /**\r
+     * Creates a new Resource\r
+     *\r
+     * @param assetType\r
+     * @param data\r
+     * @param userId\r
+     * @param instanceIdHeader\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("/{assetType}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "creates a resource", method = "POST", summary = "Creates a resource")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and Asset created",\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing  X-ECOMP-InstanceID  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404",\r
+                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "The name provided for the newly created resource is already in use for another resource in SDC - SVC4050"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Missing request body. The post request did not contain the expected body - SVC4500"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "The resource name is missing in the request body - SVC4062"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Create VFCMT request: VFCMT description has wrong format - SVC4064"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Create VFCMT request: VFCMT description has wrong format (exceeds limit) - SVC4065"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Create VFCMT request: VFCMT tags exceeds character limit - SVC4066"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Create VFCMT request: VFCMT vendor name exceeds character limit - SVC4067"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Create VFCMT request: VFCMT vendor release exceeds character limit - SVC4068"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Create VFCMT request: VFCMT ATT Contact has wrong format - SVC4069"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Create VFCMT request: VFCMT name has wrong format - SVC4070"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Create VFCMT request: VFCMT vendor name has wrong format - SVC4071"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Create VFCMT request: VFCMT vendor release has wrong format - SVC4072"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Create VFCMT request: VFCMT name exceeds character limit - SVC4073")})\r
+    // @ApiImplicitParams({@ApiImplicitParam(required = true, dataType =\r
+    // "org.openecomp.sdc.be.model.Resource", paramType = "body", value = "json describe the created\r
+    // resource")})\r
+    public Response createResourceExternal(\r
+            @Parameter(description = "Determines the format of the body of the request",\r
+                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,\r
+            @Parameter(description = "The user id",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(description = "The requested asset type", required = true,\r
+                    schema = @Schema(\r
+                            allowableValues = {"resources, services"})) @PathParam("assetType") final String assetType,\r
+            @Parameter(hidden = true) String data) {\r
+\r
+        init();\r
+\r
+        Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("Start handle request of {}", url);\r
+        Resource resource = null;\r
+        User modifier = null;\r
+        ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(ComponentTypeEnum.RESOURCE.getValue());\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        try {\r
+            // Validate X-ECOMP-InstanceID Header\r
+            if (responseWrapper.isEmpty()) {\r
+                validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);\r
+            }\r
+            // Validate USER_ID Header\r
+            if (responseWrapper.isEmpty()) {\r
+                validateHttpCspUserIdHeader(userId, responseWrapper);\r
+            }\r
+            // Validate assetType\r
+            if (responseWrapper.isEmpty()) {\r
+                if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) ){\r
+                    responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));\r
+                }\r
+            }\r
+            //Validate resource type\r
+            if(responseWrapper.isEmpty()){\r
+                JSONParser parser = new JSONParser();\r
+                JSONObject jsonObj = (JSONObject) parser.parse(data);\r
+                String resourceType = (String) jsonObj.get(FilterKeyEnum.RESOURCE_TYPE.getName());\r
+                if( StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType) ){\r
+                    resourceCommonInfo.setResourceName((String) jsonObj.get("name"));\r
+                    responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+                }\r
+            }\r
+            // Convert the user json to a resource\r
+            if (responseWrapper.isEmpty()) {\r
+                modifier = new User();\r
+                modifier.setUserId(userId);\r
+                Either<Resource, ResponseFormat> eitherResource = getComponentsUtils()\r
+                        .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class,\r
+                                null, ComponentTypeEnum.RESOURCE);\r
+                if( eitherResource.isRight() ){\r
+                    responseWrapper.setInnerElement(eitherResource.right().value());\r
+                }\r
+                else{\r
+                    resource = eitherResource.left().value();\r
+                }\r
+\r
+            }\r
+            //validate name exist\r
+            if(responseWrapper.isEmpty()){\r
+                if( Strings.isEmpty(resource.getName())){\r
+                    responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(\r
+                            ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()));\r
+\r
+                }\r
+            }\r
+\r
+            if(responseWrapper.isEmpty()){\r
+                resource.setDerivedFrom(Arrays.asList("tosca.nodes.Root"));\r
+                resource.setSystemName(ValidationUtils.convertToSystemName(resource.getName()));\r
+                resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(),\r
+                        resource.getSystemName()));\r
+                handleCategories(context, data, resource, responseWrapper);\r
+            }\r
+            // Create the resource in the dataModel\r
+            if (responseWrapper.isEmpty()) {\r
+                resource = resourceBusinessLogic.createResource(resource, null,\r
+                        modifier, null, null);\r
+                return buildCreatedResourceResponse(resource, context, responseWrapper);\r
+            } else {\r
+                return buildErrorResponse(responseWrapper.getInnerElement());\r
+            }\r
+        } catch (IOException|ParseException e) {\r
+            final String message = "failed to create vfc monitoring template resource";\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);\r
+            log.debug(message, e);\r
+            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return buildErrorResponse(responseWrapper.getInnerElement());\r
+        } catch (ComponentException e){\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(e);\r
+            responseWrapper.setInnerElement(responseFormat);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+        finally{\r
+            getComponentsUtils().auditCreateResourceExternalApi(responseWrapper.getInnerElement(), resourceCommonInfo, request, resource);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Changing the lifecycle of an asset\r
+     * @param jsonChangeInfo    The description - request body\r
+     * @param assetType The requested asset type.Valid values are: resources / services (for VFCMT â€“ use "resources")\r
+     * @param uuid The uuid of the desired resource to be changed\r
+     * @param lifecycleTransition The lifecycle operation to be performed on the asset.Valid values are:Checkin / Checkout /  CERTIFICATION_REQUEST\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("/{assetType}/{uuid}/lifecycleState/{lifecycleOperation}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Change Resource lifecycle State", method = "POST")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Resource state changed",\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),\r
+            @ApiResponse(responseCode = "400", description = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404",\r
+                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),\r
+            @ApiResponse(responseCode = "403", description = "Asset is already checked-out by another user - SVC4085"),\r
+            @ApiResponse(responseCode = "403",\r
+                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4080")})\r
+  //  @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction", paramType = "body", value = "userRemarks - Short description (free text) about the asset version being changed")})\r
+    public Response changeResourceStateExternal(\r
+            @Parameter(description = "Determines the format of the body of the request",\r
+                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,\r
+            @Parameter(description = "The user id",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(schema = @Schema(allowableValues = {"checkout, checkin"}),\r
+                    required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,\r
+            @Parameter(description = "id of component to be changed") @PathParam(value = "uuid") final String uuid,\r
+            @Parameter(description = "validValues: resources / services ",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam(\r
+                                    value = "assetType") final String assetType,\r
+            @Parameter(hidden = true) String jsonChangeInfo) {\r
+\r
+        Response response = null;\r
+\r
+        init();\r
+\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        //get the business logic\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        Wrapper<ResponseFormat> responseWrapper = runValidations(assetType);\r
+        ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);\r
+        Component component = null;\r
+        Component responseObject = null;\r
+        User modifier = null;\r
+\r
+        try{\r
+            // Validate X-ECOMP-InstanceID Header\r
+            if (responseWrapper.isEmpty()) {\r
+                validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);\r
+            }\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                //get user\r
+                Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);\r
+                if (eitherGetUser.isRight()) {\r
+                    ResponseFormat responseFormat = eitherGetUser.right().value();\r
+                    responseWrapper.setInnerElement(responseFormat);\r
+                    return buildErrorResponse(responseFormat);\r
+                }\r
+                modifier = eitherGetUser.left().value();\r
+\r
+                //get the component id from the uuid\r
+                Either<Component, ResponseFormat> latestVersion = lifecycleBusinessLogic.getLatestComponentByUuid(componentType, uuid);\r
+                if (latestVersion.isRight()) {\r
+                    ResponseFormat responseFormat = latestVersion.right().value();\r
+                    responseWrapper.setInnerElement(responseFormat);\r
+                    return buildErrorResponse(responseFormat);\r
+                }\r
+                component = latestVersion.left().value();\r
+                String componentId = component.getUniqueId();\r
+\r
+                //validate the transition is valid\r
+                Either<LifeCycleTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(lifecycleTransition, modifier);\r
+                if (validateEnum.isRight()) {\r
+                    ResponseFormat responseFormat = validateEnum.right().value();\r
+                    responseWrapper.setInnerElement(responseFormat);\r
+                    return buildErrorResponse(responseFormat);\r
+                }\r
+                LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();\r
+\r
+                //create changeInfo\r
+                LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();\r
+                try {\r
+                    if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {\r
+                        ObjectMapper mapper = new ObjectMapper();\r
+                        changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());\r
+                    }\r
+                }\r
+                catch (IOException e) {\r
+                    BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");\r
+                    log.debug("failed to convert from json {}", jsonChangeInfo, e);\r
+                    ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(modifier, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);\r
+                    responseWrapper.setInnerElement(responseFormat);\r
+                    return buildErrorResponse(responseFormat);\r
+                }\r
+\r
+                //execute business logic\r
+                Either<? extends Component, ResponseFormat> actionResponse = lifecycleBusinessLogic\r
+                    .changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true);\r
+                if (actionResponse.isRight()) {\r
+                    log.info("failed to change resource state");\r
+                    ResponseFormat responseFormat = actionResponse.right().value();\r
+                    responseWrapper.setInnerElement(responseFormat);\r
+                    return buildErrorResponse(responseFormat);\r
+                }\r
+\r
+                log.debug("change state successful !!!");\r
+                responseObject = actionResponse.left().value();\r
+                response = buildCreatedResourceResponse(responseObject, context, responseWrapper);\r
+            } else {\r
+                response = buildErrorResponse(responseWrapper.getInnerElement());\r
+            }\r
+\r
+            return response;\r
+        } catch (IOException e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");\r
+            log.debug("change lifecycle state failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            responseWrapper.setInnerElement(responseFormat);\r
+            return buildErrorResponse(responseFormat);\r
+        } catch (ComponentException e){\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(e);\r
+            responseWrapper.setInnerElement(responseFormat);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+        finally{\r
+            getComponentsUtils().auditChangeLifecycleAction(responseWrapper.getInnerElement(), componentType, requestId,\r
+                    component, responseObject, new DistributionData(instanceIdHeader, requestURI), modifier);\r
+        }\r
+    }\r
+\r
+    private Response buildCreatedResourceResponse(Component resource, ServletContext context,\r
+            Wrapper<ResponseFormat> responseWrapper) throws IOException {\r
+        ResponseFormat responseFormat;\r
+        Response response;\r
+        Either<? extends AssetMetadata, ResponseFormat> resMetadata = assetMetadataUtils\r
+                .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(),\r
+                        true);\r
+        if (resMetadata.isRight()) {\r
+            log.debug("Asset conversion Failed");\r
+            responseFormat = resMetadata.right().value();\r
+            responseWrapper.setInnerElement(responseFormat);\r
+            response = buildErrorResponse(responseFormat);\r
+        }else{\r
+            final AssetMetadata assetData = resMetadata.left().value();\r
+            assetData.setToscaModelURL(null);\r
+\r
+            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED));\r
+            Object representation = RepresentationUtils.toRepresentation(assetData);\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation);\r
+        }\r
+        return response;\r
+    }\r
+\r
+    private void handleCategories(ServletContext context, String data, Resource resource,\r
+            Wrapper<ResponseFormat> responseWrapper) {\r
+        try {\r
+            JSONParser parser = new JSONParser();\r
+            JSONObject jsonObj = (JSONObject) parser.parse(data);\r
+            String category = (String) jsonObj.get(CategoryTypeEnum.CATEGORY.getValue());\r
+            String subcategory = (String) jsonObj.get(CategoryTypeEnum.SUBCATEGORY.getValue());\r
+            if (Strings.isEmpty(category)) {\r
+                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(\r
+                        ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));\r
+            }\r
+            else if (Strings.isEmpty(subcategory)) {\r
+                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(\r
+                        ActionStatus.COMPONENT_MISSING_SUBCATEGORY));\r
+            }\r
+            if (responseWrapper.isEmpty()) {\r
+                // get All Categories\r
+                Either<List<CategoryDefinition>, ActionStatus> allResourceCategories = elementBusinessLogic\r
+                        .getAllResourceCategories();\r
+                // Error fetching categories\r
+                if (allResourceCategories.isRight()) {\r
+                    responseWrapper.setInnerElement(\r
+                            getComponentsUtils().getResponseFormat(allResourceCategories.right().value()));\r
+                } else {\r
+                    addCategories(resource, category, subcategory, allResourceCategories, responseWrapper);\r
+                }\r
+            }\r
+        } catch (ParseException e) {\r
+            log.debug("Exception occured in addCategories: {}", e.getMessage(), e);\r
+            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    private void addCategories(Resource resource, String category, String subcategory,\r
+            Either<List<CategoryDefinition>, ActionStatus> allResourceCategories,\r
+            Wrapper<ResponseFormat> responseWrapper) {\r
+        Optional<CategoryDefinition> optionalCategory =\r
+                // Stream of all the categories\r
+                allResourceCategories.left().value().stream()\r
+                        // filter in only relevant category\r
+                        .filter(e -> e.getName().equals(category))\r
+                        // get the result\r
+                        .findAny();\r
+        if (!optionalCategory.isPresent()) {\r
+            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(\r
+                    ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));\r
+        } else {\r
+            CategoryDefinition categoryDefinition = optionalCategory.get();\r
+\r
+            List<SubCategoryDefinition> subCaregories =\r
+                    // Stream of all sub-categories of the relevant\r
+                    // category\r
+                    categoryDefinition.getSubcategories().stream()\r
+                            // filter in only relevant sub-category\r
+                            .filter(e -> e.getName().equals(subcategory))\r
+                            // get the result\r
+                            .collect(Collectors.toList());\r
+\r
+            if( subCaregories.isEmpty() ){\r
+                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(\r
+                        ActionStatus.COMPONENT_INVALID_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()));\r
+            }\r
+            else{\r
+                categoryDefinition.setSubcategories(subCaregories);\r
+                resource.setCategories(Arrays.asList(categoryDefinition));\r
+            }\r
+\r
+        }\r
+    }\r
+\r
+\r
+\r
+\r
+\r
+\r
+    private Wrapper<ResponseFormat> runValidations(final String assetType) {\r
+        Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();\r
+\r
+        // Validate X-ECOMP-InstanceID Header\r
+        if (responseWrapper.isEmpty()) {\r
+            String instanceId = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);\r
+            validateXECOMPInstanceIDHeader(instanceId,responseWrapper);\r
+        }\r
+        // Validate USER_ID Header\r
+        if (responseWrapper.isEmpty()) {\r
+            validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER),responseWrapper);\r
+        }\r
+        // Validate assetType\r
+        if (responseWrapper.isEmpty()) {\r
+            if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) &&  !AssetTypeEnum.SERVICES.getValue().equals(assetType)){\r
+                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));\r
+            }\r
+        }\r
+\r
+        return responseWrapper;\r
+    }\r
+\r
+    private Either<LifeCycleTransitionEnum, ResponseFormat> validateTransitionEnum(final String lifecycleTransition, User user) {\r
+        LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT;\r
+        try {\r
+            transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);\r
+        } catch (IllegalArgumentException e) {\r
+            log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e);\r
+            ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE);\r
+            return Either.right(error);\r
+        }\r
+        return Either.left(transitionEnum);\r
+    }\r
+\r
+}\r
index 6f00168..32fb874 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.externalapi.servlet;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.apache.commons.lang3.StringUtils;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo;
-import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionRespInfo;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
-import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
-import org.openecomp.sdc.be.servlets.RepresentationUtils;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-
-/**
- * Created by chaya on 10/17/2017.
- */
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Service Activation External Servlet", description = "This Servlet serves external users for activating a specific service")
-@Singleton
-public class ServiceActivationServlet extends AbstractValidationsServlet {
-
-    @Context
-    private HttpServletRequest request;
-
-    private static final Logger log = Logger.getLogger(ServiceActivationServlet.class);
-    private final ServiceBusinessLogic serviceBusinessLogic;
-
-    @Inject
-    public ServiceActivationServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        ServiceBusinessLogic serviceBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.serviceBusinessLogic = serviceBusinessLogic;
-    }
-
-
-    /**
-     * Activates a service on a specific environment
-     *
-     * @param serviceUUID
-     * @param opEnvId
-     * @param userId
-     * @param instanceIdHeader
-     * @return
-     */
-    @POST
-    @Path("/services/{serviceUUID}/distribution/{opEnvId}/activate")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "activate a service", httpMethod = "POST", notes = "Activates a service")
-    @ApiResponses(value = {
-            @ApiResponse(code = 202, message = "ECOMP component is authenticated and required service may be distributed"),
-            @ApiResponse(code = 400, message = "Missing  X-ECOMP-InstanceID  HTTP header - POL5001"),
-            @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(code = 500, message = "The request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(code = 400, message = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),
-            @ApiResponse(code = 400, message = "Missing request body. The post request did not contain the expected body - SVC4500"),
-            @ApiResponse(code = 400, message = "The resource name is missing in the request body - SVC4062"),
-            @ApiResponse(code = 409, message = "Service state is invalid for this action"),
-            @ApiResponse(code = 502, message = "The server was acting as a gateway or proxy and received an invalid response from the upstream server")})
-    public Response activateServiceExternal(
-            @ApiParam(value = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @ApiParam(value = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @ApiParam(value = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @ApiParam(value = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @ApiParam(value = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @ApiParam(value = "The serviceUUid to activate", required = true) @PathParam("serviceUUID") final String serviceUUID,
-            @ApiParam(value = "The operational environment on which to activate the service on", required = true) @PathParam("opEnvId") final String opEnvId,
-            String data) {
-
-        init();
-
-        ResponseFormat responseFormat = null;
-        String requestURI = request.getRequestURI();
-        String url = request.getMethod() + " " + requestURI;
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-
-        try {
-
-            Wrapper<ResponseFormat> responseWrapper = validateRequestHeaders(instanceIdHeader, userId);
-
-            if (responseWrapper.isEmpty()) {
-                modifier.setUserId(userId);
-                log.debug("modifier id is {}", userId);
-
-                ServiceDistributionReqInfo reqMetadata = convertJsonToActivationMetadata(data);
-                Either<String, ResponseFormat> distResponse = serviceBusinessLogic.activateServiceOnTenantEnvironment(serviceUUID, opEnvId, modifier, reqMetadata);
-
-                if (distResponse.isRight()) {
-                    log.debug("failed to activate service distribution");
-                    responseFormat = distResponse.right().value();
-                    return buildErrorResponse(responseFormat);
-                }
-                String distributionId = distResponse.left().value();
-                Object result = RepresentationUtils.toRepresentation(new ServiceDistributionRespInfo(distributionId));
-                responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.ACCEPTED);
-                return buildOkResponse(responseFormat, result);
-            } else {
-                log.debug("request instanceId/userId header validation failed");
-                responseFormat = responseWrapper.getInnerElement();
-                return buildErrorResponse(responseFormat);
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
-            log.debug("activate distribution failed with exception", e);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-        } finally {
-            getComponentsUtils().auditExternalActivateService(responseFormat,
-                    new DistributionData(instanceIdHeader, requestURI), requestId, serviceUUID, modifier);
-        }
-    }
-
-    private Wrapper<ResponseFormat> validateRequestHeaders(String instanceIdHeader, String userId) {
-        Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
-        if (responseWrapper.isEmpty()) {
-            validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
-        }
-        if (responseWrapper.isEmpty()) {
-            validateHttpCspUserIdHeader(userId, responseWrapper);
-        }
-        return responseWrapper;
-    }
-
-    private ServiceDistributionReqInfo convertJsonToActivationMetadata(String data) {
-        ObjectMapper mapper = new ObjectMapper();
-        try {
-            return mapper.readValue(data, ServiceDistributionReqInfo.class);
-        } catch (IOException e) {
-            log.error("#convertJsonToActivationMetadata - json deserialization failed with error: ", e);
-            return new ServiceDistributionReqInfo(null);
-        }
-    }
-
-    @Override
-    protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) {
-        ResponseFormat responseFormat;
-        if( StringUtils.isEmpty(header)){
-            log.debug("MissingUSER_ID");
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED);
-            responseWrapper.setInnerElement(responseFormat);
-        }
-    }
-}
-
-
-
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.externalapi.servlet;\r
+\r
+import java.io.IOException;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.lang3.StringUtils;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo;\r
+import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionRespInfo;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;\r
+import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;\r
+import org.openecomp.sdc.be.servlets.RepresentationUtils;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.fasterxml.jackson.databind.ObjectMapper;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+/**\r
+ * Created by chaya on 10/17/2017.\r
+ */\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Service Activation External Servlet", description = "This Servlet serves external users for activating a specific service"))\r
+@Singleton\r
+public class ServiceActivationServlet extends AbstractValidationsServlet {\r
+\r
+    @Context\r
+    private HttpServletRequest request;\r
+\r
+    private static final Logger log = Logger.getLogger(ServiceActivationServlet.class);\r
+    private final ServiceBusinessLogic serviceBusinessLogic;\r
+\r
+    @Inject\r
+    public ServiceActivationServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        ServiceBusinessLogic serviceBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.serviceBusinessLogic = serviceBusinessLogic;\r
+    }\r
+\r
+\r
+    /**\r
+     * Activates a service on a specific environment\r
+     *\r
+     * @param serviceUUID\r
+     * @param opEnvId\r
+     * @param userId\r
+     * @param instanceIdHeader\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("/services/{serviceUUID}/distribution/{opEnvId}/activate")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "activate a service", method = "POST", summary = "Activates a service")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "202",\r
+                    description = "ECOMP component is authenticated and required service may be distributed"),\r
+            @ApiResponse(responseCode = "400", description = "Missing  X-ECOMP-InstanceID  HTTP header - POL5001"),\r
+            @ApiResponse(responseCode = "401",\r
+                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),\r
+            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),\r
+            @ApiResponse(responseCode = "404",\r
+                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),\r
+            @ApiResponse(responseCode = "405",\r
+                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),\r
+            @ApiResponse(responseCode = "500",\r
+                    description = "The request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "Missing request body. The post request did not contain the expected body - SVC4500"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "The resource name is missing in the request body - SVC4062"),\r
+            @ApiResponse(responseCode = "409", description = "Service state is invalid for this action"),\r
+            @ApiResponse(responseCode = "502",\r
+                    description = "The server was acting as a gateway or proxy and received an invalid response from the upstream server")})\r
+    public Response activateServiceExternal(\r
+            @Parameter(description = "Determines the format of the body of the request",\r
+                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,\r
+            @Parameter(description = "The user id",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(description = "X-ECOMP-RequestID header",\r
+                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,\r
+            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(\r
+                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,\r
+            @Parameter(description = "Determines the format of the body of the response",\r
+                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,\r
+            @Parameter(description = "The username and password",\r
+                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,\r
+            @Parameter(description = "The serviceUUid to activate",\r
+                    required = true) @PathParam("serviceUUID") final String serviceUUID,\r
+            @Parameter(description = "The operational environment on which to activate the service on",\r
+                    required = true) @PathParam("opEnvId") final String opEnvId,\r
+            String data) {\r
+\r
+        init();\r
+\r
+        ResponseFormat responseFormat = null;\r
+        String requestURI = request.getRequestURI();\r
+        String url = request.getMethod() + " " + requestURI;\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+\r
+        try {\r
+\r
+            Wrapper<ResponseFormat> responseWrapper = validateRequestHeaders(instanceIdHeader, userId);\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                modifier.setUserId(userId);\r
+                log.debug("modifier id is {}", userId);\r
+\r
+                ServiceDistributionReqInfo reqMetadata = convertJsonToActivationMetadata(data);\r
+                Either<String, ResponseFormat> distResponse = serviceBusinessLogic\r
+                        .activateServiceOnTenantEnvironment(serviceUUID, opEnvId, modifier, reqMetadata);\r
+\r
+                if (distResponse.isRight()) {\r
+                    log.debug("failed to activate service distribution");\r
+                    responseFormat = distResponse.right().value();\r
+                    return buildErrorResponse(responseFormat);\r
+                }\r
+                String distributionId = distResponse.left().value();\r
+                Object result = RepresentationUtils.toRepresentation(new ServiceDistributionRespInfo(distributionId));\r
+                responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.ACCEPTED);\r
+                return buildOkResponse(responseFormat, result);\r
+            } else {\r
+                log.debug("request instanceId/userId header validation failed");\r
+                responseFormat = responseWrapper.getInnerElement();\r
+                return buildErrorResponse(responseFormat);\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");\r
+            log.debug("activate distribution failed with exception", e);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        } finally {\r
+            getComponentsUtils().auditExternalActivateService(responseFormat,\r
+                    new DistributionData(instanceIdHeader, requestURI), requestId, serviceUUID, modifier);\r
+        }\r
+    }\r
+\r
+    private Wrapper<ResponseFormat> validateRequestHeaders(String instanceIdHeader, String userId) {\r
+        Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();\r
+        if (responseWrapper.isEmpty()) {\r
+            validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);\r
+        }\r
+        if (responseWrapper.isEmpty()) {\r
+            validateHttpCspUserIdHeader(userId, responseWrapper);\r
+        }\r
+        return responseWrapper;\r
+    }\r
+\r
+    private ServiceDistributionReqInfo convertJsonToActivationMetadata(String data) {\r
+        ObjectMapper mapper = new ObjectMapper();\r
+        try {\r
+            return mapper.readValue(data, ServiceDistributionReqInfo.class);\r
+        } catch (IOException e) {\r
+            log.error("#convertJsonToActivationMetadata - json deserialization failed with error: ", e);\r
+            return new ServiceDistributionReqInfo(null);\r
+        }\r
+    }\r
+\r
+    @Override\r
+    protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) {\r
+        ResponseFormat responseFormat;\r
+        if( StringUtils.isEmpty(header)){\r
+            log.debug("MissingUSER_ID");\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED);\r
+            responseWrapper.setInnerElement(responseFormat);\r
+        }\r
+    }\r
+}\r
+\r
+\r
+\r
index 2583797..c137e6f 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Additional Information Servlet", description = "Additional Information Servlet")
-@Singleton
-public class AdditionalInformationServlet extends BeGenericServlet {
-
-    private static final Logger log = Logger.getLogger(AdditionalInformationServlet.class);
-    private final AdditionalInformationBusinessLogic businessLogic;
-
-    @Inject
-    public AdditionalInformationServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        AdditionalInformationBusinessLogic businessLogic) {
-        super(userBusinessLogic, componentsUtils);
-        this.businessLogic = businessLogic;
-    }
-
-    /**
-     *
-     * @param resourceId
-     * @param data
-     * @param request
-     * @param userUserId
-     * @return
-     */
-    @POST
-    @Path("/resources/{resourceId}/additionalinfo")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Additional information key already exist") })
-    public Response createResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
-            @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {
-
-        return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId, data);
-
-    }
-
-    /**
-     *
-     * @param serviceId
-     * @param data
-     * @param request
-     * @param userUserId
-     * @return
-     */
-    @POST
-    @Path("/services/{serviceId}/additionalinfo")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Additional information key already exist") })
-    public Response createServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
-            @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {
-
-        return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userUserId, data);
-
-    }
-
-    /**
-     *
-     * @param resourceId
-     * @param labelId
-     * @param data
-     * @param request
-     * @param userId
-     * @return
-     */
-    @PUT
-    @Path("/resources/{resourceId}/additionalinfo/{labelId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Additional information key already exist") })
-    public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
-            @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId, data);
-
-    }
-
-    /**
-     *
-     * @param serviceId
-     * @param labelId
-     * @param data
-     * @param request
-     * @param userId
-     * @return
-     */
-    @PUT
-    @Path("/services/{serviceId}/additionalinfo/{labelId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Additional information key already exist") })
-    public Response updateServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
-            @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId, data);
-
-    }
-
-    /**
-     *
-     * @param resourceId
-     * @param labelId
-     * @param request
-     * @param userId
-     * @return
-     */
-    @DELETE
-    @Path("/resources/{resourceId}/additionalinfo/{labelId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Additional information key already exist") })
-    public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
-            @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId);
-
-    }
-
-    /**
-     *
-     * @param serviceId
-     * @param labelId
-     * @param request
-     * @param userId
-     * @return
-     */
-    @DELETE
-    @Path("/services/{serviceId}/additionalinfo/{labelId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Additional information key already exist") })
-    public Response deleteServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
-            @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId);
-
-    }
-
-    /**
-     *
-     * @param resourceId
-     * @param labelId
-     * @param request
-     * @param userId
-     * @return
-     */
-    @GET
-    @Path("/resources/{resourceId}/additionalinfo/{labelId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Additional information key already exist") })
-    public Response getResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
-            @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return getAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId);
-
-    }
-
-    /**
-     *
-     * @param serviceId
-     * @param labelId
-     * @param request
-     * @param userId
-     * @return
-     */
-    @GET
-    @Path("/services/{serviceId}/additionalinfo/{labelId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Additional information key already exist") })
-    public Response getServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
-            @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return getAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId);
-
-    }
-
-    /**
-     *
-     * @param resourceId
-     * @param request
-     * @param userId
-     * @return
-     */
-    @GET
-    @Path("/resources/{resourceId}/additionalinfo")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get all Additional Information under resource", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Additional information key already exist") })
-    public Response getAllResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userId);
-
-    }
-
-    /**
-     *
-     * @param serviceId
-     * @param request
-     * @param userId
-     * @return
-     */
-    @GET
-    @Path("/services/{serviceId}/additionalinfo")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get all Additional Information under service", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Additional information key already exist") })
-    public Response getAllServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userId);
-
-    }
-
-    /**
-     *
-     * Create additional information property under given resource/service
-     *
-     * @param nodeType
-     * @param uniqueId
-     * @param request
-     * @param userId
-     * @param data
-     * @return
-     */
-    protected Response createAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId, String data) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-        log.debug("modifier id is {}", userId);
-        log.debug("data is {}", data);
-
-        try {
-            // convert json to AdditionalInfoParameterInfo
-            AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class);
-
-            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.createAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);
-
-            if (either.isRight()) {
-                ResponseFormat responseFormat = either.right().value();
-                log.info("Failed to create additional information {}. Reason - {}", additionalInfoParameterInfo, responseFormat);
-                return buildErrorResponse(responseFormat);
-            }
-
-            AdditionalInfoParameterInfo createdAI = either.left().value();
-
-            log.debug("Additional information {}={} created successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
-
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
-            return buildOkResponse(responseFormat, createdAI);
-
-        } catch (Exception e) {
-            log.debug("Create additional information failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-        }
-
-    }
-
-    /**
-     * Update additional information property by id under given resource/service
-     *
-     * @param nodeType
-     * @param uniqueId
-     * @param labelId
-     * @param request
-     * @param userId
-     * @param data
-     * @return
-     */
-    protected Response updateAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId, String data) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-        log.debug("modifier id is {}", userId);
-        log.debug("data is {}", data);
-
-        try {
-            // convert json to AdditionalInfoParameterInfo
-            AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class);
-
-            additionalInfoParameterInfo.setUniqueId(labelId);
-
-            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.updateAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);
-
-            if (either.isRight()) {
-                ResponseFormat responseFormat = either.right().value();
-                log.info("Failed to update additional information property. Reason - {}", responseFormat);
-                return buildErrorResponse(responseFormat);
-            }
-
-            AdditionalInfoParameterInfo createdAI = either.left().value();
-
-            log.debug("Additional information {}={} updated successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
-
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-            return buildOkResponse(responseFormat, createdAI);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Additional Information");
-            log.debug("Update additional information failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-        }
-
-    }
-
-    /**
-     *
-     * Delete an additional information property by id under given resource/service
-     *
-     * @param nodeType
-     * @param uniqueId
-     * @param labelId
-     * @param request
-     * @param userId
-     * @return
-     */
-    protected Response deleteAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-        log.debug("modifier id is {}", userId);
-
-        try {
-
-            AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
-            additionalInfoParameterInfo.setUniqueId(labelId);
-
-            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.deleteAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);
-
-            if (either.isRight()) {
-                ResponseFormat responseFormat = either.right().value();
-                log.info("Failed to update additional information property. Reason - {}", responseFormat);
-                return buildErrorResponse(responseFormat);
-            }
-
-            AdditionalInfoParameterInfo createdAI = either.left().value();
-
-            log.debug("Additional information {}={} deleted successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
-
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-            return buildOkResponse(responseFormat, createdAI);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Additional Information");
-            log.debug("Delete additional information failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-        }
-
-    }
-
-    /**
-     * Get a specific additional information property by a given id under given resource/service
-     *
-     * @param nodeType
-     * @param uniqueId
-     * @param labelId
-     * @param request
-     * @param userId
-     * @return
-     */
-    protected Response getAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-        log.debug("modifier id is {}", userId);
-
-        try {
-
-            AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
-            additionalInfoParameterInfo.setUniqueId(labelId);
-
-            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.getAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);
-
-            if (either.isRight()) {
-                ResponseFormat responseFormat = either.right().value();
-                log.info("Failed to update additional information property. Reason - {}", responseFormat);
-                return buildErrorResponse(responseFormat);
-            }
-
-            AdditionalInfoParameterInfo createdAI = either.left().value();
-
-            log.debug("Additional information {}={} fetched successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
-
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-            return buildOkResponse(responseFormat, createdAI);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Additional Information");
-
-            log.debug("get additional information failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-        }
-
-    }
-
-    /**
-     * Get all additional information properties under given resource/service
-     *
-     * @param nodeType
-     * @param uniqueId
-     * @param request
-     * @param userId
-     * @return
-     */
-    protected Response getAllAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-        log.debug("modifier id is {}", userId);
-
-        try {
-            Either<AdditionalInformationDefinition, ResponseFormat> either = businessLogic.getAllAdditionalInformation(nodeType, uniqueId, userId);
-            if (either.isRight()) {
-                ResponseFormat responseFormat = either.right().value();
-                log.info("Failed to update additional information property. Reason - {}", responseFormat);
-                return buildErrorResponse(responseFormat);
-            }
-
-            AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
-
-            log.debug("All Additional information retrieved for component {} is {}", uniqueId, additionalInformationDefinition);
-
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-            return buildOkResponse(responseFormat, additionalInformationDefinition);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Additional Information");
-            log.debug("Get all addiotanl information properties failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-        }
-
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;\r
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.model.AdditionalInformationDefinition;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Additional Information Servlet", description = "Additional Information Servlet"))\r
+@Singleton\r
+public class AdditionalInformationServlet extends BeGenericServlet {\r
+\r
+    private static final Logger log = Logger.getLogger(AdditionalInformationServlet.class);\r
+    private final AdditionalInformationBusinessLogic businessLogic;\r
+\r
+    @Inject\r
+    public AdditionalInformationServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils,\r
+        AdditionalInformationBusinessLogic businessLogic) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.businessLogic = businessLogic;\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param resourceId\r
+     * @param data\r
+     * @param request\r
+     * @param userUserId\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("/resources/{resourceId}/additionalinfo")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create Additional Information Label and Value", method = "POST",\r
+            summary = "Returns created Additional Inforamtion property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Additional information created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})\r
+    public Response createResourceAdditionalInformationLabel(\r
+            @Parameter(description = "resource id to update with new property",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "Additional information key value to be created", required = true) String data,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {\r
+\r
+        return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId,\r
+                data);\r
+\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param serviceId\r
+     * @param data\r
+     * @param request\r
+     * @param userUserId\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("/services/{serviceId}/additionalinfo")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create Additional Information Label and Value", method = "POST",\r
+            summary = "Returns created Additional Inforamtion property",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Additional information created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})\r
+    public Response createServiceAdditionalInformationLabel(\r
+            @Parameter(description = "service id to update with new property",\r
+                    required = true) @PathParam("serviceId") final String serviceId,\r
+            @Parameter(description = "Additional information key value to be created", required = true) String data,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {\r
+\r
+        return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userUserId, data);\r
+\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param resourceId\r
+     * @param labelId\r
+     * @param data\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @PUT\r
+    @Path("/resources/{resourceId}/additionalinfo/{labelId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Additional Information Label and Value", method = "PUT",\r
+            summary = "Returns updated Additional Inforamtion property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Additional information updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})\r
+    public Response updateResourceAdditionalInformationLabel(\r
+            @Parameter(description = "resource id to update with new property",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,\r
+            @Parameter(description = "Additional information key value to be created", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId,\r
+                data);\r
+\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param serviceId\r
+     * @param labelId\r
+     * @param data\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @PUT\r
+    @Path("/services/{serviceId}/additionalinfo/{labelId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Additional Information Label and Value", method = "PUT",\r
+            summary = "Returns updated Additional Inforamtion property",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Additional information updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})\r
+    public Response updateServiceAdditionalInformationLabel(\r
+            @Parameter(description = "service id to update with new property",\r
+                    required = true) @PathParam("serviceId") final String serviceId,\r
+            @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,\r
+            @Parameter(description = "Additional information key value to be created", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId,\r
+                data);\r
+\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param resourceId\r
+     * @param labelId\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @DELETE\r
+    @Path("/resources/{resourceId}/additionalinfo/{labelId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create Additional Information Label and Value", method = "DELETE",\r
+            summary = "Returns deleted Additional Inforamtion property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Additional information deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})\r
+    public Response updateResourceAdditionalInformationLabel(\r
+            @Parameter(description = "resource id to update with new property",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request,\r
+                userId);\r
+\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param serviceId\r
+     * @param labelId\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @DELETE\r
+    @Path("/services/{serviceId}/additionalinfo/{labelId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create Additional Information Label and Value", method = "DELETE",\r
+            summary = "Returns deleted Additional Inforamtion property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Additional information deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})\r
+    public Response deleteServiceAdditionalInformationLabel(\r
+            @Parameter(description = "service id to update with new property",\r
+                    required = true) @PathParam("serviceId") final String serviceId,\r
+            @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId);\r
+\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param resourceId\r
+     * @param labelId\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/resources/{resourceId}/additionalinfo/{labelId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get Additional Information by id", method = "GET",\r
+            summary = "Returns Additional Inforamtion property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "fetched additional information"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})\r
+    public Response getResourceAdditionalInformationLabel(\r
+            @Parameter(description = "resource id to update with new property",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return getAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId);\r
+\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param serviceId\r
+     * @param labelId\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/services/{serviceId}/additionalinfo/{labelId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get Additional Information by id", method = "GET",\r
+            summary = "Returns Additional Inforamtion property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "fetched additional information"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})\r
+    public Response getServiceAdditionalInformationLabel(\r
+            @Parameter(description = "service id to update with new property",\r
+                    required = true) @PathParam("serviceId") final String serviceId,\r
+            @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return getAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId);\r
+\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param resourceId\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/resources/{resourceId}/additionalinfo")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get all Additional Information under resource", method = "GET",\r
+            summary = "Returns Additional Inforamtion property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "list of additional information"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})\r
+    public Response getAllResourceAdditionalInformationLabel(\r
+            @Parameter(description = "resource id to update with new property",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userId);\r
+\r
+    }\r
+\r
+    /**\r
+     *\r
+     * @param serviceId\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @GET\r
+    @Path("/services/{serviceId}/additionalinfo")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get all Additional Information under service", method = "GET",\r
+            summary = "Returns Additional Inforamtion property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "list of additional information"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})\r
+    public Response getAllServiceAdditionalInformationLabel(\r
+            @Parameter(description = "service id to update with new property",\r
+                    required = true) @PathParam("serviceId") final String serviceId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userId);\r
+\r
+    }\r
+\r
+    /**\r
+     *\r
+     * Create additional information property under given resource/service\r
+     *\r
+     * @param nodeType\r
+     * @param uniqueId\r
+     * @param request\r
+     * @param userId\r
+     * @param data\r
+     * @return\r
+     */\r
+    protected Response createAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId, String data) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        log.debug("modifier id is {}", userId);\r
+        log.debug("data is {}", data);\r
+\r
+        try {\r
+            // convert json to AdditionalInfoParameterInfo\r
+            AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class);\r
+\r
+            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.createAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);\r
+\r
+            if (either.isRight()) {\r
+                ResponseFormat responseFormat = either.right().value();\r
+                log.info("Failed to create additional information {}. Reason - {}", additionalInfoParameterInfo, responseFormat);\r
+                return buildErrorResponse(responseFormat);\r
+            }\r
+\r
+            AdditionalInfoParameterInfo createdAI = either.left().value();\r
+\r
+            log.debug("Additional information {}={} created successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());\r
+\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);\r
+            return buildOkResponse(responseFormat, createdAI);\r
+\r
+        } catch (Exception e) {\r
+            log.debug("Create additional information failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * Update additional information property by id under given resource/service\r
+     *\r
+     * @param nodeType\r
+     * @param uniqueId\r
+     * @param labelId\r
+     * @param request\r
+     * @param userId\r
+     * @param data\r
+     * @return\r
+     */\r
+    protected Response updateAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId, String data) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        log.debug("modifier id is {}", userId);\r
+        log.debug("data is {}", data);\r
+\r
+        try {\r
+            // convert json to AdditionalInfoParameterInfo\r
+            AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class);\r
+\r
+            additionalInfoParameterInfo.setUniqueId(labelId);\r
+\r
+            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.updateAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);\r
+\r
+            if (either.isRight()) {\r
+                ResponseFormat responseFormat = either.right().value();\r
+                log.info("Failed to update additional information property. Reason - {}", responseFormat);\r
+                return buildErrorResponse(responseFormat);\r
+            }\r
+\r
+            AdditionalInfoParameterInfo createdAI = either.left().value();\r
+\r
+            log.debug("Additional information {}={} updated successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());\r
+\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+            return buildOkResponse(responseFormat, createdAI);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Additional Information");\r
+            log.debug("Update additional information failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     *\r
+     * Delete an additional information property by id under given resource/service\r
+     *\r
+     * @param nodeType\r
+     * @param uniqueId\r
+     * @param labelId\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    protected Response deleteAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        try {\r
+\r
+            AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();\r
+            additionalInfoParameterInfo.setUniqueId(labelId);\r
+\r
+            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.deleteAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);\r
+\r
+            if (either.isRight()) {\r
+                ResponseFormat responseFormat = either.right().value();\r
+                log.info("Failed to update additional information property. Reason - {}", responseFormat);\r
+                return buildErrorResponse(responseFormat);\r
+            }\r
+\r
+            AdditionalInfoParameterInfo createdAI = either.left().value();\r
+\r
+            log.debug("Additional information {}={} deleted successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());\r
+\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+            return buildOkResponse(responseFormat, createdAI);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Additional Information");\r
+            log.debug("Delete additional information failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * Get a specific additional information property by a given id under given resource/service\r
+     *\r
+     * @param nodeType\r
+     * @param uniqueId\r
+     * @param labelId\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    protected Response getAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        try {\r
+\r
+            AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();\r
+            additionalInfoParameterInfo.setUniqueId(labelId);\r
+\r
+            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.getAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);\r
+\r
+            if (either.isRight()) {\r
+                ResponseFormat responseFormat = either.right().value();\r
+                log.info("Failed to update additional information property. Reason - {}", responseFormat);\r
+                return buildErrorResponse(responseFormat);\r
+            }\r
+\r
+            AdditionalInfoParameterInfo createdAI = either.left().value();\r
+\r
+            log.debug("Additional information {}={} fetched successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());\r
+\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+            return buildOkResponse(responseFormat, createdAI);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Additional Information");\r
+\r
+            log.debug("get additional information failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * Get all additional information properties under given resource/service\r
+     *\r
+     * @param nodeType\r
+     * @param uniqueId\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    protected Response getAllAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        try {\r
+            Either<AdditionalInformationDefinition, ResponseFormat> either = businessLogic.getAllAdditionalInformation(nodeType, uniqueId, userId);\r
+            if (either.isRight()) {\r
+                ResponseFormat responseFormat = either.right().value();\r
+                log.info("Failed to update additional information property. Reason - {}", responseFormat);\r
+                return buildErrorResponse(responseFormat);\r
+            }\r
+\r
+            AdditionalInformationDefinition additionalInformationDefinition = either.left().value();\r
+\r
+            log.debug("All Additional information retrieved for component {} is {}", uniqueId, additionalInformationDefinition);\r
+\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+            return buildOkResponse(responseFormat, additionalInformationDefinition);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Additional Information");\r
+            log.debug("Get all addiotanl information properties failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+    }\r
+\r
+}\r
index 423181a..3dd582c 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ArchiveBusinessLogic;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.catalog.CatalogComponent;
-import org.openecomp.sdc.common.api.Constants;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestBody;
-
-import javax.ws.rs.*;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Archive Endpoint")
-@Controller
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-public class ArchiveEndpoint {
-
-    private final ArchiveBusinessLogic archiveBusinessLogic;
-
-    @Inject
-    public ArchiveEndpoint(ArchiveBusinessLogic archiveBusinessLogic) {
-        this.archiveBusinessLogic = archiveBusinessLogic;
-    }
-
-    @POST
-    @Path("/resources/{componentId}/archive")
-    @ApiOperation(value = "Archive Resource", httpMethod = "POST", notes = "Marks a resource as archived. Can be restored with restore action", response = String.class, responseContainer = "")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Archive successful"),
-            @ApiResponse(code = 400, message = "Bad request"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Resource not found"),
-            @ApiResponse(code = 500, message = "Internal Error")
-    })
-    public Response archiveResources(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        archiveBusinessLogic.archiveComponent(ComponentTypeEnum.RESOURCE_PARAM_NAME, userId, componentId);
-        return Response.ok().build();
-    }
-
-    @POST
-    @Path("/resources/{componentId}/restore")
-    @ApiOperation(value = "Restore Resource", httpMethod = "POST", notes = "Restores a resource from archive.", response = String.class, responseContainer = "")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Restore successful"),
-            @ApiResponse(code = 400, message = "Bad request"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Resource not found"),
-            @ApiResponse(code = 500, message = "Internal Error")
-    })
-    public Response restoreResource(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        archiveBusinessLogic.restoreComponent(ComponentTypeEnum.RESOURCE_PARAM_NAME, userId, componentId);
-        return Response.ok().build();
-    }
-
-    @POST
-    @Path("/services/{componentId}/archive")
-    @ApiOperation(value = "Archive Service", httpMethod = "POST", notes = "Marks a service as archived. Can be restored with restore action", response = String.class, responseContainer = "")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Archive successful"),
-            @ApiResponse(code = 400, message = "Bad request"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Service not found"),
-            @ApiResponse(code = 500, message = "Internal Error")
-    })
-    public Response archiveService(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        archiveBusinessLogic.archiveComponent(ComponentTypeEnum.SERVICE_PARAM_NAME, userId, componentId);
-        return Response.ok().build();
-    }
-
-
-    @POST
-    @Path("/services/{componentId}/restore")
-    @ApiOperation(value = "Restore Service", httpMethod = "POST", notes = "Restores a service from archive.", response = String.class, responseContainer = "")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Restore successful"),
-            @ApiResponse(code = 400, message = "Bad request"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Service not found"),
-            @ApiResponse(code = 500, message = "Internal Error")
-    })
-    public Response restoreService(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        archiveBusinessLogic.restoreComponent(ComponentTypeEnum.SERVICE_PARAM_NAME, userId, componentId);
-        return Response.ok().build();
-    }
-
-    @GET
-    @Path("/archive")
-    @ApiOperation(value = "Get all Archived Components", httpMethod = "GET", notes = "Get all Archived Components", response = String.class, responseContainer = "")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Success"),
-            @ApiResponse(code = 400, message = "Bad request"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 500, message = "Internal Error")
-    })
-    public Map<String, List<CatalogComponent>> getArchivedComponents(@HeaderParam(value = Constants.USER_ID_HEADER) String userId){
-        return this.archiveBusinessLogic.getArchiveComponents(userId, new LinkedList<>());
-    }
-
-    @POST
-    @Path("/notif/vsp/archived")
-    @ApiOperation(value = "Notify about an archived VSP. All VFs with relation to the given CSAR IDs will be martked as vspArchived=true", httpMethod = "POST")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Success"),
-            @ApiResponse(code = 400, message = "Bad request"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 500, message = "Internal Error. A list of the failed CSAR IDs may be returned.")
-    })
-    public Response onVspArchived(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @RequestBody List<String> csarIds){
-        List<String> failedCsarIds = this.archiveBusinessLogic.onVspArchive(userId, csarIds);
-        if (!failedCsarIds.isEmpty()){
-            //There are some failed CSAR IDs, return 500 and the list of failed CSAR IDs
-            Map<String, List<String>> entity = new HashMap<>();
-            entity.put("failedIds", failedCsarIds);
-            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
-                    .entity(entity)
-                    .build();
-        }
-        return Response.ok().build();
-    }
-
-    @POST
-    @Path("/notif/vsp/restored")
-    @ApiOperation(value = "Notify about a restored VSP. All VFs with relation to the given CSAR IDs will be martked as vspArchived=false", httpMethod = "POST")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Success"),
-            @ApiResponse(code = 400, message = "Bad request"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 500, message = "Internal Error. A list of the failed CSAR IDs may be returned.")
-    })
-    public Response onVspRestored(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @RequestBody List<String> csarIds){
-        List<String> failedCsarIds = this.archiveBusinessLogic.onVspRestore(userId, csarIds);
-        if (!failedCsarIds.isEmpty()){
-            //There are some failed CSAR IDs, return 500 and the list of failed CSAR IDs
-            Map<String, List<String>> entity = new HashMap<>();
-            entity.put("failedIds", failedCsarIds);
-            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
-                    .entity(entity)
-                    .build();
-        }
-        return Response.ok().build();
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import com.jcabi.aspects.Loggable;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import javax.inject.Inject;\r
+import org.openecomp.sdc.be.components.impl.ArchiveBusinessLogic;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.model.catalog.CatalogComponent;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.springframework.stereotype.Controller;\r
+import org.springframework.web.bind.annotation.RequestBody;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+import javax.ws.rs.*;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import java.util.HashMap;\r
+import java.util.LinkedList;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Archive Endpoint"))\r
+@Controller\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+public class ArchiveEndpoint {\r
+\r
+    private final ArchiveBusinessLogic archiveBusinessLogic;\r
+\r
+    @Inject\r
+    public ArchiveEndpoint(ArchiveBusinessLogic archiveBusinessLogic) {\r
+        this.archiveBusinessLogic = archiveBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Path("/resources/{componentId}/archive")\r
+    @Operation(description = "Archive Resource", method = "POST", summary = "Marks a resource as archived. Can be restored with restore action", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Archive successful"),\r
+            @ApiResponse(responseCode = "400", description = "Bad request"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Resource not found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Error")\r
+    })\r
+    public Response archiveResources(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        archiveBusinessLogic.archiveComponent(ComponentTypeEnum.RESOURCE_PARAM_NAME, userId, componentId);\r
+        return Response.ok().build();\r
+    }\r
+\r
+    @POST\r
+    @Path("/resources/{componentId}/restore")\r
+    @Operation(description = "Restore Resource", method = "POST", summary = "Restores a resource from archive.", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Restore successful"),\r
+            @ApiResponse(responseCode = "400", description = "Bad request"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Resource not found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Error")\r
+    })\r
+    public Response restoreResource(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        archiveBusinessLogic.restoreComponent(ComponentTypeEnum.RESOURCE_PARAM_NAME, userId, componentId);\r
+        return Response.ok().build();\r
+    }\r
+\r
+    @POST\r
+    @Path("/services/{componentId}/archive")\r
+    @Operation(description = "Archive Service", method = "POST", summary = "Marks a service as archived. Can be restored with restore action",responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Archive successful"),\r
+            @ApiResponse(responseCode = "400", description = "Bad request"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Service not found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Error")\r
+    })\r
+    public Response archiveService(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        archiveBusinessLogic.archiveComponent(ComponentTypeEnum.SERVICE_PARAM_NAME, userId, componentId);\r
+        return Response.ok().build();\r
+    }\r
+\r
+\r
+    @POST\r
+    @Path("/services/{componentId}/restore")\r
+    @Operation(description = "Restore Service", method = "POST", summary = "Restores a service from archive.", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Restore successful"),\r
+            @ApiResponse(responseCode = "400", description = "Bad request"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Service not found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Error")\r
+    })\r
+    public Response restoreService(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        archiveBusinessLogic.restoreComponent(ComponentTypeEnum.SERVICE_PARAM_NAME, userId, componentId);\r
+        return Response.ok().build();\r
+    }\r
+\r
+    @GET\r
+    @Path("/archive")\r
+    @Operation(description = "Get all Archived Components", method = "GET", summary = "Get all Archived Components", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Success"),\r
+            @ApiResponse(responseCode = "400", description = "Bad request"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Error")\r
+    })\r
+    public Map<String, List<CatalogComponent>> getArchivedComponents(@HeaderParam(value = Constants.USER_ID_HEADER) String userId){\r
+        return this.archiveBusinessLogic.getArchiveComponents(userId, new LinkedList<>());\r
+    }\r
+\r
+    @POST\r
+    @Path("/notif/vsp/archived")\r
+    @Operation(description = "Notify about an archived VSP. All VFs with relation to the given CSAR IDs will be martked as vspArchived=true", method = "POST")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Success"),\r
+            @ApiResponse(responseCode = "400", description = "Bad request"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Error. A list of the failed CSAR IDs may be returned.")\r
+    })\r
+    public Response onVspArchived(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @RequestBody List<String> csarIds){\r
+        List<String> failedCsarIds = this.archiveBusinessLogic.onVspArchive(userId, csarIds);\r
+        if (!failedCsarIds.isEmpty()){\r
+            //There are some failed CSAR IDs, return 500 and the list of failed CSAR IDs\r
+            Map<String, List<String>> entity = new HashMap<>();\r
+            entity.put("failedIds", failedCsarIds);\r
+            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)\r
+                    .entity(entity)\r
+                    .build();\r
+        }\r
+        return Response.ok().build();\r
+    }\r
+\r
+    @POST\r
+    @Path("/notif/vsp/restored")\r
+    @Operation(description = "Notify about a restored VSP. All VFs with relation to the given CSAR IDs will be martked as vspArchived=false", method = "POST")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Success"),\r
+            @ApiResponse(responseCode = "400", description = "Bad request"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Error. A list of the failed CSAR IDs may be returned.")\r
+    })\r
+    public Response onVspRestored(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @RequestBody List<String> csarIds){\r
+        List<String> failedCsarIds = this.archiveBusinessLogic.onVspRestore(userId, csarIds);\r
+        if (!failedCsarIds.isEmpty()){\r
+            //There are some failed CSAR IDs, return 500 and the list of failed CSAR IDs\r
+            Map<String, List<String>> entity = new HashMap<>();\r
+            entity.put("failedIds", failedCsarIds);\r
+            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)\r
+                    .entity(entity)\r
+                    .build();\r
+        }\r
+        return Response.ok().build();\r
+    }\r
+\r
+}\r
index ce7df4c..2b55ffa 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.Map;
-
-/**
- * Root resource (exposed at "/" path)
- */
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Resource Artifact Servlet", description = "Resource Artifact Servlet")
-@Singleton
-public class ArtifactServlet extends BeGenericServlet {
-
-    private final ArtifactsBusinessLogic artifactsBusinessLogic;
-
-    @Inject
-    public ArtifactServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils, ArtifactsBusinessLogic artifactsBusinessLogic) {
-        super(userBusinessLogic, componentsUtils);
-        this.artifactsBusinessLogic = artifactsBusinessLogic;
-    }
-
-    private static final Logger log = Logger.getLogger(ArtifactServlet.class);
-
-    // *************** Resources
-    @POST
-    @Path("/resources/{resourceId}/artifacts")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Artifact already exist") })
-    public Response loadArtifact(@PathParam("resourceId") final String resourceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifact");
-            log.debug("loadArtifact unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/resources/{resourceId}/artifacts/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleUpdateRequest(data, request, resourceId, artifactId, ComponentTypeEnum.RESOURCE);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifact");
-            log.debug("updateArtifact unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @DELETE
-    @Path("/resources/{resourceId}/artifacts/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response deleteArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, null, null);
-        } catch (Exception e) {
-            log.debug("deleteArtifact unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    // *************** Services
-    @POST
-    @Path("/services/{serviceId}/artifacts")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Artifact already exist") })
-    public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleUploadRequest(data, request, serviceId, ComponentTypeEnum.SERVICE);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadInformationArtifact");
-            log.debug("loadInformationArtifact unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/services/{serviceId}/artifacts/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateInformationArtifact");
-            log.debug("updateInformationArtifact unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    // *************** Services api artifacts
-    @POST
-    @Path("/services/{serviceId}/artifacts/api/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Api Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Api Artifact Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateApiArtifact");
-            log.debug("updateApiArtifact unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @DELETE
-    @Path("/services/{serviceId}/artifacts/api/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Delete Api Artifact", httpMethod = "DELETE", notes = "Returns Deleted ArtifactDefinition", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 204, message = "Api Artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation") })
-    public Response deleteApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteApiArtifact");
-            log.debug("deleteApiArtifact unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @DELETE
-    @Path("/services/{serviceId}/artifacts/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteInformationalArtifact");
-            log.debug("deleteInformationalArtifact unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    /*
-     * DOWNLOAD Artifacts by json body in base 64 (because of userId problem with href)
-     */
-
-    @GET
-    @Path("/services/{serviceId}/artifacts/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Download service Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Service artifact downloaded"), @ApiResponse(code = 404, message = "Service/Artifact not found") })
-    public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64");
-            log.debug("downloadServiceArtifactBase64 unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @GET
-    @Path("/resources/{resourceId}/artifacts/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Download resource Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource artifact downloaded"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
-    public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleDownloadRequest(request, resourceId, artifactId, null, ComponentTypeEnum.RESOURCE, null);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64");
-            log.debug("downloadResourceArtifactBase64 unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @GET
-    @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifacts/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Download component Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "ResourceInstance artifact downloaded"), @ApiResponse(code = 404, message = "ResourceInstance/Artifact not found") })
-    public Response downloadResourceInstanceArtifactBase64(
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
-            log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    // *************** Resource lifecycle ( interfces )
-
-    @POST
-    @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Artifact and Attach to interface", httpMethod = "POST", notes = "Returns created resource", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Artifact already exist") })
-    public Response loadArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @ApiParam(value = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.CREATE, null, null);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface");
-            log.debug("loadArtifactToInterface unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    @DELETE
-    @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "delete Artifact from interface", httpMethod = "delete", notes = "delete matching artifact from interface", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Artifact already exist") })
-    public Response deleteArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId,
-            @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, interfaceType, operation);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteArtifactToInterface");
-            log.debug("deleteArtifactToInterface unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "update Artifact  Attach to interface", httpMethod = "post", notes = "updates artifact by interface", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Artifact already exist") })
-    public Response updateArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @Context final HttpServletRequest request,
-            @ApiParam(value = "json describe the artifact", required = true) String data) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.UPDATE, null, null);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface");
-            log.debug("updateArtifactToInterface unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}/heatParams")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Resource Instance HEAT_ENV parameters", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateRIArtifact(
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId,
-            @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact");
-            log.debug("updateRIArtifact unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId,
-            @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType);
-        } catch (Exception e) {
-            log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Load Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response loadComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.CREATE, componentId, containerComponentType);
-        } catch (Exception e) {
-            log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @DELETE
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Delete Resource Instance artifact", httpMethod = "POST", notes = "Returns deleted artifact", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response deleteComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId,
-            @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId);
-        } catch (Exception e) {
-            log.debug("deleteArtifact unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-
-    @GET
-    @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
-    public Response getComponentArtifacts(
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleGetArtifactsRequest(request, componentId, null, artifactGroupType, containerComponentType);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
-            log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @GET
-    @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifactsByType/{artifactGroupType}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
-    public Response getComponentInstanceArtifacts(
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,  @PathParam("componentInstanceId") final String componentInstanceId,  @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        try {
-            return handleGetArtifactsRequest(request,componentInstanceId , componentId, artifactGroupType, containerComponentType);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
-            log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-
-    @POST
-    @Path("/{assetType}/{uuid}/interfaces/{interfaceUUID}/operations/{operationUUID}/artifacts/{artifactUUID}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "uploads of artifact to component operation workflow", httpMethod = "POST", notes = "uploads of artifact to component operation workflow")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class),
-            @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
-            @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"),
-            @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(code = 400, message = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
-    @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
-    public Response uploadInterfaceOperationArtifact(
-            @ApiParam(value = "Asset type") @PathParam("assetType") String assetType,
-            @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
-            @ApiParam(value = "The uuid of the interface", required = true)@PathParam("interfaceUUID") final String interfaceUUID,
-            @ApiParam(value = "The uuid of the operation", required = true)@PathParam("operationUUID") final String operationUUID,
-            @ApiParam(value = "The uuid of the artifact", required = true)@PathParam("artifactUUID") final String artifactUUID,
-            @ApiParam( hidden = true) String data,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
-            @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-
-        try {
-            Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither =
-                artifactsBusinessLogic.updateArtifactOnInterfaceOperationByResourceUUID(data, request,
-                            ComponentTypeEnum.findByParamName(assetType), uuid, interfaceUUID, operationUUID, artifactUUID,
-                            new ResourceCommonInfo(assetType), artifactsBusinessLogic.new ArtifactOperationInfo(true,
-                                    false, ArtifactOperationEnum.UPDATE));
-            if (uploadArtifactEither.isRight()) {
-                log.debug("failed to update artifact");
-                return buildErrorResponse(uploadArtifactEither.right().value());
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uploadArtifactEither.left().value());
-        }
-        catch (Exception e) {
-            final String message = "failed to update artifact on a resource or service";
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
-            log.debug(message, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    // ////////// API END ///////////////////////////
-
-    // ************ private *********************
-
-    private Response handleUploadRequest(String data, HttpServletRequest request, String componentId, ComponentTypeEnum componentType) {
-        return handleArtifactRequest(data, componentId, null, componentType, ArtifactOperationEnum.CREATE);
-    }
-
-    private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) {
-        return handleArtifactRequest(data, componentId, artifactId, componentType, ArtifactOperationEnum.UPDATE);
-    }
-
-    private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) {
-        String userId = request.getHeader(Constants.USER_ID_HEADER);
-        ServletContext context = request.getSession().getServletContext();
-        Either<ImmutablePair<String, byte[]>, ResponseFormat> actionResult = artifactsBusinessLogic
-            .handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType);
-
-        Response response;
-        if (actionResult.isRight()) {
-            response = buildErrorResponse(actionResult.right().value());
-        } else {
-            byte[] file = actionResult.left().value().getRight();
-            String base64Contents = new String(Base64.encodeBase64(file));
-            String artifactName = actionResult.left().value().getLeft();
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-            ArtifactUiDownloadData artifactUiDownloadData = new ArtifactUiDownloadData();
-            artifactUiDownloadData.setArtifactName(artifactName);
-            artifactUiDownloadData.setBase64Contents(base64Contents);
-            response = buildOkResponse(responseFormat, artifactUiDownloadData);
-        }
-        return response;
-    }
-
-    private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) {
-        String userId = request.getHeader(Constants.USER_ID_HEADER);
-        ComponentTypeEnum componentTypeEnum  = parentId == null || parentId.isEmpty()? ComponentTypeEnum.findByParamName(containerComponentType): ComponentTypeEnum.RESOURCE_INSTANCE;
-        Either<Map<String, ArtifactDefinition>, ResponseFormat> actionResult = artifactsBusinessLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId);
-
-        Response response;
-        if (actionResult.isRight()) {
-            response = buildErrorResponse(actionResult.right().value());
-        } else {
-
-            response =  buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult.left().value());
-        }
-
-        return response;
-    }
-
-
-    private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) {
-        return handleDeleteRequest(request, componentId, artifactId, componentType, interfaceType, operationName, null);
-    }
-
-    private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName, String parentId) {
-        String userId = request.getHeader(Constants.USER_ID_HEADER);
-        ServletContext context = request.getSession().getServletContext();
-        Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsBusinessLogic.handleArtifactRequest(componentId, userId, componentType, artifactsBusinessLogic.new ArtifactOperationInfo (false, false, ArtifactOperationEnum.DELETE), artifactId, null, null, null, interfaceType, operationName,
-                parentId, null);
-        Response response;
-        if (actionResult.isRight()) {
-            response = buildErrorResponse(actionResult.right().value());
-        } else {
-            Either<ArtifactDefinition, Operation> result = actionResult.left().value();
-            if (result.isLeft()) {
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value());
-            } else {
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value());
-            }
-        }
-        return response;
-
-    }
-
-    private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId,
-            String containerComponentType) {
-        ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
-        String origMd5 = request.getHeader(Constants.MD5_HEADER);
-
-        String userId = request.getHeader(Constants.USER_ID_HEADER);
-
-        Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsBusinessLogic.handleArtifactRequest(componentId, userId, componentType,
-            artifactsBusinessLogic.new ArtifactOperationInfo (false, false,operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId,
-                containerComponentType);
-        Response response;
-        if (actionResult.isRight()) {
-            response = buildErrorResponse(actionResult.right().value());
-        } else {
-            Either<ArtifactDefinition, Operation> result = actionResult.left().value();
-            if (result.isLeft()) {
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value());
-            } else {
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value());
-            }
-        }
-        return response;
-
-    }
-
-    private Response handleArtifactRequest(String data, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) {
-        return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null);
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.Map;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.codec.binary.Base64;\r
+import org.apache.commons.lang3.tuple.ImmutablePair;\r
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.model.ArtifactDefinition;\r
+import org.openecomp.sdc.be.model.ArtifactUiDownloadData;\r
+import org.openecomp.sdc.be.model.Operation;\r
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+/**\r
+ * Root resource (exposed at "/" path)\r
+ */\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Resource Artifact Servlet", description = "Resource Artifact Servlet"))\r
+@Singleton\r
+public class ArtifactServlet extends BeGenericServlet {\r
+\r
+    private final ArtifactsBusinessLogic artifactsBusinessLogic;\r
+\r
+    @Inject\r
+    public ArtifactServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils, ArtifactsBusinessLogic artifactsBusinessLogic) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.artifactsBusinessLogic = artifactsBusinessLogic;\r
+    }\r
+\r
+    private static final Logger log = Logger.getLogger(ArtifactServlet.class);\r
+\r
+    // *************** Resources\r
+    @POST\r
+    @Path("/resources/{resourceId}/artifacts")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Create Artifact", method = "POST", summary = "Returns created ArtifactDefinition",\r
+            responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Artifact already exist")})\r
+    public Response loadArtifact(@PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "json describe the artifact", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifact");\r
+            log.debug("loadArtifact unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/resources/{resourceId}/artifacts/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Update Artifact", method = "POST", summary = "Returns updated artifact",\r
+            responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateArtifact(@PathParam("resourceId") final String resourceId,\r
+            @PathParam("artifactId") final String artifactId,\r
+            @Parameter(description = "json describe the artifact", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}" , url);\r
+        try {\r
+            return handleUpdateRequest(data, request, resourceId, artifactId, ComponentTypeEnum.RESOURCE);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifact");\r
+            log.debug("updateArtifact unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/resources/{resourceId}/artifacts/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Delete Artifact", method = "DELETE",\r
+            summary = "Returns delete artifact", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response deleteArtifact(@PathParam("resourceId") final String resourceId,\r
+            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}" , url);\r
+        try {\r
+            return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, null, null);\r
+        } catch (Exception e) {\r
+            log.debug("deleteArtifact unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    // *************** Services\r
+    @POST\r
+    @Path("/services/{serviceId}/artifacts")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Create Artifact", method = "POST",\r
+            summary = "Returns created ArtifactDefinition", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Artifact already exist")})\r
+    public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId,\r
+            @Parameter(description = "json describe the artifact", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleUploadRequest(data, request, serviceId, ComponentTypeEnum.SERVICE);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadInformationArtifact");\r
+            log.debug("loadInformationArtifact unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/services/{serviceId}/artifacts/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Update Artifact", method = "POST",\r
+            summary = "Returns updated artifact", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Service artifact created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId,\r
+            @PathParam("artifactId") final String artifactId,\r
+            @Parameter(description = "json describe the artifact", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateInformationArtifact");\r
+            log.debug("updateInformationArtifact unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    // *************** Services api artifacts\r
+    @POST\r
+    @Path("/services/{serviceId}/artifacts/api/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Update Api Artifact", method = "POST",\r
+            summary = "Returns created ArtifactDefinition", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Api Artifact Updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateApiArtifact(@PathParam("serviceId") final String serviceId,\r
+            @PathParam("artifactId") final String artifactId,\r
+            @Parameter(description = "json describe the artifact", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateApiArtifact");\r
+            log.debug("updateApiArtifact unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/services/{serviceId}/artifacts/api/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Delete Api Artifact", method = "DELETE",\r
+            summary = "Returns Deleted ArtifactDefinition", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Api Artifact deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation")})\r
+    public Response deleteApiArtifact(@PathParam("serviceId") final String serviceId,\r
+            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteApiArtifact");\r
+            log.debug("deleteApiArtifact unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/services/{serviceId}/artifacts/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Delete Artifact", method = "DELETE",\r
+            summary = "Returns delete artifact", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Service artifact deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId,\r
+            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteInformationalArtifact");\r
+            log.debug("deleteInformationalArtifact unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    /*\r
+     * DOWNLOAD Artifacts by json body in base 64 (because of userId problem with href)\r
+     */\r
+\r
+    @GET\r
+    @Path("/services/{serviceId}/artifacts/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Download service Artifact in Base64", method = "GET",\r
+            summary = "Returns downloaded artifact", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service artifact downloaded"),\r
+            @ApiResponse(responseCode = "404", description = "Service/Artifact not found")})\r
+    public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId,\r
+            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64");\r
+            log.debug("downloadServiceArtifactBase64 unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/resources/{resourceId}/artifacts/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Download resource Artifact in Base64", method = "GET",\r
+            summary = "Returns downloaded artifact", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource artifact downloaded"),\r
+            @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")})\r
+    public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId,\r
+            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleDownloadRequest(request, resourceId, artifactId, null, ComponentTypeEnum.RESOURCE, null);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64");\r
+            log.debug("downloadResourceArtifactBase64 unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifacts/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Download component Artifact in Base64", method = "GET",\r
+            summary = "Returns downloaded artifact", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "ResourceInstance artifact downloaded"),\r
+            @ApiResponse(responseCode = "404", description = "ResourceInstance/Artifact not found")})\r
+    public Response downloadResourceInstanceArtifactBase64(@Parameter(\r
+            description = "valid values: resources / services",\r
+            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                     ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleDownloadRequest(request, componentInstanceId, artifactId, componentId,\r
+                    ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");\r
+            log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    // *************** Resource lifecycle ( interfces )\r
+\r
+    @POST\r
+    @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Create Artifact and Attach to interface", method = "POST",\r
+            summary = "Returns created resource", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Artifact already exist")})\r
+    public Response loadArtifactToInterface(@PathParam("resourceId") final String resourceId,\r
+            @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @HeaderParam(value = Constants.MD5_HEADER) String origMd5,\r
+            @Parameter(description = "json describe the artifact", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null,\r
+                    ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.CREATE, null, null);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface");\r
+            log.debug("loadArtifactToInterface unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "delete Artifact from interface", method = "delete",\r
+            summary = "delete matching artifact from interface", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "delete artifact under interface deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Artifact already exist")})\r
+    public Response deleteArtifactToInterface(@PathParam("resourceId") final String resourceId,\r
+            @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation,\r
+            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, interfaceType,\r
+                    operation);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteArtifactToInterface");\r
+            log.debug("deleteArtifactToInterface unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "update Artifact  Attach to interface", method = "post",\r
+            summary = "updates artifact by interface", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "delete artifact under interface deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Artifact already exist")})\r
+    public Response updateArtifactToInterface(@PathParam("resourceId") final String resourceId,\r
+            @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation,\r
+            @PathParam("artifactId") final String artifactId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @Context final HttpServletRequest request,\r
+            @Parameter(description = "json describe the artifact", required = true) String data) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId,\r
+                    ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.UPDATE, null, null);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface");\r
+            log.debug("updateArtifactToInterface unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}/heatParams")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Update Resource Instance HEAT_ENV parameters",\r
+            method = "POST", summary = "Returns updated artifact", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Artifact updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateRIArtifact(@Parameter(description = "valid values: resources / services",\r
+            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                     ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @PathParam("artifactId") final String artifactId,\r
+            @Parameter(description = "json describe the artifact", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId,\r
+                    ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId,\r
+                    containerComponentType);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact");\r
+            log.debug("updateRIArtifact unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Update Resource Instance artifact payload", method = "POST",\r
+            summary = "Returns updated artifact", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Artifact updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @HeaderParam(value = Constants.MD5_HEADER) String origMd5,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @PathParam("artifactId") final String artifactId,\r
+            @Parameter(description = "json describe the artifact", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId,\r
+                    ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId,\r
+                    containerComponentType);\r
+        } catch (Exception e) {\r
+            log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Load Resource Instance artifact payload", method = "POST",\r
+            summary = "Returns updated artifact", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Artifact updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response loadComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @HeaderParam(value = Constants.MD5_HEADER) String origMd5,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @Parameter(description = "json describe the artifact", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleArtifactRequest(data, request, componentInstanceId, null, null, null,\r
+                    ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.CREATE, componentId,\r
+                    containerComponentType);\r
+        } catch (Exception e) {\r
+            log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Delete Resource Instance artifact", method = "POST",\r
+            summary = "Returns deleted artifact", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Artifact updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response deleteComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @HeaderParam(value = Constants.MD5_HEADER) String origMd5,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @PathParam("artifactId") final String artifactId,\r
+            @Parameter(description = "json describe the artifact", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE,\r
+                    null, null, componentId);\r
+        } catch (Exception e) {\r
+            log.debug("deleteArtifact unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+\r
+    @GET\r
+    @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Get component Artifacts", method = "GET",\r
+            summary = "Returns artifacts", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component artifacts"),\r
+            @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")})\r
+    public Response getComponentArtifacts(@Parameter(description = "valid values: resources / services",\r
+            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                     ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleGetArtifactsRequest(request, componentId, null, artifactGroupType, containerComponentType);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");\r
+            log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifactsByType/{artifactGroupType}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Get component Artifacts", method = "GET",\r
+            summary = "Returns artifacts", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component artifacts"),\r
+            @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")})\r
+    public Response getComponentInstanceArtifacts(@Parameter(description = "valid values: resources / services",\r
+            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                     ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        try {\r
+            return handleGetArtifactsRequest(request, componentInstanceId, componentId, artifactGroupType,\r
+                    containerComponentType);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");\r
+            log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+\r
+    @POST\r
+    @Path("/{assetType}/{uuid}/interfaces/{interfaceUUID}/operations/{operationUUID}/artifacts/{artifactUUID}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "uploads of artifact to component operation workflow", method = "POST", summary = "uploads of artifact to component operation workflow")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Artifact uploaded",content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),\r
+            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),\r
+            @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"),\r
+            @ApiResponse(responseCode = "400", description = "Artifact name given in input already exists in the context of the asset - SVC4125"),\r
+            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),\r
+            @ApiResponse(responseCode = "400", description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),\r
+            @ApiResponse(responseCode = "400", description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})\r
+    //@ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})\r
+    public Response uploadInterfaceOperationArtifact(\r
+            @Parameter(description = "Asset type") @PathParam("assetType") String assetType,\r
+            @Parameter(description = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,\r
+            @Parameter(description = "The uuid of the interface", required = true)@PathParam("interfaceUUID") final String interfaceUUID,\r
+            @Parameter(description = "The uuid of the operation", required = true)@PathParam("operationUUID") final String operationUUID,\r
+            @Parameter(description = "The uuid of the artifact", required = true)@PathParam("artifactUUID") final String artifactUUID,\r
+            @Parameter( hidden = true) String data,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @HeaderParam(value = Constants.MD5_HEADER) String origMd5,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}" , url);\r
+\r
+        try {\r
+            Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither =\r
+                artifactsBusinessLogic.updateArtifactOnInterfaceOperationByResourceUUID(data, request,\r
+                            ComponentTypeEnum.findByParamName(assetType), uuid, interfaceUUID, operationUUID, artifactUUID,\r
+                            new ResourceCommonInfo(assetType), artifactsBusinessLogic.new ArtifactOperationInfo(true,\r
+                                    false, ArtifactOperationEnum.UPDATE));\r
+            if (uploadArtifactEither.isRight()) {\r
+                log.debug("failed to update artifact");\r
+                return buildErrorResponse(uploadArtifactEither.right().value());\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uploadArtifactEither.left().value());\r
+        }\r
+        catch (Exception e) {\r
+            final String message = "failed to update artifact on a resource or service";\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);\r
+            log.debug(message, e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    // ////////// API END ///////////////////////////\r
+\r
+    // ************ private *********************\r
+\r
+    private Response handleUploadRequest(String data, HttpServletRequest request, String componentId, ComponentTypeEnum componentType) {\r
+        return handleArtifactRequest(data, componentId, null, componentType, ArtifactOperationEnum.CREATE);\r
+    }\r
+\r
+    private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) {\r
+        return handleArtifactRequest(data, componentId, artifactId, componentType, ArtifactOperationEnum.UPDATE);\r
+    }\r
+\r
+    private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) {\r
+        String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+        ServletContext context = request.getSession().getServletContext();\r
+        Either<ImmutablePair<String, byte[]>, ResponseFormat> actionResult = artifactsBusinessLogic\r
+            .handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType);\r
+\r
+        Response response;\r
+        if (actionResult.isRight()) {\r
+            response = buildErrorResponse(actionResult.right().value());\r
+        } else {\r
+            byte[] file = actionResult.left().value().getRight();\r
+            String base64Contents = new String(Base64.encodeBase64(file));\r
+            String artifactName = actionResult.left().value().getLeft();\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+            ArtifactUiDownloadData artifactUiDownloadData = new ArtifactUiDownloadData();\r
+            artifactUiDownloadData.setArtifactName(artifactName);\r
+            artifactUiDownloadData.setBase64Contents(base64Contents);\r
+            response = buildOkResponse(responseFormat, artifactUiDownloadData);\r
+        }\r
+        return response;\r
+    }\r
+\r
+    private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) {\r
+        String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+        ComponentTypeEnum componentTypeEnum  = parentId == null || parentId.isEmpty()? ComponentTypeEnum.findByParamName(containerComponentType): ComponentTypeEnum.RESOURCE_INSTANCE;\r
+        Either<Map<String, ArtifactDefinition>, ResponseFormat> actionResult = artifactsBusinessLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId);\r
+\r
+        Response response;\r
+        if (actionResult.isRight()) {\r
+            response = buildErrorResponse(actionResult.right().value());\r
+        } else {\r
+\r
+            response =  buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult.left().value());\r
+        }\r
+\r
+        return response;\r
+    }\r
+\r
+\r
+    private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) {\r
+        return handleDeleteRequest(request, componentId, artifactId, componentType, interfaceType, operationName, null);\r
+    }\r
+\r
+    private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName, String parentId) {\r
+        String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+        ServletContext context = request.getSession().getServletContext();\r
+        Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsBusinessLogic.handleArtifactRequest(componentId, userId, componentType, artifactsBusinessLogic.new ArtifactOperationInfo (false, false, ArtifactOperationEnum.DELETE), artifactId, null, null, null, interfaceType, operationName,\r
+                parentId, null);\r
+        Response response;\r
+        if (actionResult.isRight()) {\r
+            response = buildErrorResponse(actionResult.right().value());\r
+        } else {\r
+            Either<ArtifactDefinition, Operation> result = actionResult.left().value();\r
+            if (result.isLeft()) {\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value());\r
+            } else {\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value());\r
+            }\r
+        }\r
+        return response;\r
+\r
+    }\r
+\r
+    private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId,\r
+            String containerComponentType) {\r
+        ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);\r
+        String origMd5 = request.getHeader(Constants.MD5_HEADER);\r
+\r
+        String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+\r
+        Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsBusinessLogic.handleArtifactRequest(componentId, userId, componentType,\r
+            artifactsBusinessLogic.new ArtifactOperationInfo (false, false,operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId,\r
+                containerComponentType);\r
+        Response response;\r
+        if (actionResult.isRight()) {\r
+            response = buildErrorResponse(actionResult.right().value());\r
+        } else {\r
+            Either<ArtifactDefinition, Operation> result = actionResult.left().value();\r
+            if (result.isLeft()) {\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value());\r
+            } else {\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value());\r
+            }\r
+        }\r
+        return response;\r
+\r
+    }\r
+\r
+    private Response handleArtifactRequest(String data, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) {\r
+        return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null);\r
+    }\r
+\r
+}\r
index f2c4286..1ed1e40 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-/**
- * Web Servlet for actions on Attributes
- * 
- * @author mshitrit
- *
- */
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Resource Attribute Servlet", description = "Resource Attribute Servlet")
-@Singleton
-public class AttributeServlet extends AbstractValidationsServlet {
-    private static final Logger log = Logger.getLogger(AttributeServlet.class);
-
-    @Inject
-    public AttributeServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-    }
-
-    /**
-     * Creates new Attribute on a resource with given resource ID
-     *
-     * @param resourceId
-     * @param data
-     * @param request
-     * @param userId
-     * @return
-     */
-    @POST
-    @Path("resources/{resourceId}/attributes")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Resource Attribute", httpMethod = "POST", notes = "Returns created resource attribute", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Resource attribute already exist") })
-    public Response createAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource attribute to be created", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
-
-        try {
-            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
-            Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>();
-            // convert json to AttributeDefinition
-
-            buildAttributeFromString(data, attributesWrapper, errorWrapper);
-            if (errorWrapper.isEmpty()) {
-                AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
-                Either<PropertyDefinition, ResponseFormat> createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId);
-                if (createAttribute.isRight()) {
-                    errorWrapper.setInnerElement(createAttribute.right().value());
-                } else {
-                    attributesWrapper.setInnerElement(createAttribute.left().value());
-                }
-            }
-
-            Response response;
-            if (!errorWrapper.isEmpty()) {
-                log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement());
-                response = buildErrorResponse(errorWrapper.getInnerElement());
-            } else {
-                PropertyDefinition createdAttDef = attributesWrapper.getInnerElement();
-                log.debug("Attribute {} created successfully with id {}", createdAttDef.getName(), createdAttDef.getUniqueId());
-                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
-                response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(createdAttDef));
-            }
-
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute");
-            log.debug("create property failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-
-        }
-    }
-
-    /**
-     * Updates existing Attribute with given attributeID on a resource with given resourceID
-     *
-     * @param resourceId
-     * @param attributeId
-     * @param data
-     * @param request
-     * @param userId
-     * @return
-     */
-    @PUT
-    @Path("resources/{resourceId}/attributes/{attributeId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Resource Attribute", httpMethod = "PUT", notes = "Returns updated attribute", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource attribute updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId,
-            @ApiParam(value = "attribute id to update", required = true) @PathParam("attributeId") final String attributeId, @ApiParam(value = "Resource attribute to update", required = true) String data, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        try {
-            // convert json to PropertyDefinition
-            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
-            Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>();
-            // convert json to AttributeDefinition
-
-            buildAttributeFromString(data, attributesWrapper, errorWrapper);
-
-            if (errorWrapper.isEmpty()) {
-                AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
-                Either<PropertyDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId);
-                // update property
-                if (eitherUpdateAttribute.isRight()) {
-                    errorWrapper.setInnerElement(eitherUpdateAttribute.right().value());
-                } else {
-                    attributesWrapper.setInnerElement(eitherUpdateAttribute.left().value());
-                }
-            }
-
-            Response response;
-            if (!errorWrapper.isEmpty()) {
-                log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement());
-                response = buildErrorResponse(errorWrapper.getInnerElement());
-            } else {
-                PropertyDefinition updatedAttribute = attributesWrapper.getInnerElement();
-                log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId());
-                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute));
-            }
-
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute");
-            log.debug("update attribute failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-
-        }
-    }
-
-    /**
-     * Deletes existing Attribute with given attributeID on a resource with given resourceID
-     *
-     * @param resourceId
-     * @param attributeId
-     * @param request
-     * @param userId
-     * @return
-     */
-    @DELETE
-    @Path("resources/{resourceId}/attributes/{attributeId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Resource Attribute", httpMethod = "DELETE", notes = "Returns deleted attribute", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted attribute"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 404, message = "Resource property not found") })
-    public Response deleteAttribute(@ApiParam(value = "resource id of attribute", required = true) @PathParam("resourceId") final String resourceId,
-            @ApiParam(value = "Attribute id to delete", required = true) @PathParam("attributeId") final String attributeId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-        log.debug("modifier id is {}", userId);
-
-        try {
-
-            // delete the property
-            AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
-            Either<PropertyDefinition, ResponseFormat> eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId);
-            if (eitherAttribute.isRight()) {
-                log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value());
-                return buildErrorResponse(eitherAttribute.right().value());
-            }
-            PropertyDefinition attributeDefinition = eitherAttribute.left().value();
-            String name = attributeDefinition.getName();
-
-            log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId());
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
-            return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition));
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute");
-            log.debug("delete attribute failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-
-        }
-    }
-
-    private void buildAttributeFromString(String data, Wrapper<PropertyDefinition> attributesWrapper, Wrapper<ResponseFormat> errorWrapper) {
-
-        try {
-            Gson gson = new GsonBuilder().setPrettyPrinting().create();
-            final PropertyDefinition attribute = gson.fromJson(data, PropertyDefinition.class);
-            if (attribute == null) {
-                log.info("Attribute content is invalid - {}", data);
-                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-                errorWrapper.setInnerElement(responseFormat);
-            } else {
-                attributesWrapper.setInnerElement(attribute);
-            }
-
-        } catch (Exception e) {
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-            errorWrapper.setInnerElement(responseFormat);
-            log.debug("Attribute content is invalid - {}", data, e);
-            log.info("Attribute content is invalid - {}", data);
-        }
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.PropertyDefinition;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.google.gson.Gson;\r
+import com.google.gson.GsonBuilder;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+/**\r
+ * Web Servlet for actions on Attributes\r
+ * \r
+ * @author mshitrit\r
+ *\r
+ */\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Resource Attribute Servlet", description = "Resource Attribute Servlet"))\r
+@Singleton\r
+public class AttributeServlet extends AbstractValidationsServlet {\r
+    private static final Logger log = Logger.getLogger(AttributeServlet.class);\r
+\r
+    @Inject\r
+    public AttributeServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+    }\r
+\r
+    /**\r
+     * Creates new Attribute on a resource with given resource ID\r
+     *\r
+     * @param resourceId\r
+     * @param data\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("resources/{resourceId}/attributes")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create Resource Attribute", method = "POST",\r
+            summary = "Returns created resource attribute", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource property created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Resource attribute already exist")})\r
+    public Response createAttribute(\r
+            @Parameter(description = "resource id to update with new attribute",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "Resource attribute to be created", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);\r
+\r
+        try {\r
+            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();\r
+            Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>();\r
+            // convert json to AttributeDefinition\r
+\r
+            buildAttributeFromString(data, attributesWrapper, errorWrapper);\r
+            if (errorWrapper.isEmpty()) {\r
+                AttributeBusinessLogic businessLogic =\r
+                        getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);\r
+                Either<PropertyDefinition, ResponseFormat> createAttribute =\r
+                        businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId);\r
+                if (createAttribute.isRight()) {\r
+                    errorWrapper.setInnerElement(createAttribute.right().value());\r
+                } else {\r
+                    attributesWrapper.setInnerElement(createAttribute.left().value());\r
+                }\r
+            }\r
+\r
+            Response response;\r
+            if (!errorWrapper.isEmpty()) {\r
+                log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement());\r
+                response = buildErrorResponse(errorWrapper.getInnerElement());\r
+            } else {\r
+                PropertyDefinition createdAttDef = attributesWrapper.getInnerElement();\r
+                log.debug("Attribute {} created successfully with id {}", createdAttDef.getName(),\r
+                        createdAttDef.getUniqueId());\r
+                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);\r
+                response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(createdAttDef));\r
+            }\r
+\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute");\r
+            log.debug("create property failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Updates existing Attribute with given attributeID on a resource with given resourceID\r
+     *\r
+     * @param resourceId\r
+     * @param attributeId\r
+     * @param data\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @PUT\r
+    @Path("resources/{resourceId}/attributes/{attributeId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Resource Attribute", method = "PUT", summary = "Returns updated attribute",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource attribute updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateAttribute(\r
+            @Parameter(description = "resource id to update with new attribute",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "attribute id to update",\r
+                    required = true) @PathParam("attributeId") final String attributeId,\r
+            @Parameter(description = "Resource attribute to update", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        try {\r
+            // convert json to PropertyDefinition\r
+            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();\r
+            Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>();\r
+            // convert json to AttributeDefinition\r
+\r
+            buildAttributeFromString(data, attributesWrapper, errorWrapper);\r
+\r
+            if (errorWrapper.isEmpty()) {\r
+                AttributeBusinessLogic businessLogic =\r
+                        getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);\r
+                Either<PropertyDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic\r
+                        .updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId);\r
+                // update property\r
+                if (eitherUpdateAttribute.isRight()) {\r
+                    errorWrapper.setInnerElement(eitherUpdateAttribute.right().value());\r
+                } else {\r
+                    attributesWrapper.setInnerElement(eitherUpdateAttribute.left().value());\r
+                }\r
+            }\r
+\r
+            Response response;\r
+            if (!errorWrapper.isEmpty()) {\r
+                log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement());\r
+                response = buildErrorResponse(errorWrapper.getInnerElement());\r
+            } else {\r
+                PropertyDefinition updatedAttribute = attributesWrapper.getInnerElement();\r
+                log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId());\r
+                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute));\r
+            }\r
+\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute");\r
+            log.debug("update attribute failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Deletes existing Attribute with given attributeID on a resource with given resourceID\r
+     *\r
+     * @param resourceId\r
+     * @param attributeId\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @DELETE\r
+    @Path("resources/{resourceId}/attributes/{attributeId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create Resource Attribute", method = "DELETE", summary = "Returns deleted attribute",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "deleted attribute"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Resource property not found")})\r
+    public Response deleteAttribute(\r
+            @Parameter(description = "resource id of attribute",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "Attribute id to delete",\r
+                    required = true) @PathParam("attributeId") final String attributeId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        try {\r
+\r
+            // delete the property\r
+            AttributeBusinessLogic businessLogic =\r
+                    getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);\r
+            Either<PropertyDefinition, ResponseFormat> eitherAttribute =\r
+                    businessLogic.deleteAttribute(resourceId, attributeId, userId);\r
+            if (eitherAttribute.isRight()) {\r
+                log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value());\r
+                return buildErrorResponse(eitherAttribute.right().value());\r
+            }\r
+            PropertyDefinition attributeDefinition = eitherAttribute.left().value();\r
+            String name = attributeDefinition.getName();\r
+\r
+            log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId());\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);\r
+            return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition));\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute");\r
+            log.debug("delete attribute failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+\r
+        }\r
+    }\r
+\r
+    private void buildAttributeFromString(String data, Wrapper<PropertyDefinition> attributesWrapper,\r
+            Wrapper<ResponseFormat> errorWrapper) {\r
+        try {\r
+            Gson gson = new GsonBuilder().setPrettyPrinting().create();\r
+            final PropertyDefinition attribute = gson.fromJson(data, PropertyDefinition.class);\r
+            if (attribute == null) {\r
+                log.info("Attribute content is invalid - {}", data);\r
+                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);\r
+                errorWrapper.setInnerElement(responseFormat);\r
+            } else {\r
+                attributesWrapper.setInnerElement(attribute);\r
+            }\r
+\r
+        } catch (Exception e) {\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);\r
+            errorWrapper.setInnerElement(responseFormat);\r
+            log.debug("Attribute content is invalid - {}", data, e);\r
+            log.info("Attribute content is invalid - {}", data);\r
+        }\r
+    }\r
+}\r
index 9f12b51..ce4dfdd 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic;
-import org.openecomp.sdc.be.components.upgrade.UpgradeRequest;
-import org.openecomp.sdc.be.components.upgrade.UpgradeStatus;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.springframework.stereotype.Controller;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.List;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "policy types resource")
-@Controller
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-public class AutomatedUpgradeEndpoint extends BeGenericServlet {
-    private static final Logger log = Logger.getLogger(PolicyTypesEndpoint.class);
-
-    private final UpgradeBusinessLogic businessLogic;
-
-    @Inject
-    public AutomatedUpgradeEndpoint(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        UpgradeBusinessLogic businessLogic) {
-        super(userBusinessLogic, componentsUtils);
-        this.businessLogic = businessLogic;
-    }
-
-    @POST
-    @Path("/{componentType}/{componentId}/automatedupgrade")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Autometed upgrade", httpMethod = "POST", notes = "....", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response autometedUpgrade(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @ApiParam(value = "json describes upgrade request", required = true) String data) {
-
-     
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(POST) Start handle request of {}", url);
-
-        try {
-            
-            List<UpgradeRequest> inputsToUpdate = JsonParserUtils.toList(data, UpgradeRequest.class);
-            
-            if (log.isDebugEnabled()) {
-                log.debug("Received upgrade requests size is {}", inputsToUpdate == null ? 0 : inputsToUpdate.size());
-            }
-            UpgradeStatus actionResponse = businessLogic.automatedUpgrade(componentId, inputsToUpdate, userId);
-            
-            return actionResponse.getStatus() == ActionStatus.OK ? buildOkResponse(actionResponse) : buildErrorResponse(actionResponse.getError());
-
-        } catch (Exception e) {
-            log.error("#autometedUpgrade - Exception occurred during autometed Upgrade", e);
-             return buildGeneralErrorResponse();
-        }
-    }
-    
-    @GET
-    @Path("/{componentType}/{componentId}/dependencies")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Autometed upgrade", httpMethod = "POST", notes = "....", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response getComponentDependencies(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @ApiParam(value = "Consumer Object to be created", required = true) List<String> data) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(GET) Start handle request of {}", url);
-
-        try {
-            return  businessLogic.getComponentDependencies(componentId, userId)
-                    .either(this::buildOkResponse, this::buildErrorResponse);  
-        } catch (Exception e) {
-            log.error("#getServicesForComponent - Exception occurred during autometed Upgrade", e);
-            return buildGeneralErrorResponse();
-        }
-     
-        
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.List;\r
+import javax.inject.Inject;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic;\r
+import org.openecomp.sdc.be.components.upgrade.UpgradeRequest;\r
+import org.openecomp.sdc.be.components.upgrade.UpgradeStatus;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.springframework.stereotype.Controller;\r
+import com.jcabi.aspects.Loggable;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "policy types resource"))\r
+@Controller\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+public class AutomatedUpgradeEndpoint extends BeGenericServlet {\r
+    private static final Logger log = Logger.getLogger(PolicyTypesEndpoint.class);\r
+\r
+    private final UpgradeBusinessLogic businessLogic;\r
+\r
+    @Inject\r
+    public AutomatedUpgradeEndpoint(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils,\r
+        UpgradeBusinessLogic businessLogic) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.businessLogic = businessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Path("/{componentType}/{componentId}/automatedupgrade")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Autometed upgrade", method = "POST", summary = "....", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response autometedUpgrade(@PathParam("componentType") final String componentType,\r
+            @Context final HttpServletRequest request, @PathParam("componentId") final String componentId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "json describes upgrade request", required = true) String data) {\r
+\r
+     \r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(POST) Start handle request of {}", url);\r
+\r
+        try {\r
+            \r
+            List<UpgradeRequest> inputsToUpdate = JsonParserUtils.toList(data, UpgradeRequest.class);\r
+            \r
+            if (log.isDebugEnabled()) {\r
+                log.debug("Received upgrade requests size is {}", inputsToUpdate == null ? 0 : inputsToUpdate.size());\r
+            }\r
+            UpgradeStatus actionResponse = businessLogic.automatedUpgrade(componentId, inputsToUpdate, userId);\r
+            \r
+            return actionResponse.getStatus() == ActionStatus.OK ? buildOkResponse(actionResponse) : buildErrorResponse(actionResponse.getError());\r
+\r
+        } catch (Exception e) {\r
+            log.error("#autometedUpgrade - Exception occurred during autometed Upgrade", e);\r
+             return buildGeneralErrorResponse();\r
+        }\r
+    }\r
+    \r
+    @GET\r
+    @Path("/{componentType}/{componentId}/dependencies")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Autometed upgrade", method = "POST", summary = "....", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response getComponentDependencies(@PathParam("componentType") final String componentType,\r
+            @Context final HttpServletRequest request, @PathParam("componentId") final String componentId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "Consumer Object to be created", required = true) List<String> data) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(GET) Start handle request of {}", url);\r
+\r
+        try {\r
+            return  businessLogic.getComponentDependencies(componentId, userId)\r
+                    .either(this::buildOkResponse, this::buildErrorResponse);  \r
+        } catch (Exception e) {\r
+            log.error("#getServicesForComponent - Exception occurred during autometed Upgrade", e);\r
+            return buildGeneralErrorResponse();\r
+        }\r
+     \r
+        \r
+    }\r
+}\r
index 3750f20..5433bd5 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import javax.inject.Inject;
-import org.apache.commons.lang3.tuple.Pair;
-import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.api.HealthCheckInfo;
-import org.openecomp.sdc.common.api.HealthCheckWrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.monitoring.MonitoringEvent;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.List;
-
-@Loggable(prepend = true, value = Loggable.TRACE, trim = false)
-@Path("/")
-@Api(value = "BE Monitoring", description = "BE Monitoring")
-@Singleton
-public class BeMonitoringServlet extends BeGenericServlet {
-
-    Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
-
-    private static final Logger log = Logger.getLogger(ConfigServlet.class);
-    private final HealthCheckBusinessLogic healthCheckBusinessLogic;
-    private final MonitoringBusinessLogic monitoringBusinessLogic;
-
-    @Inject
-    public BeMonitoringServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        HealthCheckBusinessLogic healthCheckBusinessLogic,
-        MonitoringBusinessLogic monitoringBusinessLogic) {
-        super(userBusinessLogic, componentsUtils);
-        this.healthCheckBusinessLogic = healthCheckBusinessLogic;
-        this.monitoringBusinessLogic = monitoringBusinessLogic;
-    }
-
-    @GET
-    @Path("/healthCheck")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Return aggregate BE health check of SDC BE components", notes = "return BE health check", response = String.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "SDC BE components are all up"), @ApiResponse(code = 500, message = "One or more SDC BE components are down") })
-    public Response getHealthCheck(@Context final HttpServletRequest request) {
-        try {
-            Pair<Boolean, List<HealthCheckInfo>> beHealthCheckInfosStatus = healthCheckBusinessLogic.getBeHealthCheckInfosStatus();
-            Boolean aggregateStatus = beHealthCheckInfosStatus.getLeft();
-            ActionStatus status = aggregateStatus ? ActionStatus.OK : ActionStatus.GENERAL_ERROR;
-            String sdcVersion = getVersionFromContext(request);
-            if (sdcVersion == null || sdcVersion.isEmpty()) {
-                sdcVersion = "UNKNOWN";
-            }
-            String siteMode = healthCheckBusinessLogic.getSiteMode();
-            HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfosStatus.getRight(), sdcVersion, siteMode);
-            // The response can be either with 200 or 500 aggregate status - the
-            // body of individual statuses is returned either way
-
-            String healthCheckStr = prettyGson.toJson(healthCheck);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(status), healthCheckStr);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeHealthCheckError("BeHealthCheck");
-            log.debug("BE health check unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/monitoring")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    public Response processMonitoringMetrics(@Context final HttpServletRequest request, String json) {
-        try {
-            MonitoringEvent monitoringEvent = convertContentToJson(json, MonitoringEvent.class);
-            if (monitoringEvent == null) {
-                return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));
-            }
-            log.trace("Received monitoring metrics: {}", monitoringEvent);
-            Either<Boolean, ResponseFormat> result = monitoringBusinessLogic.logMonitoringEvent(monitoringEvent);
-            if (result.isRight()) {
-                return buildErrorResponse(result.right().value());
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
-
-        } catch (Exception e) {
-            log.debug("BE system metrics unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @GET
-    @Path("/version")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "return the ASDC application version", notes = "return the ASDC application version", response = String.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "return ASDC version"), @ApiResponse(code = 500, message = "Internal Error") })
-    public Response getSdcVersion(@Context final HttpServletRequest request) {
-        try {
-            String url = request.getMethod() + " " + request.getRequestURI();
-            log.debug("Start handle request of {}", url);
-
-            String version = getVersionFromContext(request);
-            log.debug("asdc version from manifest is: {}", version);
-            if (version == null || version.isEmpty()) {
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND));
-            }
-
-            HealthCheckInfo versionInfo = new HealthCheckInfo();
-            versionInfo.setVersion(version);
-
-            // The response can be either with 200 or 500 aggregate status - the
-            // body of individual statuses is returned either way
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), versionInfo);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion");
-            log.debug("BE get ASDC version unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    private String getVersionFromContext(HttpServletRequest request) {
-        ServletContext servletContext = request.getSession().getServletContext();
-        return (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR);
-    }
-
-    protected MonitoringEvent convertContentToJson(String content, Class<MonitoringEvent> clazz) {
-
-        MonitoringEvent object = null;
-        try {
-            object = gson.fromJson(content, clazz);
-            object.setFields(null);
-        } catch (Exception e) {
-            log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
-        }
-
-        return object;
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.List;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.lang3.tuple.Pair;\r
+import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.api.HealthCheckInfo;\r
+import org.openecomp.sdc.common.api.HealthCheckWrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.common.monitoring.MonitoringEvent;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.google.gson.Gson;\r
+import com.google.gson.GsonBuilder;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.TRACE, trim = false)\r
+@Path("/")\r
+@OpenAPIDefinition(info = @Info(title = "BE Monitoring", description = "BE Monitoring"))\r
+@Singleton\r
+public class BeMonitoringServlet extends BeGenericServlet {\r
+\r
+    Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();\r
+\r
+    private static final Logger log = Logger.getLogger(ConfigServlet.class);\r
+    private final HealthCheckBusinessLogic healthCheckBusinessLogic;\r
+    private final MonitoringBusinessLogic monitoringBusinessLogic;\r
+\r
+    @Inject\r
+    public BeMonitoringServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils,\r
+        HealthCheckBusinessLogic healthCheckBusinessLogic,\r
+        MonitoringBusinessLogic monitoringBusinessLogic) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.healthCheckBusinessLogic = healthCheckBusinessLogic;\r
+        this.monitoringBusinessLogic = monitoringBusinessLogic;\r
+    }\r
+\r
+    @GET\r
+    @Path("/healthCheck")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Return aggregate BE health check of SDC BE components", summary = "return BE health check",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "SDC BE components are all up"),\r
+            @ApiResponse(responseCode = "500", description = "One or more SDC BE components are down")})\r
+    public Response getHealthCheck(@Context final HttpServletRequest request) {\r
+        try {\r
+            Pair<Boolean, List<HealthCheckInfo>> beHealthCheckInfosStatus =\r
+                    healthCheckBusinessLogic.getBeHealthCheckInfosStatus();\r
+            Boolean aggregateStatus = beHealthCheckInfosStatus.getLeft();\r
+            ActionStatus status = aggregateStatus ? ActionStatus.OK : ActionStatus.GENERAL_ERROR;\r
+            String sdcVersion = getVersionFromContext(request);\r
+            if (sdcVersion == null || sdcVersion.isEmpty()) {\r
+                sdcVersion = "UNKNOWN";\r
+            }\r
+            String siteMode = healthCheckBusinessLogic.getSiteMode();\r
+            HealthCheckWrapper healthCheck =\r
+                    new HealthCheckWrapper(beHealthCheckInfosStatus.getRight(), sdcVersion, siteMode);\r
+            // The response can be either with 200 or 500 aggregate status - the\r
+            // body of individual statuses is returned either way\r
+\r
+            String healthCheckStr = prettyGson.toJson(healthCheck);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(status), healthCheckStr);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeHealthCheckError("BeHealthCheck");\r
+            log.debug("BE health check unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/monitoring")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    public Response processMonitoringMetrics(@Context final HttpServletRequest request, String json) {\r
+        try {\r
+            MonitoringEvent monitoringEvent = convertContentToJson(json, MonitoringEvent.class);\r
+            if (monitoringEvent == null) {\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));\r
+            }\r
+            log.trace("Received monitoring metrics: {}", monitoringEvent);\r
+            Either<Boolean, ResponseFormat> result = monitoringBusinessLogic.logMonitoringEvent(monitoringEvent);\r
+            if (result.isRight()) {\r
+                return buildErrorResponse(result.right().value());\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);\r
+\r
+        } catch (Exception e) {\r
+            log.debug("BE system metrics unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/version")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "return the ASDC application version", summary = "return the ASDC application version",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "return ASDC version"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Error")})\r
+    public Response getSdcVersion(@Context final HttpServletRequest request) {\r
+        try {\r
+            String url = request.getMethod() + " " + request.getRequestURI();\r
+            log.debug("Start handle request of {}", url);\r
+\r
+            String version = getVersionFromContext(request);\r
+            log.debug("asdc version from manifest is: {}", version);\r
+            if (version == null || version.isEmpty()) {\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND));\r
+            }\r
+\r
+            HealthCheckInfo versionInfo = new HealthCheckInfo();\r
+            versionInfo.setVersion(version);\r
+\r
+            // The response can be either with 200 or 500 aggregate status - the\r
+            // body of individual statuses is returned either way\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), versionInfo);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion");\r
+            log.debug("BE get ASDC version unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    private String getVersionFromContext(HttpServletRequest request) {\r
+        ServletContext servletContext = request.getSession().getServletContext();\r
+        return (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR);\r
+    }\r
+\r
+    protected MonitoringEvent convertContentToJson(String content, Class<MonitoringEvent> clazz) {\r
+\r
+        MonitoringEvent object = null;\r
+        try {\r
+            object = gson.fromJson(content, clazz);\r
+            object.setFields(null);\r
+        } catch (Exception e) {\r
+            log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);\r
+        }\r
+\r
+        return object;\r
+    }\r
+\r
+}\r
index eacfbc7..0e00e01 100644 (file)
-/*
- * Copyright Â© 2016-2018 European Support Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.List;
-import java.util.Optional;
-import org.springframework.beans.factory.annotation.Autowired;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-@Api(value = "Capability Servlet", description = "Capability Servlet")
-@Singleton
-public class CapabilityServlet extends AbstractValidationsServlet {
-    private static final Logger LOGGER = Logger.getLogger(CapabilityServlet.class);
-    private final CapabilitiesBusinessLogic capabilitiesBusinessLogic;
-
-    @Inject
-    public CapabilityServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        CapabilitiesBusinessLogic capabilitiesBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.capabilitiesBusinessLogic = capabilitiesBusinessLogic;
-    }
-
-
-    @POST
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/resources/{resourceId}/capabilities")
-    @ApiOperation(value = "Create Capabilities on resource", httpMethod = "POST",
-            notes = "Create Capabilities on resource", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Capabilities"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Capability already exist")})
-    public Response createCapabilitiesOnResource(
-            @ApiParam(value = "Capability to create", required = true) String data,
-            @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "resources" , resourceId,
-                request, userId, false, "createCapabilities");
-    }
-
-    @PUT
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/resources/{resourceId}/capabilities")
-    @ApiOperation(value = "Update Capabilities on resource", httpMethod = "PUT",
-            notes = "Update Capabilities on resource", response = CapabilityDefinition.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Update Capabilities"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response updateCapabilitiesOnResource(
-            @ApiParam(value = "Capabilities to update", required = true) String data,
-            @ApiParam(value = "Component Id") @PathParam("resourceId") String resourceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "resources", resourceId,
-                request, userId, true, "updateCapabilities");
-    }
-
-    @GET
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/resources/{resourceId}/capabilities/{capabilityId}")
-    @ApiOperation(value = "Get Capability from resource", httpMethod = "GET",
-            notes = "GET Capability from resource", response = CapabilityDefinition.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "GET Capability"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response getCapabilityOnResource(
-            @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
-            @ApiParam(value = "Capability Id") @PathParam("capabilityId") String capabilityId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return get(capabilityId, resourceId, request, userId);
-    }
-
-    @DELETE
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/resources/{resourceId}/capabilities/{capabilityId}")
-    @ApiOperation(value = "Delete capability from resource", httpMethod = "DELETE",
-            notes = "Delete capability from resource", response = CapabilityDefinition.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete capability"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response deleteCapabilityOnResource(
-            @ApiParam(value = "capability Id") @PathParam("capabilityId") String capabilityId,
-            @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return delete(capabilityId, resourceId, request, userId);
-    }
-
-    @POST
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/services/{serviceId}/capabilities")
-    @ApiOperation(value = "Create Capabilities on service", httpMethod = "POST",
-            notes = "Create Capabilities on service", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Capabilities"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Capability already exist")})
-    public Response createCapabilitiesOnService(
-            @ApiParam(value = "Capability to create", required = true) String data,
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "services" , serviceId,
-                request, userId, false, "createCapabilities");
-    }
-
-    @PUT
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/services/{serviceId}/capabilities")
-    @ApiOperation(value = "Update Capabilities on service", httpMethod = "PUT",
-            notes = "Update Capabilities on service", response = CapabilityDefinition.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Update Capabilities"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response updateCapabilitiesOnService(
-            @ApiParam(value = "Capabilities to update", required = true) String data,
-            @ApiParam(value = "Component Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "services", serviceId,
-                request, userId, true, "updateCapabilities");
-    }
-
-    @GET
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/services/{serviceId}/capabilities/{capabilityId}")
-    @ApiOperation(value = "Get Capability from service", httpMethod = "GET",
-            notes = "GET Capability from service", response = CapabilityDefinition.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "GET Capability"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response getCapabilityOnService(
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @ApiParam(value = "Capability Id") @PathParam("capabilityId") String capabilityId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return get(capabilityId, serviceId, request, userId);
-    }
-
-    @DELETE
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/services/{serviceId}/capabilities/{capabilityId}")
-    @ApiOperation(value = "Delete capability from service", httpMethod = "DELETE",
-            notes = "Delete capability from service", response = CapabilityDefinition.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete capability"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response deleteCapabilityOnService(
-            @ApiParam(value = "capability Id") @PathParam("capabilityId") String capabilityId,
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return delete(capabilityId, serviceId, request, userId);
-    }
-
-    private Response createOrUpdate (String data, String componentType, String componentId,
-                                     HttpServletRequest request,
-                                     String userId,
-                                     boolean isUpdate,
-                                     String errorContext) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        LOGGER.debug("Start create or update request of {} with modifier id {}", url, userId);
-        try {
-            String componentIdLower = componentId.toLowerCase();
-
-            Either<List<CapabilityDefinition>, ResponseFormat> mappedCapabilitiesDataEither
-                    = getMappedCapabilitiesData(data, modifier, ComponentTypeEnum.findByParamName(componentType));
-            if(mappedCapabilitiesDataEither.isRight()) {
-                LOGGER.error("Failed to create or update capabilities");
-                buildErrorResponse(mappedCapabilitiesDataEither.right().value());
-            }
-            List<CapabilityDefinition> mappedCapabilitiesData = mappedCapabilitiesDataEither.left().value();
-            Either<List<CapabilityDefinition>, ResponseFormat> actionResponse;
-            if(isUpdate) {
-                actionResponse = capabilitiesBusinessLogic.updateCapabilities(componentIdLower,
-                        mappedCapabilitiesData, modifier, errorContext, true);
-            } else {
-                actionResponse = capabilitiesBusinessLogic.createCapabilities(componentIdLower,
-                        mappedCapabilitiesData, modifier, errorContext, true);
-            }
-            if (actionResponse.isRight()) {
-                LOGGER.error("Failed to create or update capabilities");
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    actionResponse.left().value());
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Capabilities create or update");
-            LOGGER.error("Failed to create or update capabilities with an error", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    private Response get (String capabilityIdToGet,  String componentId,
-                          HttpServletRequest request, String userId){
-        String url = request.getMethod() + " " + request.getRequestURI();
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        LOGGER.debug("Start get request of {} with modifier id {}", url, userId);
-
-        try {
-            String componentIdLower = componentId.toLowerCase();
-
-            Either<CapabilityDefinition, ResponseFormat> actionResponse = capabilitiesBusinessLogic
-                    .getCapability(componentIdLower, capabilityIdToGet, modifier, true);
-            if (actionResponse.isRight()) {
-                LOGGER.error("failed to get capability");
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            Object result = RepresentationUtils.toFilteredRepresentation(actionResponse.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get capability");
-            LOGGER.error("get capabilities failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    private Response delete (String capabilityId, String componentId, HttpServletRequest
-            request, String userId){
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        LOGGER.debug("Start delete request of {} with modifier id {}", url, userId);
-
-        try {
-            String componentIdLower = componentId.toLowerCase();
-
-            Either<CapabilityDefinition, ResponseFormat> actionResponse = capabilitiesBusinessLogic
-                    .deleteCapability(componentIdLower, capabilityId, modifier, true);
-            if (actionResponse.isRight()) {
-                LOGGER.error("failed to delete capability");
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete capability");
-            LOGGER.error("Delete capability failed with an error", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    private Either<List<CapabilityDefinition>, ResponseFormat> getMappedCapabilitiesData(String inputJson, User user,
-                                                                 ComponentTypeEnum componentTypeEnum){
-        Either<UiComponentDataTransfer, ResponseFormat> mappedData = getComponentsUtils()
-                .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class,
-                        AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
-        Optional<List<CapabilityDefinition>> capabilityDefinitionList =
-                mappedData.left().value().getCapabilities().values().stream().findFirst();
-        return capabilityDefinitionList.<Either<List<CapabilityDefinition>, ResponseFormat>>
-                map(Either::left).orElseGet(() -> Either.right(getComponentsUtils()
-                .getResponseFormat(ActionStatus.GENERAL_ERROR)));
-    }
-}
+/*\r
+ * Copyright Â© 2016-2018 European Support Limited\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.List;\r
+import java.util.Optional;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.CapabilityDefinition;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+@OpenAPIDefinition(info = @Info(title = "Capability Servlet", description = "Capability Servlet"))\r
+@Singleton\r
+public class CapabilityServlet extends AbstractValidationsServlet {\r
+    private static final Logger LOGGER = Logger.getLogger(CapabilityServlet.class);\r
+    private final CapabilitiesBusinessLogic capabilitiesBusinessLogic;\r
+\r
+    @Inject\r
+    public CapabilityServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        CapabilitiesBusinessLogic capabilitiesBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.capabilitiesBusinessLogic = capabilitiesBusinessLogic;\r
+    }\r
+\r
+\r
+    @POST\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/resources/{resourceId}/capabilities")\r
+    @Operation(description = "Create Capabilities on resource", method = "POST",\r
+            summary = "Create Capabilities on resource",  responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Create Capabilities"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Capability already exist")})\r
+    public Response createCapabilitiesOnResource(\r
+            @Parameter(description = "Capability to create", required = true) String data,\r
+            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return createOrUpdate(data, "resources" , resourceId,\r
+                request, userId, false, "createCapabilities");\r
+    }\r
+\r
+    @PUT\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/resources/{resourceId}/capabilities")\r
+    @Operation(description = "Update Capabilities on resource", method = "PUT",\r
+            summary = "Update Capabilities on resource",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Update Capabilities"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateCapabilitiesOnResource(\r
+            @Parameter(description = "Capabilities to update", required = true) String data,\r
+            @Parameter(description = "Component Id") @PathParam("resourceId") String resourceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return createOrUpdate(data, "resources", resourceId,\r
+                request, userId, true, "updateCapabilities");\r
+    }\r
+\r
+    @GET\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/resources/{resourceId}/capabilities/{capabilityId}")\r
+    @Operation(description = "Get Capability from resource", method = "GET",\r
+            summary = "GET Capability from resource", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "GET Capability"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response getCapabilityOnResource(\r
+            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,\r
+            @Parameter(description = "Capability Id") @PathParam("capabilityId") String capabilityId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return get(capabilityId, resourceId, request, userId);\r
+    }\r
+\r
+    @DELETE\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/resources/{resourceId}/capabilities/{capabilityId}")\r
+    @Operation(description = "Delete capability from resource", method = "DELETE",\r
+            summary = "Delete capability from resource", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Delete capability"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response deleteCapabilityOnResource(\r
+            @Parameter(description = "capability Id") @PathParam("capabilityId") String capabilityId,\r
+            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return delete(capabilityId, resourceId, request, userId);\r
+    }\r
+\r
+    @POST\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/services/{serviceId}/capabilities")\r
+    @Operation(description = "Create Capabilities on service", method = "POST",\r
+            summary = "Create Capabilities on service", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Create Capabilities"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Capability already exist")})\r
+    public Response createCapabilitiesOnService(\r
+            @Parameter(description = "Capability to create", required = true) String data,\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return createOrUpdate(data, "services" , serviceId,\r
+                request, userId, false, "createCapabilities");\r
+    }\r
+\r
+    @PUT\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/services/{serviceId}/capabilities")\r
+    @Operation(description = "Update Capabilities on service", method = "PUT",\r
+            summary = "Update Capabilities on service",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Update Capabilities"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateCapabilitiesOnService(\r
+            @Parameter(description = "Capabilities to update", required = true) String data,\r
+            @Parameter(description = "Component Id") @PathParam("serviceId") String serviceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return createOrUpdate(data, "services", serviceId,\r
+                request, userId, true, "updateCapabilities");\r
+    }\r
+\r
+    @GET\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/services/{serviceId}/capabilities/{capabilityId}")\r
+    @Operation(description = "Get Capability from service", method = "GET",\r
+            summary = "GET Capability from service", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "GET Capability"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response getCapabilityOnService(\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Parameter(description = "Capability Id") @PathParam("capabilityId") String capabilityId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return get(capabilityId, serviceId, request, userId);\r
+    }\r
+\r
+    @DELETE\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/services/{serviceId}/capabilities/{capabilityId}")\r
+    @Operation(description = "Delete capability from service", method = "DELETE",\r
+            summary = "Delete capability from service",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Delete capability"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response deleteCapabilityOnService(\r
+            @Parameter(description = "capability Id") @PathParam("capabilityId") String capabilityId,\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return delete(capabilityId, serviceId, request, userId);\r
+    }\r
+\r
+    private Response createOrUpdate (String data, String componentType, String componentId,\r
+                                     HttpServletRequest request,\r
+                                     String userId,\r
+                                     boolean isUpdate,\r
+                                     String errorContext) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        LOGGER.debug("Start create or update request of {} with modifier id {}", url, userId);\r
+        try {\r
+            String componentIdLower = componentId.toLowerCase();\r
+\r
+            Either<List<CapabilityDefinition>, ResponseFormat> mappedCapabilitiesDataEither\r
+                    = getMappedCapabilitiesData(data, modifier, ComponentTypeEnum.findByParamName(componentType));\r
+            if(mappedCapabilitiesDataEither.isRight()) {\r
+                LOGGER.error("Failed to create or update capabilities");\r
+                buildErrorResponse(mappedCapabilitiesDataEither.right().value());\r
+            }\r
+            List<CapabilityDefinition> mappedCapabilitiesData = mappedCapabilitiesDataEither.left().value();\r
+            Either<List<CapabilityDefinition>, ResponseFormat> actionResponse;\r
+            if(isUpdate) {\r
+                actionResponse = capabilitiesBusinessLogic.updateCapabilities(componentIdLower,\r
+                        mappedCapabilitiesData, modifier, errorContext, true);\r
+            } else {\r
+                actionResponse = capabilitiesBusinessLogic.createCapabilities(componentIdLower,\r
+                        mappedCapabilitiesData, modifier, errorContext, true);\r
+            }\r
+            if (actionResponse.isRight()) {\r
+                LOGGER.error("Failed to create or update capabilities");\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    actionResponse.left().value());\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Capabilities create or update");\r
+            LOGGER.error("Failed to create or update capabilities with an error", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    private Response get (String capabilityIdToGet,  String componentId,\r
+                          HttpServletRequest request, String userId){\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        LOGGER.debug("Start get request of {} with modifier id {}", url, userId);\r
+\r
+        try {\r
+            String componentIdLower = componentId.toLowerCase();\r
+\r
+            Either<CapabilityDefinition, ResponseFormat> actionResponse = capabilitiesBusinessLogic\r
+                    .getCapability(componentIdLower, capabilityIdToGet, modifier, true);\r
+            if (actionResponse.isRight()) {\r
+                LOGGER.error("failed to get capability");\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            Object result = RepresentationUtils.toFilteredRepresentation(actionResponse.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get capability");\r
+            LOGGER.error("get capabilities failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    private Response delete (String capabilityId, String componentId, HttpServletRequest\r
+            request, String userId){\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        LOGGER.debug("Start delete request of {} with modifier id {}", url, userId);\r
+\r
+        try {\r
+            String componentIdLower = componentId.toLowerCase();\r
+\r
+            Either<CapabilityDefinition, ResponseFormat> actionResponse = capabilitiesBusinessLogic\r
+                    .deleteCapability(componentIdLower, capabilityId, modifier, true);\r
+            if (actionResponse.isRight()) {\r
+                LOGGER.error("failed to delete capability");\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete capability");\r
+            LOGGER.error("Delete capability failed with an error", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    private Either<List<CapabilityDefinition>, ResponseFormat> getMappedCapabilitiesData(String inputJson, User user,\r
+                                                                 ComponentTypeEnum componentTypeEnum){\r
+        Either<UiComponentDataTransfer, ResponseFormat> mappedData = getComponentsUtils()\r
+                .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class,\r
+                        AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);\r
+        Optional<List<CapabilityDefinition>> capabilityDefinitionList =\r
+                mappedData.left().value().getCapabilities().values().stream().findFirst();\r
+        return capabilityDefinitionList.<Either<List<CapabilityDefinition>, ResponseFormat>>\r
+                map(Either::left).orElseGet(() -> Either.right(getComponentsUtils()\r
+                .getResponseFormat(ActionStatus.GENERAL_ERROR)));\r
+    }\r
+}\r
index 638e929..e8e018e 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.reflect.TypeToken;
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.StringUtils;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.utils.DirectivesUtils;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datamodel.ForwardingPaths;
-import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
-import org.openecomp.sdc.be.info.GroupDefinitionInfo;
-import org.openecomp.sdc.be.model.*;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.InputStream;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-import java.util.Map;
-
-/**
- * Root resource (exposed at "/" path) .json
- */
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Resource Instance Servlet")
-@Singleton
-public class ComponentInstanceServlet extends AbstractValidationsServlet {
-
-    private static final String FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID = "Failed to get properties of component instance ID: {} in {} with ID: {}";
-       private static final String GET_GROUP_ARTIFACT_BY_ID = "getGroupArtifactById";
-       private static final String GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION = "getGroupArtifactById unexpected exception";
-       private static final String GET_START_HANDLE_REQUEST_OF = "(GET) Start handle request of {}";
-       private static final String START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS = "Start handle request of updateResourceInstanceProperty. Received property is {}";
-       private static final String UPDATE_RESOURCE_INSTANCE = "Update Resource Instance";
-       private static final String RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE = "Resource Instance - updateResourceInstance";
-       private static final String UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION = "update resource instance with exception";
-       private static final String FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT = "Failed to convert received data to BE format.";
-       private static final String EMPTY_BODY_WAS_SENT = "Empty body was sent.";
-       private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
-       private static final String UNSUPPORTED_COMPONENT_TYPE = "Unsupported component type {}";
-       private static final Logger log = Logger.getLogger(ComponentInstanceServlet.class);
-    private static final Type PROPERTY_CONSTRAINT_TYPE = new TypeToken<PropertyConstraint>() {}.getType();
-    private static final Gson gsonDeserializer = new GsonBuilder().registerTypeAdapter(PROPERTY_CONSTRAINT_TYPE, new PropertyConstraintDeserialiser()).create();
-    private final GroupBusinessLogic groupBL;
-    private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
-    private final ServiceBusinessLogic serviceBusinessLogic;
-
-
-    @Inject
-    public ComponentInstanceServlet(UserBusinessLogic userBusinessLogic,
-        GroupBusinessLogic groupBL, ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        ServiceBusinessLogic serviceBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.groupBL = groupBL;
-        this.componentInstanceBusinessLogic = componentInstanceBL;
-        this.serviceBusinessLogic = serviceBusinessLogic;
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create ComponentInstance", httpMethod = "POST", notes = "Returns created ComponentInstance", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Component created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Component instance already exist") })
-    public Response createComponentInstance(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("componentId") final String containerComponentId,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) {
-        ServletContext context = request.getSession().getServletContext();
-
-        try {
-
-            ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);
-            componentInstance.setInvariantName(null);
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance);
-
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance");
-            log.debug("create component instance failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
-            @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
-                    + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-        try {
-
-            log.debug(START_HANDLE_REQUEST_OF, url);
-
-            InputStream inputStream = request.getInputStream();
-
-            byte[] bytes = IOUtils.toByteArray(inputStream);
-
-            if (bytes == null || bytes.length == 0) {
-                log.info(EMPTY_BODY_WAS_SENT);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-            }
-
-            String userId = request.getHeader(Constants.USER_ID_HEADER);
-
-            String data = new String(bytes);
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-            Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
-
-            if (convertResponse.isRight()) {
-                BeEcompErrorManager.getInstance().logBeSystemError(RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE);
-                log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);
-                return buildErrorResponse(convertResponse.right().value());
-            }
-
-            ComponentInstance resourceInstance = convertResponse.left().value();
-            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, resourceInstance);
-
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            ComponentInstance resultValue = actionResponse.left().value();
-            if (componentTypeEnum.equals(ComponentTypeEnum.SERVICE)){
-                boolean shouldCreateServiceFilter = resourceInstance.getDirectives() != null && resourceInstance.getDirectives().contains(
-                        DirectivesUtils.SELECTABLE);
-
-                if(shouldCreateServiceFilter) {
-                    Either<CINodeFilterDataDefinition, ResponseFormat> either =
-                            serviceBusinessLogic.createIfNotAlreadyExistServiceFilter(componentId, componentInstanceId, userId,
-                                    true);
-                    if (either.isRight()){
-                        BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance Failed to create service filter.");
-                        log.debug("Failed to create service filter.");
-                        return buildErrorResponse(convertResponse.right().value());
-                    }
-                    resultValue.setNodeFilter(either.left().value());
-                } else {
-                    Either<String, ResponseFormat> either = serviceBusinessLogic.deleteIfNotAlreadyDeletedServiceFilter(componentId, componentInstanceId,  userId,true);
-                    if (either.isRight()){
-                        BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance Failed to delete service filter.");
-                        log.debug("Failed to delete service filter.");
-                        return buildErrorResponse(convertResponse.right().value());
-                    }
-                    resultValue.setNodeFilter(null);
-                }
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE);
-            log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update resource instance multiple component", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId,
-            @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
-                    + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request, @ApiParam(value = "Component Instance JSON Array", required = true) final String componentInstanceJsonArray) {
-
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        try {
-            log.debug(START_HANDLE_REQUEST_OF, url);
-
-            if (componentInstanceJsonArray == null || componentInstanceJsonArray.length() == 0) {
-                log.info("Empty JSON list was sent.");
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-            }
-
-            String userId = request.getHeader(Constants.USER_ID_HEADER);
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-
-            Either<List<ComponentInstance>, ResponseFormat> convertResponse = convertToMultipleResourceInstance(componentInstanceJsonArray);
-
-            if (convertResponse.isRight()) {
-                // Using both ECOMP error methods, show to Sofer
-                BeEcompErrorManager.getInstance().logBeSystemError(RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE);
-                log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);
-                return buildErrorResponse(convertResponse.right().value());
-            }
-
-            List<ComponentInstance> componentInstanceList = convertResponse.left().value();
-
-            Either<List<ComponentInstance>, ResponseFormat> actionResponse = componentInstanceBusinessLogic
-                .updateComponentInstance(containerComponentType, componentId, userId, componentInstanceList, true);
-
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE);
-            log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    @DELETE
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{resourceInstanceId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Delete ResourceInstance", httpMethod = "DELETE", notes = "Returns delete resourceInstance", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "ResourceInstance deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response deleteResourceInstance(@PathParam("componentId") final String componentId, @PathParam("resourceInstanceId") final String resourceInstanceId,
-            @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
-                    + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request) {
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        Response response = null;
-        try {
-            log.debug(START_HANDLE_REQUEST_OF, url);
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-            String userId = request.getHeader(Constants.USER_ID_HEADER);
-            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId);
-
-            if (actionResponse.isRight()) {
-                response = buildErrorResponse(actionResponse.right().value());
-            } else {
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
-            }
-            return response;
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance");
-            log.debug("delete resource instance with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true)
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/associate")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Associate RI to RI", httpMethod = "POST", notes = "Returns created RelationshipInfo", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship created"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Relationship already exist") })
-    public Response associateRIToRI(@ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId,
-            @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
-                    + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-        Response response = null;
-
-        try {
-
-            log.debug(START_HANDLE_REQUEST_OF, url);
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-
-            Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data);
-
-            Either<RequirementCapabilityRelDef, ResponseFormat> resultOp;
-            if (regInfoW.isRight()) {
-                BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - associateRIToRI");
-                log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);
-                resultOp = Either.right(regInfoW.right().value());
-            } else {
-                RequirementCapabilityRelDef requirementDef = regInfoW.left().value();
-                requirementDef.setOriginUI(true);
-                resultOp = componentInstanceBusinessLogic.associateRIToRI(componentId, userId, requirementDef, componentTypeEnum);
-            }
-
-            Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = resultOp;
-
-            if (actionResponse.isRight()) {
-                response = buildErrorResponse(actionResponse.right().value());
-            } else {
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-            }
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance");
-            log.debug("associate resource instance to another RI with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @PUT
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/dissociate")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Dissociate RI from RI", httpMethod = "PUT", notes = "Returns deleted RelationshipInfo", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship deleted"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response dissociateRIFromRI(
-            @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
-                    + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType,
-            @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, @Context final HttpServletRequest request) {
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        try {
-
-            log.debug(START_HANDLE_REQUEST_OF, url);
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-
-            Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data);
-            if (regInfoW.isRight()) {
-                BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - dissociateRIFromRI");
-                log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);
-                return buildErrorResponse(regInfoW.right().value());
-            }
-
-            RequirementCapabilityRelDef requirementDef = regInfoW.left().value();
-            Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceBusinessLogic.dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum);
-
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance");
-            log.debug("dissociate resource instance from service failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/createAndAssociate")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create RI and associate RI to RI", httpMethod = "POST", notes = "Returns created RI and RelationshipInfo", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "RI created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Relationship already exist") })
-    public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request) {
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-        try {
-
-            log.debug(START_HANDLE_REQUEST_OF, url);
-
-            InputStream inputStream = request.getInputStream();
-
-            byte[] bytes = IOUtils.toByteArray(inputStream);
-
-            if (bytes == null || bytes.length == 0) {
-                log.info(EMPTY_BODY_WAS_SENT);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-            }
-
-            String userId = request.getHeader(Constants.USER_ID_HEADER);
-
-            String data = new String(bytes);
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-
-            Either<CreateAndAssotiateInfo, ActionStatus> convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class);
-            if (convertStatus.isRight()) {
-                BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - createAndAssociateRIToRI");
-                log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);
-                Either<Object, ResponseFormat> formattedResponse = Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));
-                return buildErrorResponse(formattedResponse.right().value());
-            }
-
-            CreateAndAssotiateInfo createAndAssotiateInfo = convertStatus.left().value();
-            RequirementCapabilityRelDef requirementDef = createAndAssotiateInfo.getAssociate();
-            requirementDef.setOriginUI(true);
-            Either<CreateAndAssotiateInfo, ResponseFormat> actionResponse = componentInstanceBusinessLogic.createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo);
-
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create and Associate Resource Instance");
-            log.debug("create and associate RI failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/properties")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateResourceInstanceProperties(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @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,
-            @Context final HttpServletRequest request, @ApiParam(value = "Component Instance Properties JSON Array", required = true) final String componentInstancePropertiesJsonArray) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        try {
-            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
-            List<ComponentInstanceProperty> propertiesToUpdate = new ArrayList<>();
-            if (errorWrapper.isEmpty()) {
-                Either<List<ComponentInstanceProperty>, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties(componentInstancePropertiesJsonArray);
-                if (propertiesToUpdateEither.isRight()) {
-                    errorWrapper.setInnerElement(propertiesToUpdateEither.right().value());
-                } else {
-                    propertiesToUpdate = propertiesToUpdateEither.left().value();
-                }
-            }
-
-            if (!errorWrapper.isEmpty()) {
-                return buildErrorResponse(errorWrapper.getInnerElement());
-            }
-
-            log.debug(START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS, propertiesToUpdate);
-
-            ServletContext context = request.getSession().getServletContext();
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-
-            Either<List<ComponentInstanceProperty>, ResponseFormat> actionResponse =
-                componentInstanceBusinessLogic.createOrUpdatePropertiesValues(componentTypeEnum, componentId, componentInstanceId, propertiesToUpdate, userId);
-
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-
-            List<ComponentInstanceProperty> resourceInstanceProperties = actionResponse.left().value();
-            ObjectMapper mapper = new ObjectMapper();
-            String result = mapper.writeValueAsString(resourceInstanceProperties);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        } catch (Exception e) {
-            log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/inputs")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateResourceInstanceInput(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @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,
-            @Context final HttpServletRequest request, @ApiParam(value = "Component Instance Properties JSON Array", required = true) final String componentInstanceInputsJsonArray) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        try {
-            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
-            List<ComponentInstanceInput> inputsToUpdate = new ArrayList<>();
-            if (errorWrapper.isEmpty()) {
-                Either<List<ComponentInstanceInput>, ResponseFormat> inputsToUpdateEither = convertMultipleInputs(componentInstanceInputsJsonArray);
-                if (inputsToUpdateEither.isRight()) {
-                    errorWrapper.setInnerElement(inputsToUpdateEither.right().value());
-                } else {
-                    inputsToUpdate = inputsToUpdateEither.left().value();
-                }
-            }
-            if (!errorWrapper.isEmpty()) {
-                return buildErrorResponse(errorWrapper.getInnerElement());
-            }
-
-            log.debug(START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS, inputsToUpdate);
-
-            ServletContext context = request.getSession().getServletContext();
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-
-            Either<List<ComponentInstanceInput>, ResponseFormat> actionResponse =
-                componentInstanceBusinessLogic.createOrUpdateInstanceInputValues(componentTypeEnum, componentId, componentInstanceId, inputsToUpdate, userId);
-
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-
-            List<ComponentInstanceInput> resourceInstanceInput = actionResponse.left().value();
-            ObjectMapper mapper = new ObjectMapper();
-            String result = mapper.writeValueAsString(resourceInstanceInput);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        } catch (Exception e) {
-            log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    /**
-     * Updates ResourceInstance Attribute
-     *
-     * @param componentId
-     * @param containerComponentType
-     * @param componentInstanceId
-     * @param userId
-     * @param request
-     * @return
-     */
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/attribute")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update resource instance attribute", httpMethod = "POST", notes = "Returns updated resource instance attribute", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateResourceInstanceAttribute(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @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,
-            @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        try {
-
-            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
-            Wrapper<String> dataWrapper = new Wrapper<>();
-            Wrapper<ComponentInstanceProperty> attributeWrapper = new Wrapper<>();
-            Wrapper<ComponentInstanceBusinessLogic> blWrapper = new Wrapper<>();
-
-            validateInputStream(request, dataWrapper, errorWrapper);
-
-            if (errorWrapper.isEmpty()) {
-                validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
-            }
-
-            if (errorWrapper.isEmpty()) {
-                validateComponentInstanceBusinessLogic(request, containerComponentType, blWrapper, errorWrapper);
-            }
-
-            if (errorWrapper.isEmpty()) {
-                ComponentInstanceBusinessLogic componentInstanceLogic = blWrapper.getInnerElement();
-                ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-                log.debug("Start handle request of ComponentInstanceAttribute. Received attribute is {}", attributeWrapper.getInnerElement());
-                Either<ComponentInstanceProperty, ResponseFormat> eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId);
-                if (eitherAttribute.isRight()) {
-                    errorWrapper.setInnerElement(eitherAttribute.right().value());
-                } else {
-                    attributeWrapper.setInnerElement(eitherAttribute.left().value());
-                }
-            }
-
-            return buildResponseFromElement(errorWrapper, attributeWrapper);
-
-        } catch (Exception e) {
-            log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    @DELETE
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property/{propertyId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update resource instance", httpMethod = "DELETE", notes = "Returns deleted resource instance property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response deleteResourceInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "property id") @PathParam("propertyId") final String propertyId,
-            @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-        try {
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-
-            Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceBusinessLogic.deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId);
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
-        } catch (Exception e) {
-            log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/changeVersion")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response changeResourceInstanceVersion(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request) {
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-        try (    InputStream inputStream = request.getInputStream()) {
-
-            byte[] bytes = IOUtils.toByteArray(inputStream);
-
-            if (bytes == null || bytes.length == 0) {
-                log.info(EMPTY_BODY_WAS_SENT);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-            }
-
-            String userId = request.getHeader(Constants.USER_ID_HEADER);
-
-            String data = new String(bytes);
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-
-            Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
-
-            if (convertResponse.isRight()) {
-                BeEcompErrorManager.getInstance().logBeSystemError(RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE);
-                log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);
-                return buildErrorResponse(convertResponse.right().value());
-            }
-
-            ComponentInstance newResourceInstance = convertResponse.left().value();
-            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance);
-
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE);
-            log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateGroupInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @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, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        try {
-            Wrapper<String> dataWrapper = new Wrapper<>();
-            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
-            Wrapper<ComponentInstanceProperty> propertyWrapper = new Wrapper<>();
-
-            validateInputStream(request, dataWrapper, errorWrapper);
-
-            if (errorWrapper.isEmpty()) {
-                validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
-            }
-
-            if (!errorWrapper.isEmpty()) {
-                return buildErrorResponse(errorWrapper.getInnerElement());
-            }
-
-            ComponentInstanceProperty property = propertyWrapper.getInnerElement();
-
-            log.debug(START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS, property);
-
-            ServletContext context = request.getSession().getServletContext();
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-
-            Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceBusinessLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId);
-
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-
-            ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value();
-            ObjectMapper mapper = new ObjectMapper();
-            String result = mapper.writeValueAsString(resourceInstanceProperty);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        } catch (Exception e) {
-            log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    @GET
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupInstId", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") })
-    public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
-            @PathParam("groupInstId") final String groupInstId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(GET_START_HANDLE_REQUEST_OF, url);
-
-        try {
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            Either<GroupDefinitionInfo, ResponseFormat> actionResponse = groupBL
-                .getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId,
-                    groupInstId, userId, false);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to get all non abstract {}", containerComponentType);
-                return buildErrorResponse(actionResponse.right().value());
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID);
-            log.debug(GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    // US831698
-    @GET
-    @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get component instance properties", httpMethod = "GET", notes = "Returns component instance properties", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance - not found") })
-    public Response getInstancePropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId,
-            @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(GET_START_HANDLE_REQUEST_OF, url);
-
-        try {
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-
-            Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBusinessLogic.getComponentInstancePropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId);
-
-            if (componentInstancePropertiesById.isRight()) {
-                log.debug(FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID, componentInstanceUniqueId, containerComponentType, containerComponentId);
-                return buildErrorResponse(componentInstancePropertiesById.right().value());
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value());
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID);
-            log.debug(GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    // US330353
-    @GET
-    @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get component instance capability properties", httpMethod = "GET", notes = "Returns component instance capability properties", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") })
-    public Response getInstanceCapabilityPropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId,
-            @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName,  @PathParam("ownerId") final String ownerId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(GET_START_HANDLE_REQUEST_OF, url);
-
-        try {
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-
-            Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBusinessLogic.getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId,
-                    capabilityType, capabilityName, ownerId, userId);
-
-            if (componentInstancePropertiesById.isRight()) {
-                log.debug(FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID, componentInstanceUniqueId, containerComponentType, containerComponentId);
-                return buildErrorResponse(componentInstancePropertiesById.right().value());
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value());
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID);
-            log.debug(GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    //US 331281
-    @PUT
-    @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Instance Capabilty  Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance capabilty property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") })
-    public Response updateInstanceCapabilityProperty(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId,
-            @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, @PathParam("ownerId") final String ownerId,
-            @ApiParam(value = "Instance capabilty property to update", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(PUT) Start handle request of {}", url);
-        try {
-            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
-            List<ComponentInstanceProperty> propertiesToUpdate = new ArrayList<>();
-            if (errorWrapper.isEmpty()) {
-                Either<List<ComponentInstanceProperty>, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties(data);
-                if (propertiesToUpdateEither.isRight()) {
-                    errorWrapper.setInnerElement(propertiesToUpdateEither.right().value());
-                } else {
-                    propertiesToUpdate = propertiesToUpdateEither.left().value();
-                }
-            }
-
-            if (!errorWrapper.isEmpty()) {
-                return buildErrorResponse(errorWrapper.getInnerElement());
-            }
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-
-            Either<List<ComponentInstanceProperty>, ResponseFormat> updateCICapProperty = componentInstanceBusinessLogic.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, propertiesToUpdate, userId);
-
-            if (updateCICapProperty.isRight()) {
-                log.debug(FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID, componentInstanceUniqueId, containerComponentType, containerComponentId);
-                return buildErrorResponse(updateCICapProperty.right().value());
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateCICapProperty.left().value());
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID);
-            log.debug(GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{containerComponentId}/serviceProxy")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create service proxy", httpMethod = "POST", notes = "Returns created service proxy", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Service proxy already exist") })
-    public Response createServiceProxy(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("containerComponentId") final String containerComponentId,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) {
-        ServletContext context = request.getSession().getServletContext();
-
-        try {
-
-            ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);
-            componentInstance.setInvariantName(null);
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentTypeEnum != ComponentTypeEnum.SERVICE) {
-                log.debug("Unsupported container component type {}", containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.createServiceProxy();
-
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create service proxy");
-            log.debug("Create service proxy failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @DELETE
-    @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Delete service proxy", httpMethod = "DELETE", notes = "Returns delete service proxy", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response deleteServiceProxy(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId,
-            @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
-                    + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request) {
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        Response response = null;
-        try {
-            log.debug(START_HANDLE_REQUEST_OF, url);
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-            String userId = request.getHeader(Constants.USER_ID_HEADER);
-            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.deleteServiceProxy();
-
-            if (actionResponse.isRight()) {
-                response = buildErrorResponse(actionResponse.right().value());
-            } else {
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
-            }
-            return response;
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete service proxy");
-            log.debug("Delete service proxy failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}/changeVersion/{newServiceId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update service proxy with new version", httpMethod = "POST", notes = "Returns updated service proxy", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response changeServiceProxyVersion(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request) {
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-        try {
-
-            String userId = request.getHeader(Constants.USER_ID_HEADER);
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.changeServiceProxyVersion();
-
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update service proxy with new version");
-            log.debug("Update service proxy with new version failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-    /**
-     * REST API GET relation by Id
-     * Allows to get relation contained in specified component according to received Id
-     * @param containerComponentType
-     * @param componentId
-     * @param relationId
-     * @param request
-     * @param userId
-     * @return Response
-     */
-    @GET
-    @Path("/{containerComponentType}/{componentId}/relationId/{relationId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get relation", httpMethod = "GET", notes = "Returns relation metadata according to relationId", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "relation found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Relation not found") })
-    public Response getRelationById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId,
-            @PathParam("relationId") final String relationId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(GET_START_HANDLE_REQUEST_OF, url);
-        try {
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            if (componentTypeEnum == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-
-            Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceBusinessLogic.getRelationById(componentId, relationId, userId, componentTypeEnum);
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getRelationById");
-            log.debug("getRelationById unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    private Either<ComponentInstance, ResponseFormat> convertToResourceInstance(String data) {
-
-        Either<ComponentInstance, ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
-        if (convertStatus.isRight()) {
-            return Either.right(convertStatus.right().value());
-        }
-        ComponentInstance resourceInstanceInfo = convertStatus.left().value();
-
-        return Either.left(resourceInstanceInfo);
-    }
-
-    private Either<List<ComponentInstance>, ResponseFormat> convertToMultipleResourceInstance(String dataList) {
-
-        Either<ComponentInstance[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
-        if (convertStatus.isRight()) {
-            return Either.right(convertStatus.right().value());
-        }
-
-        return Either.left(Arrays.asList(convertStatus.left().value()));
-    }
-
-    private Either<List<ComponentInstanceProperty>, ResponseFormat> convertMultipleProperties(String dataList) {
-        if (StringUtils.isEmpty(dataList)) {
-            return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-        }
-        Either<ComponentInstanceProperty[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
-        if (convertStatus.isRight()) {
-            return Either.right(convertStatus.right().value());
-        }
-        return Either.left(Arrays.asList(convertStatus.left().value()));
-    }
-
-    private Either<List<ComponentInstanceInput>, ResponseFormat> convertMultipleInputs(String dataList) {
-        if (StringUtils.isEmpty(dataList)) {
-            return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-        }
-        Either<ComponentInstanceInput[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceInput[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
-        if (convertStatus.isRight()) {
-            return Either.right(convertStatus.right().value());
-        }
-        return Either.left(Arrays.asList(convertStatus.left().value()));
-    }
-
-
-    private Either<RequirementCapabilityRelDef, ResponseFormat> convertToRequirementCapabilityRelDef(String data) {
-
-        Either<RequirementCapabilityRelDef, ActionStatus> convertStatus = convertJsonToObject(data, RequirementCapabilityRelDef.class);
-        if (convertStatus.isRight()) {
-            return Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));
-        }
-        RequirementCapabilityRelDef requirementCapabilityRelDef = convertStatus.left().value();
-        return Either.left(requirementCapabilityRelDef);
-    }
-
-    public  <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {
-        try {
-            log.trace("convert json to object. json=\n {}", data);
-            T t;
-            t = gsonDeserializer.fromJson(data, clazz);
-            if (t == null) {
-                BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
-                log.debug("object is null after converting from json");
-                return Either.right(ActionStatus.INVALID_CONTENT);
-            }
-            return Either.left(t);
-        } catch (Exception e) {
-            // INVALID JSON
-            BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
-            log.debug("failed to convert from json", e);
-            return Either.right(ActionStatus.INVALID_CONTENT);
-        }
-    }
-
-
-    @GET
-    @Path("/{containerComponentType}/{componentId}/paths-to-delete")
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Check if forwarding path to delete on version change", httpMethod = "GET", notes = "Returns forwarding paths to delete",
-        response = Response.class)
-    public Response changeResourceInstanceVersion( @PathParam("componentId") String componentId,
-        @QueryParam("componentInstanceId") final String oldComponentInstanceId,
-        @QueryParam("newComponentInstanceId") final String newComponentInstanceId,
-        @ApiParam(value = "valid values: resources / services",
-            allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME)
-        @PathParam("containerComponentType") final String containerComponentType,
-        @Context final HttpServletRequest request) {
-        if (oldComponentInstanceId == null){
-            return  buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_OLD_COMPONENT_INSTANCE));
-        }
-        if (newComponentInstanceId == null){
-            return  buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_NEW_COMPONENT_INSTANCE));
-        }
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-        if (componentInstanceBusinessLogic == null) {
-            log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-        }
-        ComponentInstance newComponentInstance;
-        if(StringUtils.isNotEmpty(newComponentInstanceId)){
-            newComponentInstance=new ComponentInstance();
-            newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,newComponentInstanceId);
-        }else{
-            log.error("missing component id");
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_DATA));
-        }
-        Either<Set<String>,ResponseFormat> actionResponse= componentInstanceBusinessLogic.forwardingPathOnVersionChange(
-            containerComponentType,componentId,oldComponentInstanceId,newComponentInstance);
-        if (actionResponse.isRight()) {
-            return buildErrorResponse(actionResponse.right().value());
-        }
-        ForwardingPaths forwardingPaths=new ForwardingPaths();
-        forwardingPaths.setForwardingPathToDelete(actionResponse.left().value());
-        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), forwardingPaths);
-
-    }
-
-    @POST
-    @Path("/services/{componentId}/copyComponentInstance/{componentInstanceId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces((MediaType.APPLICATION_JSON))
-    @ApiOperation(value = "Copy Component Instance", httpMethod = "POST", notes = "Returns updated service information", response = Service.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 201, message = "Copy and Paste Success"),
-            @ApiResponse(code = 403, message = "Restricted Operation"),
-            @ApiResponse(code = 400, message = "Invalid Content / Missing content")})
-    public Response copyComponentInstance(
-            @ApiParam(value = "service unique id in pasted canvas") @PathParam("componentId") final String containerComponentId,
-            @ApiParam(value = "Data for copying", required = true) String data, @PathParam("componentInstanceId") final String componentInstanceId,
-            @Context final HttpServletRequest request) {
-        log.info("Start to copy component instance");
-        ServletContext context = request.getSession().getServletContext();
-        String userId = request.getHeader(Constants.USER_ID_HEADER);
-        final String CNTAINER_CMPT_TYPE = "services";
-
-        try {
-            ComponentInstance inputComponentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);
-            inputComponentInstance.setInvariantName(null);
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(CNTAINER_CMPT_TYPE);
-            if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, componentTypeEnum);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, "services"));
-            }
-            Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance = componentInstanceBusinessLogic.copyComponentInstance(
-                    inputComponentInstance, containerComponentId, componentInstanceId, userId);
-
-            if (copyComponentInstance.isRight()) {
-                log.error("Failed to copy ComponentInstance {}", copyComponentInstance.right().value());
-                return buildErrorResponse(copyComponentInstance.right().value());
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    copyComponentInstance.left().value());
-        } catch (Exception e) {
-            log.error("Failed to convert json to Map { }", data, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.USER_DEFINED,
-                    "Failed to get the copied component instance information"));
-        }
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/batchDeleteResourceInstances/")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Batch Delete ResourceInstances", httpMethod = "POST")
-    @ApiResponses(value = {
-            @ApiResponse(code = 203, message = "ResourceInstances deleted"),
-            @ApiResponse(code = 403, message = "Restricted Operation"),
-            @ApiResponse(code = 400, message = "Invalid Content / Missing Content")
-    })
-    public Response batchDeleteResourceInstances(
-            @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," +
-                    ComponentTypeEnum.PRODUCT_PARAM_NAME)
-            @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @Context final HttpServletRequest request,
-            @ApiParam(value = "Component Instance Id List", required = true) final String componentInstanceIdLisStr) {
-        try {
-            if (componentInstanceIdLisStr == null || componentInstanceIdLisStr.isEmpty()) {
-                log.error("Empty JSON List was sent",componentInstanceIdLisStr);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-            }
-
-
-            if (componentInstanceBusinessLogic == null) {
-                log.error("Unsupported component type {}", containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-
-            Either<List<String>, ResponseFormat> convertResponse = convertToStringList(componentInstanceIdLisStr);
-
-            if (convertResponse.isRight()) {
-                BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - batchDeleteResourceInstances");
-                log.error("Failed to convert received data to BE format.");
-                return buildErrorResponse(convertResponse.right().value());
-            }
-
-            String userId = request.getHeader(Constants.USER_ID_HEADER);
-            List<String> componentInstanceIdList = convertResponse.left().value();
-            log.debug("batchDeleteResourceInstances componentInstanceIdList is {}", componentInstanceIdList);
-            Map<String, List<String>> deleteErrorMap = componentInstanceBusinessLogic.batchDeleteComponentInstance(containerComponentType,
-                    componentId, componentInstanceIdList, userId);
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteErrorMap);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Batch Delete ResourceInstances");
-            log.error("batch delete resource instances with exception" , e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    @PUT
-    @Path("/{containerComponentType}/{componentId}/resourceInstance/batchDissociate")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Batch Dissociate RI from RI", httpMethod = "PUT", notes = "Returns deleted RelationShip Info", response = Response.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 201, message = "Relationship deleted"),
-            @ApiResponse(code = 403, message = "Missing Information"),
-            @ApiResponse(code = 400, message = "Invalid Content / Missing Content")
-    })
-    public Response batchDissociateRIFromRI(
-            @ApiParam(value = "allowed values are resources/services/products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true)
-            @PathParam("containerComponentType") final String containerComponentType,
-            @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,
-            @Context final HttpServletRequest request) {
-
-        try {
-            if (data == null || data.length() == 0) {
-                log.info("Empty JSON list was sent");
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-            }
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-
-            if (componentInstanceBusinessLogic == null) {
-                log.debug("Unsupported component type {}", containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
-            }
-
-            Either<List<RequirementCapabilityRelDef>, ResponseFormat> regInfoWs = convertToRequirementCapabilityRelDefList(data);
-
-            if (regInfoWs.isRight()) {
-                BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - batch dissociateRIFromRI");
-                log.debug("Failed to convert received data to BE format");
-                return buildErrorResponse(regInfoWs.right().value());
-            }
-
-            List<RequirementCapabilityRelDef> requirementDefList = regInfoWs.left().value();
-            List<RequirementCapabilityRelDef> delOkResult = componentInstanceBusinessLogic.batchDissociateRIFromRI(
-                    componentId, userId, requirementDefList, componentTypeEnum);
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), delOkResult);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Batch Dissociate Resource Instance");
-            log.debug("batch dissociate resource instance from service failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    private Either<List<String>, ResponseFormat> convertToStringList(String datalist) {
-        Either<String[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(datalist, new User(), String[].class, null, null);
-
-        if (convertStatus.isRight()) {
-            return Either.right(convertStatus.right().value());
-        }
-
-        return Either.left(Arrays.asList(convertStatus.left().value()));
-    }
-
-    private Either<List<RequirementCapabilityRelDef>, ResponseFormat> convertToRequirementCapabilityRelDefList(String data) {
-        Either<RequirementCapabilityRelDef[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), RequirementCapabilityRelDef[].class, null, null);
-
-        if (convertStatus.isRight()) {
-            return Either.right(convertStatus.right().value());
-        }
-
-        return Either.left(Arrays.asList(convertStatus.left().value()));
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.io.InputStream;\r
+import java.lang.reflect.Type;\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Set;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.QueryParam;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.io.IOUtils;\r
+import org.apache.commons.lang.StringUtils;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.utils.DirectivesUtils;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datamodel.ForwardingPaths;\r
+import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;\r
+import org.openecomp.sdc.be.info.GroupDefinitionInfo;\r
+import org.openecomp.sdc.be.model.ComponentInstance;\r
+import org.openecomp.sdc.be.model.ComponentInstanceInput;\r
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;\r
+import org.openecomp.sdc.be.model.PropertyConstraint;\r
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;\r
+import org.openecomp.sdc.be.model.Service;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.fasterxml.jackson.databind.ObjectMapper;\r
+import com.google.gson.Gson;\r
+import com.google.gson.GsonBuilder;\r
+import com.google.gson.reflect.TypeToken;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+/**\r
+ * Root resource (exposed at "/" path) .json\r
+ */\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Resource Instance Servlet"))\r
+@Singleton\r
+public class ComponentInstanceServlet extends AbstractValidationsServlet {\r
+\r
+    private static final String FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID =\r
+            "Failed to get properties of component instance ID: {} in {} with ID: {}";\r
+    private static final String GET_GROUP_ARTIFACT_BY_ID = "getGroupArtifactById";\r
+    private static final String GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION =\r
+            "getGroupArtifactById unexpected exception";\r
+    private static final String GET_START_HANDLE_REQUEST_OF = "(GET) Start handle request of {}";\r
+    private static final String START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS =\r
+            "Start handle request of updateResourceInstanceProperty. Received property is {}";\r
+    private static final String UPDATE_RESOURCE_INSTANCE = "Update Resource Instance";\r
+    private static final String RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE =\r
+            "Resource Instance - updateResourceInstance";\r
+    private static final String UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION = "update resource instance with exception";\r
+    private static final String FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT =\r
+            "Failed to convert received data to BE format.";\r
+    private static final String EMPTY_BODY_WAS_SENT = "Empty body was sent.";\r
+    private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";\r
+    private static final String UNSUPPORTED_COMPONENT_TYPE = "Unsupported component type {}";\r
+    private static final Logger log = Logger.getLogger(ComponentInstanceServlet.class);\r
+    private static final Type PROPERTY_CONSTRAINT_TYPE = new TypeToken<PropertyConstraint>() {}.getType();\r
+    private static final Gson gsonDeserializer = new GsonBuilder()\r
+            .registerTypeAdapter(PROPERTY_CONSTRAINT_TYPE, new PropertyConstraintDeserialiser()).create();\r
+    private final GroupBusinessLogic groupBL;\r
+    private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;\r
+    private final ServiceBusinessLogic serviceBusinessLogic;\r
+\r
+\r
+    @Inject\r
+    public ComponentInstanceServlet(UserBusinessLogic userBusinessLogic,\r
+        GroupBusinessLogic groupBL, ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        ServiceBusinessLogic serviceBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.groupBL = groupBL;\r
+        this.componentInstanceBusinessLogic = componentInstanceBL;\r
+        this.serviceBusinessLogic = serviceBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create ComponentInstance", method = "POST", summary = "Returns created ComponentInstance",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Component created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Component instance already exist")})\r
+    public Response createComponentInstance(@Parameter(description = "RI object to be created", required = true) String data,\r
+            @PathParam("componentId") final String containerComponentId,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",\r
+                    required = true) String userId,\r
+            @Context final HttpServletRequest request) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        try {\r
+\r
+            ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);\r
+            componentInstance.setInvariantName(null);\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(\r
+                        getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic\r
+                    .createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance);\r
+\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED),\r
+                    actionResponse.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance");\r
+            log.debug("create component instance failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update resource instance", method = "POST", summary = "Returns updated resource instance",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource instance updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId,\r
+            @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @Parameter(description = "valid values: resources / services / products",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME,\r
+                            ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+        try {\r
+\r
+            log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+            InputStream inputStream = request.getInputStream();\r
+\r
+            byte[] bytes = IOUtils.toByteArray(inputStream);\r
+\r
+            if (bytes == null || bytes.length == 0) {\r
+                log.info(EMPTY_BODY_WAS_SENT);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+            }\r
+\r
+            String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+\r
+            String data = new String(bytes);\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(\r
+                        getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+            Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);\r
+\r
+            if (convertResponse.isRight()) {\r
+                BeEcompErrorManager.getInstance().logBeSystemError(RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE);\r
+                log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);\r
+                return buildErrorResponse(convertResponse.right().value());\r
+            }\r
+\r
+            ComponentInstance resourceInstance = convertResponse.left().value();\r
+            Either<ComponentInstance, ResponseFormat> actionResponse =\r
+                    componentInstanceBusinessLogic.updateComponentInstanceMetadata(containerComponentType, componentId,\r
+                            componentInstanceId, userId, resourceInstance);\r
+\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            ComponentInstance resultValue = actionResponse.left().value();\r
+            if (componentTypeEnum.equals(ComponentTypeEnum.SERVICE)) {\r
+                boolean shouldCreateServiceFilter = resourceInstance.getDirectives() != null\r
+                        && resourceInstance.getDirectives().contains(DirectivesUtils.SELECTABLE);\r
+\r
+                if (shouldCreateServiceFilter) {\r
+                    Either<CINodeFilterDataDefinition, ResponseFormat> either = serviceBusinessLogic\r
+                            .createIfNotAlreadyExistServiceFilter(componentId, componentInstanceId, userId, true);\r
+                    if (either.isRight()) {\r
+                        BeEcompErrorManager.getInstance().logBeSystemError(\r
+                                "Resource Instance - updateResourceInstance Failed to create service filter.");\r
+                        log.debug("Failed to create service filter.");\r
+                        return buildErrorResponse(convertResponse.right().value());\r
+                    }\r
+                    resultValue.setNodeFilter(either.left().value());\r
+                } else {\r
+                    Either<String, ResponseFormat> either = serviceBusinessLogic\r
+                            .deleteIfNotAlreadyDeletedServiceFilter(componentId, componentInstanceId, userId, true);\r
+                    if (either.isRight()) {\r
+                        BeEcompErrorManager.getInstance().logBeSystemError(\r
+                                "Resource Instance - updateResourceInstance Failed to delete service filter.");\r
+                        log.debug("Failed to delete service filter.");\r
+                        return buildErrorResponse(convertResponse.right().value());\r
+                    }\r
+                    resultValue.setNodeFilter(null);\r
+                }\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    actionResponse.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE);\r
+            log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update resource instance multiple component", method = "POST",\r
+            summary = "Returns updated resource instance", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource instance updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId, @Parameter(\r
+            description = "valid values: resources / services / products",\r
+            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                    ComponentTypeEnum.SERVICE_PARAM_NAME,\r
+                    ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Context final HttpServletRequest request, @Parameter(description = "Component Instance JSON Array",\r
+                    required = true) final String componentInstanceJsonArray) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        try {\r
+            log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+            if (componentInstanceJsonArray == null || componentInstanceJsonArray.length() == 0) {\r
+                log.info("Empty JSON list was sent.");\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+            }\r
+\r
+            String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(\r
+                        getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+\r
+            Either<List<ComponentInstance>, ResponseFormat> convertResponse =\r
+                    convertToMultipleResourceInstance(componentInstanceJsonArray);\r
+\r
+            if (convertResponse.isRight()) {\r
+                // Using both ECOMP error methods, show to Sofer\r
+                BeEcompErrorManager.getInstance().logBeSystemError(RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE);\r
+                log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);\r
+                return buildErrorResponse(convertResponse.right().value());\r
+            }\r
+\r
+            List<ComponentInstance> componentInstanceList = convertResponse.left().value();\r
+\r
+            Either<List<ComponentInstance>, ResponseFormat> actionResponse = componentInstanceBusinessLogic\r
+                    .updateComponentInstance(containerComponentType, componentId, userId, componentInstanceList, true);\r
+\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    actionResponse.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE);\r
+            log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{resourceInstanceId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Delete ResourceInstance", method = "DELETE", summary = "Returns delete resourceInstance",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "ResourceInstance deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response deleteResourceInstance(@PathParam("componentId") final String componentId,\r
+            @PathParam("resourceInstanceId") final String resourceInstanceId,\r
+            @Parameter(description = "valid values: resources / services / products",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME,\r
+                            ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Context final HttpServletRequest request) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        Response response = null;\r
+        try {\r
+            log.debug(START_HANDLE_REQUEST_OF, url);\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(\r
+                        getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+            String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic\r
+                    .deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId);\r
+\r
+            if (actionResponse.isRight()) {\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+            } else {\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);\r
+            }\r
+            return response;\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance");\r
+            log.debug("delete resource instance with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @Parameter(description = "allowed values are resources /services / products",\r
+            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                    ComponentTypeEnum.SERVICE_PARAM_NAME,\r
+                    ComponentTypeEnum.PRODUCT_PARAM_NAME}),\r
+            required = true)\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/associate")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Associate RI to RI", method = "POST", summary = "Returns created RelationshipInfo",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Relationship created"),\r
+            @ApiResponse(responseCode = "403", description = "Missing information"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Relationship already exist")})\r
+    public Response associateRIToRI(@Parameter(\r
+            description = "unique id of the container component") @PathParam("componentId") final String componentId,\r
+            @Parameter(description = "allowed values are resources /services / products",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME}),\r
+                    required = true) @PathParam("containerComponentType") final String containerComponentType,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "RelationshipInfo", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+        Response response = null;\r
+\r
+        try {\r
+\r
+            log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+\r
+            Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data);\r
+\r
+            Either<RequirementCapabilityRelDef, ResponseFormat> resultOp;\r
+            if (regInfoW.isRight()) {\r
+                BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - associateRIToRI");\r
+                log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);\r
+                resultOp = Either.right(regInfoW.right().value());\r
+            } else {\r
+                RequirementCapabilityRelDef requirementDef = regInfoW.left().value();\r
+                requirementDef.setOriginUI(true);\r
+                resultOp = componentInstanceBusinessLogic.associateRIToRI(componentId, userId, requirementDef, componentTypeEnum);\r
+            }\r
+\r
+            Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = resultOp;\r
+\r
+            if (actionResponse.isRight()) {\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+            } else {\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());\r
+            }\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance");\r
+            log.debug("associate resource instance to another RI with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @PUT\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/dissociate")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Dissociate RI from RI", method = "PUT", summary = "Returns deleted RelationshipInfo",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Relationship deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Missing information"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response dissociateRIFromRI(\r
+            @Parameter(description = "allowed values are resources /services / products",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME}),\r
+                    required = true) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Parameter(\r
+                    description = "unique id of the container component") @PathParam("componentId") final String componentId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "RelationshipInfo", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        try {\r
+\r
+            log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+\r
+            Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data);\r
+            if (regInfoW.isRight()) {\r
+                BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - dissociateRIFromRI");\r
+                log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);\r
+                return buildErrorResponse(regInfoW.right().value());\r
+            }\r
+\r
+            RequirementCapabilityRelDef requirementDef = regInfoW.left().value();\r
+            Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceBusinessLogic.dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum);\r
+\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance");\r
+            log.debug("dissociate resource instance from service failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/createAndAssociate")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create RI and associate RI to RI", method = "POST",\r
+            summary = "Returns created RI and RelationshipInfo", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "RI created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Relationship already exist")})\r
+    public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId, @Parameter(\r
+            description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Context final HttpServletRequest request) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+        try {\r
+\r
+            log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+            InputStream inputStream = request.getInputStream();\r
+\r
+            byte[] bytes = IOUtils.toByteArray(inputStream);\r
+\r
+            if (bytes == null || bytes.length == 0) {\r
+                log.info(EMPTY_BODY_WAS_SENT);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+            }\r
+\r
+            String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+\r
+            String data = new String(bytes);\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+\r
+            Either<CreateAndAssotiateInfo, ActionStatus> convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class);\r
+            if (convertStatus.isRight()) {\r
+                BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - createAndAssociateRIToRI");\r
+                log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);\r
+                Either<Object, ResponseFormat> formattedResponse = Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));\r
+                return buildErrorResponse(formattedResponse.right().value());\r
+            }\r
+\r
+            CreateAndAssotiateInfo createAndAssotiateInfo = convertStatus.left().value();\r
+            RequirementCapabilityRelDef requirementDef = createAndAssotiateInfo.getAssociate();\r
+            requirementDef.setOriginUI(true);\r
+            Either<CreateAndAssotiateInfo, ResponseFormat> actionResponse = componentInstanceBusinessLogic.createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo);\r
+\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create and Associate Resource Instance");\r
+            log.debug("create and associate RI failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/properties")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update resource instance property", method = "POST",\r
+            summary = "Returns updated resource instance property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource instance created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateResourceInstanceProperties(\r
+            @Parameter(description = "service id") @PathParam("componentId") final String componentId,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Parameter(\r
+                    description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @Parameter(description = "id of user initiating the operation") @HeaderParam(\r
+                    value = Constants.USER_ID_HEADER) String userId,\r
+            @Context final HttpServletRequest request,\r
+            @Parameter(description = "Component Instance Properties JSON Array",\r
+                    required = true) final String componentInstancePropertiesJsonArray) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        try {\r
+            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();\r
+            List<ComponentInstanceProperty> propertiesToUpdate = new ArrayList<>();\r
+            if (errorWrapper.isEmpty()) {\r
+                Either<List<ComponentInstanceProperty>, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties(componentInstancePropertiesJsonArray);\r
+                if (propertiesToUpdateEither.isRight()) {\r
+                    errorWrapper.setInnerElement(propertiesToUpdateEither.right().value());\r
+                } else {\r
+                    propertiesToUpdate = propertiesToUpdateEither.left().value();\r
+                }\r
+            }\r
+\r
+            if (!errorWrapper.isEmpty()) {\r
+                return buildErrorResponse(errorWrapper.getInnerElement());\r
+            }\r
+\r
+            log.debug(START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS, propertiesToUpdate);\r
+\r
+            ServletContext context = request.getSession().getServletContext();\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+\r
+            Either<List<ComponentInstanceProperty>, ResponseFormat> actionResponse =\r
+                componentInstanceBusinessLogic.createOrUpdatePropertiesValues(componentTypeEnum, componentId, componentInstanceId, propertiesToUpdate, userId);\r
+\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+\r
+            List<ComponentInstanceProperty> resourceInstanceProperties = actionResponse.left().value();\r
+            ObjectMapper mapper = new ObjectMapper();\r
+            String result = mapper.writeValueAsString(resourceInstanceProperties);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        } catch (Exception e) {\r
+            log.error("create and associate RI failed with exception: {}", e.getMessage(), e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/inputs")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update resource instance property", method = "POST",\r
+            summary = "Returns updated resource instance property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource instance created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateResourceInstanceInput(\r
+            @Parameter(description = "service id") @PathParam("componentId") final String componentId,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Parameter(\r
+                    description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @Parameter(description = "id of user initiating the operation") @HeaderParam(\r
+                    value = Constants.USER_ID_HEADER) String userId,\r
+            @Context final HttpServletRequest request,\r
+            @Parameter(description = "Component Instance Properties JSON Array",\r
+                    required = true) final String componentInstanceInputsJsonArray) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        try {\r
+            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();\r
+            List<ComponentInstanceInput> inputsToUpdate = new ArrayList<>();\r
+            if (errorWrapper.isEmpty()) {\r
+                Either<List<ComponentInstanceInput>, ResponseFormat> inputsToUpdateEither = convertMultipleInputs(componentInstanceInputsJsonArray);\r
+                if (inputsToUpdateEither.isRight()) {\r
+                    errorWrapper.setInnerElement(inputsToUpdateEither.right().value());\r
+                } else {\r
+                    inputsToUpdate = inputsToUpdateEither.left().value();\r
+                }\r
+            }\r
+            if (!errorWrapper.isEmpty()) {\r
+                return buildErrorResponse(errorWrapper.getInnerElement());\r
+            }\r
+\r
+            log.debug(START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS, inputsToUpdate);\r
+\r
+            ServletContext context = request.getSession().getServletContext();\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+\r
+            Either<List<ComponentInstanceInput>, ResponseFormat> actionResponse =\r
+                componentInstanceBusinessLogic.createOrUpdateInstanceInputValues(componentTypeEnum, componentId, componentInstanceId, inputsToUpdate, userId);\r
+\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+\r
+            List<ComponentInstanceInput> resourceInstanceInput = actionResponse.left().value();\r
+            ObjectMapper mapper = new ObjectMapper();\r
+            String result = mapper.writeValueAsString(resourceInstanceInput);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        } catch (Exception e) {\r
+            log.error("create and associate RI failed with exception: {}", e.getMessage(), e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    /**\r
+     * Updates ResourceInstance Attribute\r
+     *\r
+     * @param componentId\r
+     * @param containerComponentType\r
+     * @param componentInstanceId\r
+     * @param userId\r
+     * @param request\r
+     * @return\r
+     */\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/attribute")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update resource instance attribute", method = "POST",\r
+            summary = "Returns updated resource instance attribute", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource instance created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateResourceInstanceAttribute(\r
+            @Parameter(description = "service id") @PathParam("componentId") final String componentId,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Parameter(\r
+                    description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @Parameter(description = "id of user initiating the operation") @HeaderParam(\r
+                    value = Constants.USER_ID_HEADER) String userId,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        try {\r
+\r
+            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();\r
+            Wrapper<String> dataWrapper = new Wrapper<>();\r
+            Wrapper<ComponentInstanceProperty> attributeWrapper = new Wrapper<>();\r
+            Wrapper<ComponentInstanceBusinessLogic> blWrapper = new Wrapper<>();\r
+\r
+            validateInputStream(request, dataWrapper, errorWrapper);\r
+\r
+            if (errorWrapper.isEmpty()) {\r
+                validateClassParse(dataWrapper.getInnerElement(), attributeWrapper,\r
+                        () -> ComponentInstanceProperty.class, errorWrapper);\r
+            }\r
+\r
+            if (errorWrapper.isEmpty()) {\r
+                validateComponentInstanceBusinessLogic(request, containerComponentType, blWrapper, errorWrapper);\r
+            }\r
+\r
+            if (errorWrapper.isEmpty()) {\r
+                ComponentInstanceBusinessLogic componentInstanceLogic = blWrapper.getInnerElement();\r
+                ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+                log.debug("Start handle request of ComponentInstanceAttribute. Received attribute is {}",\r
+                        attributeWrapper.getInnerElement());\r
+                Either<ComponentInstanceProperty, ResponseFormat> eitherAttribute =\r
+                        componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId,\r
+                                componentInstanceId, attributeWrapper.getInnerElement(), userId);\r
+                if (eitherAttribute.isRight()) {\r
+                    errorWrapper.setInnerElement(eitherAttribute.right().value());\r
+                } else {\r
+                    attributeWrapper.setInnerElement(eitherAttribute.left().value());\r
+                }\r
+            }\r
+\r
+            return buildResponseFromElement(errorWrapper, attributeWrapper);\r
+\r
+        } catch (Exception e) {\r
+            log.error("create and associate RI failed with exception: {}", e.getMessage(), e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property/{propertyId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update resource instance", method = "DELETE",\r
+            summary = "Returns deleted resource instance property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource instance created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response deleteResourceInstanceProperty(\r
+            @Parameter(description = "service id") @PathParam("componentId") final String componentId,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Parameter(\r
+                    description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @Parameter(description = "property id") @PathParam("propertyId") final String propertyId,\r
+            @Parameter(description = "id of user initiating the operation") @HeaderParam(\r
+                    value = Constants.USER_ID_HEADER) String userId,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+        try {\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(\r
+                        getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+\r
+            Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceBusinessLogic\r
+                    .deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId);\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);\r
+        } catch (Exception e) {\r
+            log.error("create and associate RI failed with exception: {}", e.getMessage(), e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/changeVersion")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update resource instance", method = "POST", summary = "Returns updated resource instance",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource instance created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response changeResourceInstanceVersion(@PathParam("componentId") final String componentId,\r
+            @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Context final HttpServletRequest request) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+        try (    InputStream inputStream = request.getInputStream()) {\r
+\r
+            byte[] bytes = IOUtils.toByteArray(inputStream);\r
+\r
+            if (bytes == null || bytes.length == 0) {\r
+                log.info(EMPTY_BODY_WAS_SENT);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+            }\r
+\r
+            String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+\r
+            String data = new String(bytes);\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+\r
+            Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);\r
+\r
+            if (convertResponse.isRight()) {\r
+                BeEcompErrorManager.getInstance().logBeSystemError(RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE);\r
+                log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);\r
+                return buildErrorResponse(convertResponse.right().value());\r
+            }\r
+\r
+            ComponentInstance newResourceInstance = convertResponse.left().value();\r
+            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance);\r
+\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE);\r
+            log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update resource instance property", method = "POST",\r
+            summary = "Returns updated resource instance property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource instance created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateGroupInstanceProperty(\r
+            @Parameter(description = "service id") @PathParam("componentId") final String componentId,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Parameter(\r
+                    description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @Parameter(description = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId,\r
+            @Parameter(description = "id of user initiating the operation") @HeaderParam(\r
+                    value = Constants.USER_ID_HEADER) String userId,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        try {\r
+            Wrapper<String> dataWrapper = new Wrapper<>();\r
+            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();\r
+            Wrapper<ComponentInstanceProperty> propertyWrapper = new Wrapper<>();\r
+\r
+            validateInputStream(request, dataWrapper, errorWrapper);\r
+\r
+            if (errorWrapper.isEmpty()) {\r
+                validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper);\r
+            }\r
+\r
+            if (!errorWrapper.isEmpty()) {\r
+                return buildErrorResponse(errorWrapper.getInnerElement());\r
+            }\r
+\r
+            ComponentInstanceProperty property = propertyWrapper.getInnerElement();\r
+\r
+            log.debug(START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS, property);\r
+\r
+            ServletContext context = request.getSession().getServletContext();\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+\r
+            Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceBusinessLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId);\r
+\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+\r
+            ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value();\r
+            ObjectMapper mapper = new ObjectMapper();\r
+            String result = mapper.writeValueAsString(resourceInstanceProperty);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        } catch (Exception e) {\r
+            log.error("create and associate RI failed with exception: {}", e.getMessage(), e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    @GET\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get group artifacts ", method = "GET",\r
+            summary = "Returns artifacts metadata according to groupInstId", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "group found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Group not found")})\r
+    public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @PathParam("groupInstId") final String groupInstId, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(GET_START_HANDLE_REQUEST_OF, url);\r
+\r
+        try {\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            Either<GroupDefinitionInfo, ResponseFormat> actionResponse = groupBL\r
+                .getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId,\r
+                    groupInstId, userId, false);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to get all non abstract {}", containerComponentType);\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID);\r
+            log.debug(GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION, e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    // US831698\r
+    @GET\r
+    @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get component instance properties", method = "GET",\r
+            summary = "Returns component instance properties", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Properties found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component/Component Instance - not found")})\r
+    public Response getInstancePropertiesById(@PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("containerComponentId") final String containerComponentId,\r
+            @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(GET_START_HANDLE_REQUEST_OF, url);\r
+\r
+        try {\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+\r
+            Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBusinessLogic.getComponentInstancePropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId);\r
+\r
+            if (componentInstancePropertiesById.isRight()) {\r
+                log.debug(FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID, componentInstanceUniqueId, containerComponentType, containerComponentId);\r
+                return buildErrorResponse(componentInstancePropertiesById.right().value());\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value());\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID);\r
+            log.debug(GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION, e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    // US330353\r
+    @GET\r
+    @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get component instance capability properties", method = "GET",\r
+            summary = "Returns component instance capability properties", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Properties found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component/Component Instance/Capability - not found")})\r
+    public Response getInstanceCapabilityPropertiesById(\r
+            @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("containerComponentId") final String containerComponentId,\r
+            @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,\r
+            @PathParam("capabilityType") final String capabilityType,\r
+            @PathParam("capabilityName") final String capabilityName, @PathParam("ownerId") final String ownerId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(GET_START_HANDLE_REQUEST_OF, url);\r
+\r
+        try {\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+\r
+            Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBusinessLogic.getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId,\r
+                    capabilityType, capabilityName, ownerId, userId);\r
+\r
+            if (componentInstancePropertiesById.isRight()) {\r
+                log.debug(FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID, componentInstanceUniqueId, containerComponentType, containerComponentId);\r
+                return buildErrorResponse(componentInstancePropertiesById.right().value());\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value());\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID);\r
+            log.debug(GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION, e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    //US 331281\r
+    @PUT\r
+    @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Instance Capabilty  Property", method = "PUT",\r
+            summary = "Returns updated property", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(\r
+            value = {@ApiResponse(responseCode = "200", description = "Resource instance capabilty property updated"),\r
+                    @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+                    @ApiResponse(responseCode = "404", description = "Component/Component Instance/Capability - not found")})\r
+    public Response updateInstanceCapabilityProperty(\r
+            @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("containerComponentId") final String containerComponentId,\r
+            @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,\r
+            @PathParam("capabilityType") final String capabilityType,\r
+            @PathParam("capabilityName") final String capabilityName, @PathParam("ownerId") final String ownerId,\r
+            @Parameter(description = "Instance capabilty property to update", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(PUT) Start handle request of {}", url);\r
+        try {\r
+            Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();\r
+            List<ComponentInstanceProperty> propertiesToUpdate = new ArrayList<>();\r
+            if (errorWrapper.isEmpty()) {\r
+                Either<List<ComponentInstanceProperty>, ResponseFormat> propertiesToUpdateEither =\r
+                        convertMultipleProperties(data);\r
+                if (propertiesToUpdateEither.isRight()) {\r
+                    errorWrapper.setInnerElement(propertiesToUpdateEither.right().value());\r
+                } else {\r
+                    propertiesToUpdate = propertiesToUpdateEither.left().value();\r
+                }\r
+            }\r
+\r
+            if (!errorWrapper.isEmpty()) {\r
+                return buildErrorResponse(errorWrapper.getInnerElement());\r
+            }\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+\r
+            Either<List<ComponentInstanceProperty>, ResponseFormat> updateCICapProperty = componentInstanceBusinessLogic.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, propertiesToUpdate, userId);\r
+\r
+            if (updateCICapProperty.isRight()) {\r
+                log.debug(FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID, componentInstanceUniqueId, containerComponentType, containerComponentId);\r
+                return buildErrorResponse(updateCICapProperty.right().value());\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateCICapProperty.left().value());\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID);\r
+            log.debug(GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION, e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{containerComponentId}/serviceProxy")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create service proxy", method = "POST", summary = "Returns created service proxy",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Service proxy created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Service proxy already exist")})\r
+    public Response createServiceProxy(@Parameter(description = "RI object to be created", required = true) String data,\r
+            @PathParam("containerComponentId") final String containerComponentId,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",\r
+                    required = true) String userId,\r
+            @Context final HttpServletRequest request) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        try {\r
+\r
+            ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);\r
+            componentInstance.setInvariantName(null);\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentTypeEnum != ComponentTypeEnum.SERVICE) {\r
+                log.debug("Unsupported container component type {}", containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.createServiceProxy();\r
+\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create service proxy");\r
+            log.debug("Create service proxy failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Delete service proxy", method = "DELETE", summary = "Returns delete service proxy",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Service proxy deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response deleteServiceProxy(@PathParam("containerComponentId") final String containerComponentId,\r
+            @PathParam("serviceProxyId") final String serviceProxyId,\r
+            @Parameter(description = "valid values: resources / services / products",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Context final HttpServletRequest request) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        Response response = null;\r
+        try {\r
+            log.debug(START_HANDLE_REQUEST_OF, url);\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+            String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.deleteServiceProxy();\r
+\r
+            if (actionResponse.isRight()) {\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+            } else {\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);\r
+            }\r
+            return response;\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete service proxy");\r
+            log.debug("Delete service proxy failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}/changeVersion/{newServiceId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update service proxy with new version", method = "POST",\r
+            summary = "Returns updated service proxy", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Service proxy created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response changeServiceProxyVersion(@PathParam("containerComponentId") final String containerComponentId,\r
+            @PathParam("serviceProxyId") final String serviceProxyId,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Context final HttpServletRequest request) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+        try {\r
+\r
+            String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+            Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.changeServiceProxyVersion();\r
+\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update service proxy with new version");\r
+            log.debug("Update service proxy with new version failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+    /**\r
+     * REST API GET relation by Id\r
+     * Allows to get relation contained in specified component according to received Id\r
+     * @param containerComponentType\r
+     * @param componentId\r
+     * @param relationId\r
+     * @param request\r
+     * @param userId\r
+     * @return Response\r
+     */\r
+    @GET\r
+    @Path("/{containerComponentType}/{componentId}/relationId/{relationId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get relation", method = "GET",\r
+            summary = "Returns relation metadata according to relationId",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "relation found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Relation not found")})\r
+    public Response getRelationById(@PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("relationId") final String relationId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(GET_START_HANDLE_REQUEST_OF, url);\r
+        try {\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            if (componentTypeEnum == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+\r
+            Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceBusinessLogic.getRelationById(componentId, relationId, userId, componentTypeEnum);\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getRelationById");\r
+            log.debug("getRelationById unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    private Either<ComponentInstance, ResponseFormat> convertToResourceInstance(String data) {\r
+\r
+        Either<ComponentInstance, ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE);\r
+        if (convertStatus.isRight()) {\r
+            return Either.right(convertStatus.right().value());\r
+        }\r
+        ComponentInstance resourceInstanceInfo = convertStatus.left().value();\r
+\r
+        return Either.left(resourceInstanceInfo);\r
+    }\r
+\r
+    private Either<List<ComponentInstance>, ResponseFormat> convertToMultipleResourceInstance(String dataList) {\r
+\r
+        Either<ComponentInstance[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);\r
+        if (convertStatus.isRight()) {\r
+            return Either.right(convertStatus.right().value());\r
+        }\r
+\r
+        return Either.left(Arrays.asList(convertStatus.left().value()));\r
+    }\r
+\r
+    private Either<List<ComponentInstanceProperty>, ResponseFormat> convertMultipleProperties(String dataList) {\r
+        if (StringUtils.isEmpty(dataList)) {\r
+            return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+        }\r
+        Either<ComponentInstanceProperty[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);\r
+        if (convertStatus.isRight()) {\r
+            return Either.right(convertStatus.right().value());\r
+        }\r
+        return Either.left(Arrays.asList(convertStatus.left().value()));\r
+    }\r
+\r
+    private Either<List<ComponentInstanceInput>, ResponseFormat> convertMultipleInputs(String dataList) {\r
+        if (StringUtils.isEmpty(dataList)) {\r
+            return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+        }\r
+        Either<ComponentInstanceInput[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceInput[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);\r
+        if (convertStatus.isRight()) {\r
+            return Either.right(convertStatus.right().value());\r
+        }\r
+        return Either.left(Arrays.asList(convertStatus.left().value()));\r
+    }\r
+\r
+\r
+    private Either<RequirementCapabilityRelDef, ResponseFormat> convertToRequirementCapabilityRelDef(String data) {\r
+\r
+        Either<RequirementCapabilityRelDef, ActionStatus> convertStatus = convertJsonToObject(data, RequirementCapabilityRelDef.class);\r
+        if (convertStatus.isRight()) {\r
+            return Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));\r
+        }\r
+        RequirementCapabilityRelDef requirementCapabilityRelDef = convertStatus.left().value();\r
+        return Either.left(requirementCapabilityRelDef);\r
+    }\r
+\r
+    public  <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {\r
+        try {\r
+            log.trace("convert json to object. json=\n {}", data);\r
+            T t;\r
+            t = gsonDeserializer.fromJson(data, clazz);\r
+            if (t == null) {\r
+                BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");\r
+                log.debug("object is null after converting from json");\r
+                return Either.right(ActionStatus.INVALID_CONTENT);\r
+            }\r
+            return Either.left(t);\r
+        } catch (Exception e) {\r
+            // INVALID JSON\r
+            BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");\r
+            log.debug("failed to convert from json", e);\r
+            return Either.right(ActionStatus.INVALID_CONTENT);\r
+        }\r
+    }\r
+\r
+\r
+    @GET\r
+    @Path("/{containerComponentType}/{componentId}/paths-to-delete")\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Check if forwarding path to delete on version change", method = "GET", summary = "Returns forwarding paths to delete",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    public Response changeResourceInstanceVersion( @PathParam("componentId") String componentId,\r
+        @QueryParam("componentInstanceId") final String oldComponentInstanceId,\r
+        @QueryParam("newComponentInstanceId") final String newComponentInstanceId,\r
+        @Parameter(description = "valid values: resources / services",\r
+                schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                        ComponentTypeEnum.SERVICE_PARAM_NAME}))\r
+        @PathParam("containerComponentType") final String containerComponentType,\r
+        @Context final HttpServletRequest request) {\r
+        if (oldComponentInstanceId == null){\r
+            return  buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_OLD_COMPONENT_INSTANCE));\r
+        }\r
+        if (newComponentInstanceId == null){\r
+            return  buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_NEW_COMPONENT_INSTANCE));\r
+        }\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+        if (componentInstanceBusinessLogic == null) {\r
+            log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+        }\r
+        ComponentInstance newComponentInstance;\r
+        if(StringUtils.isNotEmpty(newComponentInstanceId)){\r
+            newComponentInstance=new ComponentInstance();\r
+            newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,newComponentInstanceId);\r
+        }else{\r
+            log.error("missing component id");\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_DATA));\r
+        }\r
+        Either<Set<String>,ResponseFormat> actionResponse= componentInstanceBusinessLogic.forwardingPathOnVersionChange(\r
+            containerComponentType,componentId,oldComponentInstanceId,newComponentInstance);\r
+        if (actionResponse.isRight()) {\r
+            return buildErrorResponse(actionResponse.right().value());\r
+        }\r
+        ForwardingPaths forwardingPaths=new ForwardingPaths();\r
+        forwardingPaths.setForwardingPathToDelete(actionResponse.left().value());\r
+        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), forwardingPaths);\r
+\r
+    }\r
+\r
+    @POST\r
+    @Path("/services/{componentId}/copyComponentInstance/{componentInstanceId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces((MediaType.APPLICATION_JSON))\r
+    @Operation(description = "Copy Component Instance", method = "POST", summary = "Returns updated service information",responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "201", description = "Copy and Paste Success"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted Operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid Content / Missing content")})\r
+    public Response copyComponentInstance(\r
+            @Parameter(description = "service unique id in pasted canvas") @PathParam("componentId") final String containerComponentId,\r
+            @Parameter(description = "Data for copying", required = true) String data, @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @Context final HttpServletRequest request) {\r
+        log.info("Start to copy component instance");\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+        final String CNTAINER_CMPT_TYPE = "services";\r
+\r
+        try {\r
+            ComponentInstance inputComponentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);\r
+            inputComponentInstance.setInvariantName(null);\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(CNTAINER_CMPT_TYPE);\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug(UNSUPPORTED_COMPONENT_TYPE, componentTypeEnum);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, "services"));\r
+            }\r
+            Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance = componentInstanceBusinessLogic.copyComponentInstance(\r
+                    inputComponentInstance, containerComponentId, componentInstanceId, userId);\r
+\r
+            if (copyComponentInstance.isRight()) {\r
+                log.error("Failed to copy ComponentInstance {}", copyComponentInstance.right().value());\r
+                return buildErrorResponse(copyComponentInstance.right().value());\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    copyComponentInstance.left().value());\r
+        } catch (Exception e) {\r
+            log.error("Failed to convert json to Map { }", data, e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.USER_DEFINED,\r
+                    "Failed to get the copied component instance information"));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/batchDeleteResourceInstances/")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Batch Delete ResourceInstances", method = "POST")\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "203", description = "ResourceInstances deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted Operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid Content / Missing Content")\r
+    })\r
+    public Response batchDeleteResourceInstances(\r
+            @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                    ComponentTypeEnum.SERVICE_PARAM_NAME,\r
+                    ComponentTypeEnum.PRODUCT_PARAM_NAME}))\r
+            @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @Context final HttpServletRequest request,\r
+            @Parameter(description = "Component Instance Id List", required = true) final String componentInstanceIdLisStr) {\r
+        try {\r
+            if (componentInstanceIdLisStr == null || componentInstanceIdLisStr.isEmpty()) {\r
+                log.error("Empty JSON List was sent",componentInstanceIdLisStr);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+            }\r
+\r
+\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.error("Unsupported component type {}", containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+\r
+            Either<List<String>, ResponseFormat> convertResponse = convertToStringList(componentInstanceIdLisStr);\r
+\r
+            if (convertResponse.isRight()) {\r
+                BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - batchDeleteResourceInstances");\r
+                log.error("Failed to convert received data to BE format.");\r
+                return buildErrorResponse(convertResponse.right().value());\r
+            }\r
+\r
+            String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+            List<String> componentInstanceIdList = convertResponse.left().value();\r
+            log.debug("batchDeleteResourceInstances componentInstanceIdList is {}", componentInstanceIdList);\r
+            Map<String, List<String>> deleteErrorMap = componentInstanceBusinessLogic.batchDeleteComponentInstance(containerComponentType,\r
+                    componentId, componentInstanceIdList, userId);\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteErrorMap);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Batch Delete ResourceInstances");\r
+            log.error("batch delete resource instances with exception" , e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    @PUT\r
+    @Path("/{containerComponentType}/{componentId}/resourceInstance/batchDissociate")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Batch Dissociate RI from RI", method = "PUT",\r
+            summary = "Returns deleted RelationShip Info", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Relationship deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Missing Information"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid Content / Missing Content")})\r
+    public Response batchDissociateRIFromRI(\r
+            @Parameter(description = "allowed values are resources/services/products",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME,\r
+                            ComponentTypeEnum.PRODUCT_PARAM_NAME}),\r
+                    required = true) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Parameter(\r
+                    description = "unique id of the container component") @PathParam("componentId") final String componentId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "RelationshipInfo", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        try {\r
+            if (data == null || data.length() == 0) {\r
+                log.info("Empty JSON list was sent");\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+            }\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+\r
+            if (componentInstanceBusinessLogic == null) {\r
+                log.debug("Unsupported component type {}", containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));\r
+            }\r
+\r
+            Either<List<RequirementCapabilityRelDef>, ResponseFormat> regInfoWs = convertToRequirementCapabilityRelDefList(data);\r
+\r
+            if (regInfoWs.isRight()) {\r
+                BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - batch dissociateRIFromRI");\r
+                log.debug("Failed to convert received data to BE format");\r
+                return buildErrorResponse(regInfoWs.right().value());\r
+            }\r
+\r
+            List<RequirementCapabilityRelDef> requirementDefList = regInfoWs.left().value();\r
+            List<RequirementCapabilityRelDef> delOkResult = componentInstanceBusinessLogic.batchDissociateRIFromRI(\r
+                    componentId, userId, requirementDefList, componentTypeEnum);\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), delOkResult);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Batch Dissociate Resource Instance");\r
+            log.debug("batch dissociate resource instance from service failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    private Either<List<String>, ResponseFormat> convertToStringList(String datalist) {\r
+        Either<String[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(datalist, new User(), String[].class, null, null);\r
+\r
+        if (convertStatus.isRight()) {\r
+            return Either.right(convertStatus.right().value());\r
+        }\r
+\r
+        return Either.left(Arrays.asList(convertStatus.left().value()));\r
+    }\r
+\r
+    private Either<List<RequirementCapabilityRelDef>, ResponseFormat> convertToRequirementCapabilityRelDefList(String data) {\r
+        Either<RequirementCapabilityRelDef[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), RequirementCapabilityRelDef[].class, null, null);\r
+\r
+        if (convertStatus.isRight()) {\r
+            return Either.right(convertStatus.right().value());\r
+        }\r
+\r
+        return Either.left(Arrays.asList(convertStatus.left().value()));\r
+    }\r
+\r
+}\r
index 6888637..355c3e0 100644 (file)
-/*
- * Copyright Â© 2016-2018 European Support Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import java.util.List;
-import java.util.Map;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datamodel.utils.PropertyValueConstraintValidationUtil;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
-import org.openecomp.sdc.be.resources.data.EntryData;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Component Property Servlet", description = "Property Servlet - used to create properties in Service and Resource")
-@Singleton
-public class ComponentPropertyServlet extends BeGenericServlet {
-
-  private final PropertyBusinessLogic propertyBusinessLogic;
-  private final ApplicationDataTypeCache applicationDataTypeCache;
-
-       @Inject
-  public ComponentPropertyServlet(UserBusinessLogic userBusinessLogic,
-      ComponentsUtils componentsUtils,
-      ApplicationDataTypeCache applicationDataTypeCache,
-      PropertyBusinessLogic propertyBusinessLogic) {
-    super(userBusinessLogic, componentsUtils);
-    this.applicationDataTypeCache = applicationDataTypeCache;
-    this.propertyBusinessLogic = propertyBusinessLogic;
-  }
-
-  private static final Logger log = LoggerFactory.getLogger(ComponentPropertyServlet.class);
-  private static final String CREATE_PROPERTY = "Create Property";
-  private static final String DEBUG_MESSAGE = "Start handle request of {} modifier id is {}";
-
-  @POST
-  @Path("services/{serviceId}/properties")
-  @Consumes(MediaType.APPLICATION_JSON)
-  @Produces(MediaType.APPLICATION_JSON)
-  @ApiOperation(value = "Create Service Property", httpMethod = "POST", notes = "Returns created service property", response = Response.class)
-  @ApiResponses(value = { @ApiResponse(code = 201, message = "Service property created"),
-      @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-      @ApiResponse(code = 409, message = "Service property already exist") })
-  public Response createPropertyInService(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
-                                 @ApiParam(value = "Service property to be created", required = true) String data,
-                                 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    return createProperty(serviceId, data, request, userId);
-  }
-
-  @POST
-  @Path("resources/{resourceId}/properties")
-  @Consumes(MediaType.APPLICATION_JSON)
-  @Produces(MediaType.APPLICATION_JSON)
-  @ApiOperation(value = "Create Resource Property", httpMethod = "POST", notes = "Returns created service property", response = Response.class)
-  @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"),
-          @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-          @ApiResponse(code = 409, message = "Resource property already exist") })
-  public Response createPropertyInResource(@ApiParam(value = "Resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
-                                           @ApiParam(value = "Resource property to be created", required = true) String data,
-                                           @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    return createProperty(resourceId, data, request, userId);
-  }
-
-
-  @GET
-  @Path("services/{serviceId}/properties/{propertyId}")
-  @Consumes(MediaType.APPLICATION_JSON)
-  @Produces(MediaType.APPLICATION_JSON)
-  @ApiOperation(value = "Get Service Property", httpMethod = "GET", notes = "Returns property of service", response = Response.class)
-  @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-          @ApiResponse(code = 404, message = "Service property not found") })
-  public Response getPropertyInService(@ApiParam(value = "service id of property", required = true)
-                                       @PathParam("serviceId") final String serviceId, @ApiParam(value = "property id to get", required = true) @PathParam("propertyId") final String propertyId,
-                                       @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    return getProperty(serviceId, propertyId, request, userId);
-  }
-
-  @GET
-  @Path("resources/{resourceId}/properties/{propertyId}")
-  @Consumes(MediaType.APPLICATION_JSON)
-  @Produces(MediaType.APPLICATION_JSON)
-  @ApiOperation(value = "Get Resource Property", httpMethod = "GET", notes = "Returns property of resource", response = Response.class)
-  @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-          @ApiResponse(code = 404, message = "Resource property not found") })
-  public Response getPropertyInResource(@ApiParam(value = "resource id of property", required = true)
-                                       @PathParam("resourceId") final String resourceId, @ApiParam(value = "property id to get", required = true) @PathParam("propertyId") final String propertyId,
-                                       @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    return getProperty(resourceId, propertyId, request, userId);
-  }
-
-  @GET
-  @Path("services/{serviceId}/properties")
-  @Consumes(MediaType.APPLICATION_JSON)
-  @Produces(MediaType.APPLICATION_JSON)
-  @ApiOperation(value = "Get Service Property", httpMethod = "GET", notes = "Returns property list of service", response = Response.class)
-  @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-      @ApiResponse(code = 404, message = "Service property not found") })
-  public Response getPropertyListInService(@ApiParam(value = "service id of property", required = true) @PathParam("serviceId") final String serviceId,
-                                  @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    return getPropertyList(serviceId, request, userId);
-  }
-
-  @GET
-  @Path("resources/{resourceId}/properties")
-  @Consumes(MediaType.APPLICATION_JSON)
-  @Produces(MediaType.APPLICATION_JSON)
-  @ApiOperation(value = "Get Resource Property", httpMethod = "GET", notes = "Returns property list of resource", response = Response.class)
-  @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-          @ApiResponse(code = 404, message = "Resource property not found") })
-  public Response getPropertyListInResource(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId,
-                                           @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    return getPropertyList(resourceId, request, userId);
-  }
-
-  @DELETE
-  @Path("services/{serviceId}/properties/{propertyId}")
-  @Consumes(MediaType.APPLICATION_JSON)
-  @Produces(MediaType.APPLICATION_JSON)
-  @ApiOperation(value = "Delete Service Property", httpMethod = "DELETE", notes = "Returns deleted property", response = Response.class)
-  @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-          @ApiResponse(code = 404, message = "Service property not found") })
-  public Response deletePropertyInService(@ApiParam(value = "service id of property", required = true) @PathParam("serviceId") final String serviceId,
-                                          @ApiParam(value = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    return deleteProperty(serviceId, propertyId, request, userId);
-  }
-
-  @DELETE
-  @Path("resources/{resourceId}/properties/{propertyId}")
-  @Consumes(MediaType.APPLICATION_JSON)
-  @Produces(MediaType.APPLICATION_JSON)
-  @ApiOperation(value = "Delete Resource Property", httpMethod = "DELETE", notes = "Returns deleted property", response = Response.class)
-  @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-          @ApiResponse(code = 404, message = "Resource property not found") })
-  public Response deletePropertyInResource(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId,
-                                          @ApiParam(value = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    return deleteProperty(resourceId, propertyId, request, userId);
-  }
-
-  @PUT
-  @Path("services/{serviceId}/properties")
-  @Consumes(MediaType.APPLICATION_JSON)
-  @Produces(MediaType.APPLICATION_JSON)
-  @ApiOperation(value = "Update Service Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class)
-  @ApiResponses(value = { @ApiResponse(code = 200, message = "Service property updated"),
-      @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-  public Response updatePropertyInService(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
-                                 @ApiParam(value = "Service property to update", required = true) String data, @Context final HttpServletRequest request,
-                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    return updateProperty(serviceId, data, request, userId);
-  }
-
-  @PUT
-  @Path("resources/{resourceId}/properties")
-  @Consumes(MediaType.APPLICATION_JSON)
-  @Produces(MediaType.APPLICATION_JSON)
-  @ApiOperation(value = "Update Resource Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class)
-  @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource property updated"),
-          @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-  public Response updatePropertyInResource(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
-                                          @ApiParam(value = "Resource property to update", required = true) String data, @Context final HttpServletRequest request,
-                                          @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    return updateProperty(resourceId, data, request, userId);
-  }
-
-  private Response createProperty(String componentId, String data,  HttpServletRequest request,String userId) {
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
-
-    try{
-      Either<Map<String, PropertyDefinition>, ActionStatus> propertyDefinition =
-              getPropertyModel(componentId, data);
-      if (propertyDefinition.isRight()) {
-        ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(propertyDefinition.right().value());
-        return buildErrorResponse(responseFormat);
-      }
-
-      Map<String, PropertyDefinition> properties = propertyDefinition.left().value();
-      if (properties == null || properties.size() != 1) {
-        log.info("Property content is invalid - {}", data);
-        ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-        return buildErrorResponse(responseFormat);
-      }
-
-      Map.Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next();
-      PropertyDefinition newPropertyDefinition = entry.getValue();
-      newPropertyDefinition.setParentUniqueId(componentId);
-      String propertyName = newPropertyDefinition.getName();
-
-      Either<EntryData<String, PropertyDefinition>, ResponseFormat> addPropertyEither =
-              propertyBusinessLogic.addPropertyToComponent(componentId, propertyName, newPropertyDefinition, userId);
-
-      if(addPropertyEither.isRight()) {
-        return buildErrorResponse(addPropertyEither.right().value());
-      }
-
-      return buildOkResponse(newPropertyDefinition);
-
-    } catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY);
-      log.debug("create property failed with exception", e);
-      ResponseFormat responseFormat =
-              getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
-    }
-  }
-
-
-  private Response updateProperty(String componentId, String data, HttpServletRequest request, String userId) {
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug("Start handle request of {}", url);
-
-    // get modifier id
-    User modifier = new User();
-    modifier.setUserId(userId);
-    log.debug("modifier id is {}", userId);
-//
-    try {
-      // convert json to PropertyDefinition
-
-      Either<Map<String, PropertyDefinition>, ActionStatus> propertiesListEither =
-          getPropertiesListForUpdate(data);
-      if (propertiesListEither.isRight()) {
-        ResponseFormat responseFormat =
-            getComponentsUtils().getResponseFormat(propertiesListEither.right().value());
-        return buildErrorResponse(responseFormat);
-      }
-      Map<String, PropertyDefinition> properties = propertiesListEither.left().value();
-      if (properties == null) {
-        log.info("Property content is invalid - {}", data);
-        ResponseFormat responseFormat =
-            getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-        return buildErrorResponse(responseFormat);
-      }
-
-               //Validate value and Constraint of property
-               Either<Boolean, ResponseFormat> constraintValidatorResponse =
-                               PropertyValueConstraintValidationUtil.getInstance().
-                                               validatePropertyConstraints(properties.values(), applicationDataTypeCache);
-               if (constraintValidatorResponse.isRight()) {
-                       log.error("Failed validation value and constraint of property: {}",
-                                       constraintValidatorResponse.right().value());
-                       return buildErrorResponse(constraintValidatorResponse.right().value());
-               }
-
-      // update property
-
-      for(PropertyDefinition propertyDefinition : properties.values()) {
-        Either<EntryData<String, PropertyDefinition>, ResponseFormat> status =
-            propertyBusinessLogic.updateComponentProperty(
-                componentId, propertyDefinition.getUniqueId(), propertyDefinition, userId);
-        if (status.isRight()) {
-          log.info("Failed to update Property. Reason - ", status.right().value());
-          return buildErrorResponse(status.right().value());
-        }
-        EntryData<String, PropertyDefinition> property = status.left().value();
-        PropertyDefinition updatedPropertyDefinition = property.getValue();
-
-        log.debug("Property id {} updated successfully ", updatedPropertyDefinition.getUniqueId());
-      }
-
-      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-      return buildOkResponse(responseFormat, properties);
-
-    } catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Property");
-      log.debug("update property failed with exception", e);
-      ResponseFormat responseFormat =
-          getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
-
-    }
-  }
-
-  private Response getProperty(String componentId, String propertyId, HttpServletRequest request, String userId) {
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug(DEBUG_MESSAGE, url, userId);
-
-    try {
-      Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> retrievedPropertyEither =
-              propertyBusinessLogic.getComponentProperty(componentId, propertyId, userId);
-
-      if(retrievedPropertyEither.isRight()) {
-        return buildErrorResponse(retrievedPropertyEither.right().value());
-      }
-
-      return buildOkResponse(retrievedPropertyEither.left().value());
-
-    } catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY);
-      log.debug("get property failed with exception", e);
-      ResponseFormat responseFormat =
-              getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
-    }
-  }
-  private Response getPropertyList(String componentId, HttpServletRequest request, String userId) {
-
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug(DEBUG_MESSAGE, url, userId);
-
-    try {
-      Either<List<PropertyDefinition>, ResponseFormat> propertiesListEither =
-              propertyBusinessLogic.getPropertiesList(componentId, userId);
-
-      if(propertiesListEither.isRight()) {
-        return buildErrorResponse(propertiesListEither.right().value());
-      }
-
-      return buildOkResponse(propertiesListEither.left().value());
-
-    } catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY);
-      log.debug("get property failed with exception", e);
-      ResponseFormat responseFormat =
-              getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
-    }
-  }
-  private Response deleteProperty(String componentId, String propertyId, HttpServletRequest request, String userId) {
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug(DEBUG_MESSAGE, url, userId);
-
-    try {
-
-      // delete the property
-      Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> status =
-              propertyBusinessLogic.deletePropertyFromComponent(componentId, propertyId, userId);
-      if (status.isRight()) {
-        log.debug("Failed to delete Property. Reason - ", status.right().value());
-        return buildErrorResponse(status.right().value());
-      }
-      Map.Entry<String, PropertyDefinition> property = status.left().value();
-      String name = property.getKey();
-      PropertyDefinition propertyDefinition = property.getValue();
-
-      log.debug("Property {} deleted successfully with id {}", name, propertyDefinition.getUniqueId());
-      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
-      return buildOkResponse(responseFormat, propertyToJson(property));
-
-    } catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property");
-      log.debug("delete property failed with exception", e);
-      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
-
-    }
-  }
-
-}
+/*\r
+ * Copyright Â© 2016-2018 European Support Limited\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.List;\r
+import java.util.Map;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datamodel.utils.PropertyValueConstraintValidationUtil;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.model.PropertyDefinition;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;\r
+import org.openecomp.sdc.be.resources.data.EntryData;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Component Property Servlet", description = "Component Property Servlet"))\r
+@Singleton\r
+public class ComponentPropertyServlet extends BeGenericServlet {\r
+\r
+  private final PropertyBusinessLogic propertyBusinessLogic;\r
+  private final ApplicationDataTypeCache applicationDataTypeCache;\r
+\r
+       @Inject\r
+  public ComponentPropertyServlet(UserBusinessLogic userBusinessLogic,\r
+      ComponentsUtils componentsUtils,\r
+      ApplicationDataTypeCache applicationDataTypeCache,\r
+      PropertyBusinessLogic propertyBusinessLogic) {\r
+    super(userBusinessLogic, componentsUtils);\r
+    this.applicationDataTypeCache = applicationDataTypeCache;\r
+    this.propertyBusinessLogic = propertyBusinessLogic;\r
+  }\r
+\r
+  private static final Logger log = LoggerFactory.getLogger(ComponentPropertyServlet.class);\r
+  private static final String CREATE_PROPERTY = "Create Property";\r
+  private static final String DEBUG_MESSAGE = "Start handle request of {} modifier id is {}";\r
+\r
+    @POST\r
+    @Path("services/{serviceId}/properties")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create Service Property", method = "POST", summary = "Returns created service property",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Service property created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Service property already exist")})\r
+    public Response createPropertyInService(\r
+            @Parameter(description = "service id to update with new property",\r
+                    required = true) @PathParam("serviceId") final String serviceId,\r
+            @Parameter(description = "Service property to be created", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return createProperty(serviceId, data, request, userId);\r
+    }\r
+\r
+    @POST\r
+    @Path("resources/{resourceId}/properties")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create Resource Property", method = "POST", summary = "Returns created service property",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource property created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Resource property already exist")})\r
+    public Response createPropertyInResource(\r
+            @Parameter(description = "Resource id to update with new property",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "Resource property to be created", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return createProperty(resourceId, data, request, userId);\r
+    }\r
+\r
+\r
+    @GET\r
+    @Path("services/{serviceId}/properties/{propertyId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get Service Property", method = "GET", summary = "Returns property of service",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "property"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Service property not found")})\r
+    public Response getPropertyInService(\r
+            @Parameter(description = "service id of property", required = true) @PathParam("serviceId") final String serviceId,\r
+            @Parameter(description = "property id to get", required = true) @PathParam("propertyId") final String propertyId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return getProperty(serviceId, propertyId, request, userId);\r
+    }\r
+\r
+    @GET\r
+    @Path("resources/{resourceId}/properties/{propertyId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get Resource Property", method = "GET", summary = "Returns property of resource",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "property"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Resource property not found")})\r
+    public Response getPropertyInResource(\r
+            @Parameter(description = "resource id of property",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "property id to get", required = true) @PathParam("propertyId") final String propertyId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return getProperty(resourceId, propertyId, request, userId);\r
+    }\r
+\r
+    @GET\r
+    @Path("services/{serviceId}/properties")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get Service Property", method = "GET", summary = "Returns property list of service",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "property"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Service property not found")})\r
+    public Response getPropertyListInService(\r
+            @Parameter(description = "service id of property",\r
+                    required = true) @PathParam("serviceId") final String serviceId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return getPropertyList(serviceId, request, userId);\r
+    }\r
+\r
+    @GET\r
+    @Path("resources/{resourceId}/properties")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get Resource Property", method = "GET", summary = "Returns property list of resource",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "property"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Resource property not found")})\r
+    public Response getPropertyListInResource(\r
+            @Parameter(description = "resource id of property",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return getPropertyList(resourceId, request, userId);\r
+    }\r
+\r
+    @DELETE\r
+    @Path("services/{serviceId}/properties/{propertyId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Delete Service Property", method = "DELETE", summary = "Returns deleted property",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "deleted property"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Service property not found")})\r
+    public Response deletePropertyInService(\r
+            @Parameter(description = "service id of property",\r
+                    required = true) @PathParam("serviceId") final String serviceId,\r
+            @Parameter(description = "Property id to delete",\r
+                    required = true) @PathParam("propertyId") final String propertyId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return deleteProperty(serviceId, propertyId, request, userId);\r
+    }\r
+\r
+    @DELETE\r
+    @Path("resources/{resourceId}/properties/{propertyId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Delete Resource Property", method = "DELETE", summary = "Returns deleted property",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "deleted property"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Resource property not found")})\r
+    public Response deletePropertyInResource(\r
+            @Parameter(description = "resource id of property",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "Property id to delete",\r
+                    required = true) @PathParam("propertyId") final String propertyId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return deleteProperty(resourceId, propertyId, request, userId);\r
+    }\r
+\r
+    @PUT\r
+    @Path("services/{serviceId}/properties")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Service Property", method = "PUT", summary = "Returns updated property",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service property updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updatePropertyInService(\r
+            @Parameter(description = "service id to update with new property",\r
+                    required = true) @PathParam("serviceId") final String serviceId,\r
+            @Parameter(description = "Service property to update", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return updateProperty(serviceId, data, request, userId);\r
+    }\r
+\r
+    @PUT\r
+    @Path("resources/{resourceId}/properties")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Resource Property", method = "PUT", summary = "Returns updated property",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource property updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updatePropertyInResource(\r
+            @Parameter(description = "resource id to update with new property",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "Resource property to update", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return updateProperty(resourceId, data, request, userId);\r
+    }\r
+\r
+  private Response createProperty(String componentId, String data,  HttpServletRequest request,String userId) {\r
+    String url = request.getMethod() + " " + request.getRequestURI();\r
+    log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);\r
+\r
+    try{\r
+      Either<Map<String, PropertyDefinition>, ActionStatus> propertyDefinition =\r
+              getPropertyModel(componentId, data);\r
+      if (propertyDefinition.isRight()) {\r
+        ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(propertyDefinition.right().value());\r
+        return buildErrorResponse(responseFormat);\r
+      }\r
+\r
+      Map<String, PropertyDefinition> properties = propertyDefinition.left().value();\r
+      if (properties == null || properties.size() != 1) {\r
+        log.info("Property content is invalid - {}", data);\r
+        ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);\r
+        return buildErrorResponse(responseFormat);\r
+      }\r
+\r
+      Map.Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next();\r
+      PropertyDefinition newPropertyDefinition = entry.getValue();\r
+      newPropertyDefinition.setParentUniqueId(componentId);\r
+      String propertyName = newPropertyDefinition.getName();\r
+\r
+      Either<EntryData<String, PropertyDefinition>, ResponseFormat> addPropertyEither =\r
+              propertyBusinessLogic.addPropertyToComponent(componentId, propertyName, newPropertyDefinition, userId);\r
+\r
+      if(addPropertyEither.isRight()) {\r
+        return buildErrorResponse(addPropertyEither.right().value());\r
+      }\r
+\r
+      return buildOkResponse(newPropertyDefinition);\r
+\r
+    } catch (Exception e) {\r
+      BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY);\r
+      log.debug("create property failed with exception", e);\r
+      ResponseFormat responseFormat =\r
+              getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+      return buildErrorResponse(responseFormat);\r
+    }\r
+  }\r
+\r
+\r
+  private Response updateProperty(String componentId, String data, HttpServletRequest request, String userId) {\r
+    String url = request.getMethod() + " " + request.getRequestURI();\r
+    log.debug("Start handle request of {}", url);\r
+\r
+    // get modifier id\r
+    User modifier = new User();\r
+    modifier.setUserId(userId);\r
+    log.debug("modifier id is {}", userId);\r
+//\r
+    try {\r
+      // convert json to PropertyDefinition\r
+\r
+      Either<Map<String, PropertyDefinition>, ActionStatus> propertiesListEither =\r
+          getPropertiesListForUpdate(data);\r
+      if (propertiesListEither.isRight()) {\r
+        ResponseFormat responseFormat =\r
+            getComponentsUtils().getResponseFormat(propertiesListEither.right().value());\r
+        return buildErrorResponse(responseFormat);\r
+      }\r
+      Map<String, PropertyDefinition> properties = propertiesListEither.left().value();\r
+      if (properties == null) {\r
+        log.info("Property content is invalid - {}", data);\r
+        ResponseFormat responseFormat =\r
+            getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);\r
+        return buildErrorResponse(responseFormat);\r
+      }\r
+\r
+               //Validate value and Constraint of property\r
+               Either<Boolean, ResponseFormat> constraintValidatorResponse =\r
+                               PropertyValueConstraintValidationUtil.getInstance().\r
+                                               validatePropertyConstraints(properties.values(), applicationDataTypeCache);\r
+               if (constraintValidatorResponse.isRight()) {\r
+                       log.error("Failed validation value and constraint of property: {}",\r
+                                       constraintValidatorResponse.right().value());\r
+                       return buildErrorResponse(constraintValidatorResponse.right().value());\r
+               }\r
+\r
+      // update property\r
+\r
+      for(PropertyDefinition propertyDefinition : properties.values()) {\r
+        Either<EntryData<String, PropertyDefinition>, ResponseFormat> status =\r
+            propertyBusinessLogic.updateComponentProperty(\r
+                componentId, propertyDefinition.getUniqueId(), propertyDefinition, userId);\r
+        if (status.isRight()) {\r
+          log.info("Failed to update Property. Reason - ", status.right().value());\r
+          return buildErrorResponse(status.right().value());\r
+        }\r
+        EntryData<String, PropertyDefinition> property = status.left().value();\r
+        PropertyDefinition updatedPropertyDefinition = property.getValue();\r
+\r
+        log.debug("Property id {} updated successfully ", updatedPropertyDefinition.getUniqueId());\r
+      }\r
+\r
+      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+      return buildOkResponse(responseFormat, properties);\r
+\r
+    } catch (Exception e) {\r
+      BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Property");\r
+      log.debug("update property failed with exception", e);\r
+      ResponseFormat responseFormat =\r
+          getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+      return buildErrorResponse(responseFormat);\r
+\r
+    }\r
+  }\r
+\r
+  private Response getProperty(String componentId, String propertyId, HttpServletRequest request, String userId) {\r
+    String url = request.getMethod() + " " + request.getRequestURI();\r
+    log.debug(DEBUG_MESSAGE, url, userId);\r
+\r
+    try {\r
+      Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> retrievedPropertyEither =\r
+              propertyBusinessLogic.getComponentProperty(componentId, propertyId, userId);\r
+\r
+      if(retrievedPropertyEither.isRight()) {\r
+        return buildErrorResponse(retrievedPropertyEither.right().value());\r
+      }\r
+\r
+      return buildOkResponse(retrievedPropertyEither.left().value());\r
+\r
+    } catch (Exception e) {\r
+      BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY);\r
+      log.debug("get property failed with exception", e);\r
+      ResponseFormat responseFormat =\r
+              getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+      return buildErrorResponse(responseFormat);\r
+    }\r
+  }\r
+  private Response getPropertyList(String componentId, HttpServletRequest request, String userId) {\r
+\r
+    String url = request.getMethod() + " " + request.getRequestURI();\r
+    log.debug(DEBUG_MESSAGE, url, userId);\r
+\r
+    try {\r
+      Either<List<PropertyDefinition>, ResponseFormat> propertiesListEither =\r
+              propertyBusinessLogic.getPropertiesList(componentId, userId);\r
+\r
+      if(propertiesListEither.isRight()) {\r
+        return buildErrorResponse(propertiesListEither.right().value());\r
+      }\r
+\r
+      return buildOkResponse(propertiesListEither.left().value());\r
+\r
+    } catch (Exception e) {\r
+      BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY);\r
+      log.debug("get property failed with exception", e);\r
+      ResponseFormat responseFormat =\r
+              getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+      return buildErrorResponse(responseFormat);\r
+    }\r
+  }\r
+  private Response deleteProperty(String componentId, String propertyId, HttpServletRequest request, String userId) {\r
+    String url = request.getMethod() + " " + request.getRequestURI();\r
+    log.debug(DEBUG_MESSAGE, url, userId);\r
+\r
+    try {\r
+\r
+      // delete the property\r
+      Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> status =\r
+              propertyBusinessLogic.deletePropertyFromComponent(componentId, propertyId, userId);\r
+      if (status.isRight()) {\r
+        log.debug("Failed to delete Property. Reason - ", status.right().value());\r
+        return buildErrorResponse(status.right().value());\r
+      }\r
+      Map.Entry<String, PropertyDefinition> property = status.left().value();\r
+      String name = property.getKey();\r
+      PropertyDefinition propertyDefinition = property.getValue();\r
+\r
+      log.debug("Property {} deleted successfully with id {}", name, propertyDefinition.getUniqueId());\r
+      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);\r
+      return buildOkResponse(responseFormat, propertyToJson(property));\r
+\r
+    } catch (Exception e) {\r
+      BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property");\r
+      log.debug("delete property failed with exception", e);\r
+      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+      return buildErrorResponse(responseFormat);\r
+\r
+    }\r
+  }\r
+\r
+}\r
index 574359e..98f75df 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.apache.commons.collections.CollectionUtils;
-import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.mixin.GroupCompositionMixin;
-import org.openecomp.sdc.be.mixin.PolicyCompositionMixin;
-import org.openecomp.sdc.be.model.*;
-import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.be.view.ResponseView;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.List;
-import java.util.Map;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Component Servlet", description = "Component Servlet")
-@Controller
-public class ComponentServlet extends BeGenericServlet {
-    private static final String GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION = "getCertifiedNotAbstractComponents failed with exception";
-
-       private static final String GET_CERTIFIED_NON_ABSTRACT = "Get Certified Non Abstract";
-
-       private static final String FAILED_TO_GET_ALL_NON_ABSTRACT = "failed to get all non abstract {}";
-
-       private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
-
-       private static final Logger log = Logger.getLogger(ComponentServlet.class);
-
-    private final ComponentBusinessLogicProvider componentBusinessLogicProvider;
-
-    @Inject
-    public ComponentServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        ComponentBusinessLogicProvider componentBusinessLogicProvider) {
-        super(userBusinessLogic, componentsUtils);
-        this.componentBusinessLogicProvider = componentBusinessLogicProvider;
-    }
-
-    @GET
-    @Path("/{componentType}/{componentUuid}/conformanceLevelValidation")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Validate Component Conformance Level", httpMethod = "GET", notes = "Returns the result according to conformance level in BE config", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response conformanceLevelValidation(@PathParam("componentType") final String componentType, @PathParam("componentUuid") final String componentUuid, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        Response response;
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-        if (componentTypeEnum != null) {
-            ComponentBusinessLogic compBL = componentBusinessLogicProvider.getInstance(componentTypeEnum);
-            Either<Boolean, ResponseFormat> eitherConformanceLevel = compBL.validateConformanceLevel(componentUuid, componentTypeEnum, userId);
-            if (eitherConformanceLevel.isRight()) {
-                response = buildErrorResponse(eitherConformanceLevel.right().value());
-            } else {
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value()));
-            }
-        } else {
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-        }
-
-        return response;
-    }
-
-    @GET
-    @Path("/{componentType}/{componentId}/requirmentsCapabilities")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirements And Capabilities according to componentId", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        Response response;
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-        if (componentTypeEnum != null) {
-            try {
-                ComponentBusinessLogic compBL = componentBusinessLogicProvider.getInstance(componentTypeEnum);
-                Either<CapReqDef, ResponseFormat> eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId);
-                if (eitherRequirementsAndCapabilities.isRight()) {
-                    response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value());
-                } else {
-                    response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(eitherRequirementsAndCapabilities.left().value()));
-                }
-            } catch (Exception e) {
-                BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId);
-                log.debug("getRequirementAndCapabilities failed with exception", e);
-                response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            }
-        } else {
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-        }
-
-        return response;
-    }
-
-    @GET
-    @Path("/{componentType}/latestversion/notabstract")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response getLatestVersionNotAbstractCheckoutComponents(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType,
-            @QueryParam("componentUids") List<String> componentUids, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}", url);
-        Response response = null;
-
-        try {
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-            ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
-
-            log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size());
-
-            Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, componentUids, userId);
-
-            if (actionResponse.isRight()) {
-                log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, componentType);
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType);
-            log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-
-    }
-
-    @POST
-    @Path("/{componentType}/latestversion/notabstract")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response getLatestVersionNotAbstractCheckoutComponentsByBody(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "Consumer Object to be created", required = true) List<String> data) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(GET) Start handle request of {}", url);
-        Response response = null;
-
-        try {
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-            ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
-            if (log.isDebugEnabled()) {
-                log.debug("Received componentUids size is {}", data == null ? 0 : data.size());
-            }
-
-            Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, data, userId);
-
-            if (actionResponse.isRight()) {
-                log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, componentType);
-                return buildErrorResponse(actionResponse.right().value());
-
-            }
-            Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            return  buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
-
-
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType);
-            log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-
-    }
-
-    @GET
-    @Path("/{componentType}/latestversion/notabstract/metadata")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get Component uid only", httpMethod = "GET", notes = "Returns componentId", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid list", required = true) String data) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}", url);
-        Response response = null;
-        try {
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-            ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
-
-            Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId);
-            if (actionResponse.isRight()) {
-                log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, componentType);
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType);
-            log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-
-    }
-
-    @GET
-    @Path("/{componentType}/{componentId}/componentInstances")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get Component instances", httpMethod = "GET", notes = "Returns component instances", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response getComponentInstancesFilteredByPropertiesAndInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
-            @QueryParam("searchText") String searchText, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid" + " " + "list", required = true) String data) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(GET) Start handle request of {}", url);
-        Response response = null;
-        try {
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-            ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
-
-            Either<List<ComponentInstance>, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, userId);
-            if (actionResponse.isRight()) {
-                log.debug("failed to get all component instances filtered by properties and inputs", componentType);
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Instances filtered by properties & inputs" + componentType);
-            log.debug("getComponentInstancesFilteredByPropertiesAndInputs failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-
-
-    /**
-     * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list.
-     * for example: list of the string "properties, inputs" will return component with the list of properties and inputs.
-     *
-     * @param componentType
-     * @param componentId
-     * @param dataParamsToReturn
-     * @param request
-     * @param userId
-     * @return
-     */
-
-    @GET
-    @Path("/{componentType}/{componentId}/filteredDataByParams")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class)
-    @ResponseView(mixin = {GroupCompositionMixin.class, PolicyCompositionMixin.class})
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") })
-    public Response getComponentDataFilteredByParams(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @QueryParam("include") final List<String> dataParamsToReturn, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF , url);
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}" , userId);
-
-        Response response;
-
-        try {
-            String resourceIdLower = componentId.toLowerCase();
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-            ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
-
-            log.trace("get component with id {} filtered by ui params", componentId);
-            Either<UiComponentDataTransfer, ResponseFormat> actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to get component data filtered by ui params");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-            RepresentationUtils.toRepresentation(actionResponse.left().value());
-            return buildOkResponse(actionResponse.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params");
-            log.debug("get resource failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-
-    @GET
-    @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", httpMethod = "GET", notes = "Returns properties belonging to component instances of specific component by name and optionally resource type", response = Map.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response getFilteredComponentInstanceProperties(
-            @PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("propertyNameFragment") final String propertyNameFragment,
-            @QueryParam("resourceType") List<String> resourceTypes,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        User user = new User();
-        user.setUserId(userId);
-        log.debug("User Id is {}" , userId);
-        Response response;
-        try {
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-            ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
-            Map<FilterKeyEnum, List<String>> filters = new EnumMap<>(FilterKeyEnum.class);
-            List<String> propertyNameFragments = new ArrayList<>();
-            propertyNameFragments.add(propertyNameFragment);
-            filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments);
-            if(CollectionUtils.isNotEmpty(resourceTypes)){
-                filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes);
-            }
-            Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId);
-            if (actionResponse.isRight()) {
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-            Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Filtered Component Instance Properties");
-            log.debug("Getting of filtered component instance properties failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.ArrayList;\r
+import java.util.EnumMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+import javax.inject.Inject;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.QueryParam;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.collections.CollectionUtils;\r
+import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.mixin.GroupCompositionMixin;\r
+import org.openecomp.sdc.be.mixin.PolicyCompositionMixin;\r
+import org.openecomp.sdc.be.model.CapReqDef;\r
+import org.openecomp.sdc.be.model.Component;\r
+import org.openecomp.sdc.be.model.ComponentInstance;\r
+import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;\r
+import org.openecomp.sdc.be.model.Resource;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.be.view.ResponseView;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import org.springframework.stereotype.Controller;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Component Servlet",description = "Component Servlet"))\r
+@Controller\r
+public class ComponentServlet extends BeGenericServlet {\r
+    private static final String GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION = "getCertifiedNotAbstractComponents failed with exception";\r
+\r
+       private static final String GET_CERTIFIED_NON_ABSTRACT = "Get Certified Non Abstract";\r
+\r
+       private static final String FAILED_TO_GET_ALL_NON_ABSTRACT = "failed to get all non abstract {}";\r
+\r
+       private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";\r
+\r
+       private static final Logger log = Logger.getLogger(ComponentServlet.class);\r
+\r
+    private final ComponentBusinessLogicProvider componentBusinessLogicProvider;\r
+\r
+    @Inject\r
+    public ComponentServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils,\r
+        ComponentBusinessLogicProvider componentBusinessLogicProvider) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.componentBusinessLogicProvider = componentBusinessLogicProvider;\r
+    }\r
+\r
+    @GET\r
+    @Path("/{componentType}/{componentUuid}/conformanceLevelValidation")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Validate Component Conformance Level", method = "GET",\r
+            summary = "Returns the result according to conformance level in BE config", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response conformanceLevelValidation(@PathParam("componentType") final String componentType,\r
+            @PathParam("componentUuid") final String componentUuid, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        Response response;\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);\r
+        if (componentTypeEnum != null) {\r
+            ComponentBusinessLogic compBL = componentBusinessLogicProvider.getInstance(componentTypeEnum);\r
+            Either<Boolean, ResponseFormat> eitherConformanceLevel = compBL.validateConformanceLevel(componentUuid, componentTypeEnum, userId);\r
+            if (eitherConformanceLevel.isRight()) {\r
+                response = buildErrorResponse(eitherConformanceLevel.right().value());\r
+            } else {\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value()));\r
+            }\r
+        } else {\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+        }\r
+\r
+        return response;\r
+    }\r
+\r
+    @GET\r
+    @Path("/{componentType}/{componentId}/requirmentsCapabilities")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get Component Requirments And Capabilities", method = "GET",\r
+            summary = "Returns Requirements And Capabilities according to componentId", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        Response response;\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);\r
+        if (componentTypeEnum != null) {\r
+            try {\r
+                ComponentBusinessLogic compBL = componentBusinessLogicProvider.getInstance(componentTypeEnum);\r
+                Either<CapReqDef, ResponseFormat> eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId);\r
+                if (eitherRequirementsAndCapabilities.isRight()) {\r
+                    response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value());\r
+                } else {\r
+                    response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(eitherRequirementsAndCapabilities.left().value()));\r
+                }\r
+            } catch (Exception e) {\r
+                BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId);\r
+                log.debug("getRequirementAndCapabilities failed with exception", e);\r
+                response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            }\r
+        } else {\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+        }\r
+\r
+        return response;\r
+    }\r
+\r
+    @GET\r
+    @Path("/{componentType}/latestversion/notabstract")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get Component Requirments And Capabilities", method = "GET",\r
+            summary = "Returns Requirments And Capabilities according to componentId", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response getLatestVersionNotAbstractCheckoutComponents(\r
+            @PathParam("componentType") final String componentType, @Context final HttpServletRequest request,\r
+            @QueryParam("internalComponentType") String internalComponentType,\r
+            @QueryParam("componentUids") List<String> componentUids,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(get) Start handle request of {}", url);\r
+        Response response = null;\r
+\r
+        try {\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);\r
+            ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);\r
+\r
+            log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size());\r
+\r
+            Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, componentUids, userId);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, componentType);\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType);\r
+            log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+\r
+    }\r
+\r
+    @POST\r
+    @Path("/{componentType}/latestversion/notabstract")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get Component Requirments And Capabilities", method = "GET",\r
+            summary = "Returns Requirments And Capabilities according to componentId", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response getLatestVersionNotAbstractCheckoutComponentsByBody(\r
+            @PathParam("componentType") final String componentType, @Context final HttpServletRequest request,\r
+            @QueryParam("internalComponentType") String internalComponentType,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "Consumer Object to be created", required = true) List<String> data) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(GET) Start handle request of {}", url);\r
+        Response response = null;\r
+\r
+        try {\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);\r
+            ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);\r
+            if (log.isDebugEnabled()) {\r
+                log.debug("Received componentUids size is {}", data == null ? 0 : data.size());\r
+            }\r
+\r
+            Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, data, userId);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, componentType);\r
+                return buildErrorResponse(actionResponse.right().value());\r
+\r
+            }\r
+            Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            return  buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);\r
+\r
+\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType);\r
+            log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+\r
+    }\r
+\r
+    @GET\r
+    @Path("/{componentType}/latestversion/notabstract/metadata")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get Component uid only", method = "GET", summary = "Returns componentId",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly(\r
+            @PathParam("componentType") final String componentType, @Context final HttpServletRequest request,\r
+            @QueryParam("internalComponentType") String internalComponentType,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "uid list", required = true) String data) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(get) Start handle request of {}", url);\r
+        Response response = null;\r
+        try {\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);\r
+            ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);\r
+\r
+            Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId);\r
+            if (actionResponse.isRight()) {\r
+                log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, componentType);\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType);\r
+            log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+\r
+    }\r
+\r
+    @GET\r
+    @Path("/{componentType}/{componentId}/componentInstances")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get Component instances", method = "GET", summary = "Returns component instances",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response getComponentInstancesFilteredByPropertiesAndInputs(\r
+            @PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,\r
+            @Context final HttpServletRequest request, @QueryParam("searchText") String searchText,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "uid" + " " + "list", required = true) String data) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(GET) Start handle request of {}", url);\r
+        Response response = null;\r
+        try {\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);\r
+            ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);\r
+\r
+            Either<List<ComponentInstance>, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, userId);\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to get all component instances filtered by properties and inputs", componentType);\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Instances filtered by properties & inputs" + componentType);\r
+            log.debug("getComponentInstancesFilteredByPropertiesAndInputs failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+\r
+\r
+    /**\r
+     * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list.\r
+     * for example: list of the string "properties, inputs" will return component with the list of properties and inputs.\r
+     *\r
+     * @param componentType\r
+     * @param componentId\r
+     * @param dataParamsToReturn\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+\r
+    @GET\r
+    @Path("/{componentType}/{componentId}/filteredDataByParams")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve Resource", method = "GET", summary = "Returns resource according to resourceId",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ResponseView(mixin = {GroupCompositionMixin.class, PolicyCompositionMixin.class})\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Resource not found")})\r
+    public Response getComponentDataFilteredByParams(@PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @QueryParam("include") final List<String> dataParamsToReturn, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF , url);\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}" , userId);\r
+\r
+        Response response;\r
+\r
+        try {\r
+            String resourceIdLower = componentId.toLowerCase();\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);\r
+            ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);\r
+\r
+            log.trace("get component with id {} filtered by ui params", componentId);\r
+            Either<UiComponentDataTransfer, ResponseFormat> actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to get component data filtered by ui params");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+            RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            return buildOkResponse(actionResponse.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params");\r
+            log.debug("get resource failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+\r
+    @GET\r
+    @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(\r
+            description = "Retrieve properties belonging to component instances of specific component by name and optionally resource type",\r
+            method = "GET",\r
+            summary = "Returns properties belonging to component instances of specific component by name and optionally resource type",\r
+                    responses = @ApiResponse(\r
+                            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Map.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response getFilteredComponentInstanceProperties(\r
+            @PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @PathParam("propertyNameFragment") final String propertyNameFragment,\r
+            @QueryParam("resourceType") List<String> resourceTypes,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        User user = new User();\r
+        user.setUserId(userId);\r
+        log.debug("User Id is {}" , userId);\r
+        Response response;\r
+        try {\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);\r
+            ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);\r
+            Map<FilterKeyEnum, List<String>> filters = new EnumMap<>(FilterKeyEnum.class);\r
+            List<String> propertyNameFragments = new ArrayList<>();\r
+            propertyNameFragments.add(propertyNameFragment);\r
+            filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments);\r
+            if(CollectionUtils.isNotEmpty(resourceTypes)){\r
+                filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes);\r
+            }\r
+            Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId);\r
+            if (actionResponse.isRight()) {\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+            Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Filtered Component Instance Properties");\r
+            log.debug("Getting of filtered component instance properties failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+}\r
index e6553a2..2ecbab7 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.google.gson.Gson;
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.ConsumerDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/consumers")
-@Api(value = "Consumer Servlet", description = "Consumer Servlet")
-@Singleton
-public class ConsumerServlet extends BeGenericServlet {
-
-    private static final String MODIFIER_ID_IS = "modifier id is {}";
-       private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
-       private static final Logger log = Logger.getLogger(ConsumerServlet.class);
-    private final ConsumerBusinessLogic businessLogic;
-
-         @Inject
-    public ConsumerServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        ConsumerBusinessLogic businessLogic) {
-        super(userBusinessLogic, componentsUtils);
-        this.businessLogic = businessLogic;
-    }
-
-    @POST
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Consumer credentials", httpMethod = "POST", notes = "Returns created ECOMP consumer credentials", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Consumer credentials created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response createConsumer(@ApiParam(value = "Consumer Object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug(MODIFIER_ID_IS, userId);
-
-        try {
-            Either<ConsumerDefinition, ResponseFormat> convertionResponse = convertJsonToObject(data, modifier, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
-
-            if (convertionResponse.isRight()) {
-                log.debug("failed to create Consumer");
-                return buildErrorResponse(convertionResponse.right().value());
-            }
-
-            ConsumerDefinition consumer = convertionResponse.left().value();
-
-            Either<ConsumerDefinition, ResponseFormat> actionResult = businessLogic.createConsumer(modifier, consumer);
-
-            if (actionResult.isRight()) {
-                log.debug("failed to create Consumer");
-                return buildErrorResponse(actionResult.right().value());
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResult.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create consumer");
-            log.debug("create consumer failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-
-        }
-    }
-
-    @GET
-    @Path("/{consumerId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve Consumer", httpMethod = "GET", notes = "Returns consumer according to ConsumerID", response = ConsumerDefinition.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Consumer found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") })
-    public Response getConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug(MODIFIER_ID_IS, userId);
-
-        Response response = null;
-        try {
-            Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.getConsumer(consumerId, modifier);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to get consumer");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");
-            log.debug("get consumer failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    @DELETE
-    @Path("/{consumerId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Deletes Consumer", httpMethod = "DELETE", notes = "Returns deleted consumer according to ConsumerID", response = ConsumerDefinition.class)
-    @ApiResponses(value = { @ApiResponse(code = 204, message = "Consumer deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") })
-    public Response deleteConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug(MODIFIER_ID_IS, userId);
-
-        Response response = null;
-        try {
-            Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.deleteConsumer(consumerId, modifier);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to delete consumer");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");
-            log.debug("delete consumer failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    public Either<ConsumerDefinition, ResponseFormat> convertJsonToObject(String data, User user, AuditingActionEnum actionEnum) {
-        ConsumerDefinition consumer;
-        Gson gson = new Gson();
-        try {
-            log.trace("convert json to object. json=\n {}", data);
-            consumer = gson.fromJson(data, ConsumerDefinition.class);
-            if (consumer == null) {
-                BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
-                log.debug("object is null after converting from json");
-                ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorForConsumerAndAudit(user, null, actionEnum);
-                return Either.right(responseFormat);
-            }
-        } catch (Exception e) {
-            // INVALID JSON
-            BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
-            log.debug("failed to convert from json {}", data, e);
-            ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorForConsumerAndAudit(user, null, actionEnum);
-            return Either.right(responseFormat);
-        }
-        return Either.left(consumer);
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.model.ConsumerDefinition;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.google.gson.Gson;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/consumers")\r
+@OpenAPIDefinition(info = @Info(title = "Consumer Servlet",description = "Consumer Servlet"))\r
+@Singleton\r
+public class ConsumerServlet extends BeGenericServlet {\r
+\r
+    private static final String MODIFIER_ID_IS = "modifier id is {}";\r
+       private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";\r
+       private static final Logger log = Logger.getLogger(ConsumerServlet.class);\r
+    private final ConsumerBusinessLogic businessLogic;\r
+\r
+         @Inject\r
+    public ConsumerServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils,\r
+        ConsumerBusinessLogic businessLogic) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.businessLogic = businessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Consumer credentials", method = "POST",\r
+            summary = "Returns created ECOMP consumer credentials",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Consumer credentials created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response createConsumer(@Parameter(description = "Consumer Object to be created", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug(MODIFIER_ID_IS, userId);\r
+\r
+        try {\r
+            Either<ConsumerDefinition, ResponseFormat> convertionResponse = convertJsonToObject(data, modifier, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);\r
+\r
+            if (convertionResponse.isRight()) {\r
+                log.debug("failed to create Consumer");\r
+                return buildErrorResponse(convertionResponse.right().value());\r
+            }\r
+\r
+            ConsumerDefinition consumer = convertionResponse.left().value();\r
+\r
+            Either<ConsumerDefinition, ResponseFormat> actionResult = businessLogic.createConsumer(modifier, consumer);\r
+\r
+            if (actionResult.isRight()) {\r
+                log.debug("failed to create Consumer");\r
+                return buildErrorResponse(actionResult.right().value());\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResult.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create consumer");\r
+            log.debug("create consumer failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/{consumerId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve Consumer", method = "GET", summary = "Returns consumer according to ConsumerID",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = ConsumerDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Consumer found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Consumer not found")})\r
+    public Response getConsumer(@PathParam("consumerId") final String consumerId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug(MODIFIER_ID_IS, userId);\r
+\r
+        Response response = null;\r
+        try {\r
+            Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.getConsumer(consumerId, modifier);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to get consumer");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");\r
+            log.debug("get consumer failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/{consumerId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Deletes Consumer", method = "DELETE",\r
+            summary = "Returns deleted consumer according to ConsumerID",  responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = ConsumerDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Consumer deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Consumer not found")})\r
+    public Response deleteConsumer(@PathParam("consumerId") final String consumerId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug(MODIFIER_ID_IS, userId);\r
+\r
+        Response response = null;\r
+        try {\r
+            Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.deleteConsumer(consumerId, modifier);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to delete consumer");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");\r
+            log.debug("delete consumer failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    public Either<ConsumerDefinition, ResponseFormat> convertJsonToObject(String data, User user, AuditingActionEnum actionEnum) {\r
+        ConsumerDefinition consumer;\r
+        Gson gson = new Gson();\r
+        try {\r
+            log.trace("convert json to object. json=\n {}", data);\r
+            consumer = gson.fromJson(data, ConsumerDefinition.class);\r
+            if (consumer == null) {\r
+                BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");\r
+                log.debug("object is null after converting from json");\r
+                ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorForConsumerAndAudit(user, null, actionEnum);\r
+                return Either.right(responseFormat);\r
+            }\r
+        } catch (Exception e) {\r
+            // INVALID JSON\r
+            BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");\r
+            log.debug("failed to convert from json {}", data, e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorForConsumerAndAudit(user, null, actionEnum);\r
+            return Either.right(responseFormat);\r
+        }\r
+        return Either.left(consumer);\r
+    }\r
+\r
+}\r
index 26ff236..fc6c28c 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.DistributionMonitoringBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.info.DistributionStatusListResponse;
-import org.openecomp.sdc.be.info.DistributionStatusOfServiceListResponce;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-/**
- * Root resource (exposed at "/" path)
- */
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Distribution Service Servlet", description = "Distribution Service Servlet")
-@Singleton
-public class DistributionServiceServlet extends BeGenericServlet {
-    private static final Logger log = Logger.getLogger(DistributionServiceServlet.class);
-
-    @Inject
-    public DistributionServiceServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        DistributionMonitoringBusinessLogic distributionMonitoringLogic) {
-        super(userBusinessLogic, componentsUtils);
-        this.distributionMonitoringLogic = distributionMonitoringLogic;
-    }
-
-    private DistributionMonitoringBusinessLogic distributionMonitoringLogic;
-
-    @GET
-    @Path("/services/{serviceUUID}/distribution")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Returns list  bases on the  information extracted from  Auditing Records according to service uuid", response = DistributionStatusListResponse.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") })
-    public Response getServiceById(@PathParam("serviceUUID") final String serviceUUID, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-        Response response = null;
-        ResponseFormat responseFormat = null;
-
-        try {
-            Either<DistributionStatusOfServiceListResponce, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionServiceStatus(serviceUUID, userId);
-
-            if (actionResponse.isRight()) {
-
-                responseFormat = actionResponse.right().value();
-                response = buildErrorResponse(responseFormat);
-            } else {
-                responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                response = buildOkResponse(responseFormat, actionResponse.left().value());
-
-            }
-
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution list for Service");
-            log.debug("failed to get service distribution statuses", e);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-
-            response = buildErrorResponse(responseFormat);
-            return response;
-        }
-
-    }
-
-    @GET
-    @Path("/services/distribution/{did}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Return  the  list  of  distribution status objects", response = DistributionStatusListResponse.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Status not found") })
-    public Response getListOfDistributionStatuses(@PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-        Response response = null;
-        ResponseFormat responseFormat = null;
-
-        try {
-            Either<DistributionStatusListResponse, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionStatus(did, userId);
-
-            if (actionResponse.isRight()) {
-
-                responseFormat = actionResponse.right().value();
-                log.debug("failed to fount statuses for did {} {}", did, responseFormat);
-                response = buildErrorResponse(responseFormat);
-            } else {
-
-                responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                log.debug("success to fount statuses for did {} {}", did, actionResponse.left().value());
-                response = buildOkResponse(responseFormat, actionResponse.left().value());
-
-            }
-
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution Status");
-            log.debug("failed to get distribution status ", e);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-
-            response = buildErrorResponse(responseFormat);
-            return response;
-        }
-
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.DistributionMonitoringBusinessLogic;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.info.DistributionStatusListResponse;\r
+import org.openecomp.sdc.be.info.DistributionStatusOfServiceListResponce;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+/**\r
+ * Root resource (exposed at "/" path)\r
+ */\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Distribution Service Servlet",description = "Distribution Service Servlet"))\r
+@Singleton\r
+public class DistributionServiceServlet extends BeGenericServlet {\r
+    private static final Logger log = Logger.getLogger(DistributionServiceServlet.class);\r
+\r
+    @Inject\r
+    public DistributionServiceServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils,\r
+        DistributionMonitoringBusinessLogic distributionMonitoringLogic) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.distributionMonitoringLogic = distributionMonitoringLogic;\r
+    }\r
+\r
+    private DistributionMonitoringBusinessLogic distributionMonitoringLogic;\r
+\r
+    @GET\r
+    @Path("/services/{serviceUUID}/distribution")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve Distributions", method = "GET",\r
+            summary = "Returns list  bases on the  information extracted from  Auditing Records according to service uuid",\r
+                    responses = @ApiResponse(\r
+                            content = @Content(array = @ArraySchema(schema = @Schema(implementation = DistributionStatusListResponse.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Service not found")})\r
+    public Response getServiceById(@PathParam("serviceUUID") final String serviceUUID,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        Response response = null;\r
+        ResponseFormat responseFormat = null;\r
+\r
+        try {\r
+            Either<DistributionStatusOfServiceListResponce, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionServiceStatus(serviceUUID, userId);\r
+\r
+            if (actionResponse.isRight()) {\r
+\r
+                responseFormat = actionResponse.right().value();\r
+                response = buildErrorResponse(responseFormat);\r
+            } else {\r
+                responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                response = buildOkResponse(responseFormat, actionResponse.left().value());\r
+\r
+            }\r
+\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution list for Service");\r
+            log.debug("failed to get service distribution statuses", e);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+\r
+            response = buildErrorResponse(responseFormat);\r
+            return response;\r
+        }\r
+\r
+    }\r
+\r
+    @GET\r
+    @Path("/services/distribution/{did}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve Distributions", method = "GET",\r
+            summary = "Return  the  list  of  distribution status objects",\r
+                    responses = @ApiResponse(\r
+                            content = @Content(array = @ArraySchema(schema = @Schema(implementation = DistributionStatusListResponse.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Status not found")})\r
+    public Response getListOfDistributionStatuses(@PathParam("did") final String did,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        Response response = null;\r
+        ResponseFormat responseFormat = null;\r
+\r
+        try {\r
+            Either<DistributionStatusListResponse, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionStatus(did, userId);\r
+\r
+            if (actionResponse.isRight()) {\r
+\r
+                responseFormat = actionResponse.right().value();\r
+                log.debug("failed to fount statuses for did {} {}", did, responseFormat);\r
+                response = buildErrorResponse(responseFormat);\r
+            } else {\r
+\r
+                responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);\r
+                log.debug("success to fount statuses for did {} {}", did, actionResponse.left().value());\r
+                response = buildOkResponse(responseFormat, actionResponse.left().value());\r
+\r
+            }\r
+\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution Status");\r
+            log.debug("failed to get distribution status ", e);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+\r
+            response = buildErrorResponse(responseFormat);\r
+            return response;\r
+        }\r
+\r
+    }\r
+\r
+}\r
index e143203..0c81ad3 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.info.ArtifactTypesInfo;
-import org.openecomp.sdc.be.model.*;
-import org.openecomp.sdc.be.model.Tag;
-import org.openecomp.sdc.be.model.catalog.CatalogComponent;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.GroupingDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.ui.model.UiCategories;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-@Path("/v1/")
-
-/****
- * 
- * UI oriented servlet - to return elements in specific format UI needs
- * 
- *
- */
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Api(value = "Element Servlet", description = "Element Servlet")
-@Singleton
-public class ElementServlet extends BeGenericServlet {
-
-    private static final Logger log = Logger.getLogger(ElementServlet.class);
-    private final ComponentsCleanBusinessLogic componentsCleanBusinessLogic;
-    private final ElementBusinessLogic elementBusinessLogic;
-    private final UserBusinessLogic userBusinessLogic;
-
-    @Inject
-    public ElementServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        ComponentsCleanBusinessLogic componentsCleanBusinessLogic,
-        ElementBusinessLogic elementBusinessLogic) {
-        super(userBusinessLogic, componentsUtils);
-        this.componentsCleanBusinessLogic = componentsCleanBusinessLogic;
-        this.elementBusinessLogic = elementBusinessLogic;
-        this.userBusinessLogic = userBusinessLogic;
-    }
-
-    /*
-     ******************************************************************************
-     * NEW CATEGORIES category / \ subcategory subcategory / grouping
-     ******************************************************************************/
-
-    /*
-     *
-     *
-     * CATEGORIES
-     */
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
-    // retrieve all component categories
-    @GET
-    @Path("/categories/{componentType}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve the list of all resource/service/product categories/sub-categories/groupings", httpMethod = "GET", notes = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid component type"),
-            @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response getComponentCategories(@ApiParam(value = "allowed values are resources / services/ products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
-            + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-
-        try {
-            Either<List<CategoryDefinition>, ResponseFormat> either = elementBusinessLogic.getAllCategories(componentType, userId);
-            if (either.isRight()) {
-                log.debug("No categories were found for type {}", componentType);
-                return buildErrorResponse(either.right().value());
-            } else {
-                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Categories");
-            log.debug("getComponentCategories failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @GET
-    @Path("/categories")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve the all resource, service and product categories", httpMethod = "GET", notes = "Retrieve the all resource, service and product categories", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"),
-            @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response getAllCategories(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        try {
-            Either<UiCategories, ResponseFormat> either = elementBusinessLogic
-                .getAllCategories(userId);
-            if (either.isRight()) {
-                log.debug("No categories were found");
-                return buildErrorResponse(either.right().value());
-            } else {
-                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Categories");
-            log.debug("getAllCategories failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-
-    @POST
-    @Path("/category/{componentType}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create new component category", httpMethod = "POST", notes = "Create new component category")
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Category created"), @ApiResponse(code = 400, message = "Invalid category data"), @ApiResponse(code = 403, message = "USER_ID header is missing"),
-            @ApiResponse(code = 409, message = "Category already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") })
-    public Response createComponentCategory(
-            @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
-                    + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType,
-            @ApiParam(value = "Category to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        try {
-            CategoryDefinition category = RepresentationUtils.fromRepresentation(data, CategoryDefinition.class);
-
-            Either<CategoryDefinition, ResponseFormat> createResourceCategory =
-                elementBusinessLogic.createCategory(category, componentType, userId);
-            if (createResourceCategory.isRight()) {
-                return buildErrorResponse(createResourceCategory.right().value());
-            }
-
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
-            return buildOkResponse(responseFormat, createResourceCategory.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category");
-            log.debug("createResourceCategory failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    @DELETE
-    @Path("/category/{componentType}/{categoryUniqueId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class)
-    @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"),
-            @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") })
-    public Response deleteComponentCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        try {
-            Either<CategoryDefinition, ResponseFormat> createResourceCategory =
-                elementBusinessLogic.deleteCategory(categoryUniqueId, componentType, userId);
-
-            if (createResourceCategory.isRight()) {
-                return buildErrorResponse(createResourceCategory.right().value());
-            }
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
-            return buildOkResponse(responseFormat, null);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category");
-            log.debug("createResourceCategory failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    /*
-     *
-     *
-     * SUBCATEGORIES
-     *
-     */
-
-    @POST
-    @Path("/category/{componentType}/{categoryId}/subCategory")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create new component sub-category", httpMethod = "POST", notes = "Create new component sub-category for existing category")
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Subcategory created"), @ApiResponse(code = 400, message = "Invalid subcategory data"), @ApiResponse(code = 403, message = "USER_ID header is missing"),
-            @ApiResponse(code = 404, message = "Parent category wasn't found"), @ApiResponse(code = 409, message = "Subcategory already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") })
-    public Response createComponentSubCategory(
-            @ApiParam(value = "allowed values are resources / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + ","
-                    + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType,
-            @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String categoryId, @ApiParam(value = "Subcategory to be created. \ne.g. {\"name\":\"Resource-subcat\"}", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        try {
-            SubCategoryDefinition subCategory = RepresentationUtils.fromRepresentation(data, SubCategoryDefinition.class);
-
-            Either<SubCategoryDefinition, ResponseFormat> createSubcategory = elementBusinessLogic
-                .createSubCategory(subCategory, componentType, categoryId, userId);
-            if (createSubcategory.isRight()) {
-                return buildErrorResponse(createSubcategory.right().value());
-            }
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
-            return buildOkResponse(responseFormat, createSubcategory.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create sub-category");
-            log.debug("createComponentSubCategory failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    @DELETE
-    @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class)
-    @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"),
-            @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") })
-    public Response deleteComponentSubCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String subCategoryUniqueId,
-            @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        try {
-            Either<SubCategoryDefinition, ResponseFormat> deleteSubResourceCategory =
-                elementBusinessLogic.deleteSubCategory(subCategoryUniqueId, componentType, userId);
-            if (deleteSubResourceCategory.isRight()) {
-                return buildErrorResponse(deleteSubResourceCategory.right().value());
-            }
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
-            return buildOkResponse(responseFormat, null);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component category");
-            log.debug("deleteComponentSubCategory failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    /*
-     * GROUPINGS
-     */
-    @POST
-    @Path("/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create new component grouping", httpMethod = "POST", notes = "Create new component grouping for existing sub-category")
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Grouping created"), @ApiResponse(code = 400, message = "Invalid grouping data"), @ApiResponse(code = 403, message = "USER_ID header is missing"),
-            @ApiResponse(code = 404, message = "Parent category or subcategory were not found"), @ApiResponse(code = 409, message = "Grouping already exists / User not permitted to perform the action"),
-            @ApiResponse(code = 500, message = "General Error") })
-    public Response createComponentGrouping(@ApiParam(value = "allowed values are products", allowableValues = ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType,
-            @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String grandParentCategoryId,
-            @ApiParam(value = "Parent sub-category unique ID", required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId, @ApiParam(value = "Subcategory to be created", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        try {
-            GroupingDefinition grouping = RepresentationUtils.fromRepresentation(data, GroupingDefinition.class);
-
-            Either<GroupingDefinition, ResponseFormat> createGrouping = elementBusinessLogic
-                .createGrouping(grouping, componentType, grandParentCategoryId, parentSubCategoryId, userId);
-            if (createGrouping.isRight()) {
-                return buildErrorResponse(createGrouping.right().value());
-            }
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
-            return buildOkResponse(responseFormat, createGrouping.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create grouping");
-            log.debug("createComponentGrouping failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    @DELETE
-    @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class)
-    @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"),
-            @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") })
-    public Response deleteComponentGrouping(@PathParam(value = "categoryUniqueId") final String grandParentCategoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String parentSubCategoryUniqueId,
-            @PathParam(value = "groupingUniqueId") final String groupingUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        try {
-            Either<GroupingDefinition, ResponseFormat> deleteGrouping = elementBusinessLogic
-                .deleteGrouping(groupingUniqueId, componentType, userId);
-            if (deleteGrouping.isRight()) {
-                return buildErrorResponse(deleteGrouping.right().value());
-            }
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
-            return buildOkResponse(responseFormat, null);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component grouping");
-            log.debug("deleteGrouping failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
-    // retrieve all tags
-    @GET
-    @Path("/tags")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve all tags", httpMethod = "GET", notes = "Retrieve all tags", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns tags Ok"), @ApiResponse(code = 404, message = "No tags were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response getTags(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(getTags) Start handle request of {}", url);
-
-        try {
-            Either<List<Tag>, ActionStatus> either = elementBusinessLogic.getAllTags(userId);
-            if (either.isRight() || either.left().value() == null) {
-                log.debug("No tags were found");
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
-            } else {
-                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Tags");
-            log.debug("getAllTags failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
-    // retrieve all property scopes
-    @GET
-    @Path("/propertyScopes")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve all propertyScopes", httpMethod = "GET", notes = "Retrieve all propertyScopes", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns propertyScopes Ok"), @ApiResponse(code = 404, message = "No propertyScopes were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response getPropertyScopes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(getPropertyScopes) Start handle request of {}", url);
-
-        try {
-            Either<List<PropertyScope>, ActionStatus> either = elementBusinessLogic.getAllPropertyScopes(userId);
-            if (either.isRight() || either.left().value() == null) {
-                log.debug("No property scopes were found");
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
-            } else {
-                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property Scopes Categories");
-            log.debug("getPropertyScopes failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
-    // retrieve all artifact types
-    @GET
-    @Path("/artifactTypes")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response getArtifactTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(GET - getArtifactTypes) Start handle request of {}", url);
-
-        try {
-            Either<List<ArtifactType>, ActionStatus> either = elementBusinessLogic.getAllArtifactTypes(userId);
-            if (either.isRight() || either.left().value() == null) {
-                log.debug("No artifact types were found");
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
-            } else {
-
-                Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
-                ArtifactTypesInfo typesResponse = new ArtifactTypesInfo();
-                typesResponse.setArtifactTypes(either.left().value());
-                typesResponse.setHeatDefaultTimeout(defaultHeatTimeout);
-
-                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), typesResponse);
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types");
-            log.debug("getArtifactTypes failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
-    // retrieve all artifact types
-    @GET
-    @Path("/configuration/ui")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response getConfiguration(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(getConfiguration) Start handle request of {}", url);
-
-        try {
-            Either<List<ArtifactType>, ActionStatus> otherEither = elementBusinessLogic.getAllArtifactTypes(userId);
-            Either<Integer, ActionStatus> defaultHeatTimeout = elementBusinessLogic.getDefaultHeatTimeout();
-            Either<Map<String, Object>, ActionStatus> deploymentEither = elementBusinessLogic.getAllDeploymentArtifactTypes();
-            Either<Map<String, String>, ActionStatus> resourceTypesMap = elementBusinessLogic.getResourceTypesMap();
-
-            if (otherEither.isRight() || otherEither.left().value() == null) {
-                log.debug("No other artifact types were found");
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
-            } else if (deploymentEither.isRight() || deploymentEither.left().value() == null) {
-                log.debug("No deployment artifact types were found");
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
-            } else if (defaultHeatTimeout.isRight() || defaultHeatTimeout.left().value() == null) {
-                log.debug("heat default timeout was not found");
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
-            } else if (resourceTypesMap.isRight() || resourceTypesMap.left().value() == null) {
-                log.debug("No resource types were found");
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
-            } else {
-                Map<String, Object> artifacts = new HashMap<>();
-                Map<String, Object> configuration = new HashMap<>();
-
-                artifacts.put("other", otherEither.left().value());
-                artifacts.put("deployment", deploymentEither.left().value());
-                configuration.put("artifacts", artifacts);
-                configuration.put("defaultHeatTimeout", defaultHeatTimeout.left().value());
-                configuration.put("componentTypes", elementBusinessLogic.getAllComponentTypesParamNames());
-                configuration.put("roles", elementBusinessLogic.getAllSupportedRoles());
-                configuration.put("resourceTypes", resourceTypesMap.left().value());
-                configuration.put("environmentContext", ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext());
-                configuration.put("gab", ConfigurationManager.getConfigurationManager().getConfiguration().getGabConfig());
-
-                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), configuration);
-            }
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types");
-            log.debug("getArtifactTypes failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
-    // retrieve all followed resources and services
-    @GET
-    @Path("/followed")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve all followed", httpMethod = "GET", notes = "Retrieve all followed", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns followed Ok"), @ApiResponse(code = 404, message = "No followed were found"), @ApiResponse(code = 404, message = "User not found"),
-            @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response getFollowedResourcesServices(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        Response res = null;
-        User userData = null;
-        try {
-            String url = request.getMethod() + " " + request.getRequestURI();
-            log.debug("Start handle request of {}", url);
-
-            // Getting the user
-            Either<User, ActionStatus> either = userBusinessLogic.getUser(userId, false);
-            if (either.isRight()) {
-                // Couldn't find or otherwise fetch the user
-                return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));
-            }
-
-            if (either.left().value() != null) {
-                userData = either.left().value();
-                Either<Map<String, List<? extends Component>>, ResponseFormat> followedResourcesServices =
-                    elementBusinessLogic.getFollowed(userData);
-                if (followedResourcesServices.isRight()) {
-                    log.debug("failed to get followed resources services ");
-                    return buildErrorResponse(followedResourcesServices.right().value());
-                }
-                Object data = RepresentationUtils.toRepresentation(followedResourcesServices.left().value());
-                res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data);
-            } else {
-                res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Followed Resources / Services Categories");
-            log.debug("Getting followed resources/services failed with exception", e);
-            res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-        return res;
-    }
-
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
-    // retrieve all certified resources and services and their last version
-    @GET
-    @Path("/screen")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve catalog resources and services", httpMethod = "GET", notes = "Retrieve catalog resources and services", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns resources and services Ok"), @ApiResponse(code = 404, message = "No resources and services were found"), @ApiResponse(code = 404, message = "User not found"),
-            @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @QueryParam("excludeTypes") List<OriginTypeEnum> excludeTypes) {
-
-        Response res = null;
-        try {
-            String url = request.getMethod() + " " + request.getRequestURI();
-            log.debug("Start handle request of {}", url);
-
-                       Either<Map<String, List<CatalogComponent>>, ResponseFormat> catalogData = elementBusinessLogic
-          .getCatalogComponents(userId, excludeTypes);
-
-            if (catalogData.isRight()) {
-                log.debug("failed to get catalog data");
-                return buildErrorResponse(catalogData.right().value());
-            }
-            Object data = RepresentationUtils.toRepresentation(catalogData.left().value());
-            res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Catalog Components");
-            log.debug("Getting catalog components failed with exception", e);
-            res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-        return res;
-    }
-
-    @DELETE
-    @Path("/inactiveComponents/{componentType}")
-    public Response deleteMarkedResources(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        // get modifier id
-        String userId = request.getHeader(Constants.USER_ID_HEADER);
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-
-        NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType);
-        if (nodeType == null) {
-            log.info("componentType is not valid: {}", componentType);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-        }
-
-        List<NodeTypeEnum> componentsList = new ArrayList<>();
-        componentsList.add(nodeType);
-        try {
-            Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponentsResult = componentsCleanBusinessLogic.cleanComponents(componentsList);
-            Either<List<String>, ResponseFormat> cleanResult = cleanComponentsResult.get(nodeType);
-
-            if (cleanResult.isRight()) {
-                log.debug("failed to delete marked components of type {}", nodeType);
-                response = buildErrorResponse(cleanResult.right().value());
-                return response;
-            }
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), cleanResult.left().value());
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Marked Components");
-            log.debug("delete marked components failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @GET
-    @Path("/ecompPortalMenu")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve ecomp portal menu - MOC", httpMethod = "GET", notes = "Retrieve ecomp portal menu", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieve ecomp portal menu") })
-    public Response getListOfCsars(@Context final HttpServletRequest request) {
-        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                "[{\"menuId\":1,\"column\":2,\"text\":\"Design\",\"parentMenuId\":null,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":11,\"column\":1,\"text\":\"ProductDesign\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":12,\"column\":2,\"text\":\"Service\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":21,\"column\":1,\"text\":\"ViewPolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":90,\"column\":1,\"text\":\"4thLevelApp1aR16\",\"parentMenuId\":21,\"url\":\"http://google.com\",\"appid\":null,\"roles\":null}]},{\"menuId\":22,\"column\":2,\"text\":\"UpdatePolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":91,\"column\":1,\"text\":\"4thLevelApp1bR16\",\"parentMenuId\":22,\"url\":\"http://jsonlint.com/\",\"appid\":null,\"roles\":null}]},{\"menuId\":23,\"column\":3,\"text\":\"UpdateRules\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":24,\"column\":4,\"text\":\"CreateSignatures?\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":25,\"column\":5,\"text\":\"Definedata\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null}]}]}]");
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.QueryParam;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;\r
+import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.config.ConfigurationManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.info.ArtifactTypesInfo;\r
+import org.openecomp.sdc.be.model.ArtifactType;\r
+import org.openecomp.sdc.be.model.Category;\r
+import org.openecomp.sdc.be.model.Component;\r
+import org.openecomp.sdc.be.model.PropertyScope;\r
+import org.openecomp.sdc.be.model.Tag;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.model.catalog.CatalogComponent;\r
+import org.openecomp.sdc.be.model.category.CategoryDefinition;\r
+import org.openecomp.sdc.be.model.category.GroupingDefinition;\r
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;\r
+import org.openecomp.sdc.be.ui.model.UiCategories;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Path("/v1/")\r
+\r
+/****\r
+ * \r
+ * UI oriented servlet - to return elements in specific format UI needs\r
+ * \r
+ *\r
+ */\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@OpenAPIDefinition(info = @Info(title = "Element Servlet",description = "Element Servlet"))\r
+@Singleton\r
+public class ElementServlet extends BeGenericServlet {\r
+\r
+    private static final Logger log = Logger.getLogger(ElementServlet.class);\r
+    private final ComponentsCleanBusinessLogic componentsCleanBusinessLogic;\r
+    private final ElementBusinessLogic elementBusinessLogic;\r
+    private final UserBusinessLogic userBusinessLogic;\r
+\r
+    @Inject\r
+    public ElementServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils,\r
+        ComponentsCleanBusinessLogic componentsCleanBusinessLogic,\r
+        ElementBusinessLogic elementBusinessLogic) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.componentsCleanBusinessLogic = componentsCleanBusinessLogic;\r
+        this.elementBusinessLogic = elementBusinessLogic;\r
+        this.userBusinessLogic = userBusinessLogic;\r
+    }\r
+\r
+    /*\r
+     ******************************************************************************\r
+     * NEW CATEGORIES category / \ subcategory subcategory / grouping\r
+     ******************************************************************************/\r
+\r
+    /*\r
+     *\r
+     *\r
+     * CATEGORIES\r
+     */\r
+    /////////////////////////////////////////////////////////////////////////////////////////////////////\r
+    // retrieve all component categories\r
+    @GET\r
+    @Path("/categories/{componentType}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve the list of all resource/service/product categories/sub-categories/groupings",\r
+            method = "GET",\r
+            summary = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.",\r
+                    responses = @ApiResponse(\r
+                            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returns categories Ok"),\r
+            @ApiResponse(responseCode = "403", description = "Missing information"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid component type"),\r
+            @ApiResponse(responseCode = "409", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response getComponentCategories(\r
+            @Parameter(description = "allowed values are resources / services/ products", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                    ComponentTypeEnum.SERVICE_PARAM_NAME,ComponentTypeEnum.PRODUCT_PARAM_NAME}),required = true)\r
+                     @PathParam(value = "componentType") final String componentType,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {\r
+\r
+        try {\r
+            Either<List<CategoryDefinition>, ResponseFormat> either =\r
+                    elementBusinessLogic.getAllCategories(componentType, userId);\r
+            if (either.isRight()) {\r
+                log.debug("No categories were found for type {}", componentType);\r
+                return buildErrorResponse(either.right().value());\r
+            } else {\r
+                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Categories");\r
+            log.debug("getComponentCategories failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/categories")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve the all resource, service and product categories", method = "GET",\r
+            summary = "Retrieve the all resource, service and product categories", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returns categories Ok"),\r
+            @ApiResponse(responseCode = "403", description = "Missing information"),\r
+            @ApiResponse(responseCode = "409", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response getAllCategories(@Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        try {\r
+            Either<UiCategories, ResponseFormat> either = elementBusinessLogic.getAllCategories(userId);\r
+            if (either.isRight()) {\r
+                log.debug("No categories were found");\r
+                return buildErrorResponse(either.right().value());\r
+            } else {\r
+                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Categories");\r
+            log.debug("getAllCategories failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+\r
+    @POST\r
+    @Path("/category/{componentType}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create new component category", method = "POST",\r
+            summary = "Create new component category")\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Category created"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid category data"),\r
+            @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),\r
+            @ApiResponse(responseCode = "409",\r
+                    description = "Category already exists / User not permitted to perform the action"),\r
+            @ApiResponse(responseCode = "500", description = "General Error")})\r
+    public Response createComponentCategory(\r
+            @Parameter(description = "allowed values are resources /services / products",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME,ComponentTypeEnum.PRODUCT_PARAM_NAME}),\r
+                    required = true) @PathParam(value = "componentType") final String componentType,\r
+            @Parameter(description = "Category to be created", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        try {\r
+            CategoryDefinition category = RepresentationUtils.fromRepresentation(data, CategoryDefinition.class);\r
+\r
+            Either<CategoryDefinition, ResponseFormat> createResourceCategory =\r
+                    elementBusinessLogic.createCategory(category, componentType, userId);\r
+            if (createResourceCategory.isRight()) {\r
+                return buildErrorResponse(createResourceCategory.right().value());\r
+            }\r
+\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);\r
+            return buildOkResponse(responseFormat, createResourceCategory.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category");\r
+            log.debug("createResourceCategory failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/category/{componentType}/{categoryUniqueId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Category deleted"),\r
+            @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),\r
+            @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"),\r
+            @ApiResponse(responseCode = "404", description = "Category not found"),\r
+            @ApiResponse(responseCode = "500", description = "General Error")})\r
+    public Response deleteComponentCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId,\r
+            @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        try {\r
+            Either<CategoryDefinition, ResponseFormat> createResourceCategory =\r
+                    elementBusinessLogic.deleteCategory(categoryUniqueId, componentType, userId);\r
+\r
+            if (createResourceCategory.isRight()) {\r
+                return buildErrorResponse(createResourceCategory.right().value());\r
+            }\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);\r
+            return buildOkResponse(responseFormat, null);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category");\r
+            log.debug("createResourceCategory failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    /*\r
+     *\r
+     *\r
+     * SUBCATEGORIES\r
+     *\r
+     */\r
+\r
+    @POST\r
+    @Path("/category/{componentType}/{categoryId}/subCategory")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create new component sub-category", method = "POST",\r
+            summary = "Create new component sub-category for existing category")\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Subcategory created"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid subcategory data"),\r
+            @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),\r
+            @ApiResponse(responseCode = "404", description = "Parent category wasn't found"),\r
+            @ApiResponse(responseCode = "409",\r
+                    description = "Subcategory already exists / User not permitted to perform the action"),\r
+            @ApiResponse(responseCode = "500", description = "General Error")})\r
+    public Response createComponentSubCategory(\r
+            @Parameter(description = "allowed values are resources / products",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                            ComponentTypeEnum.PRODUCT_PARAM_NAME}),\r
+                    required = true) @PathParam(value = "componentType") final String componentType,\r
+            @Parameter(description = "Parent category unique ID",\r
+                    required = true) @PathParam(value = "categoryId") final String categoryId,\r
+            @Parameter(description = "Subcategory to be created. \ne.g. {\"name\":\"Resource-subcat\"}",\r
+                    required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        try {\r
+            SubCategoryDefinition subCategory =\r
+                    RepresentationUtils.fromRepresentation(data, SubCategoryDefinition.class);\r
+\r
+            Either<SubCategoryDefinition, ResponseFormat> createSubcategory =\r
+                    elementBusinessLogic.createSubCategory(subCategory, componentType, categoryId, userId);\r
+            if (createSubcategory.isRight()) {\r
+                return buildErrorResponse(createSubcategory.right().value());\r
+            }\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);\r
+            return buildOkResponse(responseFormat, createSubcategory.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create sub-category");\r
+            log.debug("createComponentSubCategory failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Category deleted"),\r
+            @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),\r
+            @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"),\r
+            @ApiResponse(responseCode = "404", description = "Category not found"),\r
+            @ApiResponse(responseCode = "500", description = "General Error")})\r
+    public Response deleteComponentSubCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId,\r
+            @PathParam(value = "subCategoryUniqueId") final String subCategoryUniqueId,\r
+            @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        try {\r
+            Either<SubCategoryDefinition, ResponseFormat> deleteSubResourceCategory =\r
+                    elementBusinessLogic.deleteSubCategory(subCategoryUniqueId, componentType, userId);\r
+            if (deleteSubResourceCategory.isRight()) {\r
+                return buildErrorResponse(deleteSubResourceCategory.right().value());\r
+            }\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);\r
+            return buildOkResponse(responseFormat, null);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component category");\r
+            log.debug("deleteComponentSubCategory failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    /*\r
+     * GROUPINGS\r
+     */\r
+    @POST\r
+    @Path("/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create new component grouping", method = "POST",\r
+            summary = "Create new component grouping for existing sub-category")\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Grouping created"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid grouping data"),\r
+            @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),\r
+            @ApiResponse(responseCode = "404", description = "Parent category or subcategory were not found"),\r
+            @ApiResponse(responseCode = "409",\r
+                    description = "Grouping already exists / User not permitted to perform the action"),\r
+            @ApiResponse(responseCode = "500", description = "General Error")})\r
+    public Response createComponentGrouping(\r
+            @Parameter(description = "allowed values are products",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.PRODUCT_PARAM_NAME}),\r
+                    required = true) @PathParam(value = "componentType") final String componentType,\r
+            @Parameter(description = "Parent category unique ID",\r
+                    required = true) @PathParam(value = "categoryId") final String grandParentCategoryId,\r
+            @Parameter(description = "Parent sub-category unique ID",\r
+                    required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId,\r
+            @Parameter(description = "Subcategory to be created", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        try {\r
+            GroupingDefinition grouping = RepresentationUtils.fromRepresentation(data, GroupingDefinition.class);\r
+\r
+            Either<GroupingDefinition, ResponseFormat> createGrouping = elementBusinessLogic.createGrouping(grouping,\r
+                    componentType, grandParentCategoryId, parentSubCategoryId, userId);\r
+            if (createGrouping.isRight()) {\r
+                return buildErrorResponse(createGrouping.right().value());\r
+            }\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);\r
+            return buildOkResponse(responseFormat, createGrouping.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create grouping");\r
+            log.debug("createComponentGrouping failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Category deleted"),\r
+            @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),\r
+            @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"),\r
+            @ApiResponse(responseCode = "404", description = "Category not found"),\r
+            @ApiResponse(responseCode = "500", description = "General Error")})\r
+    public Response deleteComponentGrouping(\r
+            @PathParam(value = "categoryUniqueId") final String grandParentCategoryUniqueId,\r
+            @PathParam(value = "subCategoryUniqueId") final String parentSubCategoryUniqueId,\r
+            @PathParam(value = "groupingUniqueId") final String groupingUniqueId,\r
+            @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        try {\r
+            Either<GroupingDefinition, ResponseFormat> deleteGrouping =\r
+                    elementBusinessLogic.deleteGrouping(groupingUniqueId, componentType, userId);\r
+            if (deleteGrouping.isRight()) {\r
+                return buildErrorResponse(deleteGrouping.right().value());\r
+            }\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);\r
+            return buildOkResponse(responseFormat, null);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component grouping");\r
+            log.debug("deleteGrouping failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    /////////////////////////////////////////////////////////////////////////////////////////////////////\r
+    // retrieve all tags\r
+    @GET\r
+    @Path("/tags")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve all tags", method = "GET", summary = "Retrieve all tags",responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returns tags Ok"),\r
+            @ApiResponse(responseCode = "404", description = "No tags were found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response getTags(@Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(getTags) Start handle request of {}", url);\r
+\r
+        try {\r
+            Either<List<Tag>, ActionStatus> either = elementBusinessLogic.getAllTags(userId);\r
+            if (either.isRight() || either.left().value() == null) {\r
+                log.debug("No tags were found");\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));\r
+            } else {\r
+                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Tags");\r
+            log.debug("getAllTags failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    /////////////////////////////////////////////////////////////////////////////////////////////////////\r
+    // retrieve all property scopes\r
+    @GET\r
+    @Path("/propertyScopes")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve all propertyScopes", method = "GET", summary = "Retrieve all propertyScopes",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returns propertyScopes Ok"),\r
+            @ApiResponse(responseCode = "404", description = "No propertyScopes were found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response getPropertyScopes(@Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(getPropertyScopes) Start handle request of {}", url);\r
+\r
+        try {\r
+            Either<List<PropertyScope>, ActionStatus> either = elementBusinessLogic.getAllPropertyScopes(userId);\r
+            if (either.isRight() || either.left().value() == null) {\r
+                log.debug("No property scopes were found");\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));\r
+            } else {\r
+                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property Scopes Categories");\r
+            log.debug("getPropertyScopes failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    /////////////////////////////////////////////////////////////////////////////////////////////////////\r
+    // retrieve all artifact types\r
+    @GET\r
+    @Path("/artifactTypes")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve all artifactTypes", method = "GET", summary = "Retrieve all artifactTypes",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returns artifactTypes Ok"),\r
+            @ApiResponse(responseCode = "404", description = "No artifactTypes were found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response getArtifactTypes(@Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(GET - getArtifactTypes) Start handle request of {}", url);\r
+\r
+        try {\r
+            Either<List<ArtifactType>, ActionStatus> either = elementBusinessLogic.getAllArtifactTypes(userId);\r
+            if (either.isRight() || either.left().value() == null) {\r
+                log.debug("No artifact types were found");\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));\r
+            } else {\r
+\r
+                Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()\r
+                        .getDefaultHeatArtifactTimeoutMinutes();\r
+                ArtifactTypesInfo typesResponse = new ArtifactTypesInfo();\r
+                typesResponse.setArtifactTypes(either.left().value());\r
+                typesResponse.setHeatDefaultTimeout(defaultHeatTimeout);\r
+\r
+                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), typesResponse);\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types");\r
+            log.debug("getArtifactTypes failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    /////////////////////////////////////////////////////////////////////////////////////////////////////\r
+    // retrieve all artifact types\r
+    @GET\r
+    @Path("/configuration/ui")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve all artifactTypes", method = "GET", summary = "Retrieve all artifactTypes",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returns artifactTypes Ok"),\r
+            @ApiResponse(responseCode = "404", description = "No artifactTypes were found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response getConfiguration(@Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(getConfiguration) Start handle request of {}", url);\r
+\r
+        try {\r
+            Either<List<ArtifactType>, ActionStatus> otherEither = elementBusinessLogic.getAllArtifactTypes(userId);\r
+            Either<Integer, ActionStatus> defaultHeatTimeout = elementBusinessLogic.getDefaultHeatTimeout();\r
+            Either<Map<String, Object>, ActionStatus> deploymentEither =\r
+                    elementBusinessLogic.getAllDeploymentArtifactTypes();\r
+            Either<Map<String, String>, ActionStatus> resourceTypesMap = elementBusinessLogic.getResourceTypesMap();\r
+\r
+            if (otherEither.isRight() || otherEither.left().value() == null) {\r
+                log.debug("No other artifact types were found");\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));\r
+            } else if (deploymentEither.isRight() || deploymentEither.left().value() == null) {\r
+                log.debug("No deployment artifact types were found");\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));\r
+            } else if (defaultHeatTimeout.isRight() || defaultHeatTimeout.left().value() == null) {\r
+                log.debug("heat default timeout was not found");\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));\r
+            } else if (resourceTypesMap.isRight() || resourceTypesMap.left().value() == null) {\r
+                log.debug("No resource types were found");\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));\r
+            } else {\r
+                Map<String, Object> artifacts = new HashMap<>();\r
+                Map<String, Object> configuration = new HashMap<>();\r
+\r
+                artifacts.put("other", otherEither.left().value());\r
+                artifacts.put("deployment", deploymentEither.left().value());\r
+                configuration.put("artifacts", artifacts);\r
+                configuration.put("defaultHeatTimeout", defaultHeatTimeout.left().value());\r
+                configuration.put("componentTypes", elementBusinessLogic.getAllComponentTypesParamNames());\r
+                configuration.put("roles", elementBusinessLogic.getAllSupportedRoles());\r
+                configuration.put("resourceTypes", resourceTypesMap.left().value());\r
+                configuration.put("environmentContext",\r
+                        ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext());\r
+                configuration.put("gab",\r
+                        ConfigurationManager.getConfigurationManager().getConfiguration().getGabConfig());\r
+\r
+                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), configuration);\r
+            }\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types");\r
+            log.debug("getArtifactTypes failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    /////////////////////////////////////////////////////////////////////////////////////////////////////\r
+    // retrieve all followed resources and services\r
+    @GET\r
+    @Path("/followed")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve all followed", method = "GET", summary = "Retrieve all followed",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returns followed Ok"),\r
+            @ApiResponse(responseCode = "404", description = "No followed were found"),\r
+            @ApiResponse(responseCode = "404", description = "User not found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response getFollowedResourcesServices(@Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        Response res = null;\r
+        User userData = null;\r
+        try {\r
+            String url = request.getMethod() + " " + request.getRequestURI();\r
+            log.debug("Start handle request of {}", url);\r
+\r
+            // Getting the user\r
+            Either<User, ActionStatus> either = userBusinessLogic.getUser(userId, false);\r
+            if (either.isRight()) {\r
+                // Couldn't find or otherwise fetch the user\r
+                return buildErrorResponse(\r
+                        getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));\r
+            }\r
+\r
+            if (either.left().value() != null) {\r
+                userData = either.left().value();\r
+                Either<Map<String, List<? extends Component>>, ResponseFormat> followedResourcesServices =\r
+                        elementBusinessLogic.getFollowed(userData);\r
+                if (followedResourcesServices.isRight()) {\r
+                    log.debug("failed to get followed resources services ");\r
+                    return buildErrorResponse(followedResourcesServices.right().value());\r
+                }\r
+                Object data = RepresentationUtils.toRepresentation(followedResourcesServices.left().value());\r
+                res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data);\r
+            } else {\r
+                res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Followed Resources / Services Categories");\r
+            log.debug("Getting followed resources/services failed with exception", e);\r
+            res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+        return res;\r
+    }\r
+\r
+    /////////////////////////////////////////////////////////////////////////////////////////////////////\r
+    // retrieve all certified resources and services and their last version\r
+    @GET\r
+    @Path("/screen")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve catalog resources and services", method = "GET",\r
+            summary = "Retrieve catalog resources and services", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returns resources and services Ok"),\r
+            @ApiResponse(responseCode = "404", description = "No resources and services were found"),\r
+            @ApiResponse(responseCode = "404", description = "User not found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response getCatalogComponents(@Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @QueryParam("excludeTypes") List<OriginTypeEnum> excludeTypes) {\r
+\r
+        Response res = null;\r
+        try {\r
+            String url = request.getMethod() + " " + request.getRequestURI();\r
+            log.debug("Start handle request of {}", url);\r
+\r
+            Either<Map<String, List<CatalogComponent>>, ResponseFormat> catalogData =\r
+                    elementBusinessLogic.getCatalogComponents(userId, excludeTypes);\r
+\r
+            if (catalogData.isRight()) {\r
+                log.debug("failed to get catalog data");\r
+                return buildErrorResponse(catalogData.right().value());\r
+            }\r
+            Object data = RepresentationUtils.toRepresentation(catalogData.left().value());\r
+            res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Catalog Components");\r
+            log.debug("Getting catalog components failed with exception", e);\r
+            res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+        return res;\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/inactiveComponents/{componentType}")\r
+    public Response deleteMarkedResources(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        // get modifier id\r
+        String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+\r
+        NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType);\r
+        if (nodeType == null) {\r
+            log.info("componentType is not valid: {}", componentType);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+        }\r
+\r
+        List<NodeTypeEnum> componentsList = new ArrayList<>();\r
+        componentsList.add(nodeType);\r
+        try {\r
+            Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponentsResult = componentsCleanBusinessLogic.cleanComponents(componentsList);\r
+            Either<List<String>, ResponseFormat> cleanResult = cleanComponentsResult.get(nodeType);\r
+\r
+            if (cleanResult.isRight()) {\r
+                log.debug("failed to delete marked components of type {}", nodeType);\r
+                response = buildErrorResponse(cleanResult.right().value());\r
+                return response;\r
+            }\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), cleanResult.left().value());\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Marked Components");\r
+            log.debug("delete marked components failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/ecompPortalMenu")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve ecomp portal menu - MOC", method = "GET", summary = "Retrieve ecomp portal menu", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Retrieve ecomp portal menu") })\r
+    public Response getListOfCsars(@Context final HttpServletRequest request) {\r
+        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                "[{\"menuId\":1,\"column\":2,\"text\":\"Design\",\"parentMenuId\":null,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":11,\"column\":1,\"text\":\"ProductDesign\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":12,\"column\":2,\"text\":\"Service\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":21,\"column\":1,\"text\":\"ViewPolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":90,\"column\":1,\"text\":\"4thLevelApp1aR16\",\"parentMenuId\":21,\"url\":\"http://google.com\",\"appid\":null,\"roles\":null}]},{\"menuId\":22,\"column\":2,\"text\":\"UpdatePolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":91,\"column\":1,\"text\":\"4thLevelApp1bR16\",\"parentMenuId\":22,\"url\":\"http://jsonlint.com/\",\"appid\":null,\"roles\":null}]},{\"menuId\":23,\"column\":3,\"text\":\"UpdateRules\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":24,\"column\":4,\"text\":\"CreateSignatures?\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":25,\"column\":5,\"text\":\"Definedata\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null}]}]}]");\r
+    }\r
+\r
+}\r
index afa57f7..580362c 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2019 Nokia Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import java.io.IOException;
-import java.util.Set;
-import java.util.stream.Collectors;
-import javax.inject.Inject;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.onap.sdc.gab.model.GABQuery;
-import org.onap.sdc.gab.model.GABQuery.GABQueryType;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GenericArtifactBrowserBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.info.GenericArtifactQueryInfo;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.owasp.esapi.ESAPI;
-import org.springframework.stereotype.Controller;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog/gab")
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-@Api(value = "Generic Artifact Browser")
-@Controller
-public class GenericArtifactBrowserServlet extends BeGenericServlet {
-
-    private static final Logger LOGGER = Logger.getLogger(GenericArtifactBrowserServlet.class);
-    private final GenericArtifactBrowserBusinessLogic gabLogic;
-    private final ArtifactsBusinessLogic artifactsBusinessLogic;
-
-    @Inject
-    public GenericArtifactBrowserServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        ArtifactsBusinessLogic artifactsBusinessLogic,
-        GenericArtifactBrowserBusinessLogic gabLogic) {
-        super(userBusinessLogic, componentsUtils);
-        this.artifactsBusinessLogic = artifactsBusinessLogic;
-        this.gabLogic = gabLogic;
-    }
-
-    @POST
-    @Path("/searchFor")
-    @ApiOperation(value = "Search json paths inside the yaml", httpMethod = "POST", notes = "Returns found entries of json paths", response = Response.class)
-    @ApiResponses(value = {
-        @ApiResponse(code = 200, message = "Returned yaml entries"),
-        @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response searchFor(
-        @ApiParam(value = "Generic Artifact search model", required = true) GenericArtifactQueryInfo query,
-        @Context final HttpServletRequest request) {
-        try {
-            Either<ImmutablePair<String, byte[]>, ResponseFormat> immutablePairResponseFormatEither = artifactsBusinessLogic
-                .downloadArtifact(ESAPI.encoder().canonicalize(query.getParentId()), ESAPI.encoder().canonicalize(query.getArtifactUniqueId()));
-            if (immutablePairResponseFormatEither.isLeft()){
-                GABQuery gabQuery = prepareGabQuery(query, immutablePairResponseFormatEither);
-                return buildOkResponse(gabLogic.searchFor(gabQuery));
-            }else{
-                throw new IOException(immutablePairResponseFormatEither.right().value().getFormattedMessage());
-            }
-        } catch (IOException e) {
-            LOGGER.error("Cannot search for a given queries in the yaml file", e);
-            return buildGeneralErrorResponse();
-        }
-    }
-
-    private GABQuery prepareGabQuery(GenericArtifactQueryInfo query,
-        Either<ImmutablePair<String, byte[]>, ResponseFormat> immutablePairResponseFormatEither) {
-        byte[] content = immutablePairResponseFormatEither.left().value().getRight();
-        Set<String> queryFields = query.getFields().stream().map(ESAPI.encoder()::canonicalize).collect(Collectors.toSet());
-        return new GABQuery(queryFields, new String(content), GABQueryType.CONTENT);
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2019 Nokia Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.io.IOException;\r
+import java.util.Set;\r
+import java.util.stream.Collectors;\r
+import javax.inject.Inject;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.lang3.tuple.ImmutablePair;\r
+import org.onap.sdc.gab.model.GABQuery;\r
+import org.onap.sdc.gab.model.GABQuery.GABQueryType;\r
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.GenericArtifactBrowserBusinessLogic;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.info.GenericArtifactQueryInfo;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import org.owasp.esapi.ESAPI;\r
+import org.springframework.stereotype.Controller;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog/gab")\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+@OpenAPIDefinition(info = @Info(title = "Generic Artifact Browser"))\r
+@Controller\r
+public class GenericArtifactBrowserServlet extends BeGenericServlet {\r
+\r
+    private static final Logger LOGGER = Logger.getLogger(GenericArtifactBrowserServlet.class);\r
+    private final GenericArtifactBrowserBusinessLogic gabLogic;\r
+    private final ArtifactsBusinessLogic artifactsBusinessLogic;\r
+\r
+    @Inject\r
+    public GenericArtifactBrowserServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils,\r
+        ArtifactsBusinessLogic artifactsBusinessLogic,\r
+        GenericArtifactBrowserBusinessLogic gabLogic) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.artifactsBusinessLogic = artifactsBusinessLogic;\r
+        this.gabLogic = gabLogic;\r
+    }\r
+\r
+    @POST\r
+    @Path("/searchFor")\r
+    @Operation(description = "Search json paths inside the yaml", method = "POST", summary = "Returns found entries of json paths",responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {\r
+        @ApiResponse(responseCode = "200", description = "Returned yaml entries"),\r
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response searchFor(\r
+        @Parameter(description = "Generic Artifact search model", required = true) GenericArtifactQueryInfo query,\r
+        @Context final HttpServletRequest request) {\r
+        try {\r
+            Either<ImmutablePair<String, byte[]>, ResponseFormat> immutablePairResponseFormatEither = artifactsBusinessLogic\r
+                .downloadArtifact(ESAPI.encoder().canonicalize(query.getParentId()), ESAPI.encoder().canonicalize(query.getArtifactUniqueId()));\r
+            if (immutablePairResponseFormatEither.isLeft()){\r
+                GABQuery gabQuery = prepareGabQuery(query, immutablePairResponseFormatEither);\r
+                return buildOkResponse(gabLogic.searchFor(gabQuery));\r
+            }else{\r
+                throw new IOException(immutablePairResponseFormatEither.right().value().getFormattedMessage());\r
+            }\r
+        } catch (IOException e) {\r
+            LOGGER.error("Cannot search for a given queries in the yaml file", e);\r
+            return buildGeneralErrorResponse();\r
+        }\r
+    }\r
+\r
+    private GABQuery prepareGabQuery(GenericArtifactQueryInfo query,\r
+        Either<ImmutablePair<String, byte[]>, ResponseFormat> immutablePairResponseFormatEither) {\r
+        byte[] content = immutablePairResponseFormatEither.left().value().getRight();\r
+        Set<String> queryFields = query.getFields().stream().map(ESAPI.encoder()::canonicalize).collect(Collectors.toSet());\r
+        return new GABQuery(queryFields, new String(content), GABQueryType.CONTENT);\r
+    }\r
+}\r
index eb61e89..387faae 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogicNew;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.common.api.Constants;
-import org.springframework.stereotype.Controller;
-
-import javax.ws.rs.*;
-import javax.ws.rs.core.MediaType;
-import java.util.List;
-
-/**
- * Here new APIs for group will be written in an attempt to gradually clean BL code
- */
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Group Servlet")
-@Controller
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-public class GroupEndpoint {
-
-    private final GroupBusinessLogicNew groupBusinessLogic;
-
-    @Inject
-    public GroupEndpoint(GroupBusinessLogicNew groupBusinessLogic) {
-        this.groupBusinessLogic = groupBusinessLogic;
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/members")
-    @ApiOperation(value = "Update group members ", httpMethod = "POST", notes = "Updates list of members and returns it", response = String.class, responseContainer = "List")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Group members updated"),
-            @ApiResponse(code = 400, message = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Component not found"),
-            @ApiResponse(code = 500, message = "Internal Error")
-    })
-    public List<String> updateGroupMembers(
-            @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("groupUniqueId") final String groupUniqueId,
-            @ApiParam(value = "List of members unique ids", required = true) List<String> members,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-        return groupBusinessLogic.updateMembers(componentId, componentTypeEnum, userId, groupUniqueId, members);
-    }
-
-    @GET
-    @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties")
-    @ApiOperation(value = "Get List of properties on a group", httpMethod = "GET", notes = "Returns list of properties", response = GroupProperty.class, responseContainer="List")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Group Updated"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public List<PropertyDataDefinition> getGroupProperties(@PathParam("containerComponentType") final String containerComponentType,
-                                                           @PathParam("componentId") final String componentId,
-                                                           @PathParam("groupUniqueId") final String groupUniqueId,
-                                                           @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return groupBusinessLogic.getProperties(containerComponentType, userId, componentId, groupUniqueId);
-    }
-
-    @PUT
-    @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties")
-    @ApiOperation(value = "Updates List of properties on a group (only values)", httpMethod = "PUT", notes = "Returns updated list of properties", response = GroupProperty.class, responseContainer="List")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Group Updated"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public List<GroupProperty> updateGroupProperties(@PathParam("containerComponentType") final String containerComponentType,
-                                                     @PathParam("componentId") final String componentId,
-                                                     @PathParam("groupUniqueId") final String groupUniqueId,
-                                                     @ApiParam(value = "Group Properties to be Updated", required = true) List<GroupProperty> properties,
-                                                     @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-        return groupBusinessLogic.updateProperties(componentId, componentTypeEnum, userId, groupUniqueId, properties);
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.List;\r
+import javax.inject.Inject;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.MediaType;\r
+import org.openecomp.sdc.be.components.impl.GroupBusinessLogicNew;\r
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.model.GroupProperty;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.springframework.stereotype.Controller;\r
+import com.jcabi.aspects.Loggable;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+/**\r
+ * Here new APIs for group will be written in an attempt to gradually clean BL code\r
+ */\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Group Servlet"))\r
+@Controller\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+public class GroupEndpoint {\r
+\r
+    private final GroupBusinessLogicNew groupBusinessLogic;\r
+\r
+    @Inject\r
+    public GroupEndpoint(GroupBusinessLogicNew groupBusinessLogic) {\r
+        this.groupBusinessLogic = groupBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/members")\r
+    @Operation(description = "Update group members ", method = "POST",\r
+            summary = "Updates list of members and returns it", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Group members updated"), @ApiResponse(\r
+            responseCode = "400",\r
+            description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Error")})\r
+    public List<String> updateGroupMembers(@PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,\r
+            @Parameter(description = "List of members unique ids", required = true) List<String> members,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+        return groupBusinessLogic.updateMembers(componentId, componentTypeEnum, userId, groupUniqueId, members);\r
+    }\r
+\r
+    @GET\r
+    @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties")\r
+    @Operation(description = "Get List of properties on a group", method = "GET",\r
+            summary = "Returns list of properties", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupProperty.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Group Updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public List<PropertyDataDefinition> getGroupProperties(\r
+            @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return groupBusinessLogic.getProperties(containerComponentType, userId, componentId, groupUniqueId);\r
+    }\r
+\r
+    @PUT\r
+    @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties")\r
+    @Operation(description = "Updates List of properties on a group (only values)", method = "PUT",\r
+            summary = "Returns updated list of properties", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupProperty.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Group Updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public List<GroupProperty> updateGroupProperties(\r
+            @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,\r
+            @Parameter(description = "Group Properties to be Updated", required = true) List<GroupProperty> properties,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+        return groupBusinessLogic.updateProperties(componentId, componentTypeEnum, userId, groupUniqueId, properties);\r
+    }\r
+\r
+}\r
index 557304f..bbc41f2 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.info.GroupDefinitionInfo;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-/**
- * Root resource (exposed at "/" path)
- */
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-@Path("/v1/catalog")
-@Api(value = "Group Servlet")
-@Singleton
-public class GroupServlet extends AbstractValidationsServlet {
-
-    private static final Logger log = Logger.getLogger(GroupServlet.class);
-    public static final String START_HANDLE_REQUEST = "Start handle request of {}";
-    private final GroupBusinessLogic groupBL;
-
-    @Inject
-    public GroupServlet(UserBusinessLogic userBusinessLogic,
-        GroupBusinessLogic groupBL, ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.groupBL = groupBL;
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/groups/{groupType}")
-    @ApiOperation(value = "Create group ", httpMethod = "POST", notes = "Creates new group in component and returns it", response = GroupDefinition.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 201, message = "Group created"),
-            @ApiResponse(code = 400, message = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Component not found"),
-            @ApiResponse(code = 500, message = "Internal Error")
-    })
-    public Response createGroup(@PathParam("containerComponentType") final String containerComponentType,
-                                @PathParam("componentId") final String componentId,
-                                @PathParam("groupType") final String type,
-                                @Context final HttpServletRequest request,
-                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(post) Start handle request of {}", url);
-
-        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-        GroupDefinition groupDefinition = groupBL
-                .createGroup(componentId, componentTypeEnum, type, userId);
-
-        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED),
-                groupDefinition);
-    }
-
-    @GET
-    @Path("/{containerComponentType}/{componentId}/groups/{groupId}")
-    @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupId", response = Resource.class)
-    @ApiResponses(value = {@ApiResponse(code = 200, message = "group found"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Group not found")})
-    public Response getGroupById(@PathParam("containerComponentType") final String containerComponentType,
-                                 @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
-                                 @Context final HttpServletRequest request,
-                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}", url);
-
-        try {
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            Either<GroupDefinitionInfo, ResponseFormat> actionResponse = groupBL
-                    .getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to get all non abstract {}", containerComponentType);
-                return buildErrorResponse(actionResponse.right().value());
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    actionResponse.left().value());
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
-            log.debug("getGroupArtifactById unexpected exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    @DELETE
-    @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}")
-    @ApiOperation(value = "Delete Group", httpMethod = "DELETE", notes = "Returns deleted group id", response = Response.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 201, message = "ResourceInstance deleted"),
-            @ApiResponse(code = 400, message = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Component not found"),
-            @ApiResponse(code = 500, message = "Internal Error")
-    })
-    public Response deleteGroup(@PathParam("containerComponentType") final String containerComponentType,
-                                @PathParam("componentId") final String componentId,
-                                @PathParam("groupUniqueId") final String groupId,
-                                @Context final HttpServletRequest request,
-                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST, url);
-        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-        GroupDefinition groupDefinition = groupBL
-                .deleteGroup(componentId, componentTypeEnum, groupId, userId);
-
-        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), groupDefinition.getUniqueId());
-    }
-
-    @PUT
-    @Path("/{containerComponentType}/{componentId}/groups/{groupId}")
-    @ApiOperation(value = "Update Group metadata", httpMethod = "PUT", notes = "Returns updated Group", response = Response.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Group updated"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 404, message = "component / group Not found")})
-    public Response updateGroup(@PathParam("containerComponentType") final String containerComponentType,
-                                @PathParam("componentId") final String componentId,
-                                @PathParam("groupId") final String groupId,
-                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-                                @ApiParam(value = "GroupDefinition", required = true) GroupDefinition groupData,
-                                @Context final HttpServletRequest request) {
-        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-        GroupDefinition updatedGroup = groupBL.updateGroup(componentId, componentTypeEnum, groupId, userId, groupData);
-        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updatedGroup);
-    }
-
-    @PUT
-    @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/metadata")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Group Metadata", httpMethod = "PUT", notes = "Returns updated group definition", response = GroupDefinition.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateGroupMetadata(
-            @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
-            @ApiParam(value = "Service object to be Updated", required = true) String data,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST, url);
-
-        User user = new User();
-        user.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-
-        try {
-            Either<GroupDefinition, ResponseFormat> convertResponse = parseToObject(data, () -> GroupDefinition.class);
-            if (convertResponse.isRight()) {
-                log.debug("failed to parse group");
-                response = buildErrorResponse(convertResponse.right().value());
-                return response;
-            }
-            GroupDefinition updatedGroup = convertResponse.left().value();
-
-            // Update GroupDefinition
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            Either<GroupDefinition, ResponseFormat> actionResponse = groupBL
-                    .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true ,true);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to update GroupDefinition");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            GroupDefinition group = actionResponse.left().value();
-            Object result = RepresentationUtils.toRepresentation(group);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Metadata");
-            log.debug("update group metadata failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.info.GroupDefinitionInfo;\r
+import org.openecomp.sdc.be.model.GroupDefinition;\r
+import org.openecomp.sdc.be.model.Resource;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+/**\r
+ * Root resource (exposed at "/" path)\r
+ */\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Group Servlet"))\r
+@Singleton\r
+public class GroupServlet extends AbstractValidationsServlet {\r
+\r
+    private static final Logger log = Logger.getLogger(GroupServlet.class);\r
+    public static final String START_HANDLE_REQUEST = "Start handle request of {}";\r
+    private final GroupBusinessLogic groupBL;\r
+\r
+    @Inject\r
+    public GroupServlet(UserBusinessLogic userBusinessLogic, GroupBusinessLogic groupBL,\r
+            ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,\r
+            ServletUtils servletUtils, ResourceImportManager resourceImportManager) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.groupBL = groupBL;\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/groups/{groupType}")\r
+    @Operation(description = "Create group ", method = "POST",\r
+            summary = "Creates new group in component and returns it", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Group created"), @ApiResponse(\r
+            responseCode = "400",\r
+            description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Error")})\r
+    public Response createGroup(@PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("groupType") final String type,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(post) Start handle request of {}", url);\r
+\r
+        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+        GroupDefinition groupDefinition = groupBL.createGroup(componentId, componentTypeEnum, type, userId);\r
+\r
+        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), groupDefinition);\r
+    }\r
+\r
+    @GET\r
+    @Path("/{containerComponentType}/{componentId}/groups/{groupId}")\r
+    @Operation(description = "Get group artifacts ", method = "GET",\r
+            summary = "Returns artifacts metadata according to groupId", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "group found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Group not found")})\r
+    public Response getGroupById(@PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(get) Start handle request of {}", url);\r
+\r
+        try {\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            Either<GroupDefinitionInfo, ResponseFormat> actionResponse =\r
+                    groupBL.getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to get all non abstract {}", containerComponentType);\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    actionResponse.left().value());\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");\r
+            log.debug("getGroupArtifactById unexpected exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}")\r
+    @Operation(description = "Delete Group", method = "DELETE", summary = "Returns deleted group id",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "ResourceInstance deleted"), @ApiResponse(\r
+            responseCode = "400",\r
+            description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Error")})\r
+    public Response deleteGroup(@PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST, url);\r
+        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+        GroupDefinition groupDefinition = groupBL.deleteGroup(componentId, componentTypeEnum, groupId, userId);\r
+\r
+        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT),\r
+                groupDefinition.getUniqueId());\r
+    }\r
+\r
+    @PUT\r
+    @Path("/{containerComponentType}/{componentId}/groups/{groupId}")\r
+    @Operation(description = "Update Group metadata", method = "PUT", summary = "Returns updated Group",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Group updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "component / group Not found")})\r
+    public Response updateGroup(@PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "GroupDefinition", required = true) GroupDefinition groupData,\r
+            @Context final HttpServletRequest request) {\r
+        ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+        GroupDefinition updatedGroup = groupBL.updateGroup(componentId, componentTypeEnum, groupId, userId, groupData);\r
+        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updatedGroup);\r
+    }\r
+\r
+    @PUT\r
+    @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/metadata")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Group Metadata", method = "PUT", summary = "Returns updated group definition",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Group Updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateGroupMetadata(@PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,\r
+            @Parameter(description = "Service object to be Updated", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST, url);\r
+\r
+        User user = new User();\r
+        user.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+\r
+        try {\r
+            Either<GroupDefinition, ResponseFormat> convertResponse = parseToObject(data, () -> GroupDefinition.class);\r
+            if (convertResponse.isRight()) {\r
+                log.debug("failed to parse group");\r
+                response = buildErrorResponse(convertResponse.right().value());\r
+                return response;\r
+            }\r
+            GroupDefinition updatedGroup = convertResponse.left().value();\r
+\r
+            // Update GroupDefinition\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);\r
+            Either<GroupDefinition, ResponseFormat> actionResponse = groupBL.validateAndUpdateGroupMetadata(componentId,\r
+                    user, componentTypeEnum, updatedGroup, true, true);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to update GroupDefinition");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            GroupDefinition group = actionResponse.left().value();\r
+            Object result = RepresentationUtils.toRepresentation(group);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Metadata");\r
+            log.debug("update group metadata failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+}\r
index ffbf0e7..79a8208 100644 (file)
@@ -1,66 +1,79 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import io.swagger.annotations.*;
-import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;
-import org.openecomp.sdc.be.mixin.GroupTypeMixin;
-import org.openecomp.sdc.be.model.GroupTypeDefinition;
-import org.openecomp.sdc.be.view.ResponseView;
-import org.openecomp.sdc.common.api.Constants;
-import org.springframework.stereotype.Controller;
-
-import javax.ws.rs.*;
-import javax.ws.rs.core.MediaType;
-import java.util.List;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "group types resource")
-@Controller
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-public class GroupTypesEndpoint {
-
-    private final GroupTypeBusinessLogic groupTypeBusinessLogic;
-
-    public GroupTypesEndpoint(GroupTypeBusinessLogic groupTypeBusinessLogic) {
-        this.groupTypeBusinessLogic = groupTypeBusinessLogic;
-    }
-
-    @GET
-    @Path("/groupTypes")
-    @ApiOperation(value = "Get group types ", httpMethod = "GET", notes = "Returns group types", response = GroupTypeDefinition.class, responseContainer = "List")
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "group types found"),
-            @ApiResponse(code = 400, message = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 500, message = "Internal Error")
-    })
-    @ResponseView(mixin = {GroupTypeMixin.class})
-    public List<GroupTypeDefinition> getGroupTypes(@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-                                                   @ApiParam(value = "An optional parameter to indicate the type of the container from where this call is executed")
-                                                   @QueryParam("internalComponentType") String internalComponentType) {
-        return groupTypeBusinessLogic.getAllGroupTypes(userId, internalComponentType);
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.List;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.QueryParam;\r
+import javax.ws.rs.core.MediaType;\r
+import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;\r
+import org.openecomp.sdc.be.mixin.GroupTypeMixin;\r
+import org.openecomp.sdc.be.model.GroupTypeDefinition;\r
+import org.openecomp.sdc.be.view.ResponseView;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.springframework.stereotype.Controller;\r
+import com.jcabi.aspects.Loggable;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "group types resource"))\r
+@Controller\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+public class GroupTypesEndpoint {\r
+\r
+    private final GroupTypeBusinessLogic groupTypeBusinessLogic;\r
+\r
+    public GroupTypesEndpoint(GroupTypeBusinessLogic groupTypeBusinessLogic) {\r
+        this.groupTypeBusinessLogic = groupTypeBusinessLogic;\r
+    }\r
+\r
+    @GET\r
+    @Path("/groupTypes")\r
+    @Operation(description = "Get group types ", method = "GET", summary = "Returns group types",\r
+            responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = GroupTypeDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "group types found"), @ApiResponse(\r
+            responseCode = "400",\r
+            description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Error")})\r
+    @ResponseView(mixin = {GroupTypeMixin.class})\r
+    public List<GroupTypeDefinition> getGroupTypes(@HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(\r
+                    description = "An optional parameter to indicate the type of the container from where this call is executed") @QueryParam("internalComponentType") String internalComponentType) {\r
+        return groupTypeBusinessLogic.getAllGroupTypes(userId, internalComponentType);\r
+    }\r
+\r
+}\r
index 4f97eaf..df061ad 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import java.util.Arrays;
-import java.util.List;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.DataTypeBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.InputsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum;
-import org.openecomp.sdc.be.model.ComponentInstInputsMap;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.ComponentInstListInput;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Api(value = "Input Catalog", description = "Input Servlet")
-@Path("/v1/catalog")
-@Singleton
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-public class InputsServlet extends AbstractValidationsServlet {
-
-    private static final Logger log = Logger.getLogger(InputsServlet.class);
-
-    private final DataTypeBusinessLogic businessLogic;
-    private final InputsBusinessLogic inputsBusinessLogic;
-
-    @Inject
-    public InputsServlet(UserBusinessLogic userBusinessLogic,
-        InputsBusinessLogic inputsBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        DataTypeBusinessLogic dataTypeBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.inputsBusinessLogic = inputsBusinessLogic;
-        this.businessLogic = dataTypeBusinessLogic;
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/update/inputs")
-    @ApiOperation(value = "Update resource  inputs", httpMethod = "POST", notes = "Returns updated input", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Input updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateComponentInputs(
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @ApiParam(value = "json describe the input", required = true) String data, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-        String userId = request.getHeader(Constants.USER_ID_HEADER);
-
-        try {
-            User modifier = new User();
-            modifier.setUserId(userId);
-            log.debug("modifier id is {}", userId);
-
-            Either<InputDefinition[], ResponseFormat> inputsEither = getComponentsUtils()
-                    .convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition[].class,
-                            AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);
-            if(inputsEither.isRight()){
-                log.debug("Failed to convert data to input definition. Status is {}", inputsEither.right().value());
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-            }
-            List<InputDefinition> inputsToUpdate = Arrays.asList(inputsEither.left().value());
-
-            log.debug("Start handle request of updateComponentInputs. Received inputs are {}", inputsToUpdate);
-
-            ServletContext context = request.getSession().getServletContext();
-            ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType);
-
-            if (businessLogic == null) {
-                log.debug("Unsupported component type {}", containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR));
-            }
-
-            Either<List<InputDefinition>, ResponseFormat> actionResponse = inputsBusinessLogic.updateInputsValue(componentType, componentId, inputsToUpdate, userId, true, false);
-
-            if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
-            }
-
-            List<InputDefinition> componentInputs = actionResponse.left().value();
-            ObjectMapper mapper = new ObjectMapper();
-            String result = mapper.writeValueAsString(componentInputs);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        }
-        catch (Exception e) {
-            log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-
-    @GET
-    @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs")
-    @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response getComponentInstanceInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
-                                               @PathParam("originComponentUid") final String originComponentUid, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}", url);
-        Response response;
-
-        try {
-            Either<List<ComponentInstanceInput>, ResponseFormat> inputsResponse = inputsBusinessLogic.getComponentInstanceInputs(userId, componentId, instanceId);
-            if (inputsResponse.isRight()) {
-                log.debug("failed to get component instance inputs {}", componentType);
-                return buildErrorResponse(inputsResponse.right().value());
-            }
-            Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType);
-            log.debug("getInputs failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @GET
-    @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{inputId}/properties")
-    @ApiOperation(value = "Get properties", httpMethod = "GET", notes = "Returns properties list", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response getInputPropertiesForComponentInstance(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
-            @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(GET) Start handle request of {}", url);
-        Response response = null;
-
-        try {
-            Either<List<ComponentInstanceProperty>, ResponseFormat> inputPropertiesRes = inputsBusinessLogic.getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId);
-            if (inputPropertiesRes.isRight()) {
-                log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId);
-                return buildErrorResponse(inputPropertiesRes.right().value());
-            }
-            Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Properites by input id: " + inputId + " for instance with id: " + instanceId);
-            log.debug("getInputPropertiesForComponentInstance failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @GET
-    @Path("/{componentType}/{componentId}/inputs/{inputId}/inputs")
-    @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response getInputsForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}", url);
-        Response response;
-        try {
-            Either<List<ComponentInstanceInput>, ResponseFormat> inputsRes = inputsBusinessLogic.getInputsForComponentInput(userId, componentId, inputId);
-
-            if (inputsRes.isRight()) {
-                log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
-                return buildErrorResponse(inputsRes.right().value());
-            }
-            Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
-            log.debug("getInputsForComponentInput failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @GET
-    @Path("/{componentType}/{componentId}/inputs/{inputId}")
-    @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}", url);
-        Response response;
-
-        try {
-            Either<InputDefinition, ResponseFormat> inputsRes = inputsBusinessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false);
-
-            if (inputsRes.isRight()) {
-                log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
-                return buildErrorResponse(inputsRes.right().value());
-            }
-            Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
-            log.debug("getInputsForComponentInput failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    private Either<ComponentInstInputsMap, ResponseFormat> parseToComponentInstanceMap(String serviceJson, User user) {
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
-    }
-
-    private Either<ComponentInstListInput, ResponseFormat> parseToComponentInstListInput(String json, User user) {
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(json, user, ComponentInstListInput.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
-    }
-
-    @POST
-    @Path("/{componentType}/{componentId}/create/inputs")
-    @ApiOperation(value = "Create inputs on service", httpMethod = "POST", notes = "Return inputs list", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response createMultipleInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) {
-
-        return super.declareProperties(userId, componentId, componentType, componentInstInputsMapObj,
-                DeclarationTypeEnum.INPUT, request);
-    }
-
-
-    /**
-     * Creates a "list input" and updates given list of properties to get value from the input.
-     * also a data type which has same properties is created.
-     * the data type will be the entry_schema of the list input.
-     * @param componentType the container type (service, resource, ...)
-     * @param componentId the container ID
-     * @param request HttpServletRequest object
-     * @param userId the User ID
-     * @param componentInstInputsMapObj the list of properties to be declared and the "list input" to be created.
-     *                                  the type of the input must be "list".
-     *                                  schema.type of the input will be the name of new data type.
-     * @return the created input
-     */
-    @POST
-    @Path("/{componentType}/{componentId}/create/listInput")
-    @ApiOperation(value = "Create a list input on service", httpMethod = "POST", notes = "Return input", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response createListInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
-                                         @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) {
-
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("#createListInput: Start handle request of {}", url);
-        Response response = null;
-
-        try {
-            // get modifier id
-            User modifier = new User();
-            modifier.setUserId(userId);
-            log.debug("modifier id is {}", userId);
-
-            Either<ComponentInstListInput, ResponseFormat> componentInstInputsMapRes =
-                parseToComponentInstListInput(componentInstInputsMapObj, modifier);
-            if (componentInstInputsMapRes.isRight()) {
-                log.debug("failed to parse componentInstInputsMap");
-                response = buildErrorResponse(componentInstInputsMapRes.right().value());
-                return response;
-            }
-
-            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-            ComponentInstListInput componentInstInputsMap = componentInstInputsMapRes.left().value();
-            if (log.isDebugEnabled()) {
-                // for inspection on debug
-                log.debug("parsed componentInstInputsMap={}", ReflectionToStringBuilder.toString(componentInstInputsMap));
-            }
-
-            Either<List<InputDefinition>, ResponseFormat> inputPropertiesRes = inputsBusinessLogic.createListInput(
-                userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);
-            if (inputPropertiesRes.isRight()) {
-                log.debug("failed to create list input for service: {}", componentId);
-                return buildErrorResponse(inputPropertiesRes.right().value());
-            }
-            Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create list input for service with id: " + componentId);
-            log.debug("createListInput failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-
-    @DELETE
-    @Path("/{componentType}/{componentId}/delete/{inputId}/input")
-    @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") })
-    public Response deleteInput (
-            @PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("inputId") final String inputId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @ApiParam(value = "Service Input to be deleted", required = true) String componentInstInputsMapObj) {
-
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}", url);
-        Response response = null;
-
-        try {
-            Either<InputDefinition, ResponseFormat> deleteInput = inputsBusinessLogic.deleteInput(componentId, userId, inputId);
-            if (deleteInput.isRight()){
-                ResponseFormat deleteResponseFormat = deleteInput.right().value();
-                response = buildErrorResponse(deleteResponseFormat);
-                return response;
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value());
-        } catch (Exception e){
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId);
-            log.debug("Delete input failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    /**
-     * Gets a specific data type associated with a component.
-     * @param componentType the container type (service, resource, ...)
-     * @param componentId the container ID
-     * @param dataTypeName the data type name
-     * @param request HttpServletRequest object
-     * @return the data type info
-     */
-    @GET
-    @Path("/{componentType}/{componentId}/dataType/{dataTypeName}")
-    @ApiOperation(value = "Get data type in service", httpMethod = "GET", notes = "Get data type in service",
-            response = DataTypeDefinition.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Data type found"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Data type not found")})
-    public Response getDataType(
-            @PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("dataTypeName") final String dataTypeName,
-            @Context final HttpServletRequest request
-    ) {
-        ComponentsUtils componentsUtils = getComponentsUtils();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(getDataType) Start handle request of {}", url);
-        Response response;
-
-        try {
-            Either<DataTypeDefinition, StorageOperationStatus> getResult = businessLogic.getPrivateDataType(componentId, dataTypeName);
-            if (getResult.isRight()) {
-                ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResult.right().value());
-                return buildErrorResponse(componentsUtils.getResponseFormat(actionStatus));
-            }
-            Object json = RepresentationUtils.toRepresentation(getResult.left().value());
-            return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get data type from service + " + componentId + " + with name: " + dataTypeName);
-            log.debug("Get data type failed with exception", e);
-            response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-    /**
-     * Gets a list of data types which a component has.
-     * @param componentType the container type (service, resource, ...)
-     * @param componentId the container ID
-     * @param request HttpServletRequest object
-     * @return the list of data types in the component
-     */
-    @GET
-    @Path("/{componentType}/{componentId}/dataTypes")
-    @ApiOperation(value = "Get data types that service has", httpMethod = "GET", notes = "Get data types in service",
-            response = Resource.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Data type found"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Component not found")})
-    public Response getDataTypes(
-            @PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId,
-            @Context final HttpServletRequest request
-    ) {
-        ServletContext context = request.getSession().getServletContext();
-        ComponentsUtils componentsUtils = getComponentsUtils();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(getDataType) Start handle request of {}", url);
-        Response response;
-
-        try {
-            Either<List<DataTypeDefinition>, StorageOperationStatus> getResult = businessLogic.getPrivateDataTypes(componentId);
-            if (getResult.isRight()) {
-                ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResult.right().value());
-                return buildErrorResponse(componentsUtils.getResponseFormat(actionStatus));
-            }
-            Object json = RepresentationUtils.toRepresentation(getResult.left().value());
-            return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get data type from service + " + componentId);
-            log.debug("Get data type failed with exception", e);
-            response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-    /**
-     * Deletes a data type from a component.
-     * @param componentType the container type (service, resource, ...)
-     * @param componentId the container ID
-     * @param dataTypeName the data type name to be deleted
-     * @param request HttpServletRequest object
-     * @return operation result
-     */
-    @DELETE
-    @Path("/{componentType}/{componentId}/dataType/{dataTypeName}")
-    @ApiOperation(value = "Delete data type from service", httpMethod = "DELETE", notes = "Delete service input",
-            response = Resource.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 200, message = "Data type deleted"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Data type not found")})
-    public Response deleteDataType(
-            @PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("dataTypeName") final String dataTypeName,
-            @Context final HttpServletRequest request
-    ) {
-        ServletContext context = request.getSession().getServletContext();
-        ComponentsUtils componentsUtils = getComponentsUtils();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}", url);
-        Response response;
-
-        try {
-            Either<DataTypeDefinition, StorageOperationStatus> deleteResult = businessLogic.deletePrivateDataType(componentId, dataTypeName);
-            if (deleteResult.isRight()) {
-                ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteResult.right().value());
-                return buildErrorResponse(componentsUtils.getResponseFormat(actionStatus));
-            }
-            Object json = RepresentationUtils.toRepresentation(deleteResult.left().value());
-            return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete data type for service + " + componentId + " + with name: " + dataTypeName);
-            log.debug("Delete data type failed with exception", e);
-            response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.lang3.builder.ReflectionToStringBuilder;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.DataTypeBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.InputsBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.ComponentInstInputsMap;\r
+import org.openecomp.sdc.be.model.ComponentInstListInput;\r
+import org.openecomp.sdc.be.model.ComponentInstanceInput;\r
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;\r
+import org.openecomp.sdc.be.model.DataTypeDefinition;\r
+import org.openecomp.sdc.be.model.InputDefinition;\r
+import org.openecomp.sdc.be.model.Resource;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.fasterxml.jackson.databind.ObjectMapper;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@OpenAPIDefinition(info = @Info(title = "Input Catalog", description = "Input Servlet"))\r
+@Path("/v1/catalog")\r
+@Singleton\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+public class InputsServlet extends AbstractValidationsServlet {\r
+\r
+    private static final Logger log = Logger.getLogger(InputsServlet.class);\r
+\r
+    private final DataTypeBusinessLogic businessLogic;\r
+    private final InputsBusinessLogic inputsBusinessLogic;\r
+\r
+    @Inject\r
+    public InputsServlet(UserBusinessLogic userBusinessLogic,\r
+        InputsBusinessLogic inputsBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        DataTypeBusinessLogic dataTypeBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.inputsBusinessLogic = inputsBusinessLogic;\r
+        this.businessLogic = dataTypeBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/update/inputs")\r
+    @Operation(description = "Update resource  inputs", method = "POST", summary = "Returns updated input",\r
+            responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Input updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateComponentInputs(@Parameter(description = "valid values: resources / services",\r
+            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                    ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @Parameter(description = "json describe the input", required = true) String data,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+\r
+        try {\r
+            User modifier = new User();\r
+            modifier.setUserId(userId);\r
+            log.debug("modifier id is {}", userId);\r
+\r
+            Either<InputDefinition[], ResponseFormat> inputsEither = getComponentsUtils()\r
+                    .convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition[].class,\r
+                            AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);\r
+            if(inputsEither.isRight()){\r
+                log.debug("Failed to convert data to input definition. Status is {}", inputsEither.right().value());\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+            }\r
+            List<InputDefinition> inputsToUpdate = Arrays.asList(inputsEither.left().value());\r
+\r
+            log.debug("Start handle request of updateComponentInputs. Received inputs are {}", inputsToUpdate);\r
+\r
+            ServletContext context = request.getSession().getServletContext();\r
+            ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType);\r
+\r
+            if (businessLogic == null) {\r
+                log.debug("Unsupported component type {}", containerComponentType);\r
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR));\r
+            }\r
+\r
+            Either<List<InputDefinition>, ResponseFormat> actionResponse = inputsBusinessLogic.updateInputsValue(componentType, componentId, inputsToUpdate, userId, true, false);\r
+\r
+            if (actionResponse.isRight()) {\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+\r
+            List<InputDefinition> componentInputs = actionResponse.left().value();\r
+            ObjectMapper mapper = new ObjectMapper();\r
+            String result = mapper.writeValueAsString(componentInputs);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        }\r
+        catch (Exception e) {\r
+            log.error("create and associate RI failed with exception: {}", e.getMessage(), e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+\r
+    @GET\r
+    @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs")\r
+    @Operation(description = "Get Inputs only", method = "GET", summary = "Returns Inputs list",\r
+            responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response getComponentInstanceInputs(@PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,\r
+            @PathParam("originComponentUid") final String originComponentUid, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(get) Start handle request of {}", url);\r
+        Response response;\r
+\r
+        try {\r
+            Either<List<ComponentInstanceInput>, ResponseFormat> inputsResponse = inputsBusinessLogic.getComponentInstanceInputs(userId, componentId, instanceId);\r
+            if (inputsResponse.isRight()) {\r
+                log.debug("failed to get component instance inputs {}", componentType);\r
+                return buildErrorResponse(inputsResponse.right().value());\r
+            }\r
+            Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType);\r
+            log.debug("getInputs failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{inputId}/properties")\r
+    @Operation(description = "Get properties", method = "GET", summary = "Returns properties list",\r
+            responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = Resource.class)))) )\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response getInputPropertiesForComponentInstance(@PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,\r
+            @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(GET) Start handle request of {}", url);\r
+        Response response = null;\r
+\r
+        try {\r
+            Either<List<ComponentInstanceProperty>, ResponseFormat> inputPropertiesRes = inputsBusinessLogic\r
+                    .getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId);\r
+            if (inputPropertiesRes.isRight()) {\r
+                log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId);\r
+                return buildErrorResponse(inputPropertiesRes.right().value());\r
+            }\r
+            Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(\r
+                    "Get Properites by input id: " + inputId + " for instance with id: " + instanceId);\r
+            log.debug("getInputPropertiesForComponentInstance failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/{componentType}/{componentId}/inputs/{inputId}/inputs")\r
+    @Operation(description = "Get inputs", method = "GET", summary = "Returns inputs list", responses = @ApiResponse(content = @Content(\r
+            array = @ArraySchema(schema = @Schema(implementation = Resource.class)))) )\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response getInputsForComponentInput(@PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(get) Start handle request of {}", url);\r
+        Response response;\r
+        try {\r
+            Either<List<ComponentInstanceInput>, ResponseFormat> inputsRes =\r
+                    inputsBusinessLogic.getInputsForComponentInput(userId, componentId, inputId);\r
+\r
+            if (inputsRes.isRight()) {\r
+                log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);\r
+                return buildErrorResponse(inputsRes.right().value());\r
+            }\r
+            Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(\r
+                    "Get inputs by input id: " + inputId + " for component with id: " + componentId);\r
+            log.debug("getInputsForComponentInput failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/{componentType}/{componentId}/inputs/{inputId}")\r
+    @Operation(description = "Get inputs", method = "GET", summary = "Returns inputs list", responses = @ApiResponse(content = @Content(\r
+            array = @ArraySchema(schema = @Schema(implementation = Resource.class)))) )\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(get) Start handle request of {}", url);\r
+        Response response;\r
+\r
+        try {\r
+            Either<InputDefinition, ResponseFormat> inputsRes =\r
+                    inputsBusinessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false);\r
+\r
+            if (inputsRes.isRight()) {\r
+                log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);\r
+                return buildErrorResponse(inputsRes.right().value());\r
+            }\r
+            Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(\r
+                    "Get inputs by input id: " + inputId + " for component with id: " + componentId);\r
+            log.debug("getInputsForComponentInput failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    private Either<ComponentInstInputsMap, ResponseFormat> parseToComponentInstanceMap(String serviceJson, User user) {\r
+        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);\r
+    }\r
+\r
+    private Either<ComponentInstListInput, ResponseFormat> parseToComponentInstListInput(String json, User user) {\r
+        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(json, user, ComponentInstListInput.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);\r
+    }\r
+\r
+    @POST\r
+    @Path("/{componentType}/{componentId}/create/inputs")\r
+    @Operation(description = "Create inputs on service", method = "POST", summary = "Return inputs list",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response createMultipleInputs(@PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "ComponentIns Inputs Object to be created",\r
+                    required = true) String componentInstInputsMapObj) {\r
+\r
+        return super.declareProperties(userId, componentId, componentType, componentInstInputsMapObj,\r
+                DeclarationTypeEnum.INPUT, request);\r
+    }\r
+\r
+\r
+    /**\r
+     * Creates a "list input" and updates given list of properties to get value from the input.\r
+     * also a data type which has same properties is created.\r
+     * the data type will be the entry_schema of the list input.\r
+     * @param componentType the container type (service, resource, ...)\r
+     * @param componentId the container ID\r
+     * @param request HttpServletRequest object\r
+     * @param userId the User ID\r
+     * @param componentInstInputsMapObj the list of properties to be declared and the "list input" to be created.\r
+     *                                  the type of the input must be "list".\r
+     *                                  schema.type of the input will be the name of new data type.\r
+     * @return the created input\r
+     */\r
+    @POST\r
+    @Path("/{componentType}/{componentId}/create/listInput")\r
+    @Operation(description = "Create a list input on service", method = "POST", summary = "Return input",\r
+            responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = Resource.class)))) )\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response createListInput(@PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "ComponentIns Inputs Object to be created",\r
+                    required = true) String componentInstInputsMapObj) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("#createListInput: Start handle request of {}", url);\r
+        Response response = null;\r
+\r
+        try {\r
+            // get modifier id\r
+            User modifier = new User();\r
+            modifier.setUserId(userId);\r
+            log.debug("modifier id is {}", userId);\r
+\r
+            Either<ComponentInstListInput, ResponseFormat> componentInstInputsMapRes =\r
+                    parseToComponentInstListInput(componentInstInputsMapObj, modifier);\r
+            if (componentInstInputsMapRes.isRight()) {\r
+                log.debug("failed to parse componentInstInputsMap");\r
+                response = buildErrorResponse(componentInstInputsMapRes.right().value());\r
+                return response;\r
+            }\r
+\r
+            ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);\r
+            ComponentInstListInput componentInstInputsMap = componentInstInputsMapRes.left().value();\r
+            if (log.isDebugEnabled()) {\r
+                // for inspection on debug\r
+                log.debug("parsed componentInstInputsMap={}",\r
+                        ReflectionToStringBuilder.toString(componentInstInputsMap));\r
+            }\r
+\r
+            Either<List<InputDefinition>, ResponseFormat> inputPropertiesRes = inputsBusinessLogic\r
+                    .createListInput(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);\r
+            if (inputPropertiesRes.isRight()) {\r
+                log.debug("failed to create list input for service: {}", componentId);\r
+                return buildErrorResponse(inputPropertiesRes.right().value());\r
+            }\r
+            Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance()\r
+                    .logBeRestApiGeneralError("Create list input for service with id: " + componentId);\r
+            log.debug("createListInput failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+\r
+    @DELETE\r
+    @Path("/{componentType}/{componentId}/delete/{inputId}/input")\r
+    @Operation(description = "Delete input from service", method = "DELETE", summary = "Delete service input",\r
+            responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = Resource.class)))) )\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Input deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Input not found")})\r
+    public Response deleteInput(@PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "Service Input to be deleted", required = true) String componentInstInputsMapObj) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(get) Start handle request of {}", url);\r
+        Response response = null;\r
+\r
+        try {\r
+            Either<InputDefinition, ResponseFormat> deleteInput =\r
+                    inputsBusinessLogic.deleteInput(componentId, userId, inputId);\r
+            if (deleteInput.isRight()) {\r
+                ResponseFormat deleteResponseFormat = deleteInput.right().value();\r
+                response = buildErrorResponse(deleteResponseFormat);\r
+                return response;\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value());\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance()\r
+                    .logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId);\r
+            log.debug("Delete input failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Gets a specific data type associated with a component.\r
+     * @param componentType the container type (service, resource, ...)\r
+     * @param componentId the container ID\r
+     * @param dataTypeName the data type name\r
+     * @param request HttpServletRequest object\r
+     * @return the data type info\r
+     */\r
+    @GET\r
+    @Path("/{componentType}/{componentId}/dataType/{dataTypeName}")\r
+    @Operation(description = "Get data type in service", method = "GET", summary = "Get data type in service",\r
+            responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = DataTypeDefinition.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Data type found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Data type not found")})\r
+    public Response getDataType(\r
+            @PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @PathParam("dataTypeName") final String dataTypeName,\r
+            @Context final HttpServletRequest request\r
+    ) {\r
+        ComponentsUtils componentsUtils = getComponentsUtils();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(getDataType) Start handle request of {}", url);\r
+        Response response;\r
+\r
+        try {\r
+            Either<DataTypeDefinition, StorageOperationStatus> getResult = businessLogic.getPrivateDataType(componentId, dataTypeName);\r
+            if (getResult.isRight()) {\r
+                ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResult.right().value());\r
+                return buildErrorResponse(componentsUtils.getResponseFormat(actionStatus));\r
+            }\r
+            Object json = RepresentationUtils.toRepresentation(getResult.left().value());\r
+            return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get data type from service + " + componentId + " + with name: " + dataTypeName);\r
+            log.debug("Get data type failed with exception", e);\r
+            response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Gets a list of data types which a component has.\r
+     * @param componentType the container type (service, resource, ...)\r
+     * @param componentId the container ID\r
+     * @param request HttpServletRequest object\r
+     * @return the list of data types in the component\r
+     */\r
+    @GET\r
+    @Path("/{componentType}/{componentId}/dataTypes")\r
+    @Operation(description = "Get data types that service has", method = "GET", summary = "Get data types in service",\r
+            responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = Resource.class)))) )\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Data type found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response getDataTypes(\r
+            @PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @Context final HttpServletRequest request\r
+    ) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+        ComponentsUtils componentsUtils = getComponentsUtils();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(getDataType) Start handle request of {}", url);\r
+        Response response;\r
+\r
+        try {\r
+            Either<List<DataTypeDefinition>, StorageOperationStatus> getResult = businessLogic.getPrivateDataTypes(componentId);\r
+            if (getResult.isRight()) {\r
+                ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResult.right().value());\r
+                return buildErrorResponse(componentsUtils.getResponseFormat(actionStatus));\r
+            }\r
+            Object json = RepresentationUtils.toRepresentation(getResult.left().value());\r
+            return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get data type from service + " + componentId);\r
+            log.debug("Get data type failed with exception", e);\r
+            response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Deletes a data type from a component.\r
+     * @param componentType the container type (service, resource, ...)\r
+     * @param componentId the container ID\r
+     * @param dataTypeName the data type name to be deleted\r
+     * @param request HttpServletRequest object\r
+     * @return operation result\r
+     */\r
+    @DELETE\r
+    @Path("/{componentType}/{componentId}/dataType/{dataTypeName}")\r
+    @Operation(description = "Delete data type from service", method = "DELETE", summary = "Delete service input",\r
+            responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {\r
+            @ApiResponse(responseCode = "200", description = "Data type deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Data type not found")})\r
+    public Response deleteDataType(\r
+            @PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId,\r
+            @PathParam("dataTypeName") final String dataTypeName,\r
+            @Context final HttpServletRequest request\r
+    ) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+        ComponentsUtils componentsUtils = getComponentsUtils();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(get) Start handle request of {}", url);\r
+        Response response;\r
+\r
+        try {\r
+            Either<DataTypeDefinition, StorageOperationStatus> deleteResult = businessLogic.deletePrivateDataType(componentId, dataTypeName);\r
+            if (deleteResult.isRight()) {\r
+                ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteResult.right().value());\r
+                return buildErrorResponse(componentsUtils.getResponseFormat(actionStatus));\r
+            }\r
+            Object json = RepresentationUtils.toRepresentation(deleteResult.left().value());\r
+            return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete data type for service + " + componentId + " + with name: " + dataTypeName);\r
+            log.debug("Delete data type failed with exception", e);\r
+            response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+}\r
index 66b465d..f6531f7 100644 (file)
-/*
- * Copyright Â© 2016-2018 European Support Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.google.common.collect.ImmutableMap;
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-@Api(value = "Interface Operation Servlet", description = "Interface Operation Servlet")
-@Singleton
-public class InterfaceOperationServlet extends AbstractValidationsServlet {
-
-    private static final Logger log = LoggerFactory.getLogger(InterfaceOperationServlet.class);
-    private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic;
-
-    @Inject
-    public InterfaceOperationServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic;
-    }
-
-    @POST
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/resources/{resourceId}/interfaceOperations")
-    @ApiOperation(value = "Create Interface Operations on Resource", httpMethod = "POST",
-            notes = "Create Interface Operations on Resource", response = InterfaceDefinition.class, responseContainer = "List")
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Interface Operations on Resource"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Resource not found"),
-            @ApiResponse(code = 409, message = "Interface Operation already exist")})
-    public Response createInterfaceOperationsOnResource(
-            @ApiParam(value = "Interface Operations to create", required = true) String data,
-            @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-        return createOrUpdate(data, ComponentTypeEnum.RESOURCE, resourceId, request, userId, false);
-    }
-
-    private Response createOrUpdate(String data, ComponentTypeEnum componentType, String componentId,
-            HttpServletRequest request, String userId, boolean isUpdate) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("Start create or update request of {} with modifier id {}", url, userId);
-
-        try {
-            String componentIdLower = componentId.toLowerCase();
-
-            List<InterfaceDefinition> mappedInterfaceData = getMappedInterfaceData(data, modifier, componentType);
-            Either<List<InterfaceDefinition>, ResponseFormat> actionResponse;
-            if (isUpdate) {
-                actionResponse =
-                    interfaceOperationBusinessLogic
-                        .updateInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true);
-            } else {
-                actionResponse =
-                    interfaceOperationBusinessLogic
-                        .createInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true);
-            }
-
-            if (actionResponse.isRight()) {
-                log.error("failed to create or update interface operation");
-                return buildErrorResponse(actionResponse.right().value());
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    getFormattedResponse(actionResponse.left().value()));
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Interface Operation Creation or update");
-            log.error("create or update interface Operation with an error", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    private List<InterfaceDefinition> getMappedInterfaceData(String inputJson, User user,
-            ComponentTypeEnum componentTypeEnum) {
-        Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither =
-                getComponentsUtils().convertJsonToObjectUsingObjectMapper(inputJson, user,
-                        UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
-        return new ArrayList<>(uiComponentEither.left().value().getInterfaces().values());
-    }
-
-    private Object getFormattedResponse(List<InterfaceDefinition> interfaceDefinitions) throws IOException {
-        Map<String, List<InterfaceDefinition>> allInterfaces =
-                ImmutableMap.of(JsonPresentationFields.INTERFACES.getPresentation(), interfaceDefinitions);
-        return RepresentationUtils.toFilteredRepresentation(allInterfaces);
-    }
-
-    @PUT
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/resources/{resourceId}/interfaceOperations")
-    @ApiOperation(value = "Update Interface Operations on Resource", httpMethod = "PUT",
-            notes = "Update Interface Operations on Resource", response = InterfaceDefinition.class, responseContainer = "List")
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Update Interface Operations on Resource"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Resource not found")})
-    public Response updateInterfaceOperationsOnResource(
-            @ApiParam(value = "Interface Operations to update", required = true) String data,
-            @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-        return createOrUpdate(data, ComponentTypeEnum.RESOURCE, resourceId, request, userId, true);
-    }
-
-    @DELETE
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/resources/{resourceId}/interfaces/{interfaceId}/operations/{operationId}")
-    @ApiOperation(value = "Delete Interface Operation from Resource", httpMethod = "DELETE",
-            notes = "Delete Interface Operation from Resource", response = InterfaceDefinition.class, responseContainer = "List")
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete Interface Operation from Resource"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Resource not found")})
-    public Response deleteInterfaceOperationsFromResource(
-            @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
-            @ApiParam(value = "Interface Id") @PathParam("interfaceId") String interfaceId,
-            @ApiParam(value = "Operation Id") @PathParam("operationId") String operationId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-        return delete(interfaceId, operationId, resourceId, request, userId);
-    }
-
-    private Response delete(String interfaceId, String operationId, String componentId, HttpServletRequest request,
-            String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("Start delete request of {} with modifier id {}", url, userId);
-
-        try {
-            String componentIdLower = componentId.toLowerCase();
-            Either<List<InterfaceDefinition>, ResponseFormat> actionResponse =
-                interfaceOperationBusinessLogic.deleteInterfaceOperation(
-                    componentIdLower, interfaceId, Collections.singletonList(operationId), modifier, true);
-            if (actionResponse.isRight()) {
-                log.error("failed to delete interface operation");
-                return buildErrorResponse(actionResponse.right().value());
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    getFormattedResponse(actionResponse.left().value()));
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Interface Operation");
-            log.error("Delete interface operation with an error", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @GET
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/resources/{resourceId}/interfaces/{interfaceId}/operations/{operationId}")
-    @ApiOperation(value = "Get Interface Operation from Resource", httpMethod = "GET",
-            notes = "GET Interface Operation from Resource", response = InterfaceDefinition.class, responseContainer = "List")
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete Interface Operation from Resource"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Resource not found")})
-    public Response getInterfaceOperationsFromResource(
-            @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
-            @ApiParam(value = "Interface Id") @PathParam("interfaceId") String interfaceId,
-            @ApiParam(value = "Operation Id") @PathParam("operationId") String operationId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-        return get(interfaceId, operationId, resourceId, request, userId);
-    }
-
-    private Response get(String interfaceId, String operationId, String componentId, HttpServletRequest request,
-            String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("Start get request of {} with modifier id {}", url, userId);
-
-        try {
-            String componentIdLower = componentId.toLowerCase();
-            Either<List<InterfaceDefinition>, ResponseFormat> actionResponse =
-                interfaceOperationBusinessLogic.getInterfaceOperation(
-                    componentIdLower, interfaceId, Collections.singletonList(operationId), modifier, true);
-            if (actionResponse.isRight()) {
-                log.error("failed to get interface operation");
-                return buildErrorResponse(actionResponse.right().value());
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    getFormattedResponse(actionResponse.left().value()));
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component interface operations");
-            log.error("get component interface operations failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/services/{serviceId}/interfaceOperations")
-    @ApiOperation(value = "Create Interface Operations on Service", httpMethod = "POST",
-            notes = "Create Interface Operations on Service", response = InterfaceDefinition.class, responseContainer = "List")
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Interface Operations on Service"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Service not found"),
-            @ApiResponse(code = 409, message = "Interface Operation already exist")})
-    public Response createInterfaceOperationsOnService(
-            @ApiParam(value = "Interface Operations to create", required = true) String data,
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-        return createOrUpdate(data, ComponentTypeEnum.SERVICE, serviceId, request, userId, false);
-    }
-
-    @PUT
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/services/{serviceId}/interfaceOperations")
-    @ApiOperation(value = "Update Interface Operations on Service", httpMethod = "PUT",
-            notes = "Update Interface Operations on Service", response = InterfaceDefinition.class, responseContainer = "List")
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Update Interface Operations on Service"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Service not found")})
-    public Response updateInterfaceOperationsOnService(
-            @ApiParam(value = "Interface Operations to update", required = true) String data,
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-        return createOrUpdate(data, ComponentTypeEnum.SERVICE, serviceId, request, userId, true);
-    }
-
-    @DELETE
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/services/{serviceId}/interfaces/{interfaceId}/operations/{operationId}")
-    @ApiOperation(value = "Delete Interface Operation from Service", httpMethod = "DELETE",
-            notes = "Delete Interface Operation from Service", response = InterfaceDefinition.class, responseContainer = "List")
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete Interface Operation from Service"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Service not found")})
-    public Response deleteInterfaceOperationsFromService(
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @ApiParam(value = "Interface Id") @PathParam("interfaceId") String interfaceId,
-            @ApiParam(value = "Operation Id") @PathParam("operationId") String operationId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-        return delete(interfaceId, operationId, serviceId, request, userId);
-    }
-
-    @GET
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/services/{serviceId}/interfaces/{interfaceId}/operations/{operationId}")
-    @ApiOperation(value = "Get Interface Operation from Service", httpMethod = "GET",
-            notes = "GET Interface Operation from Service", response = InterfaceDefinition.class, responseContainer = "List")
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Get Interface Operation from Service"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 404, message = "Service not found")})
-    public Response getInterfaceOperationsFromService(
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @ApiParam(value = "Interface Id") @PathParam("interfaceId") String interfaceId,
-            @ApiParam(value = "Operation Id") @PathParam("operationId") String operationId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-        return get(interfaceId, operationId, serviceId, request, userId);
-    }
-
-}
-
+/*\r
+ * Copyright Â© 2016-2018 European Support Limited\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.List;\r
+import java.util.Map;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.InterfaceDefinition;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+import com.google.common.collect.ImmutableMap;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+@OpenAPIDefinition(info = @Info(title = "Interface Operation Servlet", description = "Interface Operation Servlet"))\r
+@Singleton\r
+public class InterfaceOperationServlet extends AbstractValidationsServlet {\r
+\r
+    private static final Logger log = LoggerFactory.getLogger(InterfaceOperationServlet.class);\r
+    private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic;\r
+\r
+    @Inject\r
+    public InterfaceOperationServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/resources/{resourceId}/interfaceOperations")\r
+    @Operation(description = "Create Interface Operations on Resource", method = "POST",\r
+            summary = "Create Interface Operations on Resource",responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Create Interface Operations on Resource"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Resource not found"),\r
+            @ApiResponse(responseCode = "409", description = "Interface Operation already exist")})\r
+    public Response createInterfaceOperationsOnResource(\r
+            @Parameter(description = "Interface Operations to create", required = true) String data,\r
+            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {\r
+        return createOrUpdate(data, ComponentTypeEnum.RESOURCE, resourceId, request, userId, false);\r
+    }\r
+\r
+    private Response createOrUpdate(String data, ComponentTypeEnum componentType, String componentId,\r
+            HttpServletRequest request, String userId, boolean isUpdate) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("Start create or update request of {} with modifier id {}", url, userId);\r
+\r
+        try {\r
+            String componentIdLower = componentId.toLowerCase();\r
+\r
+            List<InterfaceDefinition> mappedInterfaceData = getMappedInterfaceData(data, modifier, componentType);\r
+            Either<List<InterfaceDefinition>, ResponseFormat> actionResponse;\r
+            if (isUpdate) {\r
+                actionResponse =\r
+                    interfaceOperationBusinessLogic\r
+                        .updateInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true);\r
+            } else {\r
+                actionResponse =\r
+                    interfaceOperationBusinessLogic\r
+                        .createInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true);\r
+            }\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.error("failed to create or update interface operation");\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    getFormattedResponse(actionResponse.left().value()));\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Interface Operation Creation or update");\r
+            log.error("create or update interface Operation with an error", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    private List<InterfaceDefinition> getMappedInterfaceData(String inputJson, User user,\r
+            ComponentTypeEnum componentTypeEnum) {\r
+        Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither =\r
+                getComponentsUtils().convertJsonToObjectUsingObjectMapper(inputJson, user,\r
+                        UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);\r
+        return new ArrayList<>(uiComponentEither.left().value().getInterfaces().values());\r
+    }\r
+\r
+    private Object getFormattedResponse(List<InterfaceDefinition> interfaceDefinitions) throws IOException {\r
+        Map<String, List<InterfaceDefinition>> allInterfaces =\r
+                ImmutableMap.of(JsonPresentationFields.INTERFACES.getPresentation(), interfaceDefinitions);\r
+        return RepresentationUtils.toFilteredRepresentation(allInterfaces);\r
+    }\r
+\r
+    @PUT\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/resources/{resourceId}/interfaceOperations")\r
+    @Operation(description = "Update Interface Operations on Resource", method = "PUT",\r
+            summary = "Update Interface Operations on Resource",responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Update Interface Operations on Resource"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Resource not found")})\r
+    public Response updateInterfaceOperationsOnResource(\r
+            @Parameter(description = "Interface Operations to update", required = true) String data,\r
+            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {\r
+        return createOrUpdate(data, ComponentTypeEnum.RESOURCE, resourceId, request, userId, true);\r
+    }\r
+\r
+    @DELETE\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/resources/{resourceId}/interfaces/{interfaceId}/operations/{operationId}")\r
+    @Operation(description = "Delete Interface Operation from Resource", method = "DELETE",\r
+            summary = "Delete Interface Operation from Resource", responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Delete Interface Operation from Resource"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Resource not found")})\r
+    public Response deleteInterfaceOperationsFromResource(\r
+            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,\r
+            @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId,\r
+            @Parameter(description = "Operation Id") @PathParam("operationId") String operationId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {\r
+        return delete(interfaceId, operationId, resourceId, request, userId);\r
+    }\r
+\r
+    private Response delete(String interfaceId, String operationId, String componentId, HttpServletRequest request,\r
+            String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("Start delete request of {} with modifier id {}", url, userId);\r
+\r
+        try {\r
+            String componentIdLower = componentId.toLowerCase();\r
+            Either<List<InterfaceDefinition>, ResponseFormat> actionResponse =\r
+                interfaceOperationBusinessLogic.deleteInterfaceOperation(\r
+                    componentIdLower, interfaceId, Collections.singletonList(operationId), modifier, true);\r
+            if (actionResponse.isRight()) {\r
+                log.error("failed to delete interface operation");\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    getFormattedResponse(actionResponse.left().value()));\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Interface Operation");\r
+            log.error("Delete interface operation with an error", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/resources/{resourceId}/interfaces/{interfaceId}/operations/{operationId}")\r
+    @Operation(description = "Get Interface Operation from Resource", method = "GET",\r
+            summary = "GET Interface Operation from Resource",responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Delete Interface Operation from Resource"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Resource not found")})\r
+    public Response getInterfaceOperationsFromResource(\r
+            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,\r
+            @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId,\r
+            @Parameter(description = "Operation Id") @PathParam("operationId") String operationId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {\r
+        return get(interfaceId, operationId, resourceId, request, userId);\r
+    }\r
+\r
+    private Response get(String interfaceId, String operationId, String componentId, HttpServletRequest request,\r
+            String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("Start get request of {} with modifier id {}", url, userId);\r
+\r
+        try {\r
+            String componentIdLower = componentId.toLowerCase();\r
+            Either<List<InterfaceDefinition>, ResponseFormat> actionResponse =\r
+                interfaceOperationBusinessLogic.getInterfaceOperation(\r
+                    componentIdLower, interfaceId, Collections.singletonList(operationId), modifier, true);\r
+            if (actionResponse.isRight()) {\r
+                log.error("failed to get interface operation");\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    getFormattedResponse(actionResponse.left().value()));\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component interface operations");\r
+            log.error("get component interface operations failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/services/{serviceId}/interfaceOperations")\r
+    @Operation(description = "Create Interface Operations on Service", method = "POST",\r
+            summary = "Create Interface Operations on Service", responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Create Interface Operations on Service"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Service not found"),\r
+            @ApiResponse(responseCode = "409", description = "Interface Operation already exist")})\r
+    public Response createInterfaceOperationsOnService(\r
+            @Parameter(description = "Interface Operations to create", required = true) String data,\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {\r
+        return createOrUpdate(data, ComponentTypeEnum.SERVICE, serviceId, request, userId, false);\r
+    }\r
+\r
+    @PUT\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/services/{serviceId}/interfaceOperations")\r
+    @Operation(description = "Update Interface Operations on Service", method = "PUT",\r
+            summary = "Update Interface Operations on Service",responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Update Interface Operations on Service"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Service not found")})\r
+    public Response updateInterfaceOperationsOnService(\r
+            @Parameter(description = "Interface Operations to update", required = true) String data,\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {\r
+        return createOrUpdate(data, ComponentTypeEnum.SERVICE, serviceId, request, userId, true);\r
+    }\r
+\r
+    @DELETE\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/services/{serviceId}/interfaces/{interfaceId}/operations/{operationId}")\r
+    @Operation(description = "Delete Interface Operation from Service", method = "DELETE",\r
+            summary = "Delete Interface Operation from Service",responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Delete Interface Operation from Service"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Service not found")})\r
+    public Response deleteInterfaceOperationsFromService(\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId,\r
+            @Parameter(description = "Operation Id") @PathParam("operationId") String operationId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {\r
+        return delete(interfaceId, operationId, serviceId, request, userId);\r
+    }\r
+\r
+    @GET\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/services/{serviceId}/interfaces/{interfaceId}/operations/{operationId}")\r
+    @Operation(description = "Get Interface Operation from Service", method = "GET",\r
+            summary = "GET Interface Operation from Service",responses = @ApiResponse(content = @Content(\r
+                    array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Get Interface Operation from Service"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Service not found")})\r
+    public Response getInterfaceOperationsFromService(\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId,\r
+            @Parameter(description = "Operation Id") @PathParam("operationId") String operationId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {\r
+        return get(interfaceId, operationId, serviceId, request, userId);\r
+    }\r
+\r
+}\r
+\r
index 60e8f3c..753ae13 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
-import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase;
-import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.ui.model.UiComponentMetadata;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import org.springframework.beans.factory.annotation.Autowired;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Lifecycle Actions Servlet", description = "Lifecycle Actions Servlet")
-@Singleton
-public class LifecycleServlet extends BeGenericServlet {
-
-    private static final Logger log = Logger.getLogger(LifecycleServlet.class);
-    private final LifecycleBusinessLogic lifecycleBusinessLogic;
-
-    @Inject
-    public LifecycleServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        LifecycleBusinessLogic lifecycleBusinessLogic) {
-        super(userBusinessLogic, componentsUtils);
-        this.lifecycleBusinessLogic = lifecycleBusinessLogic;
-    }
-
-
-    @POST
-    @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource state changed"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 409, message = "Resource already exist") })
-    public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification", required = false) String jsonChangeInfo,
-            @ApiParam(value = "validValues: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
-                    + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam(value = "componentCollection") final String componentCollection,
-            @ApiParam(allowableValues = "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification,  cancelCertification, certify", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
-            @ApiParam(value = "id of component to be changed") @PathParam(value = "componentId") final String componentId, @Context final HttpServletRequest request,
-            @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        Response response = null;
-
-        // get modifier from graph
-        log.debug("get modifier properties");
-        Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
-        if (eitherGetUser.isRight()) {
-            return buildErrorResponse(eitherGetUser.right().value());
-        }
-        User user = eitherGetUser.left().value();
-
-        String resourceIdLower = componentId.toLowerCase();
-        log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower);
-        Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user);
-        if (validateEnum.isRight()) {
-            return validateEnum.right().value();
-        }
-
-        LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
-
-        try {
-            if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
-                ObjectMapper mapper = new ObjectMapper();
-                changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
-            }
-        }
-
-        catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
-            log.debug("failed to convert from json {}", jsonChangeInfo, e);
-            ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
-            return buildErrorResponse(responseFormat);
-        }
-
-        try {
-            LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
-            ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
-            if (componentType != null) {
-                Either<? extends Component, ResponseFormat> actionResponse = lifecycleBusinessLogic
-                    .changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
-
-                if (actionResponse.isRight()) {
-                    log.info("failed to change resource state");
-                    response = buildErrorResponse(actionResponse.right().value());
-                    return response;
-                }
-
-                log.debug("change state successful !!!");
-                UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value());
-                Object value = RepresentationUtils.toRepresentation(componentMetatdata);
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value);
-                return response;
-            } else {
-                log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"", componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
-                        ComponentTypeEnum.PRODUCT_PARAM_NAME);
-                ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
-                return buildErrorResponse(error);
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");
-            log.debug("change lifecycle state failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) {
-        LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT;
-        try {
-            transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
-        } catch (IllegalArgumentException e) {
-            log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e);
-            ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
-            return Either.right(buildErrorResponse(error));
-        }
-        return Either.left(transitionEnum);
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;\r
+import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase;\r
+import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.model.Component;\r
+import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.ui.model.UiComponentMetadata;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.fasterxml.jackson.databind.ObjectMapper;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Lifecycle Actions Servlet", description = "Lifecycle Actions Servlet"))\r
+@Singleton\r
+public class LifecycleServlet extends BeGenericServlet {\r
+\r
+    private static final Logger log = Logger.getLogger(LifecycleServlet.class);\r
+    private final LifecycleBusinessLogic lifecycleBusinessLogic;\r
+\r
+    @Inject\r
+    public LifecycleServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils,\r
+        LifecycleBusinessLogic lifecycleBusinessLogic) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.lifecycleBusinessLogic = lifecycleBusinessLogic;\r
+    }\r
+\r
+\r
+    @POST\r
+    @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Change Resource lifecycle State", method = "POST", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource state changed"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "409", description = "Resource already exist")})\r
+    public Response changeResourceState(\r
+            @Parameter(\r
+                    description = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification",\r
+                    required = false) String jsonChangeInfo,\r
+            @Parameter(description = "validValues: resources / services / products",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam(\r
+                                    value = "componentCollection") final String componentCollection,\r
+            @Parameter(schema = @Schema(allowableValues = {\r
+                    "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification,  cancelCertification, certify"}),\r
+                    required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,\r
+            @Parameter(description = "id of component to be changed") @PathParam(\r
+                    value = "componentId") final String componentId,\r
+            @Context final HttpServletRequest request,\r
+            @Parameter(description = "id of user initiating the operation") @HeaderParam(\r
+                    value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        Response response = null;\r
+\r
+        // get modifier from graph\r
+        log.debug("get modifier properties");\r
+        Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);\r
+        if (eitherGetUser.isRight()) {\r
+            return buildErrorResponse(eitherGetUser.right().value());\r
+        }\r
+        User user = eitherGetUser.left().value();\r
+\r
+        String resourceIdLower = componentId.toLowerCase();\r
+        log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower);\r
+        Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user);\r
+        if (validateEnum.isRight()) {\r
+            return validateEnum.right().value();\r
+        }\r
+\r
+        LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();\r
+\r
+        try {\r
+            if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {\r
+                ObjectMapper mapper = new ObjectMapper();\r
+                changeInfo = new LifecycleChangeInfoWithAction(\r
+                        mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());\r
+            }\r
+        }\r
+\r
+        catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");\r
+            log.debug("failed to convert from json {}", jsonChangeInfo, e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId,\r
+                    AuditingActionEnum.CHECKOUT_RESOURCE);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+        try {\r
+            LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();\r
+            ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);\r
+            if (componentType != null) {\r
+                Either<? extends Component, ResponseFormat> actionResponse =\r
+                        lifecycleBusinessLogic.changeComponentState(componentType, componentId, user, transitionEnum,\r
+                                changeInfo, false, true);\r
+\r
+                if (actionResponse.isRight()) {\r
+                    log.info("failed to change resource state");\r
+                    response = buildErrorResponse(actionResponse.right().value());\r
+                    return response;\r
+                }\r
+\r
+                log.debug("change state successful !!!");\r
+                UiComponentMetadata componentMetatdata =\r
+                        UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value());\r
+                Object value = RepresentationUtils.toRepresentation(componentMetatdata);\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value);\r
+                return response;\r
+            } else {\r
+                log.info(\r
+                        "componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"",\r
+                        componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                        ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME);\r
+                ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId,\r
+                        AuditingActionEnum.CHECKOUT_RESOURCE);\r
+                return buildErrorResponse(error);\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");\r
+            log.debug("change lifecycle state failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) {\r
+        LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT;\r
+        try {\r
+            transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);\r
+        } catch (IllegalArgumentException e) {\r
+            log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e);\r
+            ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE);\r
+            return Either.right(buildErrorResponse(error));\r
+        }\r
+        return Either.left(transitionEnum);\r
+    }\r
+\r
+}\r
index 38f3878..1ab061f 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import org.apache.commons.lang3.StringUtils;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.PolicyDefinition;
-import org.openecomp.sdc.be.model.PolicyTargetDTO;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.springframework.stereotype.Controller;
-
-/**
- * Provides REST API to create, retrieve, update, delete a policy
- */
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Policy Servlet")
-@Controller
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-public class PolicyServlet extends AbstractValidationsServlet {
-
-    private static final Logger log = Logger.getLogger(PolicyServlet.class);
-    private final PolicyBusinessLogic policyBusinessLogic;
-
-    @Inject
-    public PolicyServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        PolicyBusinessLogic policyBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.policyBusinessLogic = policyBusinessLogic;
-    }
-
-    @POST
-    @Path("/{containerComponentType}/{componentId}/policies/{policyTypeName}")
-    @ApiOperation(value = "Create Policy", httpMethod = "POST", notes = "Returns created Policy", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Policy already exist"),  @ApiResponse(code = 404, message = "Component not found")})
-    public Response createPolicy(@PathParam("componentId") final String containerComponentId,
-                                 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-                                 @PathParam("policyTypeName") final String policyTypeName,
-                                 @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
-                                 @Context final HttpServletRequest request) {
-        init();
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        try {
-            Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
-            if (responseWrapper.isEmpty()) {
-                responseWrapper.setInnerElement(policyBusinessLogic.createPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyTypeName, userId, true)
-                        .either(l -> buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), l),
-                                this::buildErrorResponse));
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy");
-            log.error("Failed to create policy. The exception {} occurred. ", e);
-            responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    @PUT
-    @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
-    @ApiOperation(value = "Update Policy metadata", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 404, message = "component / policy Not found")})
-    public Response updatePolicy(@PathParam("componentId") final String containerComponentId,
-                                 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-                                 @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
-                                 @ApiParam(value = "PolicyDefinition", required = true) String policyData, @Context final HttpServletRequest request) {
-        init();
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        try {
-            Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
-            Wrapper<PolicyDefinition> policyWrapper = new Wrapper<>();
-            if (responseWrapper.isEmpty()) {
-                convertJsonToObjectOfClass(policyData, policyWrapper, PolicyDefinition.class, responseWrapper);
-                if (policyWrapper.isEmpty()) {
-                    responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));
-                }
-            }
-            if (!policyWrapper.isEmpty()) {
-                policyWrapper.getInnerElement().setUniqueId(policyId);
-                responseWrapper.setInnerElement(policyBusinessLogic.updatePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyWrapper.getInnerElement(), userId, true)
-                        .either(this::buildOkResponse,
-                                this::buildErrorResponse));
-            }
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy");
-            log.error("Failed to update policy. The exception {} occurred. ", e);
-            responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    @GET
-    @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
-    @ApiOperation(value = "Get Policy", httpMethod = "GET", notes = "Returns Policy", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy was found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 404, message = "component / policy Not found")})
-    public Response getPolicy(@PathParam("componentId") final String containerComponentId,
-                              @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-                              @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
-                              @Context final HttpServletRequest request) {
-        init();
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        try {
-            Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
-            if (responseWrapper.isEmpty()) {
-                responseWrapper.setInnerElement(policyBusinessLogic.getPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId)
-                        .either(this::buildOkResponse,
-                                this::buildErrorResponse));
-            }
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Policy");
-            log.error("Failed to retrieve policy. The exception {} occurred. ", e);
-            responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    @DELETE
-    @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
-    @ApiOperation(value = "Delete Policy", httpMethod = "DELETE", notes = "No body", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy was deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 404, message = "component / policy Not found")})
-    public Response deletePolicy(@PathParam("componentId") final String containerComponentId,
-                                 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-                                 @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
-                                 @Context final HttpServletRequest request) {
-        init();
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        try {
-            Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
-            if (responseWrapper.isEmpty()) {
-                responseWrapper.setInnerElement(policyBusinessLogic.deletePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId, true)
-                        .either(this::buildOkResponse,
-                                this::buildErrorResponse));
-            }
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Policy");
-            log.error("Failed to delete policy. The exception {} occurred. ", e);
-            responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    @PUT
-    @Path("/{containerComponentType}/{componentId}/policies/{policyId}/undeclare")
-    @ApiOperation(value = "undeclare Policy", httpMethod = "PUT", notes = "No body", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy was undeclared"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 404, message = "component / policy Not found")})
-    public Response undeclarePolicy(@PathParam("componentId") final String containerComponentId,
-            @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
-            @Context final HttpServletRequest request) {
-        init();
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        try {
-            Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
-            if (responseWrapper.isEmpty()) {
-                responseWrapper.setInnerElement(policyBusinessLogic.undeclarePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId, true)
-                                                        .either(this::buildOkResponse,
-                                                                this::buildErrorResponse));
-            }
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Undeclare Policy");
-            log.error("Failed to undeclare policy. The exception {} occurred. ", e);
-            responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    @GET
-    @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")
-    @ApiOperation(value = "Get component policy properties", httpMethod = "GET", notes = "Returns component policy properties", response = PropertyDataDefinition.class, responseContainer="List")
-    @ApiResponses(value = {@ApiResponse(code = 200, message = "Properties found"),@ApiResponse(code = 400, message = "invalid content - Error: containerComponentType is invalid"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Componentorpolicy  not found"),
-    @ApiResponse(code = 500, message = "The GET request failed due to internal SDC problem.") })public Response getPolicyProperties(@ApiParam(value = "the id of the component which is the container of the policy") @PathParam("componentId") final String containerComponentId,
-                                        @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-                                        @ApiParam(value = "the id of the policy which its properties are to return") @PathParam("policyId") final String policyId,
-                                        @ApiParam(value = "the userid", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-                                        @Context final HttpServletRequest request) {
-        init();
-        try {
-            return convertToComponentType(containerComponentType)
-                    .left()
-                    .bind(cmptType -> policyBusinessLogic.getPolicyProperties(cmptType, containerComponentId, policyId, userId))
-                    .either(this::buildOkResponse,
-                            this::buildErrorResponse);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("get Policy properties");
-            log.debug("#getPolicyProperties - get Policy properties has failed.", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-
-    }
-
-    @PUT
-    @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")
-    @ApiOperation(value = "Update Policy properties", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy properties updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 404, message = "component / policy Not found")})
-    public Response updatePolicyProperties(@PathParam("componentId") final String containerComponentId,
-                                           @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-                                           @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
-                                           @ApiParam(value = "PolicyDefinition", required = true) String policyData, @Context final HttpServletRequest request) {
-        init();
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        try {
-            Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
-            Wrapper<PropertyDataDefinition[]> propertiesWrapper = new Wrapper<>();
-            if (responseWrapper.isEmpty()) {
-                convertJsonToObjectOfClass(policyData, propertiesWrapper, PropertyDataDefinition[].class, responseWrapper);
-                if (propertiesWrapper.isEmpty()) {
-                    responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));
-                }
-            }
-            if (!propertiesWrapper.isEmpty()) {
-                responseWrapper.setInnerElement(
-                        policyBusinessLogic.updatePolicyProperties(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, propertiesWrapper.getInnerElement(), userId, true)
-                                .either(this::buildOkResponse, this::buildErrorResponse));
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy");
-            log.error("Failed to update policy. The exception {} occurred. ", e);
-            responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    private Wrapper<ComponentTypeEnum> validateComponentTypeAndUserId(final String containerComponentType, String userId, Wrapper<Response> responseWrapper) {
-        Wrapper<ComponentTypeEnum> componentTypeWrapper = new Wrapper<>();
-        if (StringUtils.isEmpty(userId)) {
-            log.error("Missing userId HTTP header. ");
-            responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID)));
-        }
-        if (responseWrapper.isEmpty()) {
-            validateComponentType(responseWrapper, componentTypeWrapper, containerComponentType);
-        }
-        return componentTypeWrapper;
-    }
-
-       @POST
-       @Path("/{containerComponentType}/{componentId}/policies/{policyId}/targets")
-       @Consumes(MediaType.APPLICATION_JSON)
-       @Produces(MediaType.APPLICATION_JSON)
-       @ApiOperation(value = "update policy targets", httpMethod = "POST", notes = "Returns updated Policy", response = Response.class)
-       @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy target updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-       public Response updatePolicyTargets(@PathParam("componentId") final String containerComponentId,
-                                                                               @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
-                                                                               @PathParam("policyId") final String policyId,
-                                                                               @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
-                                                                               @Context final HttpServletRequest request,
-                                                                               List<PolicyTargetDTO> requestJson) {
-               try {
-
-                   return updatePolicyTargetsFromDTO(requestJson)
-                    .left()
-                    .bind(policyTarget -> updatePolicyTargetsFromMap(policyTarget, containerComponentType, containerComponentId, policyId, userId))
-                    .either(this::buildOkResponse, this::buildErrorResponse);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy");
-            log.debug("Policy target update has been failed with the exception{}. ", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @POST
-    @Path("/{componentType}/{componentId}/create/policies")
-    @ApiOperation(value = "Create policies on service", httpMethod = "POST", notes = "Return policies list", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
-    public Response declareProperties(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns policies Object to be created", required = true) String componentInstPoliciesMapObj) {
-
-        return super.declareProperties(userId, componentId, componentType, componentInstPoliciesMapObj,
-                DeclarationTypeEnum.POLICY, request);
-    }
-
-    private Either<PolicyDefinition, ResponseFormat> updatePolicyTargetsFromMap(Map<PolicyTargetType, List<String>> policyTarget, String containerComponentType, String containerComponentId, String policyId, String userId) {
-        return convertToComponentType(containerComponentType)
-                .left()
-                .bind(cmptType -> policyBusinessLogic.updatePolicyTargets(cmptType, containerComponentId, policyId, policyTarget, userId));
-    }
-
-    private Either<Map<PolicyTargetType, List<String>>, ResponseFormat> updatePolicyTargetsFromDTO(List<PolicyTargetDTO> targetDTOList) {
-        Map<PolicyTargetType, List<String>> policyTarget = new HashMap<>();
-        for (PolicyTargetDTO currentTarget : targetDTOList) {
-            if(!addTargetsByType(policyTarget, currentTarget.getType(), currentTarget.getUniqueIds())){
-                return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_TARGET_TYPE_DOES_NOT_EXIST, currentTarget.getType()));
-            }
-        }
-        return Either.left(policyTarget);
-    }
-
-
-    public boolean addTargetsByType(Map<PolicyTargetType, List<String>> policyTarget, String type, List<String> uniqueIds) {
-        PolicyTargetType targetTypeEnum = PolicyTargetType.getByNameIgnoreCase(type);
-        if(targetTypeEnum != null){
-            policyTarget.put(targetTypeEnum, validateUniquenessOfIds(uniqueIds));
-            return true;
-        }
-        else{
-            return false;
-        }
-    }
-
-    private List<String> validateUniquenessOfIds(List<String> uniqueIds) {
-        return uniqueIds.stream().distinct().collect(Collectors.toList());
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.stream.Collectors;\r
+import javax.inject.Inject;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.lang3.StringUtils;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;\r
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.PolicyDefinition;\r
+import org.openecomp.sdc.be.model.PolicyTargetDTO;\r
+import org.openecomp.sdc.be.model.Resource;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import org.springframework.stereotype.Controller;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+/**\r
+ * Provides REST API to create, retrieve, update, delete a policy\r
+ */\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Policy Servlet"))\r
+@Controller\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+public class PolicyServlet extends AbstractValidationsServlet {\r
+\r
+    private static final Logger log = Logger.getLogger(PolicyServlet.class);\r
+    private final PolicyBusinessLogic policyBusinessLogic;\r
+\r
+    @Inject\r
+    public PolicyServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        PolicyBusinessLogic policyBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.policyBusinessLogic = policyBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/policies/{policyTypeName}")\r
+    @Operation(description = "Create Policy", method = "POST", summary = "Returns created Policy",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Policy created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Policy already exist"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response createPolicy(@PathParam("componentId") final String containerComponentId, @Parameter(description = "valid values: resources / services",\r
+            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                    ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("policyTypeName") final String policyTypeName,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",\r
+                    required = true) String userId,\r
+            @Context final HttpServletRequest request) {\r
+        init();\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        try {\r
+            Wrapper<ComponentTypeEnum> componentTypeWrapper =\r
+                    validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);\r
+            if (responseWrapper.isEmpty()) {\r
+                responseWrapper.setInnerElement(policyBusinessLogic\r
+                        .createPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyTypeName,\r
+                                userId, true)\r
+                        .either(l -> buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), l),\r
+                                this::buildErrorResponse));\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy");\r
+            log.error("Failed to create policy. The exception {} occurred. ", e);\r
+            responseWrapper.setInnerElement(\r
+                    buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    @PUT\r
+    @Path("/{containerComponentType}/{componentId}/policies/{policyId}")\r
+    @Operation(description = "Update Policy metadata", method = "PUT", summary = "Returns updated Policy",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Policy updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "component / policy Not found")})\r
+    public Response updatePolicy(@PathParam("componentId") final String containerComponentId, @Parameter(\r
+            description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("policyId") final String policyId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",\r
+                    required = true) String userId,\r
+            @Parameter(description = "PolicyDefinition", required = true) String policyData,\r
+            @Context final HttpServletRequest request) {\r
+        init();\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        try {\r
+            Wrapper<ComponentTypeEnum> componentTypeWrapper =\r
+                    validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);\r
+            Wrapper<PolicyDefinition> policyWrapper = new Wrapper<>();\r
+            if (responseWrapper.isEmpty()) {\r
+                convertJsonToObjectOfClass(policyData, policyWrapper, PolicyDefinition.class, responseWrapper);\r
+                if (policyWrapper.isEmpty()) {\r
+                    responseWrapper.setInnerElement(\r
+                            buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));\r
+                }\r
+            }\r
+            if (!policyWrapper.isEmpty()) {\r
+                policyWrapper.getInnerElement().setUniqueId(policyId);\r
+                responseWrapper.setInnerElement(policyBusinessLogic\r
+                        .updatePolicy(componentTypeWrapper.getInnerElement(), containerComponentId,\r
+                                policyWrapper.getInnerElement(), userId, true)\r
+                        .either(this::buildOkResponse, this::buildErrorResponse));\r
+            }\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy");\r
+            log.error("Failed to update policy. The exception {} occurred. ", e);\r
+            responseWrapper.setInnerElement(\r
+                    buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    @GET\r
+    @Path("/{containerComponentType}/{componentId}/policies/{policyId}")\r
+    @Operation(description = "Get Policy", method = "GET", summary = "Returns Policy", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Policy was found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "component / policy Not found")})\r
+    public Response getPolicy(@PathParam("componentId") final String containerComponentId, @Parameter(\r
+            description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("policyId") final String policyId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",\r
+                    required = true) String userId,\r
+            @Context final HttpServletRequest request) {\r
+        init();\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        try {\r
+            Wrapper<ComponentTypeEnum> componentTypeWrapper =\r
+                    validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);\r
+            if (responseWrapper.isEmpty()) {\r
+                responseWrapper.setInnerElement(policyBusinessLogic\r
+                        .getPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId)\r
+                        .either(this::buildOkResponse, this::buildErrorResponse));\r
+            }\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Policy");\r
+            log.error("Failed to retrieve policy. The exception {} occurred. ", e);\r
+            responseWrapper.setInnerElement(\r
+                    buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/{containerComponentType}/{componentId}/policies/{policyId}")\r
+    @Operation(description = "Delete Policy", method = "DELETE", summary = "No body", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Policy was deleted"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "component / policy Not found")})\r
+    public Response deletePolicy(@PathParam("componentId") final String containerComponentId, @Parameter(\r
+            description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("policyId") final String policyId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",\r
+                    required = true) String userId,\r
+            @Context final HttpServletRequest request) {\r
+        init();\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        try {\r
+            Wrapper<ComponentTypeEnum> componentTypeWrapper =\r
+                    validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);\r
+            if (responseWrapper.isEmpty()) {\r
+                responseWrapper\r
+                        .setInnerElement(\r
+                                policyBusinessLogic\r
+                                        .deletePolicy(componentTypeWrapper.getInnerElement(), containerComponentId,\r
+                                                policyId, userId, true)\r
+                                        .either(this::buildOkResponse, this::buildErrorResponse));\r
+            }\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Policy");\r
+            log.error("Failed to delete policy. The exception {} occurred. ", e);\r
+            responseWrapper.setInnerElement(\r
+                    buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    @PUT\r
+    @Path("/{containerComponentType}/{componentId}/policies/{policyId}/undeclare")\r
+    @Operation(description = "undeclare Policy", method = "PUT", summary = "No body",responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Policy was undeclared"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "component / policy Not found")})\r
+    public Response undeclarePolicy(@PathParam("componentId") final String containerComponentId, @Parameter(\r
+            description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("policyId") final String policyId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",\r
+                    required = true) String userId,\r
+            @Context final HttpServletRequest request) {\r
+        init();\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        try {\r
+            Wrapper<ComponentTypeEnum> componentTypeWrapper =\r
+                    validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);\r
+            if (responseWrapper.isEmpty()) {\r
+                responseWrapper\r
+                        .setInnerElement(\r
+                                policyBusinessLogic\r
+                                        .undeclarePolicy(componentTypeWrapper.getInnerElement(), containerComponentId,\r
+                                                policyId, userId, true)\r
+                                        .either(this::buildOkResponse, this::buildErrorResponse));\r
+            }\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Undeclare Policy");\r
+            log.error("Failed to undeclare policy. The exception {} occurred. ", e);\r
+            responseWrapper.setInnerElement(\r
+                    buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    @GET\r
+    @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")\r
+    @Operation(description = "Get component policy properties", method = "GET",\r
+            summary = "Returns component policy properties",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = PropertyDataDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Properties found"),\r
+            @ApiResponse(responseCode = "400",\r
+                    description = "invalid content - Error: containerComponentType is invalid"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Componentorpolicy  not found"),\r
+            @ApiResponse(responseCode = "500", description = "The GET request failed due to internal SDC problem.")})\r
+    public Response getPolicyProperties(@Parameter(\r
+            description = "the id of the component which is the container of the policy") @PathParam("componentId") final String containerComponentId,\r
+            @Parameter(description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @Parameter(\r
+                    description = "the id of the policy which its properties are to return") @PathParam("policyId") final String policyId,\r
+            @Parameter(description = "the userid",\r
+                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Context final HttpServletRequest request) {\r
+        init();\r
+        try {\r
+            return convertToComponentType(containerComponentType).left().bind(cmptType -> policyBusinessLogic\r
+                    .getPolicyProperties(cmptType, containerComponentId, policyId, userId))\r
+                    .either(this::buildOkResponse, this::buildErrorResponse);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("get Policy properties");\r
+            log.debug("#getPolicyProperties - get Policy properties has failed.", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+\r
+    }\r
+\r
+    @PUT\r
+    @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")\r
+    @Operation(description = "Update Policy properties", method = "PUT", summary = "Returns updated Policy",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Policy properties updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "component / policy Not found")})\r
+    public Response updatePolicyProperties(@PathParam("componentId") final String containerComponentId, @Parameter(\r
+            description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("policyId") final String policyId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",\r
+                    required = true) String userId,\r
+            @Parameter(description = "PolicyDefinition", required = true) String policyData,\r
+            @Context final HttpServletRequest request) {\r
+        init();\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        try {\r
+            Wrapper<ComponentTypeEnum> componentTypeWrapper =\r
+                    validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);\r
+            Wrapper<PropertyDataDefinition[]> propertiesWrapper = new Wrapper<>();\r
+            if (responseWrapper.isEmpty()) {\r
+                convertJsonToObjectOfClass(policyData, propertiesWrapper, PropertyDataDefinition[].class,\r
+                        responseWrapper);\r
+                if (propertiesWrapper.isEmpty()) {\r
+                    responseWrapper.setInnerElement(\r
+                            buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));\r
+                }\r
+            }\r
+            if (!propertiesWrapper.isEmpty()) {\r
+                responseWrapper.setInnerElement(policyBusinessLogic\r
+                        .updatePolicyProperties(componentTypeWrapper.getInnerElement(), containerComponentId, policyId,\r
+                                propertiesWrapper.getInnerElement(), userId, true)\r
+                        .either(this::buildOkResponse, this::buildErrorResponse));\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy");\r
+            log.error("Failed to update policy. The exception {} occurred. ", e);\r
+            responseWrapper.setInnerElement(\r
+                    buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    private Wrapper<ComponentTypeEnum> validateComponentTypeAndUserId(final String containerComponentType, String userId, Wrapper<Response> responseWrapper) {\r
+        Wrapper<ComponentTypeEnum> componentTypeWrapper = new Wrapper<>();\r
+        if (StringUtils.isEmpty(userId)) {\r
+            log.error("Missing userId HTTP header. ");\r
+            responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID)));\r
+        }\r
+        if (responseWrapper.isEmpty()) {\r
+            validateComponentType(responseWrapper, componentTypeWrapper, containerComponentType);\r
+        }\r
+        return componentTypeWrapper;\r
+    }\r
+\r
+    @POST\r
+    @Path("/{containerComponentType}/{componentId}/policies/{policyId}/targets")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "update policy targets", method = "POST", summary = "Returns updated Policy",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Policy target updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updatePolicyTargets(@PathParam("componentId") final String containerComponentId, @Parameter(\r
+            description = "valid values: resources / services",\r
+                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,\r
+                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,\r
+            @PathParam("policyId") final String policyId,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",\r
+                    required = true) String userId,\r
+            @Context final HttpServletRequest request, List<PolicyTargetDTO> requestJson) {\r
+        try {\r
+\r
+            return updatePolicyTargetsFromDTO(requestJson).left()\r
+                    .bind(policyTarget -> updatePolicyTargetsFromMap(policyTarget, containerComponentType,\r
+                            containerComponentId, policyId, userId))\r
+                    .either(this::buildOkResponse, this::buildErrorResponse);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy");\r
+            log.debug("Policy target update has been failed with the exception{}. ", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/{componentType}/{componentId}/create/policies")\r
+    @Operation(description = "Create policies on service", method = "POST", summary = "Return policies list",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Component found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Component not found")})\r
+    public Response declareProperties(@PathParam("componentType") final String componentType,\r
+            @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @Parameter(description = "ComponentIns policies Object to be created",\r
+                    required = true) String componentInstPoliciesMapObj) {\r
+\r
+        return super.declareProperties(userId, componentId, componentType, componentInstPoliciesMapObj,\r
+                DeclarationTypeEnum.POLICY, request);\r
+    }\r
+\r
+    private Either<PolicyDefinition, ResponseFormat> updatePolicyTargetsFromMap(\r
+            Map<PolicyTargetType, List<String>> policyTarget, String containerComponentType,\r
+            String containerComponentId, String policyId, String userId) {\r
+        return convertToComponentType(containerComponentType).left().bind(cmptType -> policyBusinessLogic\r
+                .updatePolicyTargets(cmptType, containerComponentId, policyId, policyTarget, userId));\r
+    }\r
+\r
+    private Either<Map<PolicyTargetType, List<String>>, ResponseFormat> updatePolicyTargetsFromDTO(\r
+            List<PolicyTargetDTO> targetDTOList) {\r
+        Map<PolicyTargetType, List<String>> policyTarget = new HashMap<>();\r
+        for (PolicyTargetDTO currentTarget : targetDTOList) {\r
+            if (!addTargetsByType(policyTarget, currentTarget.getType(), currentTarget.getUniqueIds())) {\r
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_TARGET_TYPE_DOES_NOT_EXIST,\r
+                        currentTarget.getType()));\r
+            }\r
+        }\r
+        return Either.left(policyTarget);\r
+    }\r
+\r
+\r
+    public boolean addTargetsByType(Map<PolicyTargetType, List<String>> policyTarget, String type, List<String> uniqueIds) {\r
+        PolicyTargetType targetTypeEnum = PolicyTargetType.getByNameIgnoreCase(type);\r
+        if(targetTypeEnum != null){\r
+            policyTarget.put(targetTypeEnum, validateUniquenessOfIds(uniqueIds));\r
+            return true;\r
+        }\r
+        else{\r
+            return false;\r
+        }\r
+    }\r
+\r
+    private List<String> validateUniquenessOfIds(List<String> uniqueIds) {\r
+        return uniqueIds.stream().distinct().collect(Collectors.toList());\r
+    }\r
+}\r
index dc4bb95..8030ef4 100644 (file)
@@ -1,67 +1,80 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import io.swagger.annotations.*;
-import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic;
-import org.openecomp.sdc.be.mixin.PolicyTypeMixin;
-import org.openecomp.sdc.be.model.PolicyTypeDefinition;
-import org.openecomp.sdc.be.view.ResponseView;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.springframework.stereotype.Controller;
-
-import javax.ws.rs.*;
-import javax.ws.rs.core.MediaType;
-import java.util.List;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "policy types resource")
-@Controller
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-public class PolicyTypesEndpoint {
-
-    private static final Logger log = Logger.getLogger(PolicyTypesEndpoint.class);
-
-    private final PolicyTypeBusinessLogic policyTypeBusinessLogic;
-
-    public PolicyTypesEndpoint(PolicyTypeBusinessLogic policyTypeBusinessLogic) {
-        this.policyTypeBusinessLogic = policyTypeBusinessLogic;
-    }
-
-    @GET
-    @Path("/policyTypes")
-    @ApiOperation(value = "Get policy types ", httpMethod = "GET", notes = "Returns policy types", response = PolicyTypeDefinition.class, responseContainer="List")
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "policy types found"),
-                            @ApiResponse(code = 403, message = "Restricted operation"),
-                            @ApiResponse(code = 500, message = "The GET request failed due to internal SDC problem.")})
-    @ResponseView(mixin = {PolicyTypeMixin.class})
-    public List<PolicyTypeDefinition> getPolicyTypes(@ApiParam(value = "An optional parameter to indicate the type of the container from where this call is executed")
-                                   @QueryParam("internalComponentType") String internalComponentType,
-                                                     @ApiParam(value = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        log.debug("(get) Start handle request of GET policyTypes");
-        return policyTypeBusinessLogic.getAllPolicyTypes(userId, internalComponentType);
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.List;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.QueryParam;\r
+import javax.ws.rs.core.MediaType;\r
+import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic;\r
+import org.openecomp.sdc.be.mixin.PolicyTypeMixin;\r
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;\r
+import org.openecomp.sdc.be.view.ResponseView;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.springframework.stereotype.Controller;\r
+import com.jcabi.aspects.Loggable;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "policy types resource"))\r
+@Controller\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+public class PolicyTypesEndpoint {\r
+\r
+    private static final Logger log = Logger.getLogger(PolicyTypesEndpoint.class);\r
+\r
+    private final PolicyTypeBusinessLogic policyTypeBusinessLogic;\r
+\r
+    public PolicyTypesEndpoint(PolicyTypeBusinessLogic policyTypeBusinessLogic) {\r
+        this.policyTypeBusinessLogic = policyTypeBusinessLogic;\r
+    }\r
+\r
+    @GET\r
+    @Path("/policyTypes")\r
+    @Operation(description = "Get policy types ", method = "GET", summary = "Returns policy types",responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = PolicyTypeDefinition.class)))))\r
+    @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "policy types found"),\r
+                            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+                            @ApiResponse(responseCode = "500", description = "The GET request failed due to internal SDC problem.")})\r
+    @ResponseView(mixin = {PolicyTypeMixin.class})\r
+    public List<PolicyTypeDefinition> getPolicyTypes(@Parameter(description = "An optional parameter to indicate the type of the container from where this call is executed")\r
+                                   @QueryParam("internalComponentType") String internalComponentType,\r
+                                   @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        log.debug("(get) Start handle request of GET policyTypes");\r
+        return policyTypeBusinessLogic.getAllPolicyTypes(userId, internalComponentType);\r
+    }\r
+\r
+}\r
index 922db5a..c6a6571 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ProductBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.Product;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.Map;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Product Catalog", description = "Product Servlet")
-@Singleton
-public class ProductServlet extends BeGenericServlet {
-    private static final Logger log = Logger.getLogger(ProductServlet.class);
-    private final ProductBusinessLogic productBusinessLogic;
-
-    @Inject
-    public ProductServlet(UserBusinessLogic userBusinessLogic,
-        ProductBusinessLogic productBusinessLogic,
-        ComponentsUtils componentsUtils) {
-        super(userBusinessLogic, componentsUtils);
-        this.productBusinessLogic = productBusinessLogic;
-    }
-
-    @POST
-    @Path("/products")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create product", httpMethod = "POST", notes = "Returns created product", response = Product.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Product created"), @ApiResponse(code = 403, message = "Restricted operation / Empty USER_ID header"), @ApiResponse(code = 400, message = "Invalid/missing content"),
-    @ApiResponse(code = 409, message = "Product already exists / User not found / Wrong user role") })
-    public Response createProduct(@ApiParam(value = "Product object to be created", required = true) String data, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of product strategist user", required = true) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-        try {
-            Product product = RepresentationUtils.fromRepresentation(data, Product.class);
-            Either<Product, ResponseFormat> actionResponse = productBusinessLogic.createProduct(product, modifier);
-
-            if (actionResponse.isRight()) {
-                log.debug("Failed to create product");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result);
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Product");
-            log.debug("create product failed with error ", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-    @GET
-    @Path("/products/{productId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve product", httpMethod = "GET", notes = "Returns product according to productId", response = Product.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 409, message = "Restricted operation"),
-            @ApiResponse(code = 500, message = "Internal Server Error"), @ApiResponse(code = 404, message = "Product not found"), })
-    public Response getProductById(@PathParam("productId") final String productId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-
-        try {
-            log.trace("get product with id {}", productId);
-            Either<Product, ResponseFormat> actionResponse = productBusinessLogic.getProduct(productId, modifier);
-
-            if (actionResponse.isRight()) {
-                log.debug("Failed to get product");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            Object product = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Product");
-            log.debug("get product failed with error ", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-    @GET
-    @Path("/products/productName/{productName}/productVersion/{productVersion}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns product according to name and version", response = Product.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Product not found") })
-    public Response getServiceByNameAndVersion(@PathParam("productName") final String productName, @PathParam("productVersion") final String productVersion, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-        try {
-            Either<Product, ResponseFormat> actionResponse = productBusinessLogic.getProductByNameAndVersion(productName, productVersion, userId);
-
-            if (actionResponse.isRight()) {
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            Product product = actionResponse.left().value();
-            Object result = RepresentationUtils.toRepresentation(product);
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get product by name and version");
-            log.debug("get product failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    @DELETE
-    @Path("/products/{productId}")
-    public Response deleteProduct(@PathParam("productId") final String productId, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        // get modifier id
-        String userId = request.getHeader(Constants.USER_ID_HEADER);
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-
-        try {
-            log.trace("delete product with id {}", productId);
-            Either<Product, ResponseFormat> actionResponse = productBusinessLogic.deleteProduct(productId, modifier);
-
-            if (actionResponse.isRight()) {
-                log.debug("Failed to delete product");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            Object product = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product);
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource");
-            log.debug("delete resource failed with error ", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @PUT
-    @Path("/products/{productId}/metadata")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Product Metadata", httpMethod = "PUT", notes = "Returns updated product", response = Product.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Product Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateProductMetadata(@PathParam("productId") final String productId, @ApiParam(value = "Product object to be Updated", required = true) String data, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-        Response response = null;
-
-        try {
-            String productIdLower = productId.toLowerCase();
-            Product updatedProduct = RepresentationUtils.fromRepresentation(data, Product.class);
-            Either<Product, ResponseFormat> actionResponse = productBusinessLogic.updateProductMetadata(productIdLower, updatedProduct, modifier);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to update product");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            Product product = actionResponse.left().value();
-            Object result = RepresentationUtils.toRepresentation(product);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        } catch (Exception e) {
-            log.debug("update product metadata failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-    @GET
-    @Path("/products/validate-name/{productName}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "validate product name", httpMethod = "GET", notes = "checks if the chosen product name is available ", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") })
-    public Response validateServiceName(@PathParam("productName") final String productName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-        Response response = null;
-        try {
-            Either<Map<String, Boolean>, ResponseFormat> actionResponse = productBusinessLogic.validateProductNameExists(productName, userId);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to get validate service name");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Product Name");
-            log.debug("validate product name failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.Map;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.ProductBusinessLogic;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.model.Product;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Product Catalog", description = "Product Catalog"))\r
+@Singleton\r
+public class ProductServlet extends BeGenericServlet {\r
+    private static final Logger log = Logger.getLogger(ProductServlet.class);\r
+    private final ProductBusinessLogic productBusinessLogic;\r
+\r
+    @Inject\r
+    public ProductServlet(UserBusinessLogic userBusinessLogic,\r
+        ProductBusinessLogic productBusinessLogic,\r
+        ComponentsUtils componentsUtils) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.productBusinessLogic = productBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Path("/products")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create product", method = "POST", summary = "Returns created product",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Product.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Product created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation / Empty USER_ID header"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid/missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Product already exists / User not found / Wrong user role")})\r
+    public Response createProduct(@Parameter(description = "Product object to be created", required = true) String data,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of product strategist user",\r
+                    required = true) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+        try {\r
+            Product product = RepresentationUtils.fromRepresentation(data, Product.class);\r
+            Either<Product, ResponseFormat> actionResponse = productBusinessLogic.createProduct(product, modifier);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("Failed to create product");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result);\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Product");\r
+            log.debug("create product failed with error ", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/products/{productId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve product", method = "GET", summary = "Returns product according to productId",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Product.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Product found"),\r
+            @ApiResponse(responseCode = "403", description = "Missing information"),\r
+            @ApiResponse(responseCode = "409", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error"),\r
+            @ApiResponse(responseCode = "404", description = "Product not found"),})\r
+    public Response getProductById(@PathParam("productId") final String productId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+\r
+        try {\r
+            log.trace("get product with id {}", productId);\r
+            Either<Product, ResponseFormat> actionResponse = productBusinessLogic.getProduct(productId, modifier);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("Failed to get product");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            Object product = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Product");\r
+            log.debug("get product failed with error ", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/products/productName/{productName}/productVersion/{productVersion}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve Service", method = "GET",\r
+            summary = "Returns product according to name and version",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Product.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Product found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Product not found")})\r
+    public Response getServiceByNameAndVersion(@PathParam("productName") final String productName,\r
+            @PathParam("productVersion") final String productVersion, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+        try {\r
+            Either<Product, ResponseFormat> actionResponse =\r
+                    productBusinessLogic.getProductByNameAndVersion(productName, productVersion, userId);\r
+\r
+            if (actionResponse.isRight()) {\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            Product product = actionResponse.left().value();\r
+            Object result = RepresentationUtils.toRepresentation(product);\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get product by name and version");\r
+            log.debug("get product failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/products/{productId}")\r
+    public Response deleteProduct(@PathParam("productId") final String productId, @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        // get modifier id\r
+        String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+\r
+        try {\r
+            log.trace("delete product with id {}", productId);\r
+            Either<Product, ResponseFormat> actionResponse = productBusinessLogic.deleteProduct(productId, modifier);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("Failed to delete product");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            Object product = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product);\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource");\r
+            log.debug("delete resource failed with error ", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @PUT\r
+    @Path("/products/{productId}/metadata")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Product Metadata", method = "PUT", summary = "Returns updated product",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Product.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Product Updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateProductMetadata(@PathParam("productId") final String productId,\r
+            @Parameter(description = "Product object to be Updated", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+        Response response = null;\r
+\r
+        try {\r
+            String productIdLower = productId.toLowerCase();\r
+            Product updatedProduct = RepresentationUtils.fromRepresentation(data, Product.class);\r
+            Either<Product, ResponseFormat> actionResponse =\r
+                    productBusinessLogic.updateProductMetadata(productIdLower, updatedProduct, modifier);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to update product");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            Product product = actionResponse.left().value();\r
+            Object result = RepresentationUtils.toRepresentation(product);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        } catch (Exception e) {\r
+            log.debug("update product metadata failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/products/validate-name/{productName}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "validate product name", method = "GET",\r
+            summary = "checks if the chosen product name is available ",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation")})\r
+    public Response validateServiceName(@PathParam("productName") final String productName,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+        Response response = null;\r
+        try {\r
+            Either<Map<String, Boolean>, ResponseFormat> actionResponse =\r
+                    productBusinessLogic.validateProductNameExists(productName, userId);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to get validate service name");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    actionResponse.left().value());\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Product Name");\r
+            log.debug("validate product name failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+}\r
index 1abc69b..5df3404 100644 (file)
-/*
- * Copyright Â© 2016-2018 European Support Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.RequirementBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.List;
-import java.util.Optional;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-@Api(value = "Requirement Servlet", description = "Requirement Servlet")
-@Singleton
-public class RequirementServlet extends AbstractValidationsServlet {
-    private static final Logger LOGGER = Logger.getLogger(RequirementServlet.class);
-    private final RequirementBusinessLogic requirementBusinessLogic;
-
-    @Inject
-    public RequirementServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        RequirementBusinessLogic requirementBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.requirementBusinessLogic = requirementBusinessLogic;
-    }
-
-    @POST
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/resources/{resourceId}/requirements")
-    @ApiOperation(value = "Create requirements on resource", httpMethod = "POST",
-            notes = "Create requirements on resource", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Create requirements"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "requirement already exist")})
-    public Response createRequirementsOnResource(
-            @ApiParam(value = "Requirement to create", required = true) String data,
-            @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "resources" , resourceId, request,
-                userId, false, "createRequirements");
-    }
-
-
-    @PUT
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/resources/{resourceId}/requirements")
-    @ApiOperation(value = "Update Requirements on resource", httpMethod = "PUT",
-            notes = "Update Requirements on resource", response = RequirementDefinition.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Update Requirements"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response updateRequirementsOnResource(
-            @ApiParam(value = "Requirements to update", required = true) String data,
-            @ApiParam(value = "Component Id") @PathParam("resourceId") String resourceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "resources", resourceId, request,
-                userId, true, "updateRequirements");
-    }
-
-    @GET
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/resources/{resourceId}/requirements/{requirementId}")
-    @ApiOperation(value = "Get Requirement from resource", httpMethod = "GET",
-            notes = "GET Requirement from resource", response = RequirementDefinition.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "GET requirement"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response getRequirementsFromResource(
-            @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
-            @ApiParam(value = "Requirement Id") @PathParam("requirementId") String requirementId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return get(requirementId, resourceId, request, userId);
-    }
-
-    @DELETE
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/resources/{resourceId}/requirements/{requirementId}")
-    @ApiOperation(value = "Delete requirements from resource", httpMethod = "DELETE",
-            notes = "Delete requirements from resource", response = RequirementDefinition.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete requirement"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response deleteRequirementsFromResource(
-            @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
-            @ApiParam(value = "requirement Id") @PathParam("requirementId") String requirementId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return delete(requirementId, resourceId, request, userId);
-    }
-
-    @POST
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/services/{serviceId}/requirements")
-    @ApiOperation(value = "Create requirements on service", httpMethod = "POST",
-            notes = "Create requirements on service", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Requirements"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Requirement already exist")})
-    public Response createRequirementsOnService(
-            @ApiParam(value = "Requirements to create", required = true) String data,
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "services" , serviceId, request, userId,
-                false , "createRequirements");
-    }
-
-
-    @PUT
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/services/{serviceId}/requirements")
-    @ApiOperation(value = "Update requirements on service", httpMethod = "PUT",
-            notes = "Update requirements on service", response = RequirementDefinition.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Update requirements"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response updateRequirementsOnService(
-            @ApiParam(value = "Requirements to update", required = true) String data,
-            @ApiParam(value = "Component Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "services", serviceId, request, userId,
-                true, "updateRequirements");
-    }
-
-    @GET
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/services/{serviceId}/requirements/{requirementId}")
-    @ApiOperation(value = "Get requirement from service", httpMethod = "GET",
-            notes = "GET requirement from service", response = RequirementDefinition.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "GET Requirements"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response getRequirementsOnService(
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @ApiParam(value = "Requirement Id") @PathParam("requirementId") String requirementId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return get(requirementId, serviceId, request, userId);
-    }
-
-
-    @DELETE
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/services/{serviceId}/requirements/{requirementId}")
-    @ApiOperation(value = "Delete requirement from service", httpMethod = "DELETE",
-            notes = "Delete requirement from service", response = RequirementDefinition.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete Requirements"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response deleteRequirementsOnService(
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @ApiParam(value = "Requirement Id") @PathParam("requirementId") String requirementId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return delete(requirementId, serviceId, request, userId);
-    }
-
-
-    private Response createOrUpdate (String data, String componentType, String componentId,
-                                     HttpServletRequest request, String userId,
-                                     boolean isUpdate, String errorContext) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        LOGGER.debug("Start create or update request of {} with modifier id {}", url, userId);
-
-        try {
-            String componentIdLower = componentId.toLowerCase();
-
-            Either<List<RequirementDefinition>, ResponseFormat> mappedRequirementDataEither =
-                    getMappedRequirementData(data, modifier, ComponentTypeEnum.findByParamName(componentType));
-            if(mappedRequirementDataEither.isRight()) {
-                LOGGER.error("Failed to create or update requirements");
-                return buildErrorResponse(mappedRequirementDataEither.right().value());
-            }
-            List<RequirementDefinition> mappedRequirementData = mappedRequirementDataEither.left().value();
-            Either<List<RequirementDefinition>, ResponseFormat> actionResponse;
-            if(isUpdate) {
-                actionResponse = requirementBusinessLogic.updateRequirements(componentIdLower, mappedRequirementData, modifier,
-                        errorContext, true);
-            } else {
-                actionResponse = requirementBusinessLogic.createRequirements(componentIdLower, mappedRequirementData, modifier,
-                        errorContext, true);
-            }
-
-            if (actionResponse.isRight()) {
-                LOGGER.error("Failed to create or update requirements");
-                return buildErrorResponse(actionResponse.right().value());
-            }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    actionResponse.left().value());
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("requirements create or update");
-            LOGGER.error("Failed to create or update requirements with an error", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    private Response get (String requirementIdToGet,  String componentId,
-                          HttpServletRequest request, String userId){
-        String url = request.getMethod() + " " + request.getRequestURI();
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        LOGGER.debug("Start get request of {} with modifier id {}", url, userId);
-
-        try {
-            String componentIdLower = componentId.toLowerCase();
-            Either<RequirementDefinition, ResponseFormat> actionResponse = requirementBusinessLogic
-                    .getRequirement(componentIdLower, requirementIdToGet, modifier, true);
-            if (actionResponse.isRight()) {
-                LOGGER.error("failed to get requirements");
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            Object result = RepresentationUtils.toFilteredRepresentation(actionResponse.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get requirements");
-            LOGGER.error("get requirements failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    private Response delete (String requirementId, String componentId, HttpServletRequest
-                                        request, String userId){
-        String url = request.getMethod() + " " + request.getRequestURI();
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        LOGGER.debug("Start delete request of {} with modifier id {}", url, userId);
-
-        try {
-            String componentIdLower = componentId.toLowerCase();
-
-            Either<RequirementDefinition, ResponseFormat> actionResponse = requirementBusinessLogic
-                    .deleteRequirement(componentIdLower, requirementId, modifier, true);
-            if (actionResponse.isRight()) {
-                LOGGER.error("failed to delete requirements");
-                return buildErrorResponse(actionResponse.right().value());
-            }
-            Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete requirements");
-            LOGGER.error("Delete requirements failed with an error", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    private Either<List<RequirementDefinition>, ResponseFormat> getMappedRequirementData(String inputJson, User user,
-                                                                 ComponentTypeEnum componentTypeEnum){
-        Either<UiComponentDataTransfer, ResponseFormat> mappedData = getComponentsUtils()
-                .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class,
-                        AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
-        Optional<List<RequirementDefinition>> requirementDefinitionList = mappedData.left().value()
-                .getRequirements().values().stream().findFirst();
-        return requirementDefinitionList.<Either<List<RequirementDefinition>, ResponseFormat>>
-                map(Either::left).orElseGet(() -> Either.right(getComponentsUtils()
-                .getResponseFormat(ActionStatus.GENERAL_ERROR)));
-    }
-}
+/*\r
+ * Copyright Â© 2016-2018 European Support Limited\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.List;\r
+import java.util.Optional;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.RequirementBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.RequirementDefinition;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+@OpenAPIDefinition(info = @Info(title = "Requirement Servlet", description = "Requirement Servlet"))\r
+@Singleton\r
+public class RequirementServlet extends AbstractValidationsServlet {\r
+    private static final Logger LOGGER = Logger.getLogger(RequirementServlet.class);\r
+    private final RequirementBusinessLogic requirementBusinessLogic;\r
+\r
+    @Inject\r
+    public RequirementServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        RequirementBusinessLogic requirementBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.requirementBusinessLogic = requirementBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/resources/{resourceId}/requirements")\r
+    @Operation(description = "Create requirements on resource", method = "POST",\r
+            summary = "Create requirements on resource",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Create requirements"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "requirement already exist")})\r
+    public Response createRequirementsOnResource(\r
+            @Parameter(description = "Requirement to create", required = true) String data,\r
+            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return createOrUpdate(data, "resources" , resourceId, request,\r
+                userId, false, "createRequirements");\r
+    }\r
+\r
+\r
+    @PUT\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/resources/{resourceId}/requirements")\r
+    @Operation(description = "Update Requirements on resource", method = "PUT",\r
+            summary = "Update Requirements on resource", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Update Requirements"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateRequirementsOnResource(\r
+            @Parameter(description = "Requirements to update", required = true) String data,\r
+            @Parameter(description = "Component Id") @PathParam("resourceId") String resourceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return createOrUpdate(data, "resources", resourceId, request,\r
+                userId, true, "updateRequirements");\r
+    }\r
+\r
+    @GET\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/resources/{resourceId}/requirements/{requirementId}")\r
+    @Operation(description = "Get Requirement from resource", method = "GET",\r
+            summary = "GET Requirement from resource", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "GET requirement"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response getRequirementsFromResource(\r
+            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,\r
+            @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return get(requirementId, resourceId, request, userId);\r
+    }\r
+\r
+    @DELETE\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/resources/{resourceId}/requirements/{requirementId}")\r
+    @Operation(description = "Delete requirements from resource", method = "DELETE",\r
+            summary = "Delete requirements from resource", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Delete requirement"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response deleteRequirementsFromResource(\r
+            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,\r
+            @Parameter(description = "requirement Id") @PathParam("requirementId") String requirementId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return delete(requirementId, resourceId, request, userId);\r
+    }\r
+\r
+    @POST\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/services/{serviceId}/requirements")\r
+    @Operation(description = "Create requirements on service", method = "POST",\r
+            summary = "Create requirements on service", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Create Requirements"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Requirement already exist")})\r
+    public Response createRequirementsOnService(\r
+            @Parameter(description = "Requirements to create", required = true) String data,\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return createOrUpdate(data, "services" , serviceId, request, userId,\r
+                false , "createRequirements");\r
+    }\r
+\r
+\r
+    @PUT\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/services/{serviceId}/requirements")\r
+    @Operation(description = "Update requirements on service", method = "PUT",\r
+            summary = "Update requirements on service", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Update requirements"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateRequirementsOnService(\r
+            @Parameter(description = "Requirements to update", required = true) String data,\r
+            @Parameter(description = "Component Id") @PathParam("serviceId") String serviceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return createOrUpdate(data, "services", serviceId, request, userId,\r
+                true, "updateRequirements");\r
+    }\r
+\r
+    @GET\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/services/{serviceId}/requirements/{requirementId}")\r
+    @Operation(description = "Get requirement from service", method = "GET",\r
+            summary = "GET requirement from service", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "GET Requirements"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response getRequirementsOnService(\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        return get(requirementId, serviceId, request, userId);\r
+    }\r
+\r
+\r
+    @DELETE\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/services/{serviceId}/requirements/{requirementId}")\r
+    @Operation(description = "Delete requirement from service", method = "DELETE",\r
+            summary = "Delete requirement from service", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Delete Requirements"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response deleteRequirementsOnService(\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return delete(requirementId, serviceId, request, userId);\r
+    }\r
+\r
+\r
+    private Response createOrUpdate (String data, String componentType, String componentId,\r
+                                     HttpServletRequest request, String userId,\r
+                                     boolean isUpdate, String errorContext) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        LOGGER.debug("Start create or update request of {} with modifier id {}", url, userId);\r
+\r
+        try {\r
+            String componentIdLower = componentId.toLowerCase();\r
+\r
+            Either<List<RequirementDefinition>, ResponseFormat> mappedRequirementDataEither =\r
+                    getMappedRequirementData(data, modifier, ComponentTypeEnum.findByParamName(componentType));\r
+            if(mappedRequirementDataEither.isRight()) {\r
+                LOGGER.error("Failed to create or update requirements");\r
+                return buildErrorResponse(mappedRequirementDataEither.right().value());\r
+            }\r
+            List<RequirementDefinition> mappedRequirementData = mappedRequirementDataEither.left().value();\r
+            Either<List<RequirementDefinition>, ResponseFormat> actionResponse;\r
+            if(isUpdate) {\r
+                actionResponse = requirementBusinessLogic.updateRequirements(componentIdLower, mappedRequirementData, modifier,\r
+                        errorContext, true);\r
+            } else {\r
+                actionResponse = requirementBusinessLogic.createRequirements(componentIdLower, mappedRequirementData, modifier,\r
+                        errorContext, true);\r
+            }\r
+\r
+            if (actionResponse.isRight()) {\r
+                LOGGER.error("Failed to create or update requirements");\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    actionResponse.left().value());\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("requirements create or update");\r
+            LOGGER.error("Failed to create or update requirements with an error", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    private Response get (String requirementIdToGet,  String componentId,\r
+                          HttpServletRequest request, String userId){\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        LOGGER.debug("Start get request of {} with modifier id {}", url, userId);\r
+\r
+        try {\r
+            String componentIdLower = componentId.toLowerCase();\r
+            Either<RequirementDefinition, ResponseFormat> actionResponse = requirementBusinessLogic\r
+                    .getRequirement(componentIdLower, requirementIdToGet, modifier, true);\r
+            if (actionResponse.isRight()) {\r
+                LOGGER.error("failed to get requirements");\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            Object result = RepresentationUtils.toFilteredRepresentation(actionResponse.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get requirements");\r
+            LOGGER.error("get requirements failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    private Response delete (String requirementId, String componentId, HttpServletRequest\r
+                                        request, String userId){\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        LOGGER.debug("Start delete request of {} with modifier id {}", url, userId);\r
+\r
+        try {\r
+            String componentIdLower = componentId.toLowerCase();\r
+\r
+            Either<RequirementDefinition, ResponseFormat> actionResponse = requirementBusinessLogic\r
+                    .deleteRequirement(componentIdLower, requirementId, modifier, true);\r
+            if (actionResponse.isRight()) {\r
+                LOGGER.error("failed to delete requirements");\r
+                return buildErrorResponse(actionResponse.right().value());\r
+            }\r
+            Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete requirements");\r
+            LOGGER.error("Delete requirements failed with an error", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    private Either<List<RequirementDefinition>, ResponseFormat> getMappedRequirementData(String inputJson, User user,\r
+                                                                 ComponentTypeEnum componentTypeEnum){\r
+        Either<UiComponentDataTransfer, ResponseFormat> mappedData = getComponentsUtils()\r
+                .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class,\r
+                        AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);\r
+        Optional<List<RequirementDefinition>> requirementDefinitionList = mappedData.left().value()\r
+                .getRequirements().values().stream().findFirst();\r
+        return requirementDefinitionList.<Either<List<RequirementDefinition>, ResponseFormat>>\r
+                map(Either::left).orElseGet(() -> Either.right(getComponentsUtils()\r
+                .getResponseFormat(ActionStatus.GENERAL_ERROR)));\r
+    }\r
+}\r
index d1f50c9..efbf730 100644 (file)
@@ -1,79 +1,91 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-public class RequirementsServlet extends BeGenericServlet {
-
-    private static final Logger log = Logger.getLogger(RequirementsServlet.class);
-
-    @Inject
-    public RequirementsServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils) {
-        super(userBusinessLogic, componentsUtils);
-    }
-
-    @PUT
-    @Path("resources/{resourceId}/requirements/{requirementId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Resource Requirement", httpMethod = "PUT", notes = "Returns updated requirement", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource requirement updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateRequirement(@ApiParam(value = "resource id to update with new requirement", required = true) @PathParam("resourceId") final String resourceId,
-                                      @ApiParam(value = "requirement id to update", required = true) @PathParam("requirementId") final String requirementId, @ApiParam(value = "Resource property to update", required = true) String requirementData,
-                                      @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        // Convert RequirementDefinition from JSON
-        // TODO: it's going to be another object, probably. This is placeholder
-        // for sake of JSON validation
-        // RequirementDefinition requirementDefinition;
-        ResponseFormat responseFormat;
-        try {
-            // TODO pass real entity
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
-        }  catch (Exception e) {
-            log.debug("Unexpected error: ", e);
-            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-        }
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import javax.inject.Inject;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+public class RequirementsServlet extends BeGenericServlet {\r
+\r
+    private static final Logger log = Logger.getLogger(RequirementsServlet.class);\r
+\r
+    @Inject\r
+    public RequirementsServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils) {\r
+        super(userBusinessLogic, componentsUtils);\r
+    }\r
+\r
+    @PUT\r
+    @Path("resources/{resourceId}/requirements/{requirementId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Resource Requirement", method = "PUT", summary = "Returns updated requirement", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource requirement updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateRequirement(\r
+            @Parameter(description = "resource id to update with new requirement",\r
+                    required = true) @PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "requirement id to update",\r
+                    required = true) @PathParam("requirementId") final String requirementId,\r
+            @Parameter(description = "Resource property to update", required = true) String requirementData,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        // Convert RequirementDefinition from JSON\r
+        // TODO: it's going to be another object, probably. This is placeholder\r
+        // for sake of JSON validation\r
+        // RequirementDefinition requirementDefinition;\r
+        ResponseFormat responseFormat;\r
+        try {\r
+            // TODO pass real entity\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);\r
+        }  catch (Exception e) {\r
+            log.debug("Unexpected error: ", e);\r
+            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+    }\r
+}\r
index 6e78b50..3d7471e 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
-import org.glassfish.jersey.media.multipart.FormDataParam;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.UploadResourceInfo;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-
-import javax.inject.Singleton;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.File;
-
-/**
- * Root resource (exposed at "/" path)
- */
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog/upload")
-@Api(value = "Resources Catalog Upload", description = "Upload resource yaml")
-@Singleton
-public class ResourceUploadServlet extends AbstractValidationsServlet {
-
-    private static final Logger log = Logger.getLogger(ResourceUploadServlet.class);
-    public static final String NORMATIVE_TYPE_RESOURCE = "multipart";
-    public static final String CSAR_TYPE_RESOURCE = "csar";
-    public static final String USER_TYPE_RESOURCE = "user-resource";
-    public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import";
-
-    @Inject
-    public ResourceUploadServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-    }
-
-    public enum ResourceAuthorityTypeEnum {
-        NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true), CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true);
-
-        private String urlPath;
-        private boolean isBackEndImport, isUserTypeResource;
-
-        public static ResourceAuthorityTypeEnum findByUrlPath(String urlPath) {
-            ResourceAuthorityTypeEnum found = null;
-            for (ResourceAuthorityTypeEnum curr : ResourceAuthorityTypeEnum.values()) {
-                if (curr.getUrlPath().equals(urlPath)) {
-                    found = curr;
-                    break;
-                }
-            }
-            return found;
-        }
-
-        private ResourceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeResource) {
-            this.urlPath = urlPath;
-            this.isBackEndImport = isBackEndImport;
-            this.isUserTypeResource = isUserTypeResource;
-        }
-
-        public String getUrlPath() {
-            return urlPath;
-        }
-
-        public boolean isBackEndImport() {
-            return isBackEndImport;
-        }
-
-        public boolean isUserTypeResource() {
-            return isUserTypeResource;
-        }
-    }
-
-    @POST
-    @Path("/{resourceAuthority}")
-    @Consumes(MediaType.MULTIPART_FORM_DATA)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Resource from yaml", httpMethod = "POST", notes = "Returns created resource", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Resource already exist") })
-    public Response uploadMultipart(
-            @ApiParam(value = "validValues: normative-resource / user-resource", allowableValues = NORMATIVE_TYPE_RESOURCE + "," + USER_TYPE_RESOURCE + ","
-                    + USER_TYPE_RESOURCE_UI_IMPORT) @PathParam(value = "resourceAuthority") final String resourceAuthority,
-            @ApiParam("FileInputStream") @FormDataParam("resourceZip") File file, @ApiParam("ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader,
-            @ApiParam("resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            // updateResourse Query Parameter if false checks if already exist
-            @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) {
-
-        try {
-
-            Wrapper<Response> responseWrapper = new Wrapper<>();
-            Wrapper<User> userWrapper = new Wrapper<>();
-            Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
-            Wrapper<String> yamlStringWrapper = new Wrapper<>();
-
-            String url = request.getMethod() + " " + request.getRequestURI();
-            log.debug("Start handle request of {}", url);
-
-            // When we get an errorResponse it will be filled into the
-            // responseWrapper
-            validateAuthorityType(responseWrapper, resourceAuthority);
-
-            ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority);
-
-            commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
-
-            fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file);
-
-            // PayLoad Validations
-            if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){
-                commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
-
-                specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
-            }
-
-            if (responseWrapper.isEmpty()) {
-                handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null);
-            }
-
-            return responseWrapper.getInnerElement();
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource");
-            log.debug("upload resource failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    /********************************************************************************************************************/
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.io.File;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DefaultValue;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.QueryParam;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.glassfish.jersey.media.multipart.FormDataContentDisposition;\r
+import org.glassfish.jersey.media.multipart.FormDataParam;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.UploadResourceInfo;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import com.jcabi.aspects.Loggable;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+/**\r
+ * Root resource (exposed at "/" path)\r
+ */\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog/upload")\r
+@OpenAPIDefinition(info = @Info(title = "Resources Catalog Upload", description = "Upload resource yaml"))\r
+@Singleton\r
+public class ResourceUploadServlet extends AbstractValidationsServlet {\r
+\r
+    private static final Logger log = Logger.getLogger(ResourceUploadServlet.class);\r
+    public static final String NORMATIVE_TYPE_RESOURCE = "multipart";\r
+    public static final String CSAR_TYPE_RESOURCE = "csar";\r
+    public static final String USER_TYPE_RESOURCE = "user-resource";\r
+    public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import";\r
+\r
+    @Inject\r
+    public ResourceUploadServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+    }\r
+\r
+    public enum ResourceAuthorityTypeEnum {\r
+        NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true,\r
+                true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false,\r
+                        true), CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true);\r
+\r
+        private String urlPath;\r
+        private boolean isBackEndImport, isUserTypeResource;\r
+\r
+        public static ResourceAuthorityTypeEnum findByUrlPath(String urlPath) {\r
+            ResourceAuthorityTypeEnum found = null;\r
+            for (ResourceAuthorityTypeEnum curr : ResourceAuthorityTypeEnum.values()) {\r
+                if (curr.getUrlPath().equals(urlPath)) {\r
+                    found = curr;\r
+                    break;\r
+                }\r
+            }\r
+            return found;\r
+        }\r
+\r
+        private ResourceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeResource) {\r
+            this.urlPath = urlPath;\r
+            this.isBackEndImport = isBackEndImport;\r
+            this.isUserTypeResource = isUserTypeResource;\r
+        }\r
+\r
+        public String getUrlPath() {\r
+            return urlPath;\r
+        }\r
+\r
+        public boolean isBackEndImport() {\r
+            return isBackEndImport;\r
+        }\r
+\r
+        public boolean isUserTypeResource() {\r
+            return isUserTypeResource;\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/{resourceAuthority}")\r
+    @Consumes(MediaType.MULTIPART_FORM_DATA)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create Resource from yaml", method = "POST", summary = "Returns created resource",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Resource already exist")})\r
+    public Response uploadMultipart(\r
+            @Parameter(description = "validValues: normative-resource / user-resource",\r
+                    schema = @Schema(allowableValues = {NORMATIVE_TYPE_RESOURCE ,\r
+                            USER_TYPE_RESOURCE,USER_TYPE_RESOURCE_UI_IMPORT})) @PathParam(\r
+                                    value = "resourceAuthority") final String resourceAuthority,\r
+            @Parameter(description = "FileInputStream") @FormDataParam("resourceZip") File file,\r
+            @Parameter(description = "ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader,\r
+            @Parameter(description = "resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            // updateResourse Query Parameter if false checks if already exist\r
+            @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) {\r
+\r
+        try {\r
+\r
+            Wrapper<Response> responseWrapper = new Wrapper<>();\r
+            Wrapper<User> userWrapper = new Wrapper<>();\r
+            Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();\r
+            Wrapper<String> yamlStringWrapper = new Wrapper<>();\r
+\r
+            String url = request.getMethod() + " " + request.getRequestURI();\r
+            log.debug("Start handle request of {}", url);\r
+\r
+            // When we get an errorResponse it will be filled into the\r
+            // responseWrapper\r
+            validateAuthorityType(responseWrapper, resourceAuthority);\r
+\r
+            ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority);\r
+\r
+            commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);\r
+\r
+            fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file);\r
+\r
+            // PayLoad Validations\r
+            if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){\r
+                commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());\r
+\r
+                specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);\r
+            }\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null);\r
+            }\r
+\r
+            return responseWrapper.getInnerElement();\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource");\r
+            log.debug("upload resource failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    /********************************************************************************************************************/\r
+}\r
index e18cbfc..415fdcf 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.apache.http.HttpStatus;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.CsarValidationUtils;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ImportUtils;
-import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.UploadResourceInfo;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.servlets.ResourceUploadServlet.ResourceAuthorityTypeEnum;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Resources Catalog", description = "Resources Servlet")
-@Singleton
-public class ResourcesServlet extends AbstractValidationsServlet {
-
-    private static final Logger log = Logger.getLogger(ResourcesServlet.class);
-    private final ResourceBusinessLogic resourceBusinessLogic;
-
-    @Inject
-    public ResourcesServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ResourceBusinessLogic resourceBusinessLogic,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.resourceBusinessLogic = resourceBusinessLogic;
-    }
-
-    @POST
-    @Path("/resources")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns created resource", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Resource already exist") })
-    public Response createResource(@ApiParam(value = "Resource object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
-        init();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response;
-        try {
-
-            Wrapper<Response> responseWrapper = new Wrapper<>();
-            // UI Import
-            if (isUIImport(data)) {
-                performUIImport(responseWrapper, data, request, userId, null);
-            }
-            // UI Create
-            else {
-
-                Either<Resource, ResponseFormat> convertResponse = parseToResource(data, modifier);
-                if (convertResponse.isRight()) {
-                    log.debug("failed to parse resource");
-                    response = buildErrorResponse(convertResponse.right().value());
-                    return response;
-                }
-
-                Resource resource = convertResponse.left().value();
-                Resource createdResource = resourceBusinessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null);
-                Object representation = RepresentationUtils.toRepresentation(createdResource);
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation);
-                responseWrapper.setInnerElement(response);
-            }
-            return responseWrapper.getInnerElement();
-        } catch (IOException e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Resource");
-            log.debug("create resource failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-    private boolean isUIImport(String data) {
-        boolean isUIImport;
-        try {
-            JSONObject json = new JSONObject(data);
-            String payloadName = json.getString(ImportUtils.Constants.UI_JSON_PAYLOAD_NAME);
-            isUIImport = payloadName != null && !payloadName.isEmpty();
-        } catch (JSONException e) {
-            log.debug("failed to parse json sent from client, json:{}", data, e);
-            isUIImport = false;
-        }
-        return isUIImport;
-    }
-
-    private void performUIImport(Wrapper<Response> responseWrapper, String data, final HttpServletRequest request, String userId, String resourceUniqueId) throws FileNotFoundException {
-
-        Wrapper<User> userWrapper = new Wrapper<>();
-        Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
-        Wrapper<String> yamlStringWrapper = new Wrapper<>();
-
-        ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.USER_TYPE_UI;
-
-        commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, data);
-
-        if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) {
-            fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), data, resourceAuthorityEnum, null);
-
-            // PayLoad Validations
-            commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
-        }
-        specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, data, resourceAuthorityEnum);
-
-        if (responseWrapper.isEmpty()) {
-            handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, true, resourceUniqueId);
-        }
-    }
-
-    private Either<Resource, ResponseFormat> parseToResource(String resourceJson, User user) {
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE);
-    }
-
-    private Either<Resource, ResponseFormat> parseToLightResource(String resourceJson, User user) {
-        Either<Resource, ResponseFormat> ret = getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE);
-        if (ret.isLeft()) {// drop unwanted data (sent from UI in update flow)
-            ret.left().value().setRequirements(null);
-            ret.left().value().setCapabilities(null);
-        }
-        return ret;
-    }
-
-    @DELETE
-    @Path("/resources/{resourceId}")
-    public Response deleteResource(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-
-        // get modifier id
-        String userId = request.getHeader(Constants.USER_ID_HEADER);
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}" , userId);
-
-        Response response;
-
-        try {
-            String resourceIdLower = resourceId.toLowerCase();
-            ResponseFormat actionResponse = resourceBusinessLogic.deleteResource(resourceIdLower, modifier);
-
-            if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
-                log.debug("failed to delete resource");
-                response = buildErrorResponse(actionResponse);
-                return response;
-            }
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
-            return response;
-
-        } catch (JSONException e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource");
-            log.debug("delete resource failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @DELETE
-    @Path("/resources/{resourceName}/{version}")
-    public Response deleteResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("version") final String version, @Context final HttpServletRequest request) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-
-        // get modifier id
-        String userId = request.getHeader(Constants.USER_ID_HEADER);
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}" , userId);
-
-        Response response;
-        ResponseFormat actionResponse = resourceBusinessLogic.deleteResourceByNameAndVersion(resourceName, version, modifier);
-
-        if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
-            log.debug("failed to delete resource");
-            response = buildErrorResponse(actionResponse);
-            return response;
-        }
-        response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
-        return response;
-    }
-
-    @GET
-    @Path("/resources/{resourceId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") })
-    public Response getResourceById(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}" , userId);
-
-        Response response;
-
-        try {
-            String resourceIdLower = resourceId.toLowerCase();
-            log.trace("get resource with id {}", resourceId);
-            Either<Resource, ResponseFormat> actionResponse = resourceBusinessLogic.getResource(resourceIdLower, modifier);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to get resource");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-            Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
-
-        } catch (IOException e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource");
-            log.debug("get resource failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    @GET
-    @Path("/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve Resource by name and version", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") })
-    public Response getResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}" , userId);
-        Response response;
-        try {
-            Either<Resource, ResponseFormat> actionResponse = resourceBusinessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId);
-            if (actionResponse.isRight()) {
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-            Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
-
-        } catch (IOException e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource by name and version");
-            log.debug("get resource failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    @GET
-    @Path("/resources/validate-name/{resourceName}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "validate resource name", httpMethod = "GET", notes = "checks if the chosen resource name is available ", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation") })
-    public Response validateResourceName(@PathParam("resourceName") final String resourceName, @QueryParam("subtype") String resourceType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}" , userId);
-        Response response;
-
-        if (resourceType != null && !ResourceTypeEnum.containsName(resourceType)) {
-            log.debug("invalid resource type received");
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-            return response;
-
-        }
-        ResourceTypeEnum typeEnum = null;
-        if (resourceType != null) {
-            typeEnum = ResourceTypeEnum.valueOf(resourceType);
-        }
-        Either<Map<String, Boolean>, ResponseFormat> actionResponse = resourceBusinessLogic.validateResourceNameExists(resourceName, typeEnum, userId);
-
-        if (actionResponse.isRight()) {
-            log.debug("failed to validate resource name");
-            response = buildErrorResponse(actionResponse.right().value());
-            return response;
-        }
-        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-    }
-
-    @GET
-    @Path("/resources/certified/abstract")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    public Response getCertifiedAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}" , url);
-        try {
-            List<Resource> resources = resourceBusinessLogic
-                    .getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, userId);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(resources));
-
-        } catch (IOException e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Abstract Resources");
-            log.debug("getCertifiedAbstractResources failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @GET
-    @Path("/resources/certified/notabstract")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    public Response getCertifiedNotAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}" , url);
-        try {
-            List<Resource> resouces = resourceBusinessLogic.getAllCertifiedResources(false, HighestFilterEnum.ALL, userId);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(resouces));
-
-        } catch (IOException e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract Resources");
-            log.debug("getCertifiedNotAbstractResources failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    @PUT
-    @Path("/resources/{resourceId}/metadata")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Resource Metadata", httpMethod = "PUT", notes = "Returns updated resource metadata", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource metadata updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content") })
-    public Response updateResourceMetadata(@PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource metadata to be updated", required = true) String data, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-        Response response;
-        try {
-            String resourceIdLower = resourceId.toLowerCase();
-            Either<Resource, ResponseFormat> updateInfoResource = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE);
-            if (updateInfoResource.isRight()) {
-                log.debug("failed to parse resource metadata");
-                response = buildErrorResponse(updateInfoResource.right().value());
-                return response;
-            }
-            Resource updatedResource = resourceBusinessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false);
-            Object resource = RepresentationUtils.toRepresentation(updatedResource);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
-        } catch (IOException e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Metadata");
-            log.debug("Update Resource Metadata failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @PUT
-    @Path("/resources/{resourceId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Resource", httpMethod = "PUT", notes = "Returns updated resource", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Resource already exist") })
-    public Response updateResource(@ApiParam(value = "Resource object to be updated", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @PathParam(value = "resourceId") String resourceId) {
-
-        userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
-        init();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-        Response response;
-        try {
-            Wrapper<Response> responseWrapper = new Wrapper<>();
-            // UI Import
-            if (isUIImport(data)) {
-                performUIImport(responseWrapper, data, request, userId, resourceId);
-            } else {
-                Either<Resource, ResponseFormat> convertResponse = parseToLightResource(data, modifier);
-                if (convertResponse.isRight()) {
-                    log.debug("failed to parse resource");
-                    response = buildErrorResponse(convertResponse.right().value());
-                    return response;
-                }
-                Resource updatedResource = resourceBusinessLogic.validateAndUpdateResourceFromCsar(convertResponse.left().value(), modifier, null, null, resourceId);
-                Object representation = RepresentationUtils.toRepresentation(updatedResource);
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation);
-                responseWrapper.setInnerElement(response);
-            }
-            return responseWrapper.getInnerElement();
-        } catch (IOException e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource");
-            log.debug("update resource failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @GET
-    @Path("/resources/csar/{csaruuid}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns resource created from csar uuid", response = Resource.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource retrieced"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response getResourceFromCsar(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @PathParam(value = "csaruuid") String csarUUID) {
-
-        init();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-
-        // retrieve user details
-        userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
-        User user = new User();
-        user.setUserId(userId);
-
-        log.debug("user id is {}", userId);
-
-        Response response;
-
-        try {
-
-            Either<Resource, ResponseFormat> eitherResource = resourceBusinessLogic.getLatestResourceFromCsarUuid(csarUUID, user);
-
-            // validate response
-            if (eitherResource.isRight()) {
-                log.debug("failed to get resource from csarUuid : {}", csarUUID);
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), eitherResource.right().value());
-            } else {
-                Object representation = RepresentationUtils.toRepresentation(eitherResource.left().value());
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation);
-            }
-
-            return response;
-
-        } catch (IOException e) {
-            log.debug("get resource by csar failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import javax.inject.Inject;\r
+import org.apache.http.HttpStatus;\r
+import org.json.JSONException;\r
+import org.json.JSONObject;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.CsarValidationUtils;\r
+import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ImportUtils;\r
+import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.Product;\r
+import org.openecomp.sdc.be.model.Resource;\r
+import org.openecomp.sdc.be.model.UploadResourceInfo;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.servlets.ResourceUploadServlet.ResourceAuthorityTypeEnum;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.*;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import java.io.FileNotFoundException;\r
+import java.io.IOException;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Resources Catalog", description = "Resources Servlet"))\r
+@Singleton\r
+public class ResourcesServlet extends AbstractValidationsServlet {\r
+\r
+    private static final Logger log = Logger.getLogger(ResourcesServlet.class);\r
+    private final ResourceBusinessLogic resourceBusinessLogic;\r
+\r
+    @Inject\r
+    public ResourcesServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ResourceBusinessLogic resourceBusinessLogic,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.resourceBusinessLogic = resourceBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Path("/resources")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create Resource", method = "POST", summary = "Returns created resource",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Resource already exist")})\r
+    public Response createResource(@Parameter(description = "Resource object to be created", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);\r
+        init();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}" , url);\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response;\r
+        try {\r
+\r
+            Wrapper<Response> responseWrapper = new Wrapper<>();\r
+            // UI Import\r
+            if (isUIImport(data)) {\r
+                performUIImport(responseWrapper, data, request, userId, null);\r
+            }\r
+            // UI Create\r
+            else {\r
+\r
+                Either<Resource, ResponseFormat> convertResponse = parseToResource(data, modifier);\r
+                if (convertResponse.isRight()) {\r
+                    log.debug("failed to parse resource");\r
+                    response = buildErrorResponse(convertResponse.right().value());\r
+                    return response;\r
+                }\r
+\r
+                Resource resource = convertResponse.left().value();\r
+                Resource createdResource = resourceBusinessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null);\r
+                Object representation = RepresentationUtils.toRepresentation(createdResource);\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation);\r
+                responseWrapper.setInnerElement(response);\r
+            }\r
+            return responseWrapper.getInnerElement();\r
+        } catch (IOException e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Resource");\r
+            log.debug("create resource failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+    private boolean isUIImport(String data) {\r
+        boolean isUIImport;\r
+        try {\r
+            JSONObject json = new JSONObject(data);\r
+            String payloadName = json.getString(ImportUtils.Constants.UI_JSON_PAYLOAD_NAME);\r
+            isUIImport = payloadName != null && !payloadName.isEmpty();\r
+        } catch (JSONException e) {\r
+            log.debug("failed to parse json sent from client, json:{}", data, e);\r
+            isUIImport = false;\r
+        }\r
+        return isUIImport;\r
+    }\r
+\r
+    private void performUIImport(Wrapper<Response> responseWrapper, String data, final HttpServletRequest request, String userId, String resourceUniqueId) throws FileNotFoundException {\r
+\r
+        Wrapper<User> userWrapper = new Wrapper<>();\r
+        Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();\r
+        Wrapper<String> yamlStringWrapper = new Wrapper<>();\r
+\r
+        ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.USER_TYPE_UI;\r
+\r
+        commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, data);\r
+\r
+        if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) {\r
+            fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), data, resourceAuthorityEnum, null);\r
+\r
+            // PayLoad Validations\r
+            commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());\r
+        }\r
+        specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, data, resourceAuthorityEnum);\r
+\r
+        if (responseWrapper.isEmpty()) {\r
+            handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, true, resourceUniqueId);\r
+        }\r
+    }\r
+\r
+    private Either<Resource, ResponseFormat> parseToResource(String resourceJson, User user) {\r
+        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE);\r
+    }\r
+\r
+    private Either<Resource, ResponseFormat> parseToLightResource(String resourceJson, User user) {\r
+        Either<Resource, ResponseFormat> ret = getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE);\r
+        if (ret.isLeft()) {// drop unwanted data (sent from UI in update flow)\r
+            ret.left().value().setRequirements(null);\r
+            ret.left().value().setCapabilities(null);\r
+        }\r
+        return ret;\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/resources/{resourceId}")\r
+    public Response deleteResource(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}" , url);\r
+\r
+        // get modifier id\r
+        String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}" , userId);\r
+\r
+        Response response;\r
+\r
+        try {\r
+            String resourceIdLower = resourceId.toLowerCase();\r
+            ResponseFormat actionResponse = resourceBusinessLogic.deleteResource(resourceIdLower, modifier);\r
+\r
+            if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {\r
+                log.debug("failed to delete resource");\r
+                response = buildErrorResponse(actionResponse);\r
+                return response;\r
+            }\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);\r
+            return response;\r
+\r
+        } catch (JSONException e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource");\r
+            log.debug("delete resource failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/resources/{resourceName}/{version}")\r
+    public Response deleteResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("version") final String version, @Context final HttpServletRequest request) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}" , url);\r
+\r
+        // get modifier id\r
+        String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}" , userId);\r
+\r
+        Response response;\r
+        ResponseFormat actionResponse = resourceBusinessLogic.deleteResourceByNameAndVersion(resourceName, version, modifier);\r
+\r
+        if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {\r
+            log.debug("failed to delete resource");\r
+            response = buildErrorResponse(actionResponse);\r
+            return response;\r
+        }\r
+        response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);\r
+        return response;\r
+    }\r
+\r
+    @GET\r
+    @Path("/resources/{resourceId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve Resource", method = "GET", summary = "Returns resource according to resourceId",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Resource not found")})\r
+    public Response getResourceById(@PathParam("resourceId") final String resourceId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}" , url);\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}" , userId);\r
+\r
+        Response response;\r
+\r
+        try {\r
+            String resourceIdLower = resourceId.toLowerCase();\r
+            log.trace("get resource with id {}", resourceId);\r
+            Either<Resource, ResponseFormat> actionResponse = resourceBusinessLogic.getResource(resourceIdLower, modifier);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to get resource");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+            Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);\r
+\r
+        } catch (IOException e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource");\r
+            log.debug("get resource failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve Resource by name and version", method = "GET",\r
+            summary = "Returns resource according to resourceId", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Resource not found")})\r
+    public Response getResourceByNameAndVersion(@PathParam("resourceName") final String resourceName,\r
+            @PathParam("resourceVersion") final String resourceVersion, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}" , userId);\r
+        Response response;\r
+        try {\r
+            Either<Resource, ResponseFormat> actionResponse = resourceBusinessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId);\r
+            if (actionResponse.isRight()) {\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+            Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);\r
+\r
+        } catch (IOException e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource by name and version");\r
+            log.debug("get resource failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/resources/validate-name/{resourceName}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "validate resource name", method = "GET",\r
+            summary = "checks if the chosen resource name is available ", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation")})\r
+    public Response validateResourceName(@PathParam("resourceName") final String resourceName,\r
+            @QueryParam("subtype") String resourceType, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}" , url);\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}" , userId);\r
+        Response response;\r
+\r
+        if (resourceType != null && !ResourceTypeEnum.containsName(resourceType)) {\r
+            log.debug("invalid resource type received");\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+            return response;\r
+\r
+        }\r
+        ResourceTypeEnum typeEnum = null;\r
+        if (resourceType != null) {\r
+            typeEnum = ResourceTypeEnum.valueOf(resourceType);\r
+        }\r
+        Either<Map<String, Boolean>, ResponseFormat> actionResponse = resourceBusinessLogic.validateResourceNameExists(resourceName, typeEnum, userId);\r
+\r
+        if (actionResponse.isRight()) {\r
+            log.debug("failed to validate resource name");\r
+            response = buildErrorResponse(actionResponse.right().value());\r
+            return response;\r
+        }\r
+        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());\r
+    }\r
+\r
+    @GET\r
+    @Path("/resources/certified/abstract")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    public Response getCertifiedAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(get) Start handle request of {}" , url);\r
+        try {\r
+            List<Resource> resources = resourceBusinessLogic\r
+                    .getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, userId);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(resources));\r
+\r
+        } catch (IOException e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Abstract Resources");\r
+            log.debug("getCertifiedAbstractResources failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/resources/certified/notabstract")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    public Response getCertifiedNotAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(get) Start handle request of {}" , url);\r
+        try {\r
+            List<Resource> resouces = resourceBusinessLogic.getAllCertifiedResources(false, HighestFilterEnum.ALL, userId);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(resouces));\r
+\r
+        } catch (IOException e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract Resources");\r
+            log.debug("getCertifiedNotAbstractResources failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    @PUT\r
+    @Path("/resources/{resourceId}/metadata")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Resource Metadata", method = "PUT", summary = "Returns updated resource metadata",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource metadata updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content")})\r
+    public Response updateResourceMetadata(@PathParam("resourceId") final String resourceId,\r
+            @Parameter(description = "Resource metadata to be updated", required = true) String data,\r
+            @Context final HttpServletRequest request,       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}" , url);\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+        Response response;\r
+        try {\r
+            String resourceIdLower = resourceId.toLowerCase();\r
+            Either<Resource, ResponseFormat> updateInfoResource = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE);\r
+            if (updateInfoResource.isRight()) {\r
+                log.debug("failed to parse resource metadata");\r
+                response = buildErrorResponse(updateInfoResource.right().value());\r
+                return response;\r
+            }\r
+            Resource updatedResource = resourceBusinessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false);\r
+            Object resource = RepresentationUtils.toRepresentation(updatedResource);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);\r
+        } catch (IOException e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Metadata");\r
+            log.debug("Update Resource Metadata failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @PUT\r
+    @Path("/resources/{resourceId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Resource", method = "PUT", summary = "Returns updated resource",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Resource already exist")})\r
+    public Response updateResource(\r
+            @Parameter(description = "Resource object to be updated", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @PathParam(value = "resourceId") String resourceId) {\r
+\r
+        userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);\r
+        init();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+        Response response;\r
+        try {\r
+            Wrapper<Response> responseWrapper = new Wrapper<>();\r
+            // UI Import\r
+            if (isUIImport(data)) {\r
+                performUIImport(responseWrapper, data, request, userId, resourceId);\r
+            } else {\r
+                Either<Resource, ResponseFormat> convertResponse = parseToLightResource(data, modifier);\r
+                if (convertResponse.isRight()) {\r
+                    log.debug("failed to parse resource");\r
+                    response = buildErrorResponse(convertResponse.right().value());\r
+                    return response;\r
+                }\r
+                Resource updatedResource = resourceBusinessLogic.validateAndUpdateResourceFromCsar(\r
+                        convertResponse.left().value(), modifier, null, null, resourceId);\r
+                Object representation = RepresentationUtils.toRepresentation(updatedResource);\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation);\r
+                responseWrapper.setInnerElement(response);\r
+            }\r
+            return responseWrapper.getInnerElement();\r
+        } catch (IOException e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource");\r
+            log.debug("update resource failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/resources/csar/{csaruuid}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create Resource", method = "POST", summary = "Returns resource created from csar uuid",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Resource retrieced"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response getResourceFromCsar(@Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,\r
+            @PathParam(value = "csaruuid") String csarUUID) {\r
+\r
+        init();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        // retrieve user details\r
+        userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);\r
+        User user = new User();\r
+        user.setUserId(userId);\r
+\r
+        log.debug("user id is {}", userId);\r
+\r
+        Response response;\r
+\r
+        try {\r
+\r
+            Either<Resource, ResponseFormat> eitherResource =\r
+                    resourceBusinessLogic.getLatestResourceFromCsarUuid(csarUUID, user);\r
+\r
+            // validate response\r
+            if (eitherResource.isRight()) {\r
+                log.debug("failed to get resource from csarUuid : {}", csarUUID);\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                        eitherResource.right().value());\r
+            } else {\r
+                Object representation = RepresentationUtils.toRepresentation(eitherResource.left().value());\r
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation);\r
+            }\r
+\r
+            return response;\r
+\r
+        } catch (IOException e) {\r
+            log.debug("get resource by csar failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+}\r
index f87d734..3ffef17 100644 (file)
-/*
- * Copyright Â© 2016-2018 European Support Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.SELF;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonParseException;
-import com.jcabi.aspects.Loggable;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import javax.inject.Inject;
-import org.apache.commons.lang3.StringUtils;
-import org.json.simple.JSONArray;
-import org.json.simple.parser.JSONParser;
-import org.json.simple.parser.ParseException;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.OperationInput;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.tosca.ToscaFunctions;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.types.ServiceConsumptionData;
-import org.openecomp.sdc.be.types.ServiceConsumptionSource;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Service Consumption Servlet", description = "Service Consumption Servlet")
-@Singleton
-public class ServiceConsumptionServlet extends BeGenericServlet {
-
-  private static final Logger log = LoggerFactory.getLogger(ServiceConsumptionServlet.class);
-  private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic;
-    private final ServiceBusinessLogic serviceBusinessLogic;
-
-    @Inject
-    public ServiceConsumptionServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        InterfaceOperationBusinessLogic interfaceOperationBusinessLogic,
-        ServiceBusinessLogic serviceBusinessLogic) {
-        super(userBusinessLogic, componentsUtils);
-        this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic;
-        this.serviceBusinessLogic = serviceBusinessLogic;
-    }
-
-  @POST
-  @Path("/services/{serviceId}/consumption/{serviceInstanceId}")
-  @Consumes(MediaType.APPLICATION_JSON)
-  @Produces(MediaType.APPLICATION_JSON)
-  @ApiOperation(value = "Service consumption on operation", httpMethod = "POST",
-      notes = "Returns consumption data", response = Response.class)
-      @ApiResponses(value = { @ApiResponse(code = 201, message = "Service property created"),
-      @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-      @ApiResponse(code = 409, message = "Service property already exist") })
-  public Response addInputToServiceOperation(@PathParam("serviceId")final String serviceId,
-                                             @PathParam("serviceInstanceId")final String serviceInstanceId,
-                                             @ApiParam(value = "Service Consumption Data", required = true) String data,
-                                             @Context final HttpServletRequest request,
-                                             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-    ServletContext context = request.getSession().getServletContext();
-
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
-    User modifier = new User();
-    modifier.setUserId(userId);
-
-    try {
-
-      Either<Map<String, List<ServiceConsumptionData>>, ResponseFormat> dataFromJson =
-          getServiceConsumptionData(data, modifier);
-      if(dataFromJson.isRight()) {
-        return buildErrorResponse(dataFromJson.right().value());
-      }
-
-      Map<String, List<ServiceConsumptionData>> serviceConsumptionDataMap = dataFromJson.left().value();
-
-      for(Entry<String, List<ServiceConsumptionData>> consumptionEntry : serviceConsumptionDataMap.entrySet()) {
-        List<ServiceConsumptionData> consumptionList = consumptionEntry.getValue();
-        Either<List<Operation>, ResponseFormat> operationEither =
-            serviceBusinessLogic.addServiceConsumptionData(serviceId, serviceInstanceId,
-                consumptionEntry.getKey(), consumptionList, userId);
-        if (operationEither.isRight()) {
-          return buildErrorResponse(operationEither.right().value());
-        }
-      }
-
-      return buildOkResponse(serviceConsumptionDataMap);
-
-    }
-    catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Operation Inputs");
-      log.debug("Create Operation Inputs failed with exception", e);
-      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
-    }
-
-  }
-
-  @GET
-  @Path("/services/{serviceId}/consumption/{serviceInstanceId}/interfaces/{interfaceId}/operations/{operationId}/inputs")
-  @Consumes(MediaType.APPLICATION_JSON)
-  @Produces(MediaType.APPLICATION_JSON)
-  public Response getInputsListOfOperation(@PathParam("serviceId")final String serviceId,
-                                           @PathParam("serviceInstanceId")final String serviceInstanceId,
-                                           @PathParam("interfaceId")final String interfaceId,
-                                           @PathParam("operationId")final String operationId,
-                                           @Context final HttpServletRequest request,
-                                           @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug("Start handle request of {} modifier id is {}", url, userId);
-    User user = new User();
-    user.setUserId(userId);
-
-    try {
-      Either<List<OperationInputDefinition>, ResponseFormat> inputsEither =
-          interfaceOperationBusinessLogic.getInputsListForOperation(serviceId, serviceInstanceId, interfaceId, operationId, user);
-
-      if(inputsEither.isRight()) {
-        return buildErrorResponse(inputsEither.right().value());
-      }
-
-      List<OperationInputDefinition> inputs = inputsEither.left().value();
-               return buildOkResponse(updateOperationInputListForUi(inputs, interfaceOperationBusinessLogic));
-    }
-    catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Operation Inputs");
-      log.debug("Get Operation Inputs failed with exception", e);
-      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
-    }
-  }
-
-       private List<OperationInput> updateOperationInputListForUi(List<OperationInputDefinition> inputsList,
-                                                                                                                          InterfaceOperationBusinessLogic interfaceOperationBL) {
-               List<OperationInput> operationInputs = new ArrayList<>();
-               for(OperationInputDefinition input : inputsList) {
-
-                       String value = input.getValue();
-
-                       // Additional UI mapping needed for other sources
-                       if (StringUtils.isNotBlank(value)
-                                       && !ServiceConsumptionSource.STATIC.getSource().equals(input.getSource())) {
-                               uiMappingForOtherSources(value, input);
-                       }
-
-                       // Add Constraint for UI
-                       OperationInput operationInput = new OperationInput(input);
-                       operationInput.setConstraints(interfaceOperationBL.setInputConstraint(input));
-                       operationInputs.add(operationInput);
-               }
-
-               return operationInputs;
-       }
-
-       private void uiMappingForOtherSources(String value, OperationInputDefinition input) {
-               try {
-                       Map<String, Object> valueAsMap = (new Gson()).fromJson(value, Map.class);
-                       String toscaFunction = valueAsMap.keySet().iterator().next();
-                       Object consumptionValueName = valueAsMap.values().iterator().next();
-                       if(consumptionValueName instanceof List) {
-                               List<Object> toscaFunctionList = (List<Object>) consumptionValueName;
-                               String consumptionInputValue = null;
-                               if (ToscaFunctions.GET_PROPERTY.getFunctionName().equals(toscaFunction)) {
-                                       String propertyValue = toscaFunctionList.stream()
-                                                       .map(Object::toString)
-                                                       .filter(val -> !val.equals(SELF))
-                                                       .collect(Collectors.joining("_"));
-                                       consumptionInputValue = String.valueOf(propertyValue);
-                               } else if (ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName().equals(toscaFunction)) {
-                                       //Return full output name
-                                       consumptionInputValue =
-                                                       toscaFunctionList.get(1) + "." + toscaFunctionList.get(2) + "." +toscaFunctionList.get(3);
-                               }
-                               input.setValue(consumptionInputValue);
-                       } else {
-                               input.setValue(String.valueOf(consumptionValueName));
-                       }
-               }
-               catch(JsonParseException ex){
-                       log.info("This means it is static value for which no changes are needed");
-               }
-       }
-
-  private Either<Map<String, List<ServiceConsumptionData>>, ResponseFormat> getServiceConsumptionData(String data,
-                                                                                                      User user) {
-    JSONParser parser = new JSONParser();
-    Map<String, List<ServiceConsumptionData>> serviceConsumptionDataMap = new HashMap<>();
-
-    try {
-      JSONArray operationsArray = (JSONArray) parser.parse(data);
-      Iterator iterator = operationsArray.iterator();
-      while (iterator.hasNext()) {
-        Map next = (Map) iterator.next();
-        Entry consumptionEntry = (Entry) next.entrySet().iterator().next();
-        String operationId = (String) consumptionEntry.getKey();
-        Object value = consumptionEntry.getValue();
-
-        JSONArray inputsArray = (JSONArray) parser.parse(value.toString());
-        serviceConsumptionDataMap.putIfAbsent(operationId, new ArrayList<>());
-        for(Object consumptionObject : inputsArray) {
-          Either<ServiceConsumptionData, ResponseFormat> serviceDataEither =
-              getComponentsUtils()
-                  .convertJsonToObjectUsingObjectMapper(consumptionObject.toString(), user, ServiceConsumptionData
-                      .class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
-          if(serviceDataEither.isRight()) {
-            return Either.right(serviceDataEither.right().value());
-          }
-
-          serviceConsumptionDataMap.get(operationId).add(serviceDataEither.left().value());
-        }
-      }
-    }
-    catch (ParseException e) {
-      log.info("Conetnt is invalid - {}", data);
-      return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-    }
-    return Either.left(serviceConsumptionDataMap);
-  }
-}
+/*\r
+ * Copyright Â© 2016-2018 European Support Limited\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except\r
+ * in compliance with the License. You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software distributed under the License\r
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\r
+ * or implied. See the License for the specific language governing permissions and limitations under\r
+ * the License.\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.SELF;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Map.Entry;\r
+import java.util.stream.Collectors;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.lang3.StringUtils;\r
+import org.json.simple.JSONArray;\r
+import org.json.simple.parser.JSONParser;\r
+import org.json.simple.parser.ParseException;\r
+import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.model.Operation;\r
+import org.openecomp.sdc.be.model.OperationInput;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.model.tosca.ToscaFunctions;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.types.ServiceConsumptionData;\r
+import org.openecomp.sdc.be.types.ServiceConsumptionSource;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+import com.google.gson.Gson;\r
+import com.google.gson.JsonParseException;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Service Consumption Servlet", description = "Service Consumption Servlet"))\r
+@Singleton\r
+public class ServiceConsumptionServlet extends BeGenericServlet {\r
+\r
+    private static final Logger log = LoggerFactory.getLogger(ServiceConsumptionServlet.class);\r
+    private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic;\r
+    private final ServiceBusinessLogic serviceBusinessLogic;\r
+\r
+    @Inject\r
+    public ServiceConsumptionServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils,\r
+            InterfaceOperationBusinessLogic interfaceOperationBusinessLogic,\r
+            ServiceBusinessLogic serviceBusinessLogic) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic;\r
+        this.serviceBusinessLogic = serviceBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Path("/services/{serviceId}/consumption/{serviceInstanceId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @io.swagger.v3.oas.annotations.Operation(description = "Service consumption on operation", method = "POST",\r
+            summary = "Returns consumption data", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Service property created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Service property already exist")})\r
+    public Response addInputToServiceOperation(@PathParam("serviceId") final String serviceId,\r
+            @PathParam("serviceInstanceId") final String serviceInstanceId,\r
+            @Parameter(description = "Service Consumption Data", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+\r
+        try {\r
+\r
+            Either<Map<String, List<ServiceConsumptionData>>, ResponseFormat> dataFromJson =\r
+                    getServiceConsumptionData(data, modifier);\r
+            if (dataFromJson.isRight()) {\r
+                return buildErrorResponse(dataFromJson.right().value());\r
+            }\r
+\r
+            Map<String, List<ServiceConsumptionData>> serviceConsumptionDataMap = dataFromJson.left().value();\r
+\r
+            for (Entry<String, List<ServiceConsumptionData>> consumptionEntry : serviceConsumptionDataMap.entrySet()) {\r
+                List<ServiceConsumptionData> consumptionList = consumptionEntry.getValue();\r
+                Either<List<Operation>, ResponseFormat> operationEither =\r
+                        serviceBusinessLogic.addServiceConsumptionData(serviceId, serviceInstanceId,\r
+                                consumptionEntry.getKey(), consumptionList, userId);\r
+                if (operationEither.isRight()) {\r
+                    return buildErrorResponse(operationEither.right().value());\r
+                }\r
+            }\r
+\r
+            return buildOkResponse(serviceConsumptionDataMap);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Operation Inputs");\r
+            log.debug("Create Operation Inputs failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+\r
+    }\r
+\r
+    @GET\r
+    @Path("/services/{serviceId}/consumption/{serviceInstanceId}/interfaces/{interfaceId}/operations/{operationId}/inputs")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    public Response getInputsListOfOperation(@PathParam("serviceId") final String serviceId,\r
+            @PathParam("serviceInstanceId") final String serviceInstanceId,\r
+            @PathParam("interfaceId") final String interfaceId, @PathParam("operationId") final String operationId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {} modifier id is {}", url, userId);\r
+        User user = new User();\r
+        user.setUserId(userId);\r
+\r
+        try {\r
+            Either<List<OperationInputDefinition>, ResponseFormat> inputsEither = interfaceOperationBusinessLogic\r
+                    .getInputsListForOperation(serviceId, serviceInstanceId, interfaceId, operationId, user);\r
+\r
+            if (inputsEither.isRight()) {\r
+                return buildErrorResponse(inputsEither.right().value());\r
+            }\r
+\r
+            List<OperationInputDefinition> inputs = inputsEither.left().value();\r
+            return buildOkResponse(updateOperationInputListForUi(inputs, interfaceOperationBusinessLogic));\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Operation Inputs");\r
+            log.debug("Get Operation Inputs failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+    }\r
+\r
+    private List<OperationInput> updateOperationInputListForUi(List<OperationInputDefinition> inputsList,\r
+            InterfaceOperationBusinessLogic interfaceOperationBL) {\r
+        List<OperationInput> operationInputs = new ArrayList<>();\r
+        for (OperationInputDefinition input : inputsList) {\r
+\r
+            String value = input.getValue();\r
+\r
+            // Additional UI mapping needed for other sources\r
+            if (StringUtils.isNotBlank(value)\r
+                    && !ServiceConsumptionSource.STATIC.getSource().equals(input.getSource())) {\r
+                uiMappingForOtherSources(value, input);\r
+            }\r
+\r
+            // Add Constraint for UI\r
+            OperationInput operationInput = new OperationInput(input);\r
+            operationInput.setConstraints(interfaceOperationBL.setInputConstraint(input));\r
+            operationInputs.add(operationInput);\r
+        }\r
+\r
+        return operationInputs;\r
+    }\r
+\r
+    private void uiMappingForOtherSources(String value, OperationInputDefinition input) {\r
+        try {\r
+            Map<String, Object> valueAsMap = (new Gson()).fromJson(value, Map.class);\r
+            String toscaFunction = valueAsMap.keySet().iterator().next();\r
+            Object consumptionValueName = valueAsMap.values().iterator().next();\r
+            if (consumptionValueName instanceof List) {\r
+                List<Object> toscaFunctionList = (List<Object>) consumptionValueName;\r
+                String consumptionInputValue = null;\r
+                if (ToscaFunctions.GET_PROPERTY.getFunctionName().equals(toscaFunction)) {\r
+                    String propertyValue = toscaFunctionList.stream().map(Object::toString)\r
+                            .filter(val -> !val.equals(SELF)).collect(Collectors.joining("_"));\r
+                    consumptionInputValue = String.valueOf(propertyValue);\r
+                } else if (ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName().equals(toscaFunction)) {\r
+                    // Return full output name\r
+                    consumptionInputValue =\r
+                            toscaFunctionList.get(1) + "." + toscaFunctionList.get(2) + "." + toscaFunctionList.get(3);\r
+                }\r
+                input.setValue(consumptionInputValue);\r
+            } else {\r
+                input.setValue(String.valueOf(consumptionValueName));\r
+            }\r
+        } catch (JsonParseException ex) {\r
+            log.info("This means it is static value for which no changes are needed");\r
+        }\r
+    }\r
+\r
+    private Either<Map<String, List<ServiceConsumptionData>>, ResponseFormat> getServiceConsumptionData(String data,\r
+            User user) {\r
+        JSONParser parser = new JSONParser();\r
+        Map<String, List<ServiceConsumptionData>> serviceConsumptionDataMap = new HashMap<>();\r
+\r
+        try {\r
+            JSONArray operationsArray = (JSONArray) parser.parse(data);\r
+            Iterator iterator = operationsArray.iterator();\r
+            while (iterator.hasNext()) {\r
+                Map next = (Map) iterator.next();\r
+                Entry consumptionEntry = (Entry) next.entrySet().iterator().next();\r
+                String operationId = (String) consumptionEntry.getKey();\r
+                Object value = consumptionEntry.getValue();\r
+\r
+                JSONArray inputsArray = (JSONArray) parser.parse(value.toString());\r
+                serviceConsumptionDataMap.putIfAbsent(operationId, new ArrayList<>());\r
+                for (Object consumptionObject : inputsArray) {\r
+                    Either<ServiceConsumptionData, ResponseFormat> serviceDataEither =\r
+                            getComponentsUtils().convertJsonToObjectUsingObjectMapper(consumptionObject.toString(),\r
+                                    user, ServiceConsumptionData.class, AuditingActionEnum.CREATE_RESOURCE,\r
+                                    ComponentTypeEnum.SERVICE);\r
+                    if (serviceDataEither.isRight()) {\r
+                        return Either.right(serviceDataEither.right().value());\r
+                    }\r
+\r
+                    serviceConsumptionDataMap.get(operationId).add(serviceDataEither.left().value());\r
+                }\r
+            }\r
+        } catch (ParseException e) {\r
+            log.info("Conetnt is invalid - {}", data);\r
+            return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+        }\r
+        return Either.left(serviceConsumptionDataMap);\r
+    }\r
+}\r
index 08485a2..7c22d62 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.utils.NodeFilterConstraintAction;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datamodel.utils.ConstraintConvertor;
-import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.tosca.utils.NodeFilterConverter;
-import org.openecomp.sdc.be.ui.model.UIConstraint;
-import org.openecomp.sdc.be.ui.model.UINodeFilter;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Path("/v1/catalog/services/{serviceId}/resourceInstances/{resourceInstanceId}/nodeFilter")
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-@Api(value = "Service Filter", description = "Service Filter Servlet")
-@Singleton
-public class ServiceFilterServlet extends AbstractValidationsServlet {
-
-    private static final Logger log = LoggerFactory.getLogger(ServiceFilterServlet.class);
-    private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
-    private static final String MODIFIER_ID_IS = "modifier id is {}";
-    private static final String FAILED_TO_UPDATE_OR_CREATE_NODE_FILTER = "failed to update or create node filter";
-    private static final String FAILED_TO_PARSE_SERVICE = "failed to parse service";
-    private static final String NODE_FILTER_CREATION_OR_UPDATE = "Node Filter Creation or update";
-    private static final String CREATE_OR_UPDATE_NODE_FILTER_WITH_AN_ERROR =
-            "create or update node filter with an error";
-    private final ServiceBusinessLogic serviceBusinessLogic;
-
-    @Inject
-    public ServiceFilterServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        ServiceBusinessLogic serviceBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.serviceBusinessLogic = serviceBusinessLogic;
-    }
-
-    @POST
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/")
-    @ApiOperation(value = "Add Service Filter Constraint", httpMethod = "POST", notes = "Add Service Filter Constraint",
-            response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Service Filter"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response addServiceFilterConstraint(@ApiParam(value = "Service data", required = true) String data,
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @ApiParam(value = "Resource Instance Id") @PathParam("resourceInstanceId") String ciId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-        final HttpSession session = request.getSession();
-        ServletContext context = session.getServletContext();
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug(MODIFIER_ID_IS, userId);
-
-        Response response;
-
-        try {
-            String serviceIdLower = serviceId.toLowerCase();
-
-            Either<UIConstraint, ResponseFormat> convertResponse = parseToConstraint(data, modifier);
-            if (convertResponse.isRight()) {
-                log.debug(FAILED_TO_PARSE_SERVICE);
-                response = buildErrorResponse(convertResponse.right().value());
-                return response;
-            }
-            UIConstraint uiConstraint = convertResponse.left().value();
-            if (uiConstraint == null) {
-                log.debug(FAILED_TO_PARSE_SERVICE);
-                response = buildErrorResponse(convertResponse.right().value());
-                return response;
-            }
-            Either<CINodeFilterDataDefinition, ResponseFormat> actionResponse;
-            String constraint = new ConstraintConvertor().convert(uiConstraint);
-            actionResponse = serviceBusinessLogic
-                                     .addOrDeleteServiceFilter(serviceIdLower, ciId, NodeFilterConstraintAction.ADD, uiConstraint.getServicePropertyName(),
-                                             constraint, -1, modifier, true);
-
-            if (actionResponse.isRight()) {
-                log.debug(FAILED_TO_UPDATE_OR_CREATE_NODE_FILTER);
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            CINodeFilterDataDefinition value = actionResponse.left().value();
-            UINodeFilter nodeFilter = new NodeFilterConverter().convertToUi(value);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeFilter);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION_OR_UPDATE);
-            log.debug(CREATE_OR_UPDATE_NODE_FILTER_WITH_AN_ERROR, e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @PUT
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/")
-    @ApiOperation(value = "Update Service Filter Constraint", httpMethod = "PUT",
-            notes = "Update Service Filter Constraint", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Service Filter"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response updateServiceFilterConstraint(@ApiParam(value = "Service data", required = true) String data,
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @ApiParam(value = "Resource Instance Id") @PathParam("resourceInstanceId") String ciId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug(MODIFIER_ID_IS, userId);
-
-        Response response;
-
-        try {
-            String serviceIdLower = serviceId.toLowerCase();
-
-            Either<List, ResponseFormat> convertResponse = parseToConstraints(data, modifier);
-            if (convertResponse.isRight()) {
-                log.debug(FAILED_TO_PARSE_SERVICE);
-                response = buildErrorResponse(convertResponse.right().value());
-                return response;
-            }
-            List<Map<String,String>> uiConstraintsMaps = (List<Map<String,String>>) convertResponse.left().value();
-            if (uiConstraintsMaps == null) {
-                log.debug("failed to parse data");
-                response = buildErrorResponse(convertResponse.right().value());
-                return response;
-            }
-            final ObjectMapper objectMapper = new ObjectMapper();
-            List<UIConstraint> uiConstraints = uiConstraintsMaps.stream().map(dataMap -> objectMapper.convertValue(dataMap, UIConstraint.class)).collect(
-                    Collectors.toList());
-            if (uiConstraints == null) {
-                log.debug("failed to parse data");
-                response = buildErrorResponse(convertResponse.right().value());
-                return response;
-            }
-            Either<CINodeFilterDataDefinition, ResponseFormat> actionResponse;
-            List<String> constraints = new ConstraintConvertor().convertToList(uiConstraints);
-            actionResponse = serviceBusinessLogic.updateServiceFilter(serviceIdLower, ciId, constraints, modifier, true);
-
-            if (actionResponse.isRight()) {
-                log.debug(FAILED_TO_UPDATE_OR_CREATE_NODE_FILTER);
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            CINodeFilterDataDefinition value = actionResponse.left().value();
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    new NodeFilterConverter().convertToUi(value));
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION_OR_UPDATE);
-            log.debug(CREATE_OR_UPDATE_NODE_FILTER_WITH_AN_ERROR, e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @DELETE
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/{constraintIndex}")
-    @ApiOperation(value = "Delete Service Filter Constraint", httpMethod = "Delete",
-            notes = "Delete Service Filter Constraint", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete Service Filter Constraint"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content")})
-    public Response deleteServiceFilterConstraint(
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @ApiParam(value = "Resource Instance Id") @PathParam("resourceInstanceId") String ciId,
-            @ApiParam(value = "Constraint Index") @PathParam("constraintIndex") int index,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug(MODIFIER_ID_IS, userId);
-
-        Response response;
-
-        try {
-            String serviceIdLower = serviceId.toLowerCase();
-
-            Either<CINodeFilterDataDefinition, ResponseFormat> actionResponse;
-            actionResponse = serviceBusinessLogic
-                                     .addOrDeleteServiceFilter(serviceIdLower, ciId, NodeFilterConstraintAction.DELETE,
-                                             null, null,  index, modifier, true);
-
-            if (actionResponse.isRight()) {
-
-                log.debug(FAILED_TO_UPDATE_OR_CREATE_NODE_FILTER);
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            final CINodeFilterDataDefinition value = actionResponse.left().value();
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    new NodeFilterConverter().convertToUi(value));
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION_OR_UPDATE);
-            log.debug(CREATE_OR_UPDATE_NODE_FILTER_WITH_AN_ERROR, e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    private Either<UIConstraint, ResponseFormat> parseToConstraint(String serviceJson, User user) {
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, UIConstraint.class,
-                AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
-    }
-
-    private Either<List, ResponseFormat> parseToConstraints(String serviceJson, User user) {
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, List.class,
-                AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.stream.Collectors;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpSession;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.codehaus.jackson.map.ObjectMapper;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.utils.NodeFilterConstraintAction;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datamodel.utils.ConstraintConvertor;\r
+import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.tosca.utils.NodeFilterConverter;\r
+import org.openecomp.sdc.be.ui.model.UIConstraint;\r
+import org.openecomp.sdc.be.ui.model.UINodeFilter;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Path("/v1/catalog/services/{serviceId}/resourceInstances/{resourceInstanceId}/nodeFilter")\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+@OpenAPIDefinition(info = @Info(title = "Service Filter", description = "Service Filter Servlet"))\r
+@Singleton\r
+public class ServiceFilterServlet extends AbstractValidationsServlet {\r
+\r
+    private static final Logger log = LoggerFactory.getLogger(ServiceFilterServlet.class);\r
+    private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";\r
+    private static final String MODIFIER_ID_IS = "modifier id is {}";\r
+    private static final String FAILED_TO_UPDATE_OR_CREATE_NODE_FILTER = "failed to update or create node filter";\r
+    private static final String FAILED_TO_PARSE_SERVICE = "failed to parse service";\r
+    private static final String NODE_FILTER_CREATION_OR_UPDATE = "Node Filter Creation or update";\r
+    private static final String CREATE_OR_UPDATE_NODE_FILTER_WITH_AN_ERROR =\r
+            "create or update node filter with an error";\r
+    private final ServiceBusinessLogic serviceBusinessLogic;\r
+\r
+    @Inject\r
+    public ServiceFilterServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        ServiceBusinessLogic serviceBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.serviceBusinessLogic = serviceBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/")\r
+    @Operation(description = "Add Service Filter Constraint", method = "POST", summary = "Add Service Filter Constraint",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Create Service Filter"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response addServiceFilterConstraint(@Parameter(description = "Service data", required = true) String data,\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Parameter(description = "Resource Instance Id") @PathParam("resourceInstanceId") String ciId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+        final HttpSession session = request.getSession();\r
+        ServletContext context = session.getServletContext();\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug(MODIFIER_ID_IS, userId);\r
+\r
+        Response response;\r
+\r
+        try {\r
+            String serviceIdLower = serviceId.toLowerCase();\r
+\r
+            Either<UIConstraint, ResponseFormat> convertResponse = parseToConstraint(data, modifier);\r
+            if (convertResponse.isRight()) {\r
+                log.debug(FAILED_TO_PARSE_SERVICE);\r
+                response = buildErrorResponse(convertResponse.right().value());\r
+                return response;\r
+            }\r
+            UIConstraint uiConstraint = convertResponse.left().value();\r
+            if (uiConstraint == null) {\r
+                log.debug(FAILED_TO_PARSE_SERVICE);\r
+                response = buildErrorResponse(convertResponse.right().value());\r
+                return response;\r
+            }\r
+            Either<CINodeFilterDataDefinition, ResponseFormat> actionResponse;\r
+            String constraint = new ConstraintConvertor().convert(uiConstraint);\r
+            actionResponse = serviceBusinessLogic\r
+                                     .addOrDeleteServiceFilter(serviceIdLower, ciId, NodeFilterConstraintAction.ADD, uiConstraint.getServicePropertyName(),\r
+                                             constraint, -1, modifier, true);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug(FAILED_TO_UPDATE_OR_CREATE_NODE_FILTER);\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            CINodeFilterDataDefinition value = actionResponse.left().value();\r
+            UINodeFilter nodeFilter = new NodeFilterConverter().convertToUi(value);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeFilter);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION_OR_UPDATE);\r
+            log.debug(CREATE_OR_UPDATE_NODE_FILTER_WITH_AN_ERROR, e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @PUT\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/")\r
+    @Operation(description = "Update Service Filter Constraint", method = "PUT",\r
+            summary = "Update Service Filter Constraint", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Create Service Filter"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateServiceFilterConstraint(@Parameter(description = "Service data", required = true) String data,\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Parameter(description = "Resource Instance Id") @PathParam("resourceInstanceId") String ciId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug(MODIFIER_ID_IS, userId);\r
+\r
+        Response response;\r
+\r
+        try {\r
+            String serviceIdLower = serviceId.toLowerCase();\r
+\r
+            Either<List, ResponseFormat> convertResponse = parseToConstraints(data, modifier);\r
+            if (convertResponse.isRight()) {\r
+                log.debug(FAILED_TO_PARSE_SERVICE);\r
+                response = buildErrorResponse(convertResponse.right().value());\r
+                return response;\r
+            }\r
+            List<Map<String,String>> uiConstraintsMaps = (List<Map<String,String>>) convertResponse.left().value();\r
+            if (uiConstraintsMaps == null) {\r
+                log.debug("failed to parse data");\r
+                response = buildErrorResponse(convertResponse.right().value());\r
+                return response;\r
+            }\r
+            final ObjectMapper objectMapper = new ObjectMapper();\r
+            List<UIConstraint> uiConstraints = uiConstraintsMaps.stream().map(dataMap -> objectMapper.convertValue(dataMap, UIConstraint.class)).collect(\r
+                    Collectors.toList());\r
+            if (uiConstraints == null) {\r
+                log.debug("failed to parse data");\r
+                response = buildErrorResponse(convertResponse.right().value());\r
+                return response;\r
+            }\r
+            Either<CINodeFilterDataDefinition, ResponseFormat> actionResponse;\r
+            List<String> constraints = new ConstraintConvertor().convertToList(uiConstraints);\r
+            actionResponse = serviceBusinessLogic.updateServiceFilter(serviceIdLower, ciId, constraints, modifier, true);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug(FAILED_TO_UPDATE_OR_CREATE_NODE_FILTER);\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            CINodeFilterDataDefinition value = actionResponse.left().value();\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    new NodeFilterConverter().convertToUi(value));\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION_OR_UPDATE);\r
+            log.debug(CREATE_OR_UPDATE_NODE_FILTER_WITH_AN_ERROR, e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/{constraintIndex}")\r
+    @Operation(description = "Delete Service Filter Constraint", method = "Delete",\r
+            summary = "Delete Service Filter Constraint", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Delete Service Filter Constraint"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response deleteServiceFilterConstraint(\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Parameter(description = "Resource Instance Id") @PathParam("resourceInstanceId") String ciId,\r
+            @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug(MODIFIER_ID_IS, userId);\r
+\r
+        Response response;\r
+\r
+        try {\r
+            String serviceIdLower = serviceId.toLowerCase();\r
+\r
+            Either<CINodeFilterDataDefinition, ResponseFormat> actionResponse;\r
+            actionResponse = serviceBusinessLogic\r
+                                     .addOrDeleteServiceFilter(serviceIdLower, ciId, NodeFilterConstraintAction.DELETE,\r
+                                             null, null,  index, modifier, true);\r
+\r
+            if (actionResponse.isRight()) {\r
+\r
+                log.debug(FAILED_TO_UPDATE_OR_CREATE_NODE_FILTER);\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            final CINodeFilterDataDefinition value = actionResponse.left().value();\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    new NodeFilterConverter().convertToUi(value));\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION_OR_UPDATE);\r
+            log.debug(CREATE_OR_UPDATE_NODE_FILTER_WITH_AN_ERROR, e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    private Either<UIConstraint, ResponseFormat> parseToConstraint(String serviceJson, User user) {\r
+        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, UIConstraint.class,\r
+                AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);\r
+    }\r
+\r
+    private Either<List, ResponseFormat> parseToConstraints(String serviceJson, User user) {\r
+        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, List.class,\r
+                AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);\r
+    }\r
+}\r
index a9c257f..22054f6 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-
-import com.google.common.collect.Sets;
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.apache.commons.collections.MapUtils;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
-import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.Collections;
-import java.util.Set;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog/services/{serviceId}/paths")
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-@Api(value = "Service Forwarding Path", description = "Service Forwarding Path Servlet")
-@Singleton
-public class ServiceForwardingPathServlet extends AbstractValidationsServlet {
-
-    private static final Logger log = Logger.getLogger(ServiceForwardingPathServlet.class);
-    private final ServiceBusinessLogic serviceBusinessLogic;
-
-    @Inject
-    public ServiceForwardingPathServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        ServiceBusinessLogic serviceBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.serviceBusinessLogic = serviceBusinessLogic;
-    }
-
-    @POST
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/")
-    @ApiOperation(value = "Create Forwarding Path", httpMethod = "POST", notes = "Create Forwarding Path", response = Service.class)
-    @ApiResponses(value =
-            {@ApiResponse(code = 201, message = "Create Forwarding Path"),
-                    @ApiResponse(code = 403, message = "Restricted operation"),
-                    @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-                    @ApiResponse(code = 409, message = "Forwarding Path already exist")})
-    public Response createForwardingPath(
-            @ApiParam(value = "Forwarding Path to create", required = true) String data,
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, serviceId, request, userId, false);
-    }
-
-
-
-    @PUT
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/")
-    @ApiOperation(value = "Update Forwarding Path", httpMethod = "PUT", notes = "Update Forwarding Path", response = Service.class)
-    @ApiResponses(value =
-            {@ApiResponse(code = 201, message = "Update Forwarding Path"),
-                    @ApiResponse(code = 403, message = "Restricted operation"),
-                    @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-                    @ApiResponse(code = 409, message = "Forwarding Path already exist")})
-    public Response updateForwardingPath(
-            @ApiParam(value = "Update Path to create", required = true) String data,
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, serviceId, request, userId, true);
-    }
-
-    private Response createOrUpdate( String data, String serviceId, HttpServletRequest request, String userId, boolean isUpdate) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response;
-
-        try {
-            String serviceIdLower = serviceId.toLowerCase();
-
-            Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
-            if (convertResponse.isRight()) {
-                log.debug("failed to parse service");
-                response = buildErrorResponse(convertResponse.right().value());
-                return response;
-            }
-            Service updatedService = convertResponse.left().value();
-            Either<Service, ResponseFormat> actionResponse ;
-            if (isUpdate) {
-                actionResponse = serviceBusinessLogic.updateForwardingPath(serviceIdLower, updatedService, modifier, true);
-            } else {
-                actionResponse = serviceBusinessLogic.createForwardingPath(serviceIdLower, updatedService, modifier, true);
-            }
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to update or create paths");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            Service service = actionResponse.left().value();
-            Object result = RepresentationUtils.toRepresentation(service);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Forward Path Creation or update");
-            log.debug("create or update forwarding path with an error", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @GET
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/{forwardingPathId}")
-    @ApiOperation(value = "Get Forwarding Path", httpMethod = "GET", notes = "GET Forwarding Path", response = ForwardingPathDataDefinition.class)
-    @ApiResponses(value =
-            {@ApiResponse(code = 201, message = "Get Forwarding Path"),
-                    @ApiResponse(code = 403, message = "Restricted operation"),
-                    @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-                    @ApiResponse(code = 409, message = "Forwarding Path already exist")})
-    public Response getForwardingPath(
-            @ApiParam(value = "Forwarding Path to create", required = true) String datax,
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @ApiParam(value = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-
-        try {
-            Either<UiComponentDataTransfer, ResponseFormat> serviceResponse = serviceBusinessLogic.getComponentDataFilteredByParams(serviceId, modifier, Collections.singletonList(ComponentFieldsEnum.FORWARDING_PATHS.getValue()));
-            if (serviceResponse.isRight()) {
-                return buildErrorResponse(serviceResponse.right().value());
-            }
-
-            UiServiceDataTransfer uiServiceDataTransfer = (UiServiceDataTransfer) serviceResponse.left().value();
-
-            ForwardingPathDataDefinition forwardingPathDataDefinition = new ForwardingPathDataDefinition();
-            if (!MapUtils.isEmpty(uiServiceDataTransfer.getForwardingPaths())) {
-                forwardingPathDataDefinition = uiServiceDataTransfer.getForwardingPaths().get(forwardingPathId);
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(forwardingPathDataDefinition));
-
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
-            log.debug("update service metadata failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @DELETE
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Path("/{forwardingPathId}")
-    @ApiOperation(value = "Delete Forwarding Path", httpMethod = "DELETE", notes = "Delete Forwarding Path", response = Service.class)
-    @ApiResponses(value =
-            {@ApiResponse(code = 201, message = "Delete Forwarding Path"),
-                    @ApiResponse(code = 403, message = "Restricted operation"),
-                    @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-                    @ApiResponse(code = 409, message = "Forwarding Path already exist")})
-    public Response deleteForwardingPath(
-            @ApiParam(value = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,
-            @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response;
-
-        try {
-            String serviceIdLower = serviceId.toLowerCase();
-
-            Either<Set<String>, ResponseFormat> actionResponse = serviceBusinessLogic.deleteForwardingPaths(serviceIdLower, Sets.newHashSet(forwardingPathId), modifier, true);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to delete paths");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            Set<String> deletedPaths = actionResponse.left().value();
-            Object result = RepresentationUtils.toRepresentation(deletedPaths);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete forward paths");
-            log.debug("Delete service paths with an error", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-
-    private Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);//TODO: change sSERVICE constant
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+\r
+import java.util.Collections;\r
+import java.util.Set;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.collections.MapUtils;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.Service;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;\r
+import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.google.common.collect.Sets;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog/services/{serviceId}/paths")\r
+@Consumes(MediaType.APPLICATION_JSON)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+@OpenAPIDefinition(info = @Info(title = "Service Forwarding Path", description = "Service Forwarding Path Servlet"))\r
+@Singleton\r
+public class ServiceForwardingPathServlet extends AbstractValidationsServlet {\r
+\r
+    private static final Logger log = Logger.getLogger(ServiceForwardingPathServlet.class);\r
+    private final ServiceBusinessLogic serviceBusinessLogic;\r
+\r
+    @Inject\r
+    public ServiceForwardingPathServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        ServiceBusinessLogic serviceBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.serviceBusinessLogic = serviceBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/")\r
+    @Operation(description = "Create Forwarding Path", method = "POST", summary = "Create Forwarding Path",responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))))\r
+    @ApiResponses(value =\r
+            {@ApiResponse(responseCode = "201", description = "Create Forwarding Path"),\r
+                    @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+                    @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})\r
+    public Response createForwardingPath(\r
+            @Parameter(description = "Forwarding Path to create", required = true) String data,\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return createOrUpdate(data, serviceId, request, userId, false);\r
+    }\r
+\r
+\r
+\r
+    @PUT\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/")\r
+    @Operation(description = "Update Forwarding Path", method = "PUT", summary = "Update Forwarding Path",responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))))\r
+    @ApiResponses(value =\r
+            {@ApiResponse(responseCode = "201", description = "Update Forwarding Path"),\r
+                    @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+                    @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})\r
+    public Response updateForwardingPath(\r
+            @Parameter(description = "Update Path to create", required = true) String data,\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        return createOrUpdate(data, serviceId, request, userId, true);\r
+    }\r
+\r
+    private Response createOrUpdate( String data, String serviceId, HttpServletRequest request, String userId, boolean isUpdate) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response;\r
+\r
+        try {\r
+            String serviceIdLower = serviceId.toLowerCase();\r
+\r
+            Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);\r
+            if (convertResponse.isRight()) {\r
+                log.debug("failed to parse service");\r
+                response = buildErrorResponse(convertResponse.right().value());\r
+                return response;\r
+            }\r
+            Service updatedService = convertResponse.left().value();\r
+            Either<Service, ResponseFormat> actionResponse ;\r
+            if (isUpdate) {\r
+                actionResponse = serviceBusinessLogic.updateForwardingPath(serviceIdLower, updatedService, modifier, true);\r
+            } else {\r
+                actionResponse = serviceBusinessLogic.createForwardingPath(serviceIdLower, updatedService, modifier, true);\r
+            }\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to update or create paths");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            Service service = actionResponse.left().value();\r
+            Object result = RepresentationUtils.toRepresentation(service);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Forward Path Creation or update");\r
+            log.debug("create or update forwarding path with an error", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/{forwardingPathId}")\r
+    @Operation(description = "Get Forwarding Path", method = "GET", summary = "GET Forwarding Path",responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = ForwardingPathDataDefinition.class)))))\r
+    @ApiResponses(value =\r
+            {@ApiResponse(responseCode = "201", description = "Get Forwarding Path"),\r
+                    @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+                    @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})\r
+    public Response getForwardingPath(\r
+            @Parameter(description = "Forwarding Path to create", required = true) String datax,\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Parameter(description = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+\r
+        try {\r
+            Either<UiComponentDataTransfer, ResponseFormat> serviceResponse = serviceBusinessLogic.getComponentDataFilteredByParams(serviceId, modifier, Collections.singletonList(ComponentFieldsEnum.FORWARDING_PATHS.getValue()));\r
+            if (serviceResponse.isRight()) {\r
+                return buildErrorResponse(serviceResponse.right().value());\r
+            }\r
+\r
+            UiServiceDataTransfer uiServiceDataTransfer = (UiServiceDataTransfer) serviceResponse.left().value();\r
+\r
+            ForwardingPathDataDefinition forwardingPathDataDefinition = new ForwardingPathDataDefinition();\r
+            if (!MapUtils.isEmpty(uiServiceDataTransfer.getForwardingPaths())) {\r
+                forwardingPathDataDefinition = uiServiceDataTransfer.getForwardingPaths().get(forwardingPathId);\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(forwardingPathDataDefinition));\r
+\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");\r
+            log.debug("update service metadata failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Path("/{forwardingPathId}")\r
+    @Operation(description = "Delete Forwarding Path", method = "DELETE", summary = "Delete Forwarding Path",responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))))\r
+    @ApiResponses(value =\r
+            {@ApiResponse(responseCode = "201", description = "Delete Forwarding Path"),\r
+                    @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+                    @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})\r
+    public Response deleteForwardingPath(\r
+            @Parameter(description = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,\r
+            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response;\r
+\r
+        try {\r
+            String serviceIdLower = serviceId.toLowerCase();\r
+\r
+            Either<Set<String>, ResponseFormat> actionResponse = serviceBusinessLogic.deleteForwardingPaths(serviceIdLower, Sets.newHashSet(forwardingPathId), modifier, true);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to delete paths");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            Set<String> deletedPaths = actionResponse.left().value();\r
+            Object result = RepresentationUtils.toRepresentation(deletedPaths);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete forward paths");\r
+            log.debug("Delete service paths with an error", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+\r
+    private Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {\r
+        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);//TODO: change sSERVICE constant\r
+    }\r
+}\r
index 9e960b0..8e71775 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.gson.reflect.TypeToken;
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import javax.inject.Inject;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import org.apache.http.HttpStatus;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datamodel.ServiceRelations;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.GroupInstanceProperty;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Service Catalog", description = "Service Servlet")
-@Singleton
-public class ServiceServlet extends AbstractValidationsServlet {
-
-    private static final Logger log = Logger.getLogger(ServiceServlet.class);
-    private final ServiceBusinessLogic serviceBusinessLogic;
-    private final ResourceBusinessLogic resourceBusinessLogic;
-
-    @Inject
-    public ServiceServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        ServiceBusinessLogic serviceBusinessLogic,
-        ResourceBusinessLogic resourceBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.serviceBusinessLogic = serviceBusinessLogic;
-        this.resourceBusinessLogic = resourceBusinessLogic;
-    }
-
-    @POST
-    @Path("/services")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Create Service", httpMethod = "POST", notes = "Returns created service", response = Service.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Service created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Service already exist") })
-    public Response createService(@ApiParam(value = "Service object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-        try {
-            Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
-            if (convertResponse.isRight()) {
-                log.debug("failed to parse service");
-                response = buildErrorResponse(convertResponse.right().value());
-                return response;
-            }
-
-            Service service = convertResponse.left().value();
-            Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.createService(service, modifier);
-
-            if (actionResponse.isRight()) {
-                log.debug("Failed to create service");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result);
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Service");
-            log.debug("create service failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-    public Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
-    }
-
-    @GET
-    @Path("/services/validate-name/{serviceName}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "validate service name", httpMethod = "GET", notes = "checks if the chosen service name is available ", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") })
-    public Response validateServiceName(@PathParam("serviceName") final String serviceName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-        Response response = null;
-        try {
-            Either<Map<String, Boolean>, ResponseFormat> actionResponse = serviceBusinessLogic.validateServiceNameExists(serviceName, userId);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to get validate service name");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
-            log.debug("validate service name failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @GET
-    @Path("/audit-records/{componentType}/{componentUniqueId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "get component audit records", httpMethod = "GET", notes = "get audit records for a service or a resource", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") })
-    public Response getComponentAuditRecords(@PathParam("componentType") final String componentType, @PathParam("componentUniqueId") final String componentUniqueId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        init();
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        Wrapper<String> uuidWrapper = new Wrapper<>();
-        Wrapper<String> versionWrapper = new Wrapper<>();
-        Wrapper<User> userWrapper = new Wrapper<>();
-        Wrapper<ComponentTypeEnum> componentWrapper = new Wrapper<>();
-        try {
-            validateUserExist(responseWrapper, userWrapper, userId);
-
-            if (responseWrapper.isEmpty()) {
-                validateComponentType(responseWrapper, componentWrapper, componentType);
-            }
-
-            if (responseWrapper.isEmpty()) {
-                fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), componentWrapper.getInnerElement(), componentUniqueId, context);
-            }
-
-            if (responseWrapper.isEmpty()) {
-                Either<List<Map<String, Object>>, ResponseFormat> eitherServiceAudit = serviceBusinessLogic.getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId);
-
-                if (eitherServiceAudit.isRight()) {
-                    Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value());
-                    responseWrapper.setInnerElement(errorResponse);
-                } else {
-                    List<Map<String, Object>> auditRecords = eitherServiceAudit.left().value();
-                    Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), auditRecords);
-                    responseWrapper.setInnerElement(okResponse);
-
-                }
-            }
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
-            log.debug("get Service Audit Records failed with exception", e);
-            Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            responseWrapper.setInnerElement(errorResponse);
-        }
-        return responseWrapper.getInnerElement();
-    }
-
-    private void fillUUIDAndVersion(Wrapper<Response> responseWrapper, Wrapper<String> uuidWrapper, Wrapper<String> versionWrapper, User user, final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) {
-
-        if (componentTypeEnum == ComponentTypeEnum.RESOURCE) {
-            Either<Resource, ResponseFormat> eitherResource = resourceBusinessLogic.getResource(componentUniqueId, user);
-            if (eitherResource.isLeft()) {
-                uuidWrapper.setInnerElement(eitherResource.left().value().getUUID());
-                versionWrapper.setInnerElement(eitherResource.left().value().getVersion());
-            } else {
-                responseWrapper.setInnerElement(buildErrorResponse(eitherResource.right().value()));
-            }
-
-        } else {
-            Either<Service, ResponseFormat> eitherService = serviceBusinessLogic.getService(componentUniqueId, user);
-            if (eitherService.isLeft()) {
-                uuidWrapper.setInnerElement(eitherService.left().value().getUUID());
-                versionWrapper.setInnerElement(eitherService.left().value().getVersion());
-            } else {
-                responseWrapper.setInnerElement(buildErrorResponse(eitherService.right().value()));
-
-            }
-        }
-    }
-
-    @DELETE
-    @Path("/services/{serviceId}")
-    public Response deleteService(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        // get modifier id
-        String userId = request.getHeader(Constants.USER_ID_HEADER);
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-
-        try {
-            String serviceIdLower = serviceId.toLowerCase();
-            ResponseFormat actionResponse = serviceBusinessLogic.deleteService(serviceIdLower, modifier);
-
-            if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
-                log.debug("failed to delete service");
-                response = buildErrorResponse(actionResponse);
-                return response;
-            }
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
-            log.debug("delete service failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @DELETE
-    @Path("/services/{serviceName}/{version}")
-    public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("version") final String version, @Context final HttpServletRequest request) {
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        // get modifier id
-        String userId = request.getHeader(Constants.USER_ID_HEADER);
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-
-        try {
-            ResponseFormat actionResponse = serviceBusinessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier);
-
-            if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
-                log.debug("failed to delete service");
-                response = buildErrorResponse(actionResponse);
-                return response;
-            }
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
-            log.debug("delete service failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    @PUT
-    @Path("/services/{serviceId}/metadata")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Service Metadata", httpMethod = "PUT", notes = "Returns updated service", response = Service.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Service Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId, @ApiParam(value = "Service object to be Updated", required = true) String data, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-
-        try {
-            String serviceIdLower = serviceId.toLowerCase();
-
-            Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
-            if (convertResponse.isRight()) {
-                log.debug("failed to parse service");
-                response = buildErrorResponse(convertResponse.right().value());
-                return response;
-            }
-            Service updatedService = convertResponse.left().value();
-            Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to update service");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            Service service = actionResponse.left().value();
-            Object result = RepresentationUtils.toRepresentation(service);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
-            log.debug("update service metadata failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-    /**
-     * updates group instance property values
-     * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated
-     * @param serviceId
-     * @param componentInstanceId
-     * @param groupInstanceId
-     * @param data
-     * @param request
-     * @param userId
-     * @return
-     */
-    @PUT
-    @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Group Instance Property Values", httpMethod = "PUT", notes = "Returns updated group instance", response = Service.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Instance Property Values Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
-    public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,@PathParam("componentInstanceId") final String componentInstanceId, @PathParam("groupInstanceId") final String groupInstanceId, @ApiParam(value = "Group instance object to be Updated", required = true) String data, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        Response response = null;
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}",userId);
-
-        Either<List<GroupInstanceProperty>, ResponseFormat> actionResponse = null;
-        try {
-            List<GroupInstanceProperty> updatedProperties;
-            Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>(){}.getType();
-            ArrayList<GroupInstanceProperty> newProperties = gson.fromJson(data, listType);
-            if (newProperties == null) {
-                actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
-            }
-            if(actionResponse == null){
-                log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId);
-                actionResponse = serviceBusinessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);
-                if(actionResponse.isRight()){
-                    actionResponse = Either.right(actionResponse.right().value());
-                }
-            }
-            if(actionResponse.isLeft()){
-                updatedProperties = actionResponse.left().value();
-                ObjectMapper mapper = new ObjectMapper();
-                String result = mapper.writeValueAsString(updatedProperties);
-                response =  buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-            }
-            else{
-                response = buildErrorResponse(actionResponse.right().value());
-            }
-        } catch (Exception e) {
-            log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-        return response;
-    }
-
-    @GET
-    @Path("/services/{serviceId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to serviceId", response = Service.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") })
-    public Response getServiceById(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-        try {
-            String serviceIdLower = serviceId.toLowerCase();
-            log.debug("get service with id {}", serviceId);
-            Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getService(serviceIdLower, modifier);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to get service");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            Service service = actionResponse.left().value();
-            Object result = RepresentationUtils.toRepresentation(service);
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
-            log.debug("get service failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    @GET
-    @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to name and version", response = Service.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") })
-    public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-        try {
-            Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId);
-
-            if (actionResponse.isRight()) {
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            Service service = actionResponse.left().value();
-            Object result = RepresentationUtils.toRepresentation(service);
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version");
-            log.debug("get service failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-    @POST
-    @Path("/services/{serviceId}/distribution-state/{state}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Update Service Distribution State", httpMethod = "POST", notes = "service with the changed distribution status")
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Service distribution state changed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available for distribution"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") })
-    public Response updateServiceDistributionState(@ApiParam(value = "DistributionChangeInfo - get comment out of body", required = true) LifecycleChangeInfoWithAction jsonChangeInfo, @PathParam("serviceId") final String serviceId,
-            @ApiParam(allowableValues = "approve, reject", required = true) @PathParam("state") final String state, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-        try {
-            Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.changeServiceDistributionState(serviceId, state, jsonChangeInfo, modifier);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to Update Service Distribution State");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-            Service service = actionResponse.left().value();
-            Object result = RepresentationUtils.toRepresentation(service);
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Distribution State");
-            log.debug("updateServiceDistributionState failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-    @POST
-    @Path("/services/{serviceId}/distribution/{env}/activate")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Activate distribution", httpMethod = "POST", notes = "activate distribution")
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 409, message = "Service cannot be distributed due to missing deployment artifacts"), @ApiResponse(code = 404, message = "Requested service was not found"),
-            @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") })
-    public Response activateDistribution(@PathParam("serviceId") final String serviceId, @PathParam("env") final String env, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-        try {
-            Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.activateDistribution(serviceId, env, modifier, request);
-
-            if (distResponse.isRight()) {
-                log.debug("failed to activate service distribution");
-                response = buildErrorResponse(distResponse.right().value());
-                return response;
-            }
-            Service service = distResponse.left().value();
-            Object result = RepresentationUtils.toRepresentation(service);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
-            log.debug("activate distribution failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-    @POST
-    @Path("/services/{serviceId}/distribution/{did}/markDeployed")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Mark distribution as deployed", httpMethod = "POST", notes = "relevant audit record will be created")
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Service was marked as deployed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") })
-    public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId, @PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-        try {
-            Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.markDistributionAsDeployed(serviceId, did, modifier);
-
-            if (distResponse.isRight()) {
-                log.debug("failed to mark distribution as deployed");
-                response = buildErrorResponse(distResponse.right().value());
-                return response;
-            }
-            Service service = distResponse.left().value();
-            Object result = RepresentationUtils.toRepresentation(service);
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed");
-            log.debug("mark distribution as deployed failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-    @POST
-    @Path("/services/{serviceId}/tempUrlToBeDeleted")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") })
-    public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        ServletContext context = request.getSession().getServletContext();
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response;
-        try {
-            Service service = (serviceBusinessLogic.getService(serviceId, modifier)).left().value();
-            Either<Service, ResponseFormat> res = serviceBusinessLogic.updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED);
-
-            if (res.isRight()) {
-                response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted");
-            log.debug("failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-        }
-    }
-
-
-    @GET
-    @Path("/services/{serviceId}/linksMap")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve Service component relations map", httpMethod = "GET", notes = "Returns service components relations", response = ServiceRelations.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") })
-    public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(userId);
-        log.debug("modifier id is {}", userId);
-
-        Response response = null;
-        try {
-            String serviceIdLower = serviceId.toLowerCase();
-            log.debug("get service components relations with id {}", serviceId);
-            Either<ServiceRelations, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceComponentsRelations(serviceIdLower, modifier);
-
-            if (actionResponse.isRight()) {
-                log.debug("failed to get service relations data");
-                response = buildErrorResponse(actionResponse.right().value());
-                return response;
-            }
-
-            ServiceRelations serviceRelations = actionResponse.left().value();
-            Object result = RepresentationUtils.toRepresentation(serviceRelations);
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
-            log.debug("get service relations data failed with exception", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
-        }
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import com.fasterxml.jackson.databind.ObjectMapper;\r
+import com.google.gson.reflect.TypeToken;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+import javax.inject.Inject;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.PUT;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import org.apache.http.HttpStatus;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;\r
+import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datamodel.ServiceRelations;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.DistributionStatusEnum;\r
+import org.openecomp.sdc.be.model.GroupInstanceProperty;\r
+import org.openecomp.sdc.be.model.Resource;\r
+import org.openecomp.sdc.be.model.Service;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import java.lang.reflect.Type;\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Service Catalog", description = "Service Servlet"))\r
+@Singleton\r
+public class ServiceServlet extends AbstractValidationsServlet {\r
+\r
+    private static final Logger log = Logger.getLogger(ServiceServlet.class);\r
+    private final ServiceBusinessLogic serviceBusinessLogic;\r
+    private final ResourceBusinessLogic resourceBusinessLogic;\r
+\r
+    @Inject\r
+    public ServiceServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        ServiceBusinessLogic serviceBusinessLogic,\r
+        ResourceBusinessLogic resourceBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.serviceBusinessLogic = serviceBusinessLogic;\r
+        this.resourceBusinessLogic = resourceBusinessLogic;\r
+    }\r
+\r
+    @POST\r
+    @Path("/services")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Create Service", method = "POST", summary = "Returns created service",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Service created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Service already exist")})\r
+    public Response createService(@Parameter(description = "Service object to be created", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+        try {\r
+            Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);\r
+            if (convertResponse.isRight()) {\r
+                log.debug("failed to parse service");\r
+                response = buildErrorResponse(convertResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            Service service = convertResponse.left().value();\r
+            Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.createService(service, modifier);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("Failed to create service");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result);\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Service");\r
+            log.debug("create service failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+    public Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {\r
+        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);\r
+    }\r
+\r
+    @GET\r
+    @Path("/services/validate-name/{serviceName}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "validate service name", method = "GET",\r
+            summary = "checks if the chosen service name is available ", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation")})\r
+    public Response validateServiceName(@PathParam("serviceName") final String serviceName,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+        Response response = null;\r
+        try {\r
+            Either<Map<String, Boolean>, ResponseFormat> actionResponse =\r
+                    serviceBusinessLogic.validateServiceNameExists(serviceName, userId);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to get validate service name");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                    actionResponse.left().value());\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");\r
+            log.debug("validate service name failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/audit-records/{componentType}/{componentUniqueId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "get component audit records", method = "GET",\r
+            summary = "get audit records for a service or a resource", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation")})\r
+    public Response getComponentAuditRecords(@PathParam("componentType") final String componentType,\r
+            @PathParam("componentUniqueId") final String componentUniqueId, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+        init();\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        Wrapper<String> uuidWrapper = new Wrapper<>();\r
+        Wrapper<String> versionWrapper = new Wrapper<>();\r
+        Wrapper<User> userWrapper = new Wrapper<>();\r
+        Wrapper<ComponentTypeEnum> componentWrapper = new Wrapper<>();\r
+        try {\r
+            validateUserExist(responseWrapper, userWrapper, userId);\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                validateComponentType(responseWrapper, componentWrapper, componentType);\r
+            }\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(),\r
+                        componentWrapper.getInnerElement(), componentUniqueId, context);\r
+            }\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                Either<List<Map<String, Object>>, ResponseFormat> eitherServiceAudit =\r
+                        serviceBusinessLogic.getComponentAuditRecords(versionWrapper.getInnerElement(),\r
+                                uuidWrapper.getInnerElement(), userId);\r
+\r
+                if (eitherServiceAudit.isRight()) {\r
+                    Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value());\r
+                    responseWrapper.setInnerElement(errorResponse);\r
+                } else {\r
+                    List<Map<String, Object>> auditRecords = eitherServiceAudit.left().value();\r
+                    Response okResponse =\r
+                            buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), auditRecords);\r
+                    responseWrapper.setInnerElement(okResponse);\r
+\r
+                }\r
+            }\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");\r
+            log.debug("get Service Audit Records failed with exception", e);\r
+            Response errorResponse =\r
+                    buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            responseWrapper.setInnerElement(errorResponse);\r
+        }\r
+        return responseWrapper.getInnerElement();\r
+    }\r
+\r
+    private void fillUUIDAndVersion(Wrapper<Response> responseWrapper, Wrapper<String> uuidWrapper, Wrapper<String> versionWrapper, User user, final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) {\r
+\r
+        if (componentTypeEnum == ComponentTypeEnum.RESOURCE) {\r
+            Either<Resource, ResponseFormat> eitherResource = resourceBusinessLogic.getResource(componentUniqueId, user);\r
+            if (eitherResource.isLeft()) {\r
+                uuidWrapper.setInnerElement(eitherResource.left().value().getUUID());\r
+                versionWrapper.setInnerElement(eitherResource.left().value().getVersion());\r
+            } else {\r
+                responseWrapper.setInnerElement(buildErrorResponse(eitherResource.right().value()));\r
+            }\r
+\r
+        } else {\r
+            Either<Service, ResponseFormat> eitherService = serviceBusinessLogic.getService(componentUniqueId, user);\r
+            if (eitherService.isLeft()) {\r
+                uuidWrapper.setInnerElement(eitherService.left().value().getUUID());\r
+                versionWrapper.setInnerElement(eitherService.left().value().getVersion());\r
+            } else {\r
+                responseWrapper.setInnerElement(buildErrorResponse(eitherService.right().value()));\r
+\r
+            }\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/services/{serviceId}")\r
+    public Response deleteService(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        // get modifier id\r
+        String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+\r
+        try {\r
+            String serviceIdLower = serviceId.toLowerCase();\r
+            ResponseFormat actionResponse = serviceBusinessLogic.deleteService(serviceIdLower, modifier);\r
+\r
+            if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {\r
+                log.debug("failed to delete service");\r
+                response = buildErrorResponse(actionResponse);\r
+                return response;\r
+            }\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");\r
+            log.debug("delete service failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @DELETE\r
+    @Path("/services/{serviceName}/{version}")\r
+    public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("version") final String version, @Context final HttpServletRequest request) {\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        // get modifier id\r
+        String userId = request.getHeader(Constants.USER_ID_HEADER);\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+\r
+        try {\r
+            ResponseFormat actionResponse = serviceBusinessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier);\r
+\r
+            if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {\r
+                log.debug("failed to delete service");\r
+                response = buildErrorResponse(actionResponse);\r
+                return response;\r
+            }\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");\r
+            log.debug("delete service failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    @PUT\r
+    @Path("/services/{serviceId}/metadata")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Service Metadata", method = "PUT", summary = "Returns updated service",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service Updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId,\r
+            @Parameter(description = "Service object to be Updated", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+\r
+        try {\r
+            String serviceIdLower = serviceId.toLowerCase();\r
+\r
+            Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);\r
+            if (convertResponse.isRight()) {\r
+                log.debug("failed to parse service");\r
+                response = buildErrorResponse(convertResponse.right().value());\r
+                return response;\r
+            }\r
+            Service updatedService = convertResponse.left().value();\r
+            Either<Service, ResponseFormat> actionResponse =\r
+                    serviceBusinessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to update service");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            Service service = actionResponse.left().value();\r
+            Object result = RepresentationUtils.toRepresentation(service);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");\r
+            log.debug("update service metadata failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+    /**\r
+     * updates group instance property values\r
+     * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated\r
+     * @param serviceId\r
+     * @param componentInstanceId\r
+     * @param groupInstanceId\r
+     * @param data\r
+     * @param request\r
+     * @param userId\r
+     * @return\r
+     */\r
+    @PUT\r
+    @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Group Instance Property Values", method = "PUT",\r
+            summary = "Returns updated group instance", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Group Instance Property Values Updated"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})\r
+    public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,\r
+            @PathParam("componentInstanceId") final String componentInstanceId,\r
+            @PathParam("groupInstanceId") final String groupInstanceId,\r
+            @Parameter(description = "Group instance object to be Updated", required = true) String data,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        Response response = null;\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}",userId);\r
+\r
+        Either<List<GroupInstanceProperty>, ResponseFormat> actionResponse = null;\r
+        try {\r
+            List<GroupInstanceProperty> updatedProperties;\r
+            Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>(){}.getType();\r
+            ArrayList<GroupInstanceProperty> newProperties = gson.fromJson(data, listType);\r
+            if (newProperties == null) {\r
+                actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));\r
+            }\r
+            if(actionResponse == null){\r
+                log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId);\r
+                actionResponse = serviceBusinessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);\r
+                if(actionResponse.isRight()){\r
+                    actionResponse = Either.right(actionResponse.right().value());\r
+                }\r
+            }\r
+            if(actionResponse.isLeft()){\r
+                updatedProperties = actionResponse.left().value();\r
+                ObjectMapper mapper = new ObjectMapper();\r
+                String result = mapper.writeValueAsString(updatedProperties);\r
+                response =  buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+            }\r
+            else{\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+            }\r
+        } catch (Exception e) {\r
+            log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+        return response;\r
+    }\r
+\r
+    @GET\r
+    @Path("/services/{serviceId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to serviceId",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Service not found")})\r
+    public Response getServiceById(@PathParam("serviceId") final String serviceId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+        try {\r
+            String serviceIdLower = serviceId.toLowerCase();\r
+            log.debug("get service with id {}", serviceId);\r
+            Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getService(serviceIdLower, modifier);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to get service");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            Service service = actionResponse.left().value();\r
+            Object result = RepresentationUtils.toRepresentation(service);\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");\r
+            log.debug("get service failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve Service", method = "GET",\r
+            summary = "Returns service according to name and version", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Service not found")})\r
+    public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName,\r
+            @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+        try {\r
+            Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId);\r
+\r
+            if (actionResponse.isRight()) {\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            Service service = actionResponse.left().value();\r
+            Object result = RepresentationUtils.toRepresentation(service);\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version");\r
+            log.debug("get service failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/services/{serviceId}/distribution-state/{state}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Update Service Distribution State", method = "POST",\r
+            summary = "service with the changed distribution status")\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service distribution state changed"),\r
+            @ApiResponse(responseCode = "409", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "403", description = "Service is not available for distribution"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Requested service was not found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})\r
+    public Response updateServiceDistributionState(\r
+            @Parameter(description = "DistributionChangeInfo - get comment out of body",\r
+                    required = true) LifecycleChangeInfoWithAction jsonChangeInfo,\r
+            @PathParam("serviceId") final String serviceId,\r
+            @Parameter(schema = @Schema(allowableValues = {"approve", "reject"}),\r
+                    required = true) @PathParam("state") final String state,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+        try {\r
+            Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.changeServiceDistributionState(serviceId, state, jsonChangeInfo, modifier);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to Update Service Distribution State");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+            Service service = actionResponse.left().value();\r
+            Object result = RepresentationUtils.toRepresentation(service);\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Distribution State");\r
+            log.debug("updateServiceDistributionState failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/services/{serviceId}/distribution/{env}/activate")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Activate distribution", method = "POST", summary = "activate distribution")\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"),\r
+            @ApiResponse(responseCode = "409",\r
+                    description = "Service cannot be distributed due to missing deployment artifacts"),\r
+            @ApiResponse(responseCode = "404", description = "Requested service was not found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})\r
+    public Response activateDistribution(@PathParam("serviceId") final String serviceId,\r
+            @PathParam("env") final String env, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+        try {\r
+            Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.activateDistribution(serviceId, env, modifier, request);\r
+\r
+            if (distResponse.isRight()) {\r
+                log.debug("failed to activate service distribution");\r
+                response = buildErrorResponse(distResponse.right().value());\r
+                return response;\r
+            }\r
+            Service service = distResponse.left().value();\r
+            Object result = RepresentationUtils.toRepresentation(service);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");\r
+            log.debug("activate distribution failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/services/{serviceId}/distribution/{did}/markDeployed")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Mark distribution as deployed", method = "POST",\r
+            summary = "relevant audit record will be created")\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service was marked as deployed"),\r
+            @ApiResponse(responseCode = "409", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "403", description = "Service is not available"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Requested service was not found"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})\r
+    public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId,\r
+            @PathParam("did") final String did, @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+        try {\r
+            Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.markDistributionAsDeployed(serviceId, did, modifier);\r
+\r
+            if (distResponse.isRight()) {\r
+                log.debug("failed to mark distribution as deployed");\r
+                response = buildErrorResponse(distResponse.right().value());\r
+                return response;\r
+            }\r
+            Service service = distResponse.left().value();\r
+            Object result = RepresentationUtils.toRepresentation(service);\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed");\r
+            log.debug("mark distribution as deployed failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+    @POST\r
+    @Path("/services/{serviceId}/tempUrlToBeDeleted")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.") })\r
+    public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        ServletContext context = request.getSession().getServletContext();\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response;\r
+        try {\r
+            Service service = (serviceBusinessLogic.getService(serviceId, modifier)).left().value();\r
+            Either<Service, ResponseFormat> res = serviceBusinessLogic.updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED);\r
+\r
+            if (res.isRight()) {\r
+                response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            }\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted");\r
+            log.debug("failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+        }\r
+    }\r
+\r
+\r
+    @GET\r
+    @Path("/services/{serviceId}/linksMap")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve Service component relations map", method = "GET",\r
+            summary = "Returns service components relations",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServiceRelations.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Service found"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "Service not found")})\r
+    public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId,\r
+            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(userId);\r
+        log.debug("modifier id is {}", userId);\r
+\r
+        Response response = null;\r
+        try {\r
+            String serviceIdLower = serviceId.toLowerCase();\r
+            log.debug("get service components relations with id {}", serviceId);\r
+            Either<ServiceRelations, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceComponentsRelations(serviceIdLower, modifier);\r
+\r
+            if (actionResponse.isRight()) {\r
+                log.debug("failed to get service relations data");\r
+                response = buildErrorResponse(actionResponse.right().value());\r
+                return response;\r
+            }\r
+\r
+            ServiceRelations serviceRelations = actionResponse.left().value();\r
+            Object result = RepresentationUtils.toRepresentation(serviceRelations);\r
+\r
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");\r
+            log.debug("get service relations data failed with exception", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+\r
+        }\r
+    }\r
+\r
+}\r
index 33df8bc..a3e47a0 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import javax.inject.Inject;
-import org.apache.commons.collections4.ListUtils;
-import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;
-import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;
-import org.openecomp.sdc.be.components.impl.RelationshipTypeBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
-import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.RelationshipTypeDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
-@Api(value = "Types Fetch Servlet", description = "Types Fetch Servlet")
-@Singleton
-public class TypesFetchServlet extends AbstractValidationsServlet {
-
-    private static final Logger log = Logger.getLogger(TypesFetchServlet.class);
-    private static final String FAILED_TO_GET_ALL_NON_ABSTRACT = "failed to get all non abstract {}";
-    private final PropertyBusinessLogic propertyBusinessLogic;
-    private final RelationshipTypeBusinessLogic relationshipTypeBusinessLogic;
-    private final CapabilitiesBusinessLogic capabilitiesBusinessLogic;
-    private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic;
-    private final ResourceBusinessLogic resourceBusinessLogic;
-
-    @Inject
-    public TypesFetchServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        PropertyBusinessLogic propertyBusinessLogic,
-        RelationshipTypeBusinessLogic relationshipTypeBusinessLogic,
-        CapabilitiesBusinessLogic capabilitiesBusinessLogic,
-        InterfaceOperationBusinessLogic interfaceOperationBusinessLogic,
-        ResourceBusinessLogic resourceBusinessLogic) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.propertyBusinessLogic = propertyBusinessLogic;
-        this.relationshipTypeBusinessLogic = relationshipTypeBusinessLogic;
-        this.capabilitiesBusinessLogic = capabilitiesBusinessLogic;
-        this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic;
-        this.resourceBusinessLogic = resourceBusinessLogic;
-    }
-
-    @GET
-    @Path("dataTypes")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get data types", httpMethod = "GET", notes = "Returns data types", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "datatypes"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 404, message = "Data types not found") })
-    public Response getAllDataTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        Wrapper<User> userWrapper = new Wrapper<>();
-        try {
-            init();
-            validateUserExist(responseWrapper, userWrapper, userId);
-
-            if (responseWrapper.isEmpty()) {
-                String url = request.getMethod() + " " + request.getRequestURI();
-                log.debug("Start handle request of {} | modifier id is {}", url, userId);
-
-                Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes =
-                    propertyBusinessLogic.getAllDataTypes();
-
-                if (allDataTypes.isRight()) {
-                    log.info("Failed to get all dara types. Reason - {}", allDataTypes.right().value());
-                    Response errorResponse = buildErrorResponse(allDataTypes.right().value());
-                    responseWrapper.setInnerElement(errorResponse);
-
-                } else {
-
-                    Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
-                    String dataTypeJson = gson.toJson(dataTypes);
-                    Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
-                    responseWrapper.setInnerElement(okResponse);
-
-                }
-            }
-
-            return responseWrapper.getInnerElement();
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property");
-            log.debug("get all data types failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-        }
-    }
-
-    @GET
-    @Path("interfaceLifecycleTypes")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get interface lifecycle types", httpMethod = "GET", notes = "Returns interface lifecycle types", response = Response.class)
-    @ApiResponses(value = {
-        @ApiResponse(code = 200, message = "Interface lifecycle types"),
-        @ApiResponse(code = 403, message = "Restricted operation"),
-        @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-        @ApiResponse(code = 404, message = "Interface lifecycle types not found")
-    })
-    public Response getInterfaceLifecycleTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        Wrapper<User> userWrapper = new Wrapper<>();
-
-        try {
-            validateUserExist(responseWrapper, userWrapper, userId);
-
-            if (responseWrapper.isEmpty()) {
-                String url = request.getMethod() + " " + request.getRequestURI();
-                log.info("Start handle request of {} | modifier id is {}", url, userId);
-
-                Either<Map<String, InterfaceDefinition>, ResponseFormat> allInterfaceLifecycleTypes =
-                    interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes();
-
-                if (allInterfaceLifecycleTypes.isRight()) {
-                    log.info("Failed to get all interface lifecycle types. Reason - {}",
-                        allInterfaceLifecycleTypes.right().value());
-                    Response errorResponse = buildErrorResponse(allInterfaceLifecycleTypes.right().value());
-                    responseWrapper.setInnerElement(errorResponse);
-
-                } else {
-                    String interfaceLifecycleTypeJson = gson.toJson(allInterfaceLifecycleTypes.left().value());
-                    Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), interfaceLifecycleTypeJson);
-                    responseWrapper.setInnerElement(okResponse);
-
-                }
-            }
-
-            return responseWrapper.getInnerElement();
-        } catch (Exception e) {
-            log.debug("get all interface lifecycle types failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-        }
-    }
-    @GET
-    @Path("capabilityTypes")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get capability types", httpMethod = "GET", notes = "Returns capability types", response =
-            Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 200, message = "capabilityTypes"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 404, message = "Capability types not found")})
-    public Response getAllCapabilityTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value =
-            Constants.USER_ID_HEADER) String userId) {
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        Wrapper<User> userWrapper = new Wrapper<>();
-
-        try {
-            init();
-            validateUserExist(responseWrapper, userWrapper, userId);
-
-            if (responseWrapper.isEmpty()) {
-                String url = request.getMethod() + " " + request.getRequestURI();
-                log.debug("Start handle request of {} | modifier id is {}", url, userId);
-
-                Either<Map<String, CapabilityTypeDefinition>, ResponseFormat> allDataTypes =
-                    capabilitiesBusinessLogic.getAllCapabilityTypes();
-
-                if (allDataTypes.isRight()) {
-                    log.info("Failed to get all capability types. Reason - {}", allDataTypes.right().value());
-                    Response errorResponse = buildErrorResponse(allDataTypes.right().value());
-                    responseWrapper.setInnerElement(errorResponse);
-
-                } else {
-
-                    Map<String, CapabilityTypeDefinition> dataTypes = allDataTypes.left().value();
-                    String dataTypeJson = gson.toJson(dataTypes);
-                    Response okResponse =
-                            buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
-                    responseWrapper.setInnerElement(okResponse);
-
-                }
-            }
-
-            return responseWrapper.getInnerElement();
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capability Types");
-            log.debug("get all capability types failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-        }
-    }
-
-    @GET
-    @Path("relationshipTypes")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get relationship types", httpMethod = "GET", notes = "Returns relationship types", response =
-            Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 200, message = "relationshipTypes"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 404, message = "Relationship types not found")})
-    public Response getAllRelationshipTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value =
-            Constants.USER_ID_HEADER) String userId) {
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        Wrapper<User> userWrapper = new Wrapper<>();
-
-        try {
-            init();
-            validateUserExist(responseWrapper, userWrapper, userId);
-
-            if (responseWrapper.isEmpty()) {
-                String url = request.getMethod() + " " + request.getRequestURI();
-                log.debug("Start handle request of {} | modifier id is {}", url, userId);
-
-                Either<Map<String, RelationshipTypeDefinition>, ResponseFormat> allDataTypes =
-                    relationshipTypeBusinessLogic.getAllRelationshipTypes();
-
-                if (allDataTypes.isRight()) {
-                    log.info("Failed to get all relationship types. Reason - {}", allDataTypes.right().value());
-                    Response errorResponse = buildErrorResponse(allDataTypes.right().value());
-                    responseWrapper.setInnerElement(errorResponse);
-
-                } else {
-
-                    Map<String, RelationshipTypeDefinition> dataTypes = allDataTypes.left().value();
-                    String dataTypeJson = gson.toJson(dataTypes);
-                    Response okResponse =
-                            buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
-                    responseWrapper.setInnerElement(okResponse);
-
-                }
-            }
-
-            return responseWrapper.getInnerElement();
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Relationship Types");
-            log.debug("get all relationship types failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-        }
-    }
-
-    @GET
-    @Path("nodeTypes")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Get node types", httpMethod = "GET", notes = "Returns node types", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 200, message = "nodeTypes"), @ApiResponse(code = 403, message =
-            "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 404, message = "Node types not found")})
-    public Response getAllNodeTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value =
-            Constants.USER_ID_HEADER) String userId) {
-
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        Wrapper<User> userWrapper = new Wrapper<>();
-        ServletContext context = request.getSession().getServletContext();
-        Either<Map<String, Component>, Response> response;
-        Map<String, Component> componentMap;
-
-        try {
-            init();
-            validateUserExist(responseWrapper, userWrapper, userId);
-
-            if (responseWrapper.isEmpty()) {
-                String url = request.getMethod() + " " + request.getRequestURI();
-                log.debug("Start handle request of {} | modifier id is {}", url, userId);
-
-                response = getComponent(resourceBusinessLogic, true, userId);
-                if (response.isRight()) {
-                    return response.right().value();
-                }
-                componentMap = new HashMap<>(response.left().value());
-
-                response = getComponent(resourceBusinessLogic, false, userId);
-                if (response.isRight()) {
-                    return response.right().value();
-                }
-                componentMap.putAll(response.left().value());
-
-                String nodeTypesJson = gson.toJson(componentMap);
-                Response okResponse =
-                        buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeTypesJson);
-                responseWrapper.setInnerElement(okResponse);
-            }
-
-            return responseWrapper.getInnerElement();
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Node Types");
-            log.debug("get all node types failed with exception", e);
-            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            return buildErrorResponse(responseFormat);
-        }
-    }
-
-    private Either<Map<String, Component>, Response> getComponent(ComponentBusinessLogic resourceBL, boolean isAbstract,
-                                                                  String userId) {
-        Either<List<Component>, ResponseFormat> actionResponse;
-        List<Component> componentList;
-
-        actionResponse =
-                resourceBL.getLatestVersionNotAbstractComponentsMetadata(isAbstract, HighestFilterEnum.HIGHEST_ONLY
-                        , ComponentTypeEnum.RESOURCE, null, userId);
-        if (actionResponse.isRight()) {
-            log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, ComponentTypeEnum.RESOURCE.getValue());
-            return Either.right(buildErrorResponse(actionResponse.right().value()));
-        }
-
-        componentList = actionResponse.left().value();
-
-        return Either.left(ListUtils.emptyIfNull(componentList).stream()
-                .filter(component -> ((ResourceMetadataDataDefinition) component
-                        .getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName() != null)
-                .collect(Collectors.toMap(
-                        component -> ((ResourceMetadataDataDefinition) component
-                                .getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName(),
-                        component -> component, (component1, component2) -> component1)));
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.stream.Collectors;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.collections4.ListUtils;\r
+import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.RelationshipTypeBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;\r
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;\r
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.CapabilityTypeDefinition;\r
+import org.openecomp.sdc.be.model.Component;\r
+import org.openecomp.sdc.be.model.DataTypeDefinition;\r
+import org.openecomp.sdc.be.model.InterfaceDefinition;\r
+import org.openecomp.sdc.be.model.RelationshipTypeDefinition;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog")\r
+@OpenAPIDefinition(info = @Info(title = "Types Fetch Servlet",description = "Types Fetch Servlet"))\r
+@Singleton\r
+public class TypesFetchServlet extends AbstractValidationsServlet {\r
+\r
+    private static final Logger log = Logger.getLogger(TypesFetchServlet.class);\r
+    private static final String FAILED_TO_GET_ALL_NON_ABSTRACT = "failed to get all non abstract {}";\r
+    private final PropertyBusinessLogic propertyBusinessLogic;\r
+    private final RelationshipTypeBusinessLogic relationshipTypeBusinessLogic;\r
+    private final CapabilitiesBusinessLogic capabilitiesBusinessLogic;\r
+    private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic;\r
+    private final ResourceBusinessLogic resourceBusinessLogic;\r
+\r
+    @Inject\r
+    public TypesFetchServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        PropertyBusinessLogic propertyBusinessLogic,\r
+        RelationshipTypeBusinessLogic relationshipTypeBusinessLogic,\r
+        CapabilitiesBusinessLogic capabilitiesBusinessLogic,\r
+        InterfaceOperationBusinessLogic interfaceOperationBusinessLogic,\r
+        ResourceBusinessLogic resourceBusinessLogic) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.propertyBusinessLogic = propertyBusinessLogic;\r
+        this.relationshipTypeBusinessLogic = relationshipTypeBusinessLogic;\r
+        this.capabilitiesBusinessLogic = capabilitiesBusinessLogic;\r
+        this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic;\r
+        this.resourceBusinessLogic = resourceBusinessLogic;\r
+    }\r
+\r
+    @GET\r
+    @Path("dataTypes")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get data types", method = "GET", summary = "Returns data types", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "datatypes"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Data types not found")})\r
+    public Response getAllDataTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        Wrapper<User> userWrapper = new Wrapper<>();\r
+        try {\r
+            init();\r
+            validateUserExist(responseWrapper, userWrapper, userId);\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                String url = request.getMethod() + " " + request.getRequestURI();\r
+                log.debug("Start handle request of {} | modifier id is {}", url, userId);\r
+\r
+                Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes =\r
+                    propertyBusinessLogic.getAllDataTypes();\r
+\r
+                if (allDataTypes.isRight()) {\r
+                    log.info("Failed to get all dara types. Reason - {}", allDataTypes.right().value());\r
+                    Response errorResponse = buildErrorResponse(allDataTypes.right().value());\r
+                    responseWrapper.setInnerElement(errorResponse);\r
+\r
+                } else {\r
+\r
+                    Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();\r
+                    String dataTypeJson = gson.toJson(dataTypes);\r
+                    Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);\r
+                    responseWrapper.setInnerElement(okResponse);\r
+\r
+                }\r
+            }\r
+\r
+            return responseWrapper.getInnerElement();\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property");\r
+            log.debug("get all data types failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("interfaceLifecycleTypes")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get interface lifecycle types", method = "GET", summary = "Returns interface lifecycle types", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {\r
+        @ApiResponse(responseCode = "200", description = "Interface lifecycle types"),\r
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+        @ApiResponse(responseCode = "404", description = "Interface lifecycle types not found")\r
+    })\r
+    public Response getInterfaceLifecycleTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        Wrapper<User> userWrapper = new Wrapper<>();\r
+\r
+        try {\r
+            validateUserExist(responseWrapper, userWrapper, userId);\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                String url = request.getMethod() + " " + request.getRequestURI();\r
+                log.info("Start handle request of {} | modifier id is {}", url, userId);\r
+\r
+                Either<Map<String, InterfaceDefinition>, ResponseFormat> allInterfaceLifecycleTypes =\r
+                    interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes();\r
+\r
+                if (allInterfaceLifecycleTypes.isRight()) {\r
+                    log.info("Failed to get all interface lifecycle types. Reason - {}",\r
+                        allInterfaceLifecycleTypes.right().value());\r
+                    Response errorResponse = buildErrorResponse(allInterfaceLifecycleTypes.right().value());\r
+                    responseWrapper.setInnerElement(errorResponse);\r
+\r
+                } else {\r
+                    String interfaceLifecycleTypeJson = gson.toJson(allInterfaceLifecycleTypes.left().value());\r
+                    Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), interfaceLifecycleTypeJson);\r
+                    responseWrapper.setInnerElement(okResponse);\r
+\r
+                }\r
+            }\r
+\r
+            return responseWrapper.getInnerElement();\r
+        } catch (Exception e) {\r
+            log.debug("get all interface lifecycle types failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+    }\r
+    @GET\r
+    @Path("capabilityTypes")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get capability types", method = "GET", summary = "Returns capability types", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "capabilityTypes"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Capability types not found")})\r
+    public Response getAllCapabilityTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value =\r
+            Constants.USER_ID_HEADER) String userId) {\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        Wrapper<User> userWrapper = new Wrapper<>();\r
+\r
+        try {\r
+            init();\r
+            validateUserExist(responseWrapper, userWrapper, userId);\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                String url = request.getMethod() + " " + request.getRequestURI();\r
+                log.debug("Start handle request of {} | modifier id is {}", url, userId);\r
+\r
+                Either<Map<String, CapabilityTypeDefinition>, ResponseFormat> allDataTypes =\r
+                    capabilitiesBusinessLogic.getAllCapabilityTypes();\r
+\r
+                if (allDataTypes.isRight()) {\r
+                    log.info("Failed to get all capability types. Reason - {}", allDataTypes.right().value());\r
+                    Response errorResponse = buildErrorResponse(allDataTypes.right().value());\r
+                    responseWrapper.setInnerElement(errorResponse);\r
+\r
+                } else {\r
+\r
+                    Map<String, CapabilityTypeDefinition> dataTypes = allDataTypes.left().value();\r
+                    String dataTypeJson = gson.toJson(dataTypes);\r
+                    Response okResponse =\r
+                            buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);\r
+                    responseWrapper.setInnerElement(okResponse);\r
+\r
+                }\r
+            }\r
+\r
+            return responseWrapper.getInnerElement();\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capability Types");\r
+            log.debug("get all capability types failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("relationshipTypes")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get relationship types", method = "GET", summary = "Returns relationship types", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "relationshipTypes"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Relationship types not found")})\r
+    public Response getAllRelationshipTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value =\r
+            Constants.USER_ID_HEADER) String userId) {\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        Wrapper<User> userWrapper = new Wrapper<>();\r
+\r
+        try {\r
+            init();\r
+            validateUserExist(responseWrapper, userWrapper, userId);\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                String url = request.getMethod() + " " + request.getRequestURI();\r
+                log.debug("Start handle request of {} | modifier id is {}", url, userId);\r
+\r
+                Either<Map<String, RelationshipTypeDefinition>, ResponseFormat> allDataTypes =\r
+                    relationshipTypeBusinessLogic.getAllRelationshipTypes();\r
+\r
+                if (allDataTypes.isRight()) {\r
+                    log.info("Failed to get all relationship types. Reason - {}", allDataTypes.right().value());\r
+                    Response errorResponse = buildErrorResponse(allDataTypes.right().value());\r
+                    responseWrapper.setInnerElement(errorResponse);\r
+\r
+                } else {\r
+\r
+                    Map<String, RelationshipTypeDefinition> dataTypes = allDataTypes.left().value();\r
+                    String dataTypeJson = gson.toJson(dataTypes);\r
+                    Response okResponse =\r
+                            buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);\r
+                    responseWrapper.setInnerElement(okResponse);\r
+\r
+                }\r
+            }\r
+\r
+            return responseWrapper.getInnerElement();\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Relationship Types");\r
+            log.debug("get all relationship types failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("nodeTypes")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Get node types", method = "GET", summary = "Returns node types", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "nodeTypes"), @ApiResponse(responseCode = "403", description =\r
+            "Restricted operation"), @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "404", description = "Node types not found")})\r
+    public Response getAllNodeTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value =\r
+            Constants.USER_ID_HEADER) String userId) {\r
+\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        Wrapper<User> userWrapper = new Wrapper<>();\r
+        ServletContext context = request.getSession().getServletContext();\r
+        Either<Map<String, Component>, Response> response;\r
+        Map<String, Component> componentMap;\r
+\r
+        try {\r
+            init();\r
+            validateUserExist(responseWrapper, userWrapper, userId);\r
+\r
+            if (responseWrapper.isEmpty()) {\r
+                String url = request.getMethod() + " " + request.getRequestURI();\r
+                log.debug("Start handle request of {} | modifier id is {}", url, userId);\r
+\r
+                response = getComponent(resourceBusinessLogic, true, userId);\r
+                if (response.isRight()) {\r
+                    return response.right().value();\r
+                }\r
+                componentMap = new HashMap<>(response.left().value());\r
+\r
+                response = getComponent(resourceBusinessLogic, false, userId);\r
+                if (response.isRight()) {\r
+                    return response.right().value();\r
+                }\r
+                componentMap.putAll(response.left().value());\r
+\r
+                String nodeTypesJson = gson.toJson(componentMap);\r
+                Response okResponse =\r
+                        buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeTypesJson);\r
+                responseWrapper.setInnerElement(okResponse);\r
+            }\r
+\r
+            return responseWrapper.getInnerElement();\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Node Types");\r
+            log.debug("get all node types failed with exception", e);\r
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            return buildErrorResponse(responseFormat);\r
+        }\r
+    }\r
+\r
+    private Either<Map<String, Component>, Response> getComponent(ComponentBusinessLogic resourceBL, boolean isAbstract,\r
+                                                                  String userId) {\r
+        Either<List<Component>, ResponseFormat> actionResponse;\r
+        List<Component> componentList;\r
+\r
+        actionResponse =\r
+                resourceBL.getLatestVersionNotAbstractComponentsMetadata(isAbstract, HighestFilterEnum.HIGHEST_ONLY\r
+                        , ComponentTypeEnum.RESOURCE, null, userId);\r
+        if (actionResponse.isRight()) {\r
+            log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, ComponentTypeEnum.RESOURCE.getValue());\r
+            return Either.right(buildErrorResponse(actionResponse.right().value()));\r
+        }\r
+\r
+        componentList = actionResponse.left().value();\r
+\r
+        return Either.left(ListUtils.emptyIfNull(componentList).stream()\r
+                .filter(component -> ((ResourceMetadataDataDefinition) component\r
+                        .getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName() != null)\r
+                .collect(Collectors.toMap(\r
+                        component -> ((ResourceMetadataDataDefinition) component\r
+                                .getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName(),\r
+                        component -> component, (component1, component2) -> component1)));\r
+    }\r
+}\r
index 0d0aa4e..5847a06 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.jcabi.aspects.Loggable;
-import io.swagger.annotations.*;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.glassfish.jersey.media.multipart.FormDataParam;
-import org.openecomp.sdc.be.components.impl.CommonImportManager;
-import org.openecomp.sdc.be.components.validation.AccessValidations;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-import org.openecomp.sdc.be.model.AnnotationTypeDefinition;
-import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations;
-import org.openecomp.sdc.be.utils.TypeUtils;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.springframework.http.HttpStatus;
-import org.springframework.stereotype.Controller;
-
-import javax.ws.rs.*;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Here new APIs for types upload written in an attempt to gradually servlet code
- */
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog/uploadType")
-@Consumes(MediaType.MULTIPART_FORM_DATA)
-@Produces(MediaType.APPLICATION_JSON)
-@Api(value = "Catalog Types Upload")
-@Controller
-public class TypesUploadEndpoint {
-
-    private final CommonImportManager commonImportManager;
-    private final AnnotationTypeOperations annotationTypeOperations;
-    private final AccessValidations accessValidations;
-
-    public TypesUploadEndpoint(CommonImportManager commonImportManager, AnnotationTypeOperations annotationTypeOperations, AccessValidations accessValidations) {
-        this.commonImportManager = commonImportManager;
-        this.annotationTypeOperations = annotationTypeOperations;
-        this.accessValidations = accessValidations;
-    }
-
-    @POST
-    @Path("/annotationtypes")
-    @ApiOperation(value = "Create AnnotationTypes from yaml", httpMethod = "POST", notes = "Returns created annotation types", response = Response.class)
-    @ApiResponses(value = {
-            @ApiResponse(code = 201, message = "annotation types created"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "annotation types already exist")})
-    public Response uploadAnnotationTypes(
-            @ApiParam("FileInputStream") @FormDataParam("annotationTypesZip") File file,
-            @HeaderParam("USER_ID") String userId) throws IOException {
-        accessValidations.validateUserExists(userId, "Annotation Types Creation");
-        Wrapper<String> yamlStringWrapper = new Wrapper<>();
-        AbstractValidationsServlet.extractZipContents(yamlStringWrapper, file);
-        List<ImmutablePair<AnnotationTypeDefinition, Boolean>> typesResults = commonImportManager.createElementTypes(yamlStringWrapper.getInnerElement(), TypesUploadEndpoint::buildAnnotationFromFieldMap, annotationTypeOperations);
-        HttpStatus status = getHttpStatus(typesResults);
-        return Response.status(status.value())
-                .entity(typesResults)
-                .build();
-    }
-
-    @VisibleForTesting
-    static <T extends ToscaDataDefinition> HttpStatus getHttpStatus(List<ImmutablePair<T, Boolean>> typesResults) {
-        boolean typeActionFailed = false;
-        boolean typeExists = false;
-        boolean typeActionSucceeded = false;
-        for (ImmutablePair<T, Boolean> typeResult : typesResults) {
-            Boolean result = typeResult.getRight();
-            if (result==null) {
-                typeExists = true;
-            } else if (result) {
-                typeActionSucceeded = true;
-            } else {
-                typeActionFailed = true;
-            }
-        }
-        HttpStatus status = HttpStatus.OK;
-        if (typeActionFailed) {
-            status =  HttpStatus.BAD_REQUEST;
-        } else if (typeActionSucceeded) {
-            status = HttpStatus.CREATED;
-        } else if (typeExists) {
-            status = HttpStatus.CONFLICT;
-        }
-        return status;
-    }
-
-    private static <T extends ToscaDataDefinition> T buildAnnotationFromFieldMap(String typeName, Map<String, Object> toscaJson) {
-        AnnotationTypeDefinition annotationType = new AnnotationTypeDefinition();
-        annotationType.setVersion(TypeUtils.getFirstCertifiedVersionVersion());
-        annotationType.setHighestVersion(true);
-        annotationType.setType(typeName);
-        TypeUtils.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, annotationType::setDescription);
-        CommonImportManager.setProperties(toscaJson, annotationType::setProperties);
-        return (T) annotationType;
-    }
-
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.util.List;\r
+import java.util.Map;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.lang3.tuple.ImmutablePair;\r
+import org.glassfish.jersey.media.multipart.FormDataParam;\r
+import org.openecomp.sdc.be.components.impl.CommonImportManager;\r
+import org.openecomp.sdc.be.components.validation.AccessValidations;\r
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;\r
+import org.openecomp.sdc.be.model.AnnotationTypeDefinition;\r
+import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations;\r
+import org.openecomp.sdc.be.utils.TypeUtils;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.springframework.http.HttpStatus;\r
+import org.springframework.stereotype.Controller;\r
+import com.google.common.annotations.VisibleForTesting;\r
+import com.jcabi.aspects.Loggable;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+/**\r
+ * Here new APIs for types upload written in an attempt to gradually servlet responseCode\r
+ */\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog/uploadType")\r
+@Consumes(MediaType.MULTIPART_FORM_DATA)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+@OpenAPIDefinition(info = @Info(title = "Catalog Types Upload"))\r
+@Controller\r
+public class TypesUploadEndpoint {\r
+\r
+    private final CommonImportManager commonImportManager;\r
+    private final AnnotationTypeOperations annotationTypeOperations;\r
+    private final AccessValidations accessValidations;\r
+\r
+    public TypesUploadEndpoint(CommonImportManager commonImportManager, AnnotationTypeOperations annotationTypeOperations, AccessValidations accessValidations) {\r
+        this.commonImportManager = commonImportManager;\r
+        this.annotationTypeOperations = annotationTypeOperations;\r
+        this.accessValidations = accessValidations;\r
+    }\r
+\r
+    @POST\r
+    @Path("/annotationtypes")\r
+    @Operation(description = "Create AnnotationTypes from yaml", method = "POST",\r
+            summary = "Returns created annotation types",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "annotation types created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "annotation types already exist")})\r
+    \r
+    public Response uploadAnnotationTypes(@Parameter(description = "FileInputStream") @FormDataParam("annotationTypesZip") File file,\r
+            @HeaderParam("USER_ID") String userId) throws IOException {\r
+        accessValidations.validateUserExists(userId, "Annotation Types Creation");\r
+        Wrapper<String> yamlStringWrapper = new Wrapper<>();\r
+        AbstractValidationsServlet.extractZipContents(yamlStringWrapper, file);\r
+        List<ImmutablePair<AnnotationTypeDefinition, Boolean>> typesResults =\r
+                commonImportManager.createElementTypes(yamlStringWrapper.getInnerElement(),\r
+                        TypesUploadEndpoint::buildAnnotationFromFieldMap, annotationTypeOperations);\r
+        HttpStatus status = getHttpStatus(typesResults);\r
+        return Response.status(status.value()).entity(typesResults).build();\r
+    }\r
+\r
+    @VisibleForTesting\r
+    static <T extends ToscaDataDefinition> HttpStatus getHttpStatus(List<ImmutablePair<T, Boolean>> typesResults) {\r
+        boolean typeActionFailed = false;\r
+        boolean typeExists = false;\r
+        boolean typeActionSucceeded = false;\r
+        for (ImmutablePair<T, Boolean> typeResult : typesResults) {\r
+            Boolean result = typeResult.getRight();\r
+            if (result==null) {\r
+                typeExists = true;\r
+            } else if (result) {\r
+                typeActionSucceeded = true;\r
+            } else {\r
+                typeActionFailed = true;\r
+            }\r
+        }\r
+        HttpStatus status = HttpStatus.OK;\r
+        if (typeActionFailed) {\r
+            status =  HttpStatus.BAD_REQUEST;\r
+        } else if (typeActionSucceeded) {\r
+            status = HttpStatus.CREATED;\r
+        } else if (typeExists) {\r
+            status = HttpStatus.CONFLICT;\r
+        }\r
+        return status;\r
+    }\r
+\r
+    private static <T extends ToscaDataDefinition> T buildAnnotationFromFieldMap(String typeName, Map<String, Object> toscaJson) {\r
+        AnnotationTypeDefinition annotationType = new AnnotationTypeDefinition();\r
+        annotationType.setVersion(TypeUtils.getFirstCertifiedVersionVersion());\r
+        annotationType.setHighestVersion(true);\r
+        annotationType.setType(typeName);\r
+        TypeUtils.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, annotationType::setDescription);\r
+        CommonImportManager.setProperties(toscaJson, annotationType::setProperties);\r
+        return (T) annotationType;\r
+    }\r
+\r
+\r
+}\r
index e838dc9..d1eef49 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.google.gson.reflect.TypeToken;
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.glassfish.jersey.media.multipart.FormDataParam;
-import org.openecomp.sdc.be.components.impl.*;
-import org.openecomp.sdc.be.components.impl.model.ToscaTypeImportData;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupTypeDefinition;
-import org.openecomp.sdc.be.model.PolicyTypeDefinition;
-import org.openecomp.sdc.be.model.RelationshipTypeDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.normatives.ToscaTypeMetadata;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.ConsumerTwoParam;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.springframework.stereotype.Controller;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog/uploadType")
-@Consumes(MediaType.MULTIPART_FORM_DATA)
-@Produces(MediaType.APPLICATION_JSON)
-@Api(value = "Catalog Types Upload")
-@Controller
-public class TypesUploadServlet extends AbstractValidationsServlet {
-    private static final Logger log = Logger.getLogger(TypesUploadServlet.class);
-    public static final String CREATE = "Create ";
-
-    private final CapabilityTypeImportManager capabilityTypeImportManager;
-    private final InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager;
-    private final CategoriesImportManager categoriesImportManager;
-    private final DataTypeImportManager dataTypeImportManager;
-    private final GroupTypeImportManager groupTypeImportManager;
-    private final PolicyTypeImportManager policyTypeImportManager;
-    private final RelationshipTypeImportManager relationshipTypeImportManager;
-
-    @Inject
-    public TypesUploadServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        CapabilityTypeImportManager capabilityTypeImportManager,
-        InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager,
-        CategoriesImportManager categoriesImportManager,
-        DataTypeImportManager dataTypeImportManager,
-        GroupTypeImportManager groupTypeImportManager,
-        PolicyTypeImportManager policyTypeImportManager,
-        RelationshipTypeImportManager relationshipTypeImportManager) {
-        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
-        this.capabilityTypeImportManager = capabilityTypeImportManager;
-        this.interfaceLifecycleTypeImportManager = interfaceLifecycleTypeImportManager;
-        this.categoriesImportManager = categoriesImportManager;
-        this.dataTypeImportManager = dataTypeImportManager;
-        this.groupTypeImportManager = groupTypeImportManager;
-        this.policyTypeImportManager = policyTypeImportManager;
-        this.relationshipTypeImportManager = relationshipTypeImportManager;
-    }
-
-    @POST
-    @Path("/capability")
-    @ApiOperation(value = "Create Capability Type from yaml", httpMethod = "POST", notes = "Returns created Capability Type", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Capability Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-    @ApiResponse(code = 409, message = "Capability Type already exist") })
-    public Response uploadCapabilityType(@ApiParam("FileInputStream") @FormDataParam("capabilityTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> capabilityTypeImportManager.createCapabilityTypes(ymlPayload));
-        return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.CapabilityType.name());
-    }
-
-    @POST
-    @Path("/relationship")
-    @ApiOperation(value = "Create Relationship Type from yaml", httpMethod = "POST",
-            notes = "Returns created Relationship Type", response = Response.class)
-    @ApiResponses(value = {@ApiResponse(code = 201, message = "Relationship Type created"),
-            @ApiResponse(code = 403, message = "Restricted operation"),
-            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-            @ApiResponse(code = 409, message = "Relationship Type already exist")})
-    public Response uploadRelationshipType(@ApiParam("FileInputStream") @FormDataParam("relationshipTypeZip") File file,
-                                           @Context final HttpServletRequest request,
-                                           @HeaderParam("USER_ID") String creator) {
-        return uploadElementTypeServletLogic(this::createRelationshipTypes, file, request, creator,
-                NodeTypeEnum.RelationshipType.getName());
-    }
-
-    @POST
-    @Path("/interfaceLifecycle")
-    @ApiOperation(value = "Create Interface Lyfecycle Type from yaml", httpMethod = "POST", notes = "Returns created Interface Lifecycle Type", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Interface Lifecycle Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-    @ApiResponse(code = 409, message = "Interface Lifecycle Type already exist") })
-    public Response uploadInterfaceLifecycleType(@ApiParam("FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload));
-        return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "Interface Types");
-    }
-
-    @POST
-    @Path("/categories")
-    @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created categories", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Categories created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-    @ApiResponse(code = 409, message = "Category already exist") })
-    public Response uploadCategories(@ApiParam("FileInputStream") @FormDataParam("categoriesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> categoriesImportManager.createCategories(ymlPayload));
-        return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "categories");
-    }
-
-    @POST
-    @Path("/datatypes")
-    @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created data types", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "Data types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-    @ApiResponse(code = 409, message = "Data types already exist") })
-    public Response uploadDataTypes(@ApiParam("FileInputStream") @FormDataParam("dataTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = this::createDataTypes;
-        return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.DataType.getName());
-    }
-
-    @POST
-    @Path("/grouptypes")
-    @ApiOperation(value = "Create GroupTypes from yaml", httpMethod = "POST", notes = "Returns created group types", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "group types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-    @ApiResponse(code = 409, message = "group types already exist") })
-    public Response uploadGroupTypes(@ApiParam("toscaTypeMetadata") @FormDataParam("toscaTypeMetadata") String toscaTypesMetaData,
-                                     @ApiParam("FileInputStream") @FormDataParam("groupTypesZip") File file,
-                                     @Context final HttpServletRequest request,
-                                     @HeaderParam("USER_ID") String creator) {
-        Map<String, ToscaTypeMetadata> typesMetadata = getTypesMetadata(toscaTypesMetaData);
-        return uploadTypesWithMetaData(this::createGroupTypes, typesMetadata, file, request, creator, NodeTypeEnum.GroupType.getName());
-    }
-
-    @POST
-    @Path("/policytypes")
-    @ApiOperation(value = "Create PolicyTypes from yaml", httpMethod = "POST", notes = "Returns created policy types", response = Response.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "policy types created"),
-                            @ApiResponse(code = 403, message = "Restricted operation"),
-                            @ApiResponse(code = 400, message = "Invalid content / Missing content"),
-    @ApiResponse(code = 409, message = "policy types already exist") })
-    public Response uploadPolicyTypes(
-            @ApiParam("toscaTypeMetadata") @FormDataParam("toscaTypeMetadata") String toscaTypesMetaData,
-            @ApiParam("FileInputStream") @FormDataParam("policyTypesZip") File file,
-            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-        Map<String, ToscaTypeMetadata> typesMetadata = getTypesMetadata(toscaTypesMetaData);
-        return uploadTypesWithMetaData(this::createPolicyTypes, typesMetadata, file, request, creator, NodeTypeEnum.PolicyType.getName());
-    }
-
-    private Map<String, ToscaTypeMetadata> getTypesMetadata(String toscaTypesMetaData) {
-        return gson.fromJson(toscaTypesMetaData, new TypeToken<Map<String, ToscaTypeMetadata>>(){}.getType());
-    }
-
-    private Response uploadElementTypeServletLogic(ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod, File file, final HttpServletRequest request, String creator, String elementTypeName) {
-        init();
-        String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER);
-        try {
-            Wrapper<String> yamlStringWrapper = new Wrapper<>();
-
-            String url = request.getMethod() + " " + request.getRequestURI();
-            log.debug("Start handle request of {}", url);
-            Wrapper<Response> responseWrapper = doUploadTypeValidations(request, userId, file);
-            if (responseWrapper.isEmpty()) {
-                fillZipContents(yamlStringWrapper, file);
-            }
-            if (responseWrapper.isEmpty()) {
-                createElementsMethod.accept(responseWrapper, yamlStringWrapper.getInnerElement());
-            }
-            return responseWrapper.getInnerElement();
-        } catch (Exception e) {
-            log.debug("create {} failed with exception:", elementTypeName, e);
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE + elementTypeName);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    private Wrapper<Response> doUploadTypeValidations(final HttpServletRequest request, String userId, File file) {
-        Wrapper<Response> responseWrapper = new Wrapper<>();
-        Wrapper<User> userWrapper = new Wrapper<>();
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}", url);
-
-        validateUserExist(responseWrapper, userWrapper, userId);
-
-        if (responseWrapper.isEmpty()) {
-            validateUserRole(responseWrapper, userWrapper.getInnerElement());
-        }
-
-        if (responseWrapper.isEmpty()) {
-            validateDataNotNull(responseWrapper, file);
-        }
-        return responseWrapper;
-    }
-
-    private Response uploadTypesWithMetaData(ConsumerTwoParam<Wrapper<Response>, ToscaTypeImportData> createElementsMethod, Map<String, ToscaTypeMetadata> typesMetaData, File file, final HttpServletRequest request, String creator, String elementTypeName) {
-        init();
-        String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER);
-        Wrapper<String> yamlStringWrapper = new Wrapper<>();
-        try {
-            Wrapper<Response> responseWrapper = doUploadTypeValidations(request, userId, file);
-            if (responseWrapper.isEmpty()) {
-                fillZipContents(yamlStringWrapper, file);
-            }
-            if (responseWrapper.isEmpty()) {
-                ToscaTypeImportData toscaTypeImportData = new ToscaTypeImportData(yamlStringWrapper.getInnerElement(), typesMetaData);
-                createElementsMethod.accept(responseWrapper, toscaTypeImportData);
-            }
-            return responseWrapper.getInnerElement();
-        } catch (Exception e) {
-            log.debug("create {} failed with exception:", elementTypeName, e);
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE + elementTypeName);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    private <T> void createElementsType(Wrapper<Response> responseWrapper, Supplier<Either<T, ResponseFormat>> elementsCreater) {
-        Either<T, ResponseFormat> eitherResult = elementsCreater.get();
-        if (eitherResult.isRight()) {
-            Response response = buildErrorResponse(eitherResult.right().value());
-            responseWrapper.setInnerElement(response);
-        } else {
-            try {
-                Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), RepresentationUtils.toRepresentation(eitherResult.left().value()));
-                responseWrapper.setInnerElement(response);
-            } catch (Exception e) {
-                Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-                responseWrapper.setInnerElement(response);
-                log.error("#createElementsType - json serialization failed with error: ", e);
-            }
-        }
-    }
-
-    // data types
-    private void createDataTypes(Wrapper<Response> responseWrapper, String dataTypesYml) {
-        final Supplier<Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> dataTypeImportManager.createDataTypes(dataTypesYml);
-        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.DATA_TYPE_ALREADY_EXIST, NodeTypeEnum.DataType.name());
-    }
-
-    // group types
-    private void createGroupTypes(Wrapper<Response> responseWrapper, ToscaTypeImportData toscaTypeImportData) {
-        final Supplier<Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> groupTypeImportManager.createGroupTypes(toscaTypeImportData);
-        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.GROUP_TYPE_ALREADY_EXIST, NodeTypeEnum.GroupType.name());
-    }
-
-    // policy types
-    private void createPolicyTypes(Wrapper<Response> responseWrapper, ToscaTypeImportData toscaTypeImportData) {
-        final Supplier<Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> policyTypeImportManager.createPolicyTypes(toscaTypeImportData);
-        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.POLICY_TYPE_ALREADY_EXIST, NodeTypeEnum.PolicyType.name());
-    }
-
-    // data types
-    private <ElementTypeDefinition> void buildStatusForElementTypeCreate(Wrapper<Response> responseWrapper, Supplier<Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml, ActionStatus alreadyExistStatus, String elementTypeName) {
-        Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = generateElementTypeFromYml.get();
-
-        if (eitherResult.isRight()) {
-            Response response = buildErrorResponse(eitherResult.right().value());
-            responseWrapper.setInnerElement(response);
-        } else {
-            Object representation;
-            try {
-                List<ImmutablePair<ElementTypeDefinition, Boolean>> list = eitherResult.left().value();
-                ActionStatus status = ActionStatus.OK;
-                if (list != null) {
-
-                    // Group result by the right value - true or false.
-                    // I.e., get the number of data types which are new and
-                    // which are old.
-                    Map<Boolean, List<ImmutablePair<ElementTypeDefinition, Boolean>>> collect = list.stream().collect(Collectors.groupingBy(ImmutablePair<ElementTypeDefinition, Boolean>::getRight));
-                    if (collect != null) {
-                        Set<Boolean> keySet = collect.keySet();
-                        if (keySet.size() == 1) {
-                            Boolean isNew = keySet.iterator().next();
-                            if (isNew.booleanValue()) {
-                                // all data types created at the first time
-                                status = ActionStatus.CREATED;
-                            } else {
-                                // All data types already exists
-
-                                status = alreadyExistStatus;
-                            }
-                        }
-                    }
-                }
-                representation = RepresentationUtils.toRepresentation(eitherResult.left().value());
-
-                Response response = buildOkResponse(getComponentsUtils().getResponseFormat(status), representation);
-                responseWrapper.setInnerElement(response);
-
-            } catch (IOException e) {
-                BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE + elementTypeName);
-                log.debug("failed to convert {} to json", elementTypeName, e);
-                Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-                responseWrapper.setInnerElement(response);
-            }
-        }
-    }
-    // relationship types
-    private void createRelationshipTypes(Wrapper<Response> responseWrapper, String relationshipTypesYml) {
-        final Supplier<Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat>>
-                generateElementTypeFromYml =
-                () -> relationshipTypeImportManager.createRelationshipTypes(relationshipTypesYml);
-        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml,
-                ActionStatus.RELATIONSHIP_TYPE_ALREADY_EXIST, NodeTypeEnum.RelationshipType.name());
-    }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Set;\r
+import java.util.function.Supplier;\r
+import java.util.stream.Collectors;\r
+import javax.inject.Inject;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.apache.commons.lang3.tuple.ImmutablePair;\r
+import org.glassfish.jersey.media.multipart.FormDataParam;\r
+import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager;\r
+import org.openecomp.sdc.be.components.impl.CategoriesImportManager;\r
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;\r
+import org.openecomp.sdc.be.components.impl.DataTypeImportManager;\r
+import org.openecomp.sdc.be.components.impl.GroupTypeImportManager;\r
+import org.openecomp.sdc.be.components.impl.InterfaceLifecycleTypeImportManager;\r
+import org.openecomp.sdc.be.components.impl.PolicyTypeImportManager;\r
+import org.openecomp.sdc.be.components.impl.RelationshipTypeImportManager;\r
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;\r
+import org.openecomp.sdc.be.components.impl.model.ToscaTypeImportData;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.impl.ServletUtils;\r
+import org.openecomp.sdc.be.model.DataTypeDefinition;\r
+import org.openecomp.sdc.be.model.GroupTypeDefinition;\r
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;\r
+import org.openecomp.sdc.be.model.RelationshipTypeDefinition;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.model.normatives.ToscaTypeMetadata;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.ConsumerTwoParam;\r
+import org.openecomp.sdc.common.datastructure.Wrapper;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import org.springframework.stereotype.Controller;\r
+import com.google.gson.reflect.TypeToken;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/catalog/uploadType")\r
+@Consumes(MediaType.MULTIPART_FORM_DATA)\r
+@Produces(MediaType.APPLICATION_JSON)\r
+@OpenAPIDefinition(info = @Info(title = "Catalog Types Upload"))\r
+@Controller\r
+public class TypesUploadServlet extends AbstractValidationsServlet {\r
+    private static final Logger log = Logger.getLogger(TypesUploadServlet.class);\r
+    public static final String CREATE = "Create ";\r
+\r
+    private final CapabilityTypeImportManager capabilityTypeImportManager;\r
+    private final InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager;\r
+    private final CategoriesImportManager categoriesImportManager;\r
+    private final DataTypeImportManager dataTypeImportManager;\r
+    private final GroupTypeImportManager groupTypeImportManager;\r
+    private final PolicyTypeImportManager policyTypeImportManager;\r
+    private final RelationshipTypeImportManager relationshipTypeImportManager;\r
+\r
+    @Inject\r
+    public TypesUploadServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentInstanceBusinessLogic componentInstanceBL,\r
+        ComponentsUtils componentsUtils, ServletUtils servletUtils,\r
+        ResourceImportManager resourceImportManager,\r
+        CapabilityTypeImportManager capabilityTypeImportManager,\r
+        InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager,\r
+        CategoriesImportManager categoriesImportManager,\r
+        DataTypeImportManager dataTypeImportManager,\r
+        GroupTypeImportManager groupTypeImportManager,\r
+        PolicyTypeImportManager policyTypeImportManager,\r
+        RelationshipTypeImportManager relationshipTypeImportManager) {\r
+        super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);\r
+        this.capabilityTypeImportManager = capabilityTypeImportManager;\r
+        this.interfaceLifecycleTypeImportManager = interfaceLifecycleTypeImportManager;\r
+        this.categoriesImportManager = categoriesImportManager;\r
+        this.dataTypeImportManager = dataTypeImportManager;\r
+        this.groupTypeImportManager = groupTypeImportManager;\r
+        this.policyTypeImportManager = policyTypeImportManager;\r
+        this.relationshipTypeImportManager = relationshipTypeImportManager;\r
+    }\r
+\r
+    @POST\r
+    @Path("/capability")\r
+    @Operation(description = "Create Capability Type from yaml", method = "POST",\r
+            summary = "Returns created Capability Type", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Capability Type created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Capability Type already exist")})\r
+    public Response uploadCapabilityType(@Parameter(description = "FileInputStream") @FormDataParam("capabilityTypeZip") File file,\r
+            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {\r
+        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod =\r
+                (responseWrapper, ymlPayload) -> createElementsType(responseWrapper,\r
+                        () -> capabilityTypeImportManager.createCapabilityTypes(ymlPayload));\r
+        return uploadElementTypeServletLogic(createElementsMethod, file, request, creator,\r
+                NodeTypeEnum.CapabilityType.name());\r
+    }\r
+\r
+    @POST\r
+    @Path("/relationship")\r
+    @Operation(description = "Create Relationship Type from yaml", method = "POST",\r
+            summary = "Returns created Relationship Type", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Relationship Type created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Relationship Type already exist")})\r
+    public Response uploadRelationshipType(@Parameter(description = "FileInputStream") @FormDataParam("relationshipTypeZip") File file,\r
+                                           @Context final HttpServletRequest request,\r
+                                           @HeaderParam("USER_ID") String creator) {\r
+        return uploadElementTypeServletLogic(this::createRelationshipTypes, file, request, creator,\r
+                NodeTypeEnum.RelationshipType.getName());\r
+    }\r
+\r
+    @POST\r
+    @Path("/interfaceLifecycle")\r
+    @Operation(description = "Create Interface Lyfecycle Type from yaml", method = "POST",\r
+            summary = "Returns created Interface Lifecycle Type", responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Interface Lifecycle Type created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Interface Lifecycle Type already exist")})\r
+    public Response uploadInterfaceLifecycleType(\r
+            @Parameter(description = "FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file,\r
+            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {\r
+        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod =\r
+                (responseWrapper, ymlPayload) -> createElementsType(responseWrapper,\r
+                        () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload));\r
+        return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "Interface Types");\r
+    }\r
+\r
+    @POST\r
+    @Path("/categories")\r
+    @Operation(description = "Create Categories from yaml", method = "POST", summary = "Returns created categories",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Categories created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Category already exist")})\r
+    public Response uploadCategories(@Parameter(description = "FileInputStream") @FormDataParam("categoriesZip") File file,\r
+            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {\r
+        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod =\r
+                (responseWrapper, ymlPayload) -> createElementsType(responseWrapper,\r
+                        () -> categoriesImportManager.createCategories(ymlPayload));\r
+        return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "categories");\r
+    }\r
+\r
+    @POST\r
+    @Path("/datatypes")\r
+    @Operation(description = "Create Categories from yaml", method = "POST", summary = "Returns created data types",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Data types created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "Data types already exist")})\r
+    public Response uploadDataTypes(@Parameter(description = "FileInputStream") @FormDataParam("dataTypesZip") File file,\r
+            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {\r
+        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = this::createDataTypes;\r
+        return uploadElementTypeServletLogic(createElementsMethod, file, request, creator,\r
+                NodeTypeEnum.DataType.getName());\r
+    }\r
+\r
+    @POST\r
+    @Path("/grouptypes")\r
+    @Operation(description = "Create GroupTypes from yaml", method = "POST", summary = "Returns created group types",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "group types created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "group types already exist")})\r
+    public Response uploadGroupTypes(\r
+            @Parameter(description = "toscaTypeMetadata") @FormDataParam("toscaTypeMetadata") String toscaTypesMetaData,\r
+            @Parameter(description = "FileInputStream") @FormDataParam("groupTypesZip") File file,\r
+            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {\r
+        Map<String, ToscaTypeMetadata> typesMetadata = getTypesMetadata(toscaTypesMetaData);\r
+        return uploadTypesWithMetaData(this::createGroupTypes, typesMetadata, file, request, creator,\r
+                NodeTypeEnum.GroupType.getName());\r
+    }\r
+\r
+    @POST\r
+    @Path("/policytypes")\r
+    @Operation(description = "Create PolicyTypes from yaml", method = "POST", summary = "Returns created policy types",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "policy types created"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),\r
+            @ApiResponse(responseCode = "409", description = "policy types already exist")})\r
+    public Response uploadPolicyTypes(\r
+            @Parameter(description = "toscaTypeMetadata") @FormDataParam("toscaTypeMetadata") String toscaTypesMetaData,\r
+            @Parameter(description = "FileInputStream") @FormDataParam("policyTypesZip") File file,\r
+            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {\r
+        Map<String, ToscaTypeMetadata> typesMetadata = getTypesMetadata(toscaTypesMetaData);\r
+        return uploadTypesWithMetaData(this::createPolicyTypes, typesMetadata, file, request, creator,\r
+                NodeTypeEnum.PolicyType.getName());\r
+    }\r
+\r
+    private Map<String, ToscaTypeMetadata> getTypesMetadata(String toscaTypesMetaData) {\r
+        return gson.fromJson(toscaTypesMetaData, new TypeToken<Map<String, ToscaTypeMetadata>>(){}.getType());\r
+    }\r
+\r
+    private Response uploadElementTypeServletLogic(ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod, File file, final HttpServletRequest request, String creator, String elementTypeName) {\r
+        init();\r
+        String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER);\r
+        try {\r
+            Wrapper<String> yamlStringWrapper = new Wrapper<>();\r
+\r
+            String url = request.getMethod() + " " + request.getRequestURI();\r
+            log.debug("Start handle request of {}", url);\r
+            Wrapper<Response> responseWrapper = doUploadTypeValidations(request, userId, file);\r
+            if (responseWrapper.isEmpty()) {\r
+                fillZipContents(yamlStringWrapper, file);\r
+            }\r
+            if (responseWrapper.isEmpty()) {\r
+                createElementsMethod.accept(responseWrapper, yamlStringWrapper.getInnerElement());\r
+            }\r
+            return responseWrapper.getInnerElement();\r
+        } catch (Exception e) {\r
+            log.debug("create {} failed with exception:", elementTypeName, e);\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE + elementTypeName);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    private Wrapper<Response> doUploadTypeValidations(final HttpServletRequest request, String userId, File file) {\r
+        Wrapper<Response> responseWrapper = new Wrapper<>();\r
+        Wrapper<User> userWrapper = new Wrapper<>();\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {}", url);\r
+\r
+        validateUserExist(responseWrapper, userWrapper, userId);\r
+\r
+        if (responseWrapper.isEmpty()) {\r
+            validateUserRole(responseWrapper, userWrapper.getInnerElement());\r
+        }\r
+\r
+        if (responseWrapper.isEmpty()) {\r
+            validateDataNotNull(responseWrapper, file);\r
+        }\r
+        return responseWrapper;\r
+    }\r
+\r
+    private Response uploadTypesWithMetaData(ConsumerTwoParam<Wrapper<Response>, ToscaTypeImportData> createElementsMethod, Map<String, ToscaTypeMetadata> typesMetaData, File file, final HttpServletRequest request, String creator, String elementTypeName) {\r
+        init();\r
+        String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER);\r
+        Wrapper<String> yamlStringWrapper = new Wrapper<>();\r
+        try {\r
+            Wrapper<Response> responseWrapper = doUploadTypeValidations(request, userId, file);\r
+            if (responseWrapper.isEmpty()) {\r
+                fillZipContents(yamlStringWrapper, file);\r
+            }\r
+            if (responseWrapper.isEmpty()) {\r
+                ToscaTypeImportData toscaTypeImportData = new ToscaTypeImportData(yamlStringWrapper.getInnerElement(), typesMetaData);\r
+                createElementsMethod.accept(responseWrapper, toscaTypeImportData);\r
+            }\r
+            return responseWrapper.getInnerElement();\r
+        } catch (Exception e) {\r
+            log.debug("create {} failed with exception:", elementTypeName, e);\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE + elementTypeName);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    private <T> void createElementsType(Wrapper<Response> responseWrapper, Supplier<Either<T, ResponseFormat>> elementsCreater) {\r
+        Either<T, ResponseFormat> eitherResult = elementsCreater.get();\r
+        if (eitherResult.isRight()) {\r
+            Response response = buildErrorResponse(eitherResult.right().value());\r
+            responseWrapper.setInnerElement(response);\r
+        } else {\r
+            try {\r
+                Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), RepresentationUtils.toRepresentation(eitherResult.left().value()));\r
+                responseWrapper.setInnerElement(response);\r
+            } catch (Exception e) {\r
+                Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+                responseWrapper.setInnerElement(response);\r
+                log.error("#createElementsType - json serialization failed with error: ", e);\r
+            }\r
+        }\r
+    }\r
+\r
+    // data types\r
+    private void createDataTypes(Wrapper<Response> responseWrapper, String dataTypesYml) {\r
+        final Supplier<Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml =\r
+                () -> dataTypeImportManager.createDataTypes(dataTypesYml);\r
+        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml,\r
+                ActionStatus.DATA_TYPE_ALREADY_EXIST, NodeTypeEnum.DataType.name());\r
+    }\r
+\r
+    // group types\r
+    private void createGroupTypes(Wrapper<Response> responseWrapper, ToscaTypeImportData toscaTypeImportData) {\r
+        final Supplier<Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml =\r
+                () -> groupTypeImportManager.createGroupTypes(toscaTypeImportData);\r
+        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml,\r
+                ActionStatus.GROUP_TYPE_ALREADY_EXIST, NodeTypeEnum.GroupType.name());\r
+    }\r
+\r
+    // policy types\r
+    private void createPolicyTypes(Wrapper<Response> responseWrapper, ToscaTypeImportData toscaTypeImportData) {\r
+        final Supplier<Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml =\r
+                () -> policyTypeImportManager.createPolicyTypes(toscaTypeImportData);\r
+        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml,\r
+                ActionStatus.POLICY_TYPE_ALREADY_EXIST, NodeTypeEnum.PolicyType.name());\r
+    }\r
+\r
+    // data types\r
+    private <ElementTypeDefinition> void buildStatusForElementTypeCreate(Wrapper<Response> responseWrapper, Supplier<Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml, ActionStatus alreadyExistStatus, String elementTypeName) {\r
+        Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = generateElementTypeFromYml.get();\r
+\r
+        if (eitherResult.isRight()) {\r
+            Response response = buildErrorResponse(eitherResult.right().value());\r
+            responseWrapper.setInnerElement(response);\r
+        } else {\r
+            Object representation;\r
+            try {\r
+                List<ImmutablePair<ElementTypeDefinition, Boolean>> list = eitherResult.left().value();\r
+                ActionStatus status = ActionStatus.OK;\r
+                if (list != null) {\r
+\r
+                    // Group result by the right value - true or false.\r
+                    // I.e., get the number of data types which are new and\r
+                    // which are old.\r
+                    Map<Boolean, List<ImmutablePair<ElementTypeDefinition, Boolean>>> collect = list.stream().collect(Collectors.groupingBy(ImmutablePair<ElementTypeDefinition, Boolean>::getRight));\r
+                    if (collect != null) {\r
+                        Set<Boolean> keySet = collect.keySet();\r
+                        if (keySet.size() == 1) {\r
+                            Boolean isNew = keySet.iterator().next();\r
+                            if (isNew.booleanValue()) {\r
+                                // all data types created at the first time\r
+                                status = ActionStatus.CREATED;\r
+                            } else {\r
+                                // All data types already exists\r
+\r
+                                status = alreadyExistStatus;\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+                representation = RepresentationUtils.toRepresentation(eitherResult.left().value());\r
+\r
+                Response response = buildOkResponse(getComponentsUtils().getResponseFormat(status), representation);\r
+                responseWrapper.setInnerElement(response);\r
+\r
+            } catch (IOException e) {\r
+                BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE + elementTypeName);\r
+                log.debug("failed to convert {} to json", elementTypeName, e);\r
+                Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+                responseWrapper.setInnerElement(response);\r
+            }\r
+        }\r
+    }\r
+    // relationship types\r
+    private void createRelationshipTypes(Wrapper<Response> responseWrapper, String relationshipTypesYml) {\r
+        final Supplier<Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat>>\r
+                generateElementTypeFromYml =\r
+                () -> relationshipTypeImportManager.createRelationshipTypes(relationshipTypesYml);\r
+        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml,\r
+                ActionStatus.RELATIONSHIP_TYPE_ALREADY_EXIST, NodeTypeEnum.RelationshipType.name());\r
+    }\r
+\r
+}\r
index 328b4a9..15646c2 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.servlets;
-
-import com.jcabi.aspects.Loggable;
-import fj.data.Either;
-import io.swagger.annotations.*;
-import javax.inject.Inject;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-import java.util.ArrayList;
-import java.util.List;
-
-@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/user")
-@Api(value = "User Administration", description = "User admininstarator operations")
-@Singleton
-public class UserAdminServlet extends BeGenericServlet {
-
-    private static final String UTF_8 = "UTF-8";
-       private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
-       private static final String ROLE_DELIMITER = ",";
-    private static final Logger log = Logger.getLogger(UserAdminServlet.class);
-    private final UserBusinessLogic userBusinessLogic;
-
-    @Inject
-    public UserAdminServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils) {
-        super(userBusinessLogic, componentsUtils);
-        this.userBusinessLogic = userBusinessLogic;
-    }
-
-    /***************************************
-     * API start
-     *************************************************************/
-
-    /* User by userId CRUD start */
-
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
-    // retrieve all user details
-    @GET
-    @Path("/{userId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "retrieve user details", httpMethod = "GET", notes = "Returns user details according to userId", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"),
-            @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response get(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}", url);
-
-        try {
-            Either<User, ActionStatus> either = userBusinessLogic.getUser(userId, false);
-
-            if (either.isRight()) {
-                return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));
-            } else {
-                if (either.left().value() != null) {
-                    return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
-                } else {
-                    return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-                }
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User");
-            log.debug("get user failed with unexpected error: {}", e.getMessage(), e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @GET
-    @Path("/{userId}/role")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "retrieve user role", notes = "Returns user role according to userId", response = String.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user role Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"),
-            @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response getRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(getRole) Start handle request of {}", url);
-
-        try {
-            Either<User, ActionStatus> either = userBusinessLogic.getUser(userId, false);
-            if (either.isRight()) {
-                return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));
-            } else {
-                if (either.left().value() != null) {
-                    String roleJson = "{ \"role\" : \"" + either.left().value().getRole() + "\" }";
-                    return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), roleJson);
-                } else {
-                    return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-                }
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User Role");
-            log.debug("Get user role failed with unexpected error: {}", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
-    // update user role
-    @POST
-    @Path("/{userId}/role")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "update user role", notes = "Update user role", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Update user OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information/Restricted operation"),
-            @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response updateUserRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser, @Context final HttpServletRequest request,
-            @ApiParam(value = "json describe the update role", required = true) String data, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(modifierUserId);
-        log.debug("modifier id is {}", modifierUserId);
-
-        Response response = null;
-
-        try {
-            User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value();
-            Either<User, ResponseFormat> updateUserResponse = userBusinessLogic.updateUserRole(modifier, userIdUpdateUser, updateInfoUser.getRole());
-
-            if (updateUserResponse.isRight()) {
-                log.debug("failed to update user role");
-                response = buildErrorResponse(updateUserResponse.right().value());
-                return response;
-            }
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value());
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata");
-            log.debug("Update User Role failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    /* User role CRUD end */
-
-    /* New user CRUD start */
-    @POST
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "add user", httpMethod = "POST", notes = "Provision new user", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 201, message = "New user created"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"),
-            @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response createUser(@Context final HttpServletRequest request, @ApiParam(value = "json describe the user", required = true) String newUserData, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        // get modifier id
-        User modifier = new User();
-        modifier.setUserId(modifierAttId);
-        log.debug("modifier id is {}", modifierAttId);
-
-        Response response = null;
-
-        try {
-            User newUserInfo = getComponentsUtils().convertJsonToObject(newUserData, modifier, User.class, AuditingActionEnum.ADD_USER).left().value();
-            Either<User, ResponseFormat> createUserResponse = userBusinessLogic.createUser(modifier, newUserInfo);
-
-            if (createUserResponse.isRight()) {
-                log.debug("failed to create user");
-                response = buildErrorResponse(createUserResponse.right().value());
-                return response;
-            }
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), createUserResponse.left().value());
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata");
-            log.debug("Create User failed with exception", e);
-            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            return response;
-
-        }
-    }
-
-    /* New user CRUD end */
-
-    /* User authorization start */
-
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
-    // User Authorization
-    @GET
-    @Path("/authorize")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-
-    @ApiOperation(value = "authorize", notes = "authorize user", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 403, message = "Restricted Access"), @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response authorize(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName, @HeaderParam("HTTP_CSP_LASTNAME") String lastName,
-            @HeaderParam("HTTP_CSP_EMAIL") String email) {
-
-        try {
-            userId = userId != null ? URLDecoder.decode(userId, UTF_8) : null;
-            firstName = firstName != null ? URLDecoder.decode(firstName, UTF_8) : null;
-            lastName = lastName != null ? URLDecoder.decode(lastName, UTF_8) : null;
-            email = email != null ? URLDecoder.decode(email, UTF_8) : null;
-        } catch (UnsupportedEncodingException e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Authorize User - decode headers");
-            ResponseFormat errorResponseWrapper = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-            log.error("#authorize - authorization decoding failed with error: ", e);
-            return buildErrorResponse(errorResponseWrapper);
-        }
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF, url);
-
-        User authUser = new User();
-        authUser.setUserId(userId);
-        authUser.setFirstName(firstName);
-        authUser.setLastName(lastName);
-        authUser.setEmail(email);
-        log.debug("auth user id is {}", userId);
-
-        Response response = null;
-        try {
-            Either<User, ResponseFormat> authorize = userBusinessLogic.authorize(authUser);
-
-            if (authorize.isRight()) {
-                log.debug("authorize user failed");
-                response = buildErrorResponse(authorize.right().value());
-                return response;
-            }
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), authorize.left().value());
-            return response;
-
-        } catch (Exception e) {
-            log.debug("authorize user failed with unexpected error: {}", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    /* User authorization end */
-
-    @GET
-    @Path("/admins")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "retrieve all administrators", httpMethod = "GET", notes = "Returns all administrators", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response getAdminsUser(@Context final HttpServletRequest request) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}", url);
-
-        try {
-            Either<List<User>, ResponseFormat> either = userBusinessLogic.getAllAdminUsers();
-
-            if (either.isRight()) {
-                log.debug("Failed to get all admin users");
-                return buildErrorResponse(either.right().value());
-            } else {
-                if (either.left().value() != null) {
-                    return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
-                } else {
-                    return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-                }
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Administrators");
-            log.debug("get all admins failed with unexpected error: {}", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-
-    @GET
-    @Path("/users")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "Retrieve the list of all active ASDC users or only group of users having specific roles.", httpMethod = "GET", notes = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns users Ok"), @ApiResponse(code = 204, message = "No provisioned ASDC users of requested role"), @ApiResponse(code = 403, message = "Restricted Access"),
-            @ApiResponse(code = 400, message = "Missing content"), @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response getUsersList(@Context final HttpServletRequest request, @ApiParam(value = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId,
-            @ApiParam(value = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {} modifier id is {}", url, userId);
-
-        List<String> rolesList = new ArrayList<>();
-        if (roles != null && !roles.trim().isEmpty()) {
-            String[] rolesArr = roles.split(ROLE_DELIMITER);
-            for (String role : rolesArr) {
-                rolesList.add(role.trim());
-            }
-        }
-
-        try {
-            Either<List<User>, ResponseFormat> either = userBusinessLogic.getUsersList(userId, rolesList, roles);
-
-            if (either.isRight()) {
-                log.debug("Failed to get ASDC users");
-                return buildErrorResponse(either.right().value());
-            } else {
-                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
-            }
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users");
-            log.debug("get users failed with unexpected error: {}", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-
-    }
-
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
-    // delete user
-    @DELETE
-    @Path("/{userId}")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Produces(MediaType.APPLICATION_JSON)
-    @ApiOperation(value = "delete user", notes = "Delete user", response = User.class)
-    @ApiResponses(value = { @ApiResponse(code = 200, message = "Update deleted OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"),
-            @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") })
-    public Response deActivateUser(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userIdHeader) {
-
-        String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {} modifier id is {}", url, userIdHeader);
-
-        User modifier = new User();
-        modifier.setUserId(userIdHeader);
-
-        Response response = null;
-        try {
-            Either<User, ResponseFormat> deactiveUserResponse = userBusinessLogic.deActivateUser(modifier, userId);
-
-            if (deactiveUserResponse.isRight()) {
-                log.debug("Failed to deactivate user");
-                response = buildErrorResponse(deactiveUserResponse.right().value());
-                return response;
-            }
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deactiveUserResponse.left().value());
-            return response;
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users");
-            log.debug("deactivate user failed with unexpected error: {}", e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-        }
-    }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * SDC\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.sdc.be.servlets;\r
+\r
+import java.io.UnsupportedEncodingException;\r
+import java.net.URLDecoder;\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+import javax.inject.Inject;\r
+import javax.inject.Singleton;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.ws.rs.Consumes;\r
+import javax.ws.rs.DELETE;\r
+import javax.ws.rs.GET;\r
+import javax.ws.rs.HeaderParam;\r
+import javax.ws.rs.POST;\r
+import javax.ws.rs.Path;\r
+import javax.ws.rs.PathParam;\r
+import javax.ws.rs.Produces;\r
+import javax.ws.rs.QueryParam;\r
+import javax.ws.rs.core.Context;\r
+import javax.ws.rs.core.MediaType;\r
+import javax.ws.rs.core.Response;\r
+import org.openecomp.sdc.be.config.BeEcompErrorManager;\r
+import org.openecomp.sdc.be.dao.api.ActionStatus;\r
+import org.openecomp.sdc.be.impl.ComponentsUtils;\r
+import org.openecomp.sdc.be.model.User;\r
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;\r
+import org.openecomp.sdc.be.user.UserBusinessLogic;\r
+import org.openecomp.sdc.common.api.Constants;\r
+import org.openecomp.sdc.common.log.wrappers.Logger;\r
+import org.openecomp.sdc.exception.ResponseFormat;\r
+import com.jcabi.aspects.Loggable;\r
+import fj.data.Either;\r
+import io.swagger.v3.oas.annotations.OpenAPIDefinition;\r
+import io.swagger.v3.oas.annotations.Operation;\r
+import io.swagger.v3.oas.annotations.Parameter;\r
+import io.swagger.v3.oas.annotations.info.Info;\r
+import io.swagger.v3.oas.annotations.media.ArraySchema;\r
+import io.swagger.v3.oas.annotations.media.Content;\r
+import io.swagger.v3.oas.annotations.media.Schema;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponse;\r
+import io.swagger.v3.oas.annotations.responses.ApiResponses;\r
+\r
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)\r
+@Path("/v1/user")\r
+@OpenAPIDefinition(info = @Info(title = "User Administration", description = "User admininstarator operations"))\r
+@Singleton\r
+public class UserAdminServlet extends BeGenericServlet {\r
+\r
+    private static final String UTF_8 = "UTF-8";\r
+       private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";\r
+       private static final String ROLE_DELIMITER = ",";\r
+    private static final Logger log = Logger.getLogger(UserAdminServlet.class);\r
+    private final UserBusinessLogic userBusinessLogic;\r
+\r
+    @Inject\r
+    public UserAdminServlet(UserBusinessLogic userBusinessLogic,\r
+        ComponentsUtils componentsUtils) {\r
+        super(userBusinessLogic, componentsUtils);\r
+        this.userBusinessLogic = userBusinessLogic;\r
+    }\r
+\r
+    /***************************************\r
+     * API start\r
+     *************************************************************/\r
+\r
+    /* User by userId CRUD start */\r
+\r
+    /////////////////////////////////////////////////////////////////////////////////////////////////////\r
+    // retrieve all user details\r
+    @GET\r
+    @Path("/{userId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "retrieve user details", method = "GET",\r
+            summary = "Returns user details according to userId",responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returns user Ok"),\r
+            @ApiResponse(responseCode = "404", description = "User not found"),\r
+            @ApiResponse(responseCode = "405", description = "Method Not Allowed"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response get(\r
+            @Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(get) Start handle request of {}", url);\r
+\r
+        try {\r
+            Either<User, ActionStatus> either = userBusinessLogic.getUser(userId, false);\r
+\r
+            if (either.isRight()) {\r
+                return buildErrorResponse(\r
+                        getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));\r
+            } else {\r
+                if (either.left().value() != null) {\r
+                    return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                            either.left().value());\r
+                } else {\r
+                    return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+                }\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User");\r
+            log.debug("get user failed with unexpected error: {}", e.getMessage(), e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/{userId}/role")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "retrieve user role", summary = "Returns user role according to userId",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returns user role Ok"),\r
+            @ApiResponse(responseCode = "404", description = "User not found"),\r
+            @ApiResponse(responseCode = "405", description = "Method Not Allowed"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response getRole(\r
+            @Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,\r
+            @Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(getRole) Start handle request of {}", url);\r
+\r
+        try {\r
+            Either<User, ActionStatus> either = userBusinessLogic.getUser(userId, false);\r
+            if (either.isRight()) {\r
+                return buildErrorResponse(\r
+                        getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));\r
+            } else {\r
+                if (either.left().value() != null) {\r
+                    String roleJson = "{ \"role\" : \"" + either.left().value().getRole() + "\" }";\r
+                    return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), roleJson);\r
+                } else {\r
+                    return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+                }\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User Role");\r
+            log.debug("Get user role failed with unexpected error: {}", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    /////////////////////////////////////////////////////////////////////////////////////////////////////\r
+    // update user role\r
+    @POST\r
+    @Path("/{userId}/role")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "update user role", summary = "Update user role", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Update user OK"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid Content."),\r
+            @ApiResponse(responseCode = "403", description = "Missing information/Restricted operation"),\r
+            @ApiResponse(responseCode = "404", description = "User not found"),\r
+            @ApiResponse(responseCode = "405", description = "Method Not Allowed"),\r
+            @ApiResponse(responseCode = "409", description = "User already exists"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response updateUserRole(\r
+            @Parameter(description = "userId of user to get",\r
+                    required = true) @PathParam("userId") final String userIdUpdateUser,\r
+            @Context final HttpServletRequest request,\r
+            @Parameter(description = "json describe the update role", required = true) String data,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(modifierUserId);\r
+        log.debug("modifier id is {}", modifierUserId);\r
+\r
+        Response response = null;\r
+\r
+        try {\r
+            User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value();\r
+            Either<User, ResponseFormat> updateUserResponse = userBusinessLogic.updateUserRole(modifier, userIdUpdateUser, updateInfoUser.getRole());\r
+\r
+            if (updateUserResponse.isRight()) {\r
+                log.debug("failed to update user role");\r
+                response = buildErrorResponse(updateUserResponse.right().value());\r
+                return response;\r
+            }\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value());\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata");\r
+            log.debug("Update User Role failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    /* User role CRUD end */\r
+\r
+    /* New user CRUD start */\r
+    @POST\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "add user", method = "POST", summary = "Provision new user", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "New user created"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid Content."),\r
+            @ApiResponse(responseCode = "403", description = "Missing information"),\r
+            @ApiResponse(responseCode = "405", description = "Method Not Allowed"),\r
+            @ApiResponse(responseCode = "409", description = "User already exists"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response createUser(@Context final HttpServletRequest request,\r
+            @Parameter(description = "json describe the user", required = true) String newUserData,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        // get modifier id\r
+        User modifier = new User();\r
+        modifier.setUserId(modifierAttId);\r
+        log.debug("modifier id is {}", modifierAttId);\r
+\r
+        Response response = null;\r
+\r
+        try {\r
+            User newUserInfo = getComponentsUtils().convertJsonToObject(newUserData, modifier, User.class, AuditingActionEnum.ADD_USER).left().value();\r
+            Either<User, ResponseFormat> createUserResponse = userBusinessLogic.createUser(modifier, newUserInfo);\r
+\r
+            if (createUserResponse.isRight()) {\r
+                log.debug("failed to create user");\r
+                response = buildErrorResponse(createUserResponse.right().value());\r
+                return response;\r
+            }\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), createUserResponse.left().value());\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata");\r
+            log.debug("Create User failed with exception", e);\r
+            response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+            return response;\r
+\r
+        }\r
+    }\r
+\r
+    /* New user CRUD end */\r
+\r
+    /* User authorization start */\r
+\r
+    /////////////////////////////////////////////////////////////////////////////////////////////////////\r
+    // User Authorization\r
+    @GET\r
+    @Path("/authorize")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+\r
+    @Operation(description = "authorize", summary = "authorize user", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returns user Ok"), @ApiResponse(responseCode = "403", description = "Restricted Access"), @ApiResponse(responseCode = "500", description = "Internal Server Error") })\r
+    public Response authorize(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName, @HeaderParam("HTTP_CSP_LASTNAME") String lastName,\r
+            @HeaderParam("HTTP_CSP_EMAIL") String email) {\r
+\r
+        try {\r
+            userId = userId != null ? URLDecoder.decode(userId, UTF_8) : null;\r
+            firstName = firstName != null ? URLDecoder.decode(firstName, UTF_8) : null;\r
+            lastName = lastName != null ? URLDecoder.decode(lastName, UTF_8) : null;\r
+            email = email != null ? URLDecoder.decode(email, UTF_8) : null;\r
+        } catch (UnsupportedEncodingException e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Authorize User - decode headers");\r
+            ResponseFormat errorResponseWrapper = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);\r
+            log.error("#authorize - authorization decoding failed with error: ", e);\r
+            return buildErrorResponse(errorResponseWrapper);\r
+        }\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug(START_HANDLE_REQUEST_OF, url);\r
+\r
+        User authUser = new User();\r
+        authUser.setUserId(userId);\r
+        authUser.setFirstName(firstName);\r
+        authUser.setLastName(lastName);\r
+        authUser.setEmail(email);\r
+        log.debug("auth user id is {}", userId);\r
+\r
+        Response response = null;\r
+        try {\r
+            Either<User, ResponseFormat> authorize = userBusinessLogic.authorize(authUser);\r
+\r
+            if (authorize.isRight()) {\r
+                log.debug("authorize user failed");\r
+                response = buildErrorResponse(authorize.right().value());\r
+                return response;\r
+            }\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), authorize.left().value());\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            log.debug("authorize user failed with unexpected error: {}", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    /* User authorization end */\r
+\r
+    @GET\r
+    @Path("/admins")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "retrieve all administrators", method = "GET", summary = "Returns all administrators",\r
+            responses = @ApiResponse(\r
+                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returns user Ok"),\r
+            @ApiResponse(responseCode = "405", description = "Method Not Allowed"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response getAdminsUser(@Context final HttpServletRequest request) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("(get) Start handle request of {}", url);\r
+\r
+        try {\r
+            Either<List<User>, ResponseFormat> either = userBusinessLogic.getAllAdminUsers();\r
+\r
+            if (either.isRight()) {\r
+                log.debug("Failed to get all admin users");\r
+                return buildErrorResponse(either.right().value());\r
+            } else {\r
+                if (either.left().value() != null) {\r
+                    return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),\r
+                            either.left().value());\r
+                } else {\r
+                    return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+                }\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Administrators");\r
+            log.debug("get all admins failed with unexpected error: {}", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+\r
+    @GET\r
+    @Path("/users")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "Retrieve the list of all active ASDC users or only group of users having specific roles.",\r
+            method = "GET",\r
+            summary = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header",\r
+                    responses = @ApiResponse(\r
+                            content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returns users Ok"),\r
+            @ApiResponse(responseCode = "204", description = "No provisioned ASDC users of requested role"),\r
+            @ApiResponse(responseCode = "403", description = "Restricted Access"),\r
+            @ApiResponse(responseCode = "400", description = "Missing content"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response getUsersList(@Context final HttpServletRequest request, @Parameter(\r
+            description = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId,\r
+            @Parameter(\r
+                    description = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {} modifier id is {}", url, userId);\r
+\r
+        List<String> rolesList = new ArrayList<>();\r
+        if (roles != null && !roles.trim().isEmpty()) {\r
+            String[] rolesArr = roles.split(ROLE_DELIMITER);\r
+            for (String role : rolesArr) {\r
+                rolesList.add(role.trim());\r
+            }\r
+        }\r
+\r
+        try {\r
+            Either<List<User>, ResponseFormat> either = userBusinessLogic.getUsersList(userId, rolesList, roles);\r
+\r
+            if (either.isRight()) {\r
+                log.debug("Failed to get ASDC users");\r
+                return buildErrorResponse(either.right().value());\r
+            } else {\r
+                return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());\r
+            }\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users");\r
+            log.debug("get users failed with unexpected error: {}", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+\r
+    }\r
+\r
+    /////////////////////////////////////////////////////////////////////////////////////////////////////\r
+    // delete user\r
+    @DELETE\r
+    @Path("/{userId}")\r
+    @Consumes(MediaType.APPLICATION_JSON)\r
+    @Produces(MediaType.APPLICATION_JSON)\r
+    @Operation(description = "delete user", summary = "Delete user", responses = @ApiResponse(\r
+            content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))))\r
+    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Update deleted OK"),\r
+            @ApiResponse(responseCode = "400", description = "Invalid Content."),\r
+            @ApiResponse(responseCode = "403", description = "Missing information"),\r
+            @ApiResponse(responseCode = "404", description = "User not found"),\r
+            @ApiResponse(responseCode = "405", description = "Method Not Allowed"),\r
+            @ApiResponse(responseCode = "409", description = "Restricted operation"),\r
+            @ApiResponse(responseCode = "500", description = "Internal Server Error")})\r
+    public Response deActivateUser(\r
+            @Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,\r
+            @Context final HttpServletRequest request,\r
+            @HeaderParam(value = Constants.USER_ID_HEADER) String userIdHeader) {\r
+\r
+        String url = request.getMethod() + " " + request.getRequestURI();\r
+        log.debug("Start handle request of {} modifier id is {}", url, userIdHeader);\r
+\r
+        User modifier = new User();\r
+        modifier.setUserId(userIdHeader);\r
+\r
+        Response response = null;\r
+        try {\r
+            Either<User, ResponseFormat> deactiveUserResponse = userBusinessLogic.deActivateUser(modifier, userId);\r
+\r
+            if (deactiveUserResponse.isRight()) {\r
+                log.debug("Failed to deactivate user");\r
+                response = buildErrorResponse(deactiveUserResponse.right().value());\r
+                return response;\r
+            }\r
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deactiveUserResponse.left().value());\r
+            return response;\r
+\r
+        } catch (Exception e) {\r
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users");\r
+            log.debug("deactivate user failed with unexpected error: {}", e);\r
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));\r
+        }\r
+    }\r
+}\r