diff options
Diffstat (limited to 'ms')
108 files changed, 4329 insertions, 1396 deletions
diff --git a/ms/blueprintsprocessor/.gitignore b/ms/blueprintsprocessor/.gitignore index f72f78ad..04f991d1 100644 --- a/ms/blueprintsprocessor/.gitignore +++ b/ms/blueprintsprocessor/.gitignore @@ -28,4 +28,5 @@ **/transaction.log **/*versionsBackup **/blackDuckHub* -**/*.jsonld
\ No newline at end of file +**/*.jsonld +/target-ide/ diff --git a/ms/blueprintsprocessor/application/etc/logback.xml b/ms/blueprintsprocessor/application/etc/logback.xml new file mode 100755 index 00000000..a97bb8c3 --- /dev/null +++ b/ms/blueprintsprocessor/application/etc/logback.xml @@ -0,0 +1,36 @@ +<!--
+ ~ Copyright © 2017-2018 AT&T Intellectual Property.
+ ~
+ ~ 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.
+ -->
+
+<configuration>
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <!-- encoders are assigned the type
+ ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
+ <encoder>
+ <pattern>%d{HH:mm:ss.SSS} %-5level %logger{100} - %msg%n</pattern>
+ </encoder>
+ </appender>
+
+
+ <logger name="org.springframework" level="info"/>
+ <logger name="org.springframework.web" level="info"/>
+ <logger name="org.hibernate" level="error"/>
+ <logger name="org.onap.ccsdk.apps" level="info"/>
+
+ <root level="warn">
+ <appender-ref ref="STDOUT"/>
+ </root>
+
+</configuration>
diff --git a/ms/blueprintsprocessor/application/etc/run.source b/ms/blueprintsprocessor/application/etc/run.source new file mode 100755 index 00000000..7557ab12 --- /dev/null +++ b/ms/blueprintsprocessor/application/etc/run.source @@ -0,0 +1,12 @@ +java -classpath "/etc:${APP_HOME}/lib/*:/lib/*:/src:/schema:/generated-sources:${APP_CONFIG_HOME}:${APP_HOME}" \ +-DappName=${APPLICATIONNAME} -DappVersion=${BUNDLEVERSION} \ +-DrouteOffer=${ROUTEOFFER} \ +-DVERSION_ROUTEOFFER_ENVCONTEXT=${BUNDLEVERSION}/${STICKYSELECTORKEY}/${ENVCONTEXT} \ +-DSecurityFilePath=/etc \ +-DREST_NAME_NORMALIZER_PATTERN_FILE=/etc/PatternInputs.txt \ +-Dms_name=org.onap.ccsdk.apps.blueprintsprocessor \ +-Dlogging.config=${APP_CONFIG_HOME}/logback.xml \ +-Djava.security.egd=file:/dev/./urandom \ +-DAPPNAME=${APP_NAME} -DAPPENV=${APP_ENV} -DAPPVERSION=${APP_VERSION} -DNAMESPACE=${NAMESPACE} \ +-Dspring.config.location=${APP_CONFIG_HOME}/ \ +org.onap.ccsdk.apps.blueprintsprocessor.BlueprintProcessorApplication diff --git a/ms/blueprintsprocessor/application/opt/app/onap/config/application.properties b/ms/blueprintsprocessor/application/opt/app/onap/config/application.properties new file mode 100755 index 00000000..c4880b67 --- /dev/null +++ b/ms/blueprintsprocessor/application/opt/app/onap/config/application.properties @@ -0,0 +1,36 @@ +#
+# Copyright � 2017-2018 AT&T Intellectual Property.
+# Modifications Copyright © 2019 Bell Canada.
+#
+# 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.
+#
+#logging.level.web=DEBUG
+
+# Web server config
+server.port=8080
+
+blueprintsprocessor.grpcEnable=false
+blueprintsprocessor.httpPort=8080
+blueprintsprocessor.grpcPort=9111
+# Blueprint Processor File Execution and Handling Properties
+blueprintsprocessor.blueprintDeployPath=/opt/app/onap/blueprints/deploy
+blueprintsprocessor.blueprintArchivePath=/opt/app/onap/blueprints/archive
+# Primary Database Configuration
+blueprintsprocessor.db.primary.url=jdbc:mysql://db:3306/sdnctl
+blueprintsprocessor.db.primary.username=sdnctl
+blueprintsprocessor.db.primary.password=sdnctl
+blueprintsprocessor.db.primary.driverClassName=org.mariadb.jdbc.Driver
+blueprintsprocessor.db.primary.hibernateHbm2ddlAuto=validate
+blueprintsprocessor.db.primary.hibernateDDLAuto=none
+blueprintsprocessor.db.primary.hibernateNamingStrategy=org.hibernate.cfg.ImprovedNamingStrategy
+blueprintsprocessor.db.primary.hibernateDialect=org.hibernate.dialect.MySQL5InnoDBDialect
\ No newline at end of file diff --git a/ms/blueprintsprocessor/application/opt/app/onap/config/logback.xml b/ms/blueprintsprocessor/application/opt/app/onap/config/logback.xml new file mode 100755 index 00000000..a97bb8c3 --- /dev/null +++ b/ms/blueprintsprocessor/application/opt/app/onap/config/logback.xml @@ -0,0 +1,36 @@ +<!--
+ ~ Copyright © 2017-2018 AT&T Intellectual Property.
+ ~
+ ~ 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.
+ -->
+
+<configuration>
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <!-- encoders are assigned the type
+ ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
+ <encoder>
+ <pattern>%d{HH:mm:ss.SSS} %-5level %logger{100} - %msg%n</pattern>
+ </encoder>
+ </appender>
+
+
+ <logger name="org.springframework" level="info"/>
+ <logger name="org.springframework.web" level="info"/>
+ <logger name="org.hibernate" level="error"/>
+ <logger name="org.onap.ccsdk.apps" level="info"/>
+
+ <root level="warn">
+ <appender-ref ref="STDOUT"/>
+ </root>
+
+</configuration>
diff --git a/ms/blueprintsprocessor/application/pom.xml b/ms/blueprintsprocessor/application/pom.xml index 679a8b90..06752b79 100644..100755 --- a/ms/blueprintsprocessor/application/pom.xml +++ b/ms/blueprintsprocessor/application/pom.xml @@ -3,6 +3,7 @@ ~ Copyright © 2017-2018 AT&T Intellectual Property. ~ ~ Modifications Copyright © 2018 IBM. + ~ Modifications Copyright © 2019 Bell Canada. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. @@ -31,6 +32,10 @@ <dependencies> <dependency> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <artifactId>core</artifactId> + </dependency> + <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> @@ -69,13 +74,91 @@ <scope>test</scope> </dependency> </dependencies> - <build> + <resources> + <resource> + <!--config and resource files --> + <directory>${basedir}/etc</directory> + <targetPath>${basedir}/target/etc</targetPath> + <filtering>true</filtering> + <includes> + <include>**/*</include> + </includes> + </resource> + <resource> + <!--config and resource files --> + <directory>${basedir}/src/main/resources</directory> + <targetPath>${basedir}/target/src/main/resources</targetPath> + <filtering>true</filtering> + <includes> + <include>**/*</include> + </includes> + </resource> + <resource> + <directory>src/main/resources</directory> + <includes> + <include>**/*</include> + </includes> + <filtering>true</filtering> + </resource> + </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> + <plugin> + <artifactId>maven-resources-plugin</artifactId> + <version>2.6</version> + <executions> + <execution> + <id>copy-dockerfile</id> + <goals> + <goal>copy-resources</goal> + </goals><!-- here the phase you need --> + <phase>validate</phase> + <configuration> + <outputDirectory>${basedir}/target/docker-stage</outputDirectory> + <resources> + <resource> + <directory>src/main/docker</directory> + <includes> + <include>*</include> + </includes> + <filtering>true</filtering> + </resource> + </resources> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-antrun-plugin</artifactId> + <executions> + <execution> + <id>ant-test</id> + <phase>package</phase> + <configuration> + <tasks> + <fixcrlf srcdir="${basedir}" eol="unix" includes="**/*.sh, **/*.source"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.1</version> + <configuration> + <!-- <skip>${skip.compile}</skip>--> + <source>1.8</source> + <target>1.8</target> + </configuration> + </plugin> </plugins> </build> </project> diff --git a/ms/blueprintsprocessor/application/src/main/resources/application-dev.properties b/ms/blueprintsprocessor/application/src/main/resources/application-dev.properties new file mode 100755 index 00000000..6bfa2407 --- /dev/null +++ b/ms/blueprintsprocessor/application/src/main/resources/application-dev.properties @@ -0,0 +1,36 @@ +#
+# Copyright � 2017-2018 AT&T Intellectual Property.
+# Modifications Copyright © 2019 IBM, Bell Canada.
+#
+# 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.
+#
+#logging.level.web=DEBUG
+
+# Web server config
+server.port=8080
+
+blueprintsprocessor.grpcEnable=false
+blueprintsprocessor.httpPort=8080
+blueprintsprocessor.grpcPort=9111
+# Blueprint Processor File Execution and Handling Properties
+blueprintsprocessor.blueprintDeployPath=/opt/app/onap/blueprints/deploy
+blueprintsprocessor.blueprintArchivePath=/opt/app/onap/blueprints/archive
+# Primary Database Configuration
+blueprintsprocessor.db.primary.url=jdbc:mysql://localhost:3306/sdnctl
+blueprintsprocessor.db.primary.username=sdnctl
+blueprintsprocessor.db.primary.password=sdnctl
+blueprintsprocessor.db.primary.driverClassName=org.mariadb.jdbc.Driver
+blueprintsprocessor.db.primary.hibernateHbm2ddlAuto=update
+blueprintsprocessor.db.primary.hibernateDDLAuto=none
+blueprintsprocessor.db.primary.hibernateNamingStrategy=org.hibernate.cfg.ImprovedNamingStrategy
+blueprintsprocessor.db.primary.hibernateDialect=org.hibernate.dialect.MySQL5InnoDBDialect
\ No newline at end of file diff --git a/ms/blueprintsprocessor/application/src/main/resources/application.properties b/ms/blueprintsprocessor/application/src/main/resources/application.properties index fa1a1e6e..62695207 100644..100755 --- a/ms/blueprintsprocessor/application/src/main/resources/application.properties +++ b/ms/blueprintsprocessor/application/src/main/resources/application.properties @@ -1,5 +1,6 @@ #
# Copyright � 2017-2018 AT&T Intellectual Property.
+# Modifications Copyright © 2019 IBM, Bell Canada.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -14,6 +15,10 @@ # limitations under the License.
#
#logging.level.web=DEBUG
+
+# Web server config
+server.port=8080
+
blueprintsprocessor.grpcEnable=false
blueprintsprocessor.httpPort=8080
blueprintsprocessor.grpcPort=9111
@@ -21,7 +26,7 @@ blueprintsprocessor.grpcPort=9111 blueprintsprocessor.blueprintDeployPath=/opt/app/onap/blueprints/deploy
blueprintsprocessor.blueprintArchivePath=/opt/app/onap/blueprints/archive
# Primary Database Configuration
-blueprintsprocessor.db.primary.url=jdbc:mysql://localhost:3306/sdnctl
+blueprintsprocessor.db.primary.url=jdbc:mysql://db:3306/sdnctl
blueprintsprocessor.db.primary.username=sdnctl
blueprintsprocessor.db.primary.password=sdnctl
blueprintsprocessor.db.primary.driverClassName=org.mariadb.jdbc.Driver
diff --git a/ms/blueprintsprocessor/application/src/test/resources/application.properties b/ms/blueprintsprocessor/application/src/test/resources/application.properties index f896ee05..d21264c0 100644 --- a/ms/blueprintsprocessor/application/src/test/resources/application.properties +++ b/ms/blueprintsprocessor/application/src/test/resources/application.properties @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# Web server config +server.port=8080 # Blueprint Processor File Execution and Handling Properties blueprintsprocessor.blueprintDeployPath=/opt/app/onap/blueprints/deploy blueprintsprocessor.blueprintArchivePath=/opt/app/onap/blueprints/archive diff --git a/ms/blueprintsprocessor/distribution/pom.xml b/ms/blueprintsprocessor/distribution/pom.xml new file mode 100755 index 00000000..fb5e3c12 --- /dev/null +++ b/ms/blueprintsprocessor/distribution/pom.xml @@ -0,0 +1,196 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ Copyright © 2019 IBM, Bell Canada. + ~ + ~ 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. + --> +<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> + <parent> + <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> + <artifactId>parent</artifactId> + <version>0.4.1-SNAPSHOT</version> + <relativePath>../parent</relativePath> + </parent> + <artifactId>distribution</artifactId> + <packaging>pom</packaging> + <name>Blueprints Processor Distribution</name> + <properties> + <assembly.id>maven</assembly.id> + <name.space>org.onap.ccsdk.apps</name.space> <!-- <name.space>${namespace}</name.space> --> + <serviceArtifactName>blueprintsprocessor</serviceArtifactName> + <image.name>onap/ccsdk-blueprintsprocessor</image.name> + <docker.buildArg.https_proxy>${https_proxy}</docker.buildArg.https_proxy> + <docker.push.phase>deploy</docker.push.phase> + <docker.verbose>true</docker.verbose> + </properties> + + <dependencies> + <dependency> + <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> + <artifactId>application</artifactId> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <artifactId>maven-resources-plugin</artifactId> + <version>2.6</version> + <executions> + <execution> + <id>copy-dockerfile</id> + <goals> + <goal>copy-resources</goal> + </goals><!-- here the phase you need --> + <phase>validate</phase> + <configuration> + <outputDirectory>${basedir}/target/docker-stage</outputDirectory> + <resources> + <resource> + <directory>src/main/docker</directory> + <includes> + <include>*</include> + </includes> + <filtering>true</filtering> + </resource> + </resources> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-antrun-plugin</artifactId> + <executions> + <execution> + <id>ant-test</id> + <phase>package</phase> + <configuration> + <tasks> + <fixcrlf srcdir="${basedir}" eol="unix" includes="**/*.sh, **/*.source"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <!--build the final artifact for docker deployment --> + <artifactId>maven-assembly-plugin</artifactId> + <version>3.1.0</version> + <configuration> + <!-- <skipAssembly>${skip.assembly}</skipAssembly>--> + <outputDirectory>${basedir}/target/docker-stage</outputDirectory> + <descriptors> + <descriptor>src/main/docker/distribution.xml</descriptor> + </descriptors> + <tarLongFileMode>posix</tarLongFileMode> + </configuration> + <executions> + <execution> + <id>${assembly.id}</id> + <phase>package</phase> + <goals> + <goal>single</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.codehaus.groovy.maven</groupId> + <artifactId>gmaven-plugin</artifactId> + <version>1.0</version> + <executions> + <execution> + <phase>validate</phase> + <goals> + <goal>execute</goal> + </goals> + <configuration> + <source> + println project.properties['ccsdk.project.version'] + def versionArray + if (project.properties['ccsdk.project.version'] != null ) { + versionArray = project.properties['ccsdk.project.version'].split('\\.') + } + + if (project.properties['ccsdk.project.version'].endsWith("-SNAPSHOT")) + { + project.properties['project.docker.latesttag.version']=versionArray[0] + '.' + versionArray[1] + "-STAGING-latest" + } else { + project.properties['project.docker.latesttag.version']=versionArray[0]+'.' + versionArray[1]+"-STAGING-latest" + } + + println 'New Tag for docker:' + project.properties['project.docker.latesttag.version'] + </source> + </configuration> + </execution> + </executions> + </plugin> + + </plugins> + </build> + + <profiles> + <profile> + <id>docker</id> + <build> + <plugins> + <plugin> + <groupId>io.fabric8</groupId> + <artifactId>docker-maven-plugin</artifactId> + <version>0.26.1</version> + <inherited>false</inherited> + <configuration> + <images> + <image> + <name>${image.name}</name> + <build> + <cleanup>try</cleanup> + <dockerFileDir>${basedir}/target/docker-stage</dockerFileDir> + <tags> + <tag>${project.version}</tag> + <tag>${project.version}-STAGING-${maven.build.timestamp}</tag> + <tag>${project.docker.latesttag.version}</tag> + </tags> + </build> + </image> + </images> + <verbose>true</verbose> + </configuration> + <executions> + <execution> + <id>generate-images</id> + <phase>package</phase> + <goals> + <goal>build</goal> + </goals> + </execution> + <execution> + <id>push-images</id> + <phase>${docker.push.phase}</phase> + <goals> + <goal>build</goal> + <goal>push</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + + </profiles> +</project>
\ No newline at end of file diff --git a/ms/blueprintsprocessor/distribution/src/main/dc/docker-compose.yaml b/ms/blueprintsprocessor/distribution/src/main/dc/docker-compose.yaml new file mode 100755 index 00000000..c0eade50 --- /dev/null +++ b/ms/blueprintsprocessor/distribution/src/main/dc/docker-compose.yaml @@ -0,0 +1,33 @@ +version: '3.3'
+
+services:
+ db:
+ image: mariadb:latest
+ container_name: ccsdk-mariadb
+ ports:
+ - "3306:3306"
+ volumes:
+ - ~/vm_mysql:/var/lib/mysql
+ restart: always
+ environment:
+ MYSQL_ROOT_PASSWORD: sdnctl
+ MYSQL_DATABASE: sdnctl
+ MYSQL_USER: sdnctl
+ MYSQL_PASSWORD: sdnctl
+ blueprints-processor:
+ depends_on:
+ - db
+ image: onap/ccsdk-blueprintsprocessor:latest
+ container_name: bp-rest
+ ports:
+ - "8000:8080"
+ restart: always
+ volumes:
+ - ~/share/vm_ms/blueprintsprocessor/config:/opt/app/onap/config
+ - ~/share/vm_ms/blueprintsprocessor/logs:/logs
+ environment:
+ APPLICATIONNAME: BlueprintsProcessor
+ BUNDLEVERSION: 1.0.0
+ APP_CONFIG_HOME: /opt/app/onap/config
+ STICKYSELECTORKEY:
+ ENVCONTEXT: dev
\ No newline at end of file diff --git a/ms/blueprintsprocessor/distribution/src/main/docker/Dockerfile b/ms/blueprintsprocessor/distribution/src/main/docker/Dockerfile new file mode 100755 index 00000000..21362329 --- /dev/null +++ b/ms/blueprintsprocessor/distribution/src/main/docker/Dockerfile @@ -0,0 +1,20 @@ +FROM anapsix/alpine-java:8_jdk + +ENV HTTP_PROXY ${HTTP_PROXY} +ENV HTTPS_PROXY ${HTTPS_PROXY} + +RUN apk add --no-cache curl + +COPY startService.sh /startService.sh +RUN chmod 777 /startService.sh && dos2unix /startService.sh + +COPY @project.build.finalName@-@assembly.id@.tar.gz /source.tar.gz + +RUN (mkdir -p /source /opt/app/onap) && (tar -xzf /source.tar.gz -C /source) \ +&& (mv /source/@project.build.finalName@ /source/app) \ +&& (cp -rf /source/app/opt/app/onap/lib /opt/app/onap/) \ +&& (cp -rf /source/app/etc /) \ +&& (cp -rf /source/app/config /) \ +&& (rm -rf /source) + +ENTRYPOINT /startService.sh
\ No newline at end of file diff --git a/ms/blueprintsprocessor/distribution/src/main/docker/distribution.xml b/ms/blueprintsprocessor/distribution/src/main/docker/distribution.xml new file mode 100755 index 00000000..b538b73b --- /dev/null +++ b/ms/blueprintsprocessor/distribution/src/main/docker/distribution.xml @@ -0,0 +1,69 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ Copyright © 2018-2019 Bell Canada. + ~ + ~ 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. + --> + +<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd"> + <!-- create a tar.gz file containing the projects dependencies --> + <id>${assembly.id}</id> + <formats> + <format>tar.gz</format> + </formats> + <dependencySets> + <dependencySet> + <outputDirectory>/opt/app/onap/lib</outputDirectory> + <outputFileNameMapping>${artifact.groupId}-${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension}</outputFileNameMapping> + <excludes> + </excludes> + </dependencySet> + </dependencySets> + <fileSets> + <fileSet> + <directory>${project.basedir}/../application/src/main/resources</directory> + <includes> + <include>application.properties</include> + <include>logback.xml</include> + </includes> + <outputDirectory>./</outputDirectory> + <useDefaultExcludes>true</useDefaultExcludes> + </fileSet> + <fileSet> + <directory>${project.basedir}/src/main/docker</directory> + <includes> + <include>Dockerfile</include> + <include>startService.sh</include> + </includes> + <outputDirectory>./</outputDirectory> + <useDefaultExcludes>true</useDefaultExcludes> + </fileSet> + <fileSet> + <directory>${project.basedir}/../application/src/main/resources</directory> + <outputDirectory>src/main/resources</outputDirectory> + <useDefaultExcludes>true</useDefaultExcludes> + </fileSet> + <fileSet> + <directory>${project.basedir}/../application/opt/app/onap/config</directory> + <outputDirectory>./config</outputDirectory> + <useDefaultExcludes>true</useDefaultExcludes> + </fileSet> + <fileSet> + <directory>${project.basedir}/../application/etc</directory> + <outputDirectory>./etc</outputDirectory> + <useDefaultExcludes>true</useDefaultExcludes> + </fileSet> + </fileSets> +</assembly>
\ No newline at end of file diff --git a/ms/blueprintsprocessor/distribution/src/main/docker/startService.sh b/ms/blueprintsprocessor/distribution/src/main/docker/startService.sh new file mode 100755 index 00000000..79bcbc06 --- /dev/null +++ b/ms/blueprintsprocessor/distribution/src/main/docker/startService.sh @@ -0,0 +1,9 @@ +#!/bin/sh + +nodeName=BlueprintsProcessor_1.0.0_$(cat /proc/self/cgroup | grep docker | sed s/\\//\\n/g | tail -1) + +echo "APP Config HOME : ${APP_CONFIG_HOME}" +export APP_HOME=/opt/app/onap + +cp -rf /config /opt/app/onap/ +source /etc/run.source diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt index 05f6a2db..a2c7344b 100644 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt @@ -17,6 +17,7 @@ package org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.JsonNodeFactory import org.junit.Test import org.junit.runner.RunWith import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers @@ -46,6 +47,8 @@ class ComponentNetconfExecutorTest { fun testComponentNetconfExecutor() { val executionServiceInput = ExecutionServiceInput() + executionServiceInput.payload = JsonNodeFactory.instance.objectNode() + val commonHeader = CommonHeader() commonHeader.requestId = "1234" executionServiceInput.commonHeader = commonHeader diff --git a/ms/blueprintsprocessor/functions/pom.xml b/ms/blueprintsprocessor/functions/pom.xml index 2a952f88..2a952f88 100644..100755 --- a/ms/blueprintsprocessor/functions/pom.xml +++ b/ms/blueprintsprocessor/functions/pom.xml diff --git a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt index 5eb40225..9e2ba0b9 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt @@ -22,7 +22,7 @@ import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInp import org.onap.ccsdk.apps.blueprintsprocessor.functions.python.executor.utils.PythonExecutorUtils import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractComponentFunction import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmptyNThrow +import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmptyOrThrow import org.onap.ccsdk.apps.controllerblueprints.core.data.OperationAssignment import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired @@ -62,7 +62,7 @@ open class ComponentJythonExecutor(private val pythonExecutorProperty: PythonExe val content: String? = bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName) - checkNotEmptyNThrow(content, "artifact ($artifactName) content is empty") + checkNotEmptyOrThrow(content, "artifact ($artifactName) content is empty") val pythonPath: MutableList<String> = operationAssignment.implementation?.dependencies ?: arrayListOf() pythonPath.add(blueprintBasePath) diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt index 07591a50..83cf59c2 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt @@ -17,6 +17,7 @@ package org.onap.ccsdk.apps.blueprintsprocessor.functions.python.executor import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.JsonNodeFactory import org.junit.Test import org.junit.runner.RunWith import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers @@ -26,6 +27,7 @@ import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.apps.controllerblueprints.core.asJsonNode import org.onap.ccsdk.apps.controllerblueprints.core.putJsonElement import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.TestPropertySource @@ -43,8 +45,10 @@ class ComponentJythonExecutorTest { @Test fun testPythonComponentInjection() { - + /* val executionServiceInput = ExecutionServiceInput() + executionServiceInput.payload = JsonNodeFactory.instance.objectNode() + val commonHeader = CommonHeader() commonHeader.requestId = "1234" executionServiceInput.commonHeader = commonHeader @@ -55,8 +59,12 @@ class ComponentJythonExecutorTest { actionIdentifiers.actionName = "activate" executionServiceInput.actionIdentifiers = actionIdentifiers + */ - val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(commonHeader.requestId, + val executionServiceInput = JacksonUtils.readValueFromClassPathFile("payload/requests/sample-activate-request.json", + ExecutionServiceInput::class.java)!! + + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234", "./../../../../components/model-catalog/blueprint-model/starter-blueprint/baseconfiguration") val stepMetaData: MutableMap<String, JsonNode> = hashMapOf() @@ -68,6 +76,7 @@ class ComponentJythonExecutorTest { componentJythonExecutor.bluePrintRuntimeService = bluePrintRuntimeService componentJythonExecutor.stepName = "activate-jython" + componentJythonExecutor.apply(executionServiceInput) } diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/resources/requests/sample-activate-request.json b/ms/blueprintsprocessor/functions/python-executor/src/test/resources/payload/requests/sample-activate-request.json index 7142f045..7142f045 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/test/resources/requests/sample-activate-request.json +++ b/ms/blueprintsprocessor/functions/python-executor/src/test/resources/payload/requests/sample-activate-request.json diff --git a/ms/blueprintsprocessor/functions/resource-resolution/pom.xml b/ms/blueprintsprocessor/functions/resource-resolution/pom.xml index 2f08c580..925f9e33 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/pom.xml +++ b/ms/blueprintsprocessor/functions/resource-resolution/pom.xml @@ -14,7 +14,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -<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"> +<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> <parent> <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> @@ -27,4 +28,29 @@ <name>Blueprints Processor Function - Resource Resolution</name> <description>Blueprints Processor Function - Resource Resolution</description> + <dependencies> + <!--<dependency> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <artifactId>db-resources</artifactId> + <version>${project.version}</version> + </dependency>--> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-data-jpa</artifactId> + </dependency> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + </dependency> + <dependency> + <groupId>org.mariadb.jdbc</groupId> + <artifactId>mariadb-java-client</artifactId> + </dependency> + <dependency> + <groupId>org.hibernate</groupId> + <artifactId>hibernate-testing</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + </project> diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt index 9d6f4a6b..c4ae1397 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt @@ -6,53 +6,83 @@ import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintContext import org.onap.ccsdk.apps.controllerblueprints.core.service.DefaultBluePrintRuntimeService
class ResourceAssignmentRuntimeService(private var id: String, private var bluePrintContext: BluePrintContext)
- : DefaultBluePrintRuntimeService(id, bluePrintContext){
+ : DefaultBluePrintRuntimeService(id, bluePrintContext) {
- private var resourceResolutionStore: MutableMap<String, JsonNode> = hashMapOf()
+ private lateinit var resolutionId: String
+ private var resourceStore: MutableMap<String, JsonNode> = hashMapOf()
- override fun getExecutionContext(): MutableMap<String, JsonNode> {
- return resourceResolutionStore
+ fun createUniqueId(key: String) {
+ resolutionId = "$id-$key"
}
- @Suppress("UNCHECKED_CAST")
- override fun setExecutionContext(executionContext: MutableMap<String, JsonNode>) {
- this.resourceResolutionStore = executionContext
+ fun cleanResourceStore() {
+ resourceStore.clear()
}
- override fun put(key: String, value: JsonNode) {
- resourceResolutionStore[key] = value
+ fun putResolutionStore(key: String, value: JsonNode) {
+ resourceStore[key] = value
}
- override fun get(key: String): JsonNode {
- return resourceResolutionStore[key] ?: throw BluePrintProcessorException("failed to get execution property($key)")
+ fun getResolutionStore(key: String): JsonNode {
+ return resourceStore[key]
+ ?: throw BluePrintProcessorException("failed to get execution property ($key)")
}
- override fun check(key: String): Boolean {
- return resourceResolutionStore.containsKey(key)
+ fun checkResolutionStore(key: String): Boolean {
+ return resourceStore.containsKey(key)
}
- override fun cleanRuntime() {
- resourceResolutionStore.clear()
+ fun getJsonNodeFromResolutionStore(key: String): JsonNode {
+ return getResolutionStore(key)
}
- private fun getJsonNode(key: String): JsonNode {
- return get(key)
+ fun getStringFromResolutionStore(key: String): String? {
+ return getResolutionStore(key).asText()
}
- override fun getAsString(key: String): String? {
- return get(key).asText()
+ fun getBooleanFromResolutionStore(key: String): Boolean? {
+ return getResolutionStore(key).asBoolean()
}
- override fun getAsBoolean(key: String): Boolean? {
- return get(key).asBoolean()
+ fun getIntFromResolutionStore(key: String): Int? {
+ return getResolutionStore(key).asInt()
}
- override fun getAsInt(key: String): Int? {
- return get(key).asInt()
+ fun getDoubleFromResolutionStore(key: String): Double? {
+ return getResolutionStore(key).asDouble()
}
- override fun getAsDouble(key: String): Double? {
- return get(key).asDouble()
+ fun putDictionaryStore(key: String, value: JsonNode) {
+ resourceStore["dictionary-$key"] = value
+ }
+
+ fun getDictionaryStore(key: String): JsonNode {
+ return resourceStore["dictionary-$key"]
+ ?: throw BluePrintProcessorException("failed to get execution property (dictionary-$key)")
+ }
+
+ fun checkDictionaryStore(key: String): Boolean {
+ return resourceStore.containsKey("dictionary-$key")
+ }
+
+ fun getJsonNodeFromDictionaryStore(key: String): JsonNode {
+ return getResolutionStore("dictionary-$key")
+ }
+
+ fun getStringFromDictionaryStore(key: String): String? {
+ return getResolutionStore("dictionary-$key").asText()
+ }
+
+ fun getBooleanFromDictionaryStore(key: String): Boolean? {
+ return getResolutionStore("dictionary-$key").asBoolean()
+ }
+
+ fun getIntFromDictionaryStore(key: String): Int? {
+ return getResolutionStore("dictionary-$key").asInt()
+ }
+
+ fun getDoubleFromDictionaryStore(key: String): Double? {
+ return getResolutionStore("dictionary-$key").asDouble()
}
}
diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt index 5a7161da..38e5c95f 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt @@ -18,6 +18,7 @@ package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution
import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor
+import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService
@@ -88,7 +89,7 @@ class ResourceResolutionService { val resourceDictionaries: MutableMap<String, ResourceDefinition> = JacksonUtils.getMapFromFile(dictionaryFile, ResourceDefinition::class.java)
?: throw BluePrintProcessorException("couldn't get Dictionary Definitions")
- executeProcessors(bluePrintRuntimeService, resourceDictionaries, resourceAssignments)
+ executeProcessors(bluePrintRuntimeService, resourceDictionaries, resourceAssignments, templateArtifactName)
// Check Template is there
val templateContent = bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, mappingArtifactName)
@@ -107,11 +108,13 @@ class ResourceResolutionService { }
- fun executeProcessors(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- resourceDictionaries: MutableMap<String, ResourceDefinition>,
- resourceAssignments: MutableList<ResourceAssignment>) {
+ private fun executeProcessors(blueprintRuntimeService: BluePrintRuntimeService<*>,
+ resourceDictionaries: MutableMap<String, ResourceDefinition>,
+ resourceAssignments: MutableList<ResourceAssignment>,
+ templateArtifactName: String) {
val bulkSequenced = BulkResourceSequencingUtils.process(resourceAssignments)
+ val resourceAssignmentRuntimeService = ResourceAssignmentUtils.transformToRARuntimeService(blueprintRuntimeService, templateArtifactName)
bulkSequenced.map { batchResourceAssignments ->
batchResourceAssignments.filter { it.name != "*" && it.name != "start" }
@@ -124,7 +127,7 @@ class ResourceResolutionService { "for resource assignment(${resourceAssignment.name})")
try {
// Set BluePrint Runtime Service
- resourceAssignmentProcessor.bluePrintRuntimeService = bluePrintRuntimeService
+ resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService
// Set Resource Dictionaries
resourceAssignmentProcessor.resourceDictionaries = resourceDictionaries
// Invoke Apply Method
diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceSourceProperties.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceSourceProperties.kt index b141025d..9bad0998 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceSourceProperties.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceSourceProperties.kt @@ -33,8 +33,8 @@ open class DefaultResourceSource : ResourceSourceProperties() { open class DatabaseResourceSource : ResourceSourceProperties() { lateinit var type: String lateinit var query: String - var inputKeyMapping: MutableList<String>? = null - var outputKeyMapping: MutableList<String>? = null + var inputKeyMapping: MutableMap<String, String>? = null + var outputKeyMapping: MutableMap<String, String>? = null lateinit var keyDependencies: MutableList<String> } @@ -43,8 +43,8 @@ open class RestResourceSource : ResourceSourceProperties() { lateinit var urlPath: String lateinit var path: String lateinit var expressionType: String - var inputKeyMapping: MutableList<String>? = null - var outputKeyMapping: MutableList<String>? = null + var inputKeyMapping: MutableMap<String, String>? = null + var outputKeyMapping: MutableMap<String, String>? = null lateinit var keyDependencies: MutableList<String> } @@ -53,7 +53,7 @@ open class CapabilityResourceSource : ResourceSourceProperties() { lateinit var instanceName: String lateinit var path: String lateinit var expressionType: String - var inputKeyMapping: MutableList<String>? = null - var outputKeyMapping: MutableList<String>? = null + var inputKeyMapping: MutableMap<String, String>? = null + var outputKeyMapping: MutableMap<String, String>? = null lateinit var keyDependencies: MutableList<String> }
\ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceAssignmentProcessor.kt index 99338498..6c235599 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceAssignmentProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceAssignmentProcessor.kt @@ -18,8 +18,8 @@ package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.pr import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.CapabilityResourceSource import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.utils.ResourceAssignmentUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.ApplicationContext import org.springframework.stereotype.Service @@ -40,17 +40,16 @@ open class CapabilityResourceAssignmentProcessor : ResourceAssignmentProcessor() return "resource-assignment-processor-capability" } - override fun process(executionRequest: ResourceAssignment) { + override fun process(resourceAssignment: ResourceAssignment) { - val resourceDefinition = resourceDictionaries[executionRequest.dictionaryName] - ?: throw BluePrintProcessorException("couldn't get resource definition for ${executionRequest.dictionaryName}") + val resourceDefinition = resourceDictionaries[resourceAssignment.dictionaryName] + ?: throw BluePrintProcessorException("couldn't get resource definition for ${resourceAssignment.dictionaryName}") - val resourceSource = resourceDefinition.sources[executionRequest.dictionarySource] - ?: throw BluePrintProcessorException("couldn't get resource definition ${executionRequest.dictionaryName} source(${executionRequest.dictionarySource})") + val resourceSource = resourceDefinition.sources[resourceAssignment.dictionarySource] + ?: throw BluePrintProcessorException("couldn't get resource definition ${resourceAssignment.dictionaryName} source(${resourceAssignment.dictionarySource})") - checkNotNull(resourceSource.properties) { "failed to get ${executionRequest.dictionarySource} properties" } - - val capabilityResourceSourceProperty = ResourceAssignmentUtils.transformResourceSource(resourceSource.properties!!, CapabilityResourceSource::class.java) + val resourceSourceProps = checkNotNull(resourceSource.properties) { "failed to get $resourceSource properties" } + val capabilityResourceSourceProperty = JacksonUtils.getInstanceFromMap(resourceSourceProps, CapabilityResourceSource::class.java) val instanceType = capabilityResourceSourceProperty.type val instanceName = capabilityResourceSourceProperty.instanceName @@ -74,14 +73,14 @@ open class CapabilityResourceAssignmentProcessor : ResourceAssignmentProcessor() checkNotNull(componentResourceAssignmentProcessor) { "failed to get capability resource assignment processor($instanceName)" } // Assign Current Blueprint runtime and ResourceDictionaries - componentResourceAssignmentProcessor.bluePrintRuntimeService = bluePrintRuntimeService + componentResourceAssignmentProcessor.raRuntimeService = raRuntimeService componentResourceAssignmentProcessor.resourceDictionaries = resourceDictionaries // Invoke componentResourceAssignmentProcessor - componentResourceAssignmentProcessor.apply(executionRequest) + componentResourceAssignmentProcessor.apply(resourceAssignment) } - override fun recover(runtimeException: RuntimeException, executionRequest: ResourceAssignment) { + override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { TODO("To Implement") } diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceAssignmentProcessor.kt index 1c5455fd..e389f362 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceAssignmentProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceAssignmentProcessor.kt @@ -17,24 +17,50 @@ package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor +import com.fasterxml.jackson.databind.node.NullNode +import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment +import org.slf4j.LoggerFactory import org.springframework.stereotype.Service /** * DefaultResourceAssignmentProcessor * - * @author Brinda Santh + * @author Kapil Singal */ @Service("resource-assignment-processor-default") open class DefaultResourceAssignmentProcessor : ResourceAssignmentProcessor() { + private val logger = LoggerFactory.getLogger(DefaultResourceAssignmentProcessor::class.java) + override fun getName(): String { return "resource-assignment-processor-default" } - override fun process(executionRequest: ResourceAssignment) { + override fun process(resourceAssignment: ResourceAssignment) { + try { + // Check if It has Input + var value: Any? = raRuntimeService.getInputValue(resourceAssignment.name) + + // If value is null get it from default source + if (value == null || value is NullNode) { + logger.info("Looking for defaultValue as couldn't find value in input For template key (${resourceAssignment.name})") + value = resourceAssignment.property?.defaultValue + } + + logger.info("For template key (${resourceAssignment.name}) setting value as ($value)") + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value) + + // Check the value has populated for mandatory case + ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) + } catch (e: Exception) { + ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) + throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e) + } + } - override fun recover(runtimeException: RuntimeException, executionRequest: ResourceAssignment) { + override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { } }
\ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/InputResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/InputResourceAssignmentProcessor.kt index bd9c188a..5757de2a 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/InputResourceAssignmentProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/InputResourceAssignmentProcessor.kt @@ -17,41 +17,46 @@ package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor -import org.onap.ccsdk.apps.controllerblueprints.core.* +import com.fasterxml.jackson.databind.node.NullNode +import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmpty import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment +import org.slf4j.LoggerFactory import org.springframework.stereotype.Service -import com.fasterxml.jackson.databind.node.NullNode -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.utils.ResourceAssignmentUtils /** * InputResourceAssignmentProcessor * - * @author Brinda Santh + * @author Kapil Singal */ @Service("resource-assignment-processor-input") open class InputResourceAssignmentProcessor : ResourceAssignmentProcessor() { + private val logger = LoggerFactory.getLogger(InputResourceAssignmentProcessor::class.java) + override fun getName(): String { return "resource-assignment-processor-input" } - override fun process(executionRequest: ResourceAssignment) { + override fun process(resourceAssignment: ResourceAssignment) { try { - if (checkNotEmpty(executionRequest.name)) { - val value = bluePrintRuntimeService!!.getInputValue(executionRequest.name) + if (checkNotEmpty(resourceAssignment.name)) { + val value = raRuntimeService.getInputValue(resourceAssignment.name) // if value is null don't call setResourceDataValue to populate the value if (value != null && value !is NullNode) { - ResourceAssignmentUtils.setResourceDataValue(executionRequest, value) + logger.info("input source template key (${resourceAssignment.name}) found from input and value is ($value)") + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value) } } // Check the value has populated for mandatory case - ResourceAssignmentUtils.assertTemplateKeyValueNotNull(executionRequest) + ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) } catch (e: Exception) { - ResourceAssignmentUtils.setFailedResourceDataValue(executionRequest, e.message) - throw BluePrintProcessorException("Failed in template key ($executionRequest) assignments with : (${e.message})", e) + ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) + throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with : (${e.message})", e) } } - override fun recover(runtimeException: RuntimeException, executionRequest: ResourceAssignment) { + override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { } }
\ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/PrimaryDataResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/PrimaryDataResourceAssignmentProcessor.kt index ec98d09e..94271830 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/PrimaryDataResourceAssignmentProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/PrimaryDataResourceAssignmentProcessor.kt @@ -17,24 +17,147 @@ package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor +import com.fasterxml.jackson.databind.node.JsonNodeFactory +import com.fasterxml.jackson.databind.node.NullNode +import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.service.PrimaryDBLibGenericService +import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource +import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils +import org.onap.ccsdk.apps.controllerblueprints.core.* +import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment +import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDictionaryConstants +import org.slf4j.LoggerFactory import org.springframework.stereotype.Service +import java.util.* /** * PrimaryDataResourceAssignmentProcessor * - * @author Brinda Santh + * @author Kapil Singal */ @Service("resource-assignment-processor-primary-db") -open class PrimaryDataResourceAssignmentProcessor : ResourceAssignmentProcessor(){ +open class PrimaryDataResourceAssignmentProcessor(private val primaryDBLibGenericService: PrimaryDBLibGenericService) + : ResourceAssignmentProcessor() { + + private val logger = LoggerFactory.getLogger(PrimaryDataResourceAssignmentProcessor::class.java) override fun getName(): String { return "resource-assignment-processor-primary-db" } - override fun process(executionRequest: ResourceAssignment) { + override fun process(resourceAssignment: ResourceAssignment) { + try { + validate(resourceAssignment) + + // Check if It has Input + val value = raRuntimeService.getInputValue(resourceAssignment.name) + if (value != null && value !is NullNode) { + logger.info("primary-db source template key (${resourceAssignment.name}) found from input and value is ($value)") + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value) + } else { + val dName = resourceAssignment.dictionaryName + val dSource = resourceAssignment.dictionarySource + val resourceDefinition = resourceDictionaries[dName] + ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName") + val resourceSource = resourceDefinition.sources[dSource] + ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)") + val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " } + val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java) + + val sql = checkNotNull(sourceProperties.query) { "failed to get request query for $dName under $dSource properties" } + val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" } + + logger.info("$dSource dictionary information : ($sql), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})") + + val rows = primaryDBLibGenericService.query(sql, populateNamedParameter(inputKeyMapping)) + if (rows.isNullOrEmpty()) { + logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)") + } else { + populateResource(resourceAssignment, sourceProperties, rows) + } + } + + // Check the value has populated for mandatory case + ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) + } catch (e: Exception) { + ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) + throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e) + } + } + + @Throws(BluePrintProcessorException::class) + private fun validate(resourceAssignment: ResourceAssignment) { + checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined") + checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})") + checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PRIMARY_DB, resourceAssignment.dictionarySource) { + "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PRIMARY_DB} but it is ${resourceAssignment.dictionarySource}" + } + } + + private fun populateNamedParameter(inputKeyMapping: Map<String, String>): Map<String, Any> { + val namedParameters = HashMap<String, Any>() + inputKeyMapping.forEach { + val expressionValue = raRuntimeService.getDictionaryStore(it.value) + logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)") + namedParameters[it.key] = expressionValue + } + logger.info("Parameter information : ({})", namedParameters) + return namedParameters + } + + @Throws(BluePrintProcessorException::class) + private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: DatabaseResourceSource, rows: List<Map<String, Any>>) { + val dName = resourceAssignment.dictionaryName + val dSource = resourceAssignment.dictionarySource + val type = nullToEmpty(resourceAssignment.property?.type) + + val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" } + logger.info("Response processing type($type)") + + // Primitive Types + when(type) { + in BluePrintTypes.validPrimitiveTypes() -> { + val dbColumnValue = rows[0][outputKeyMapping[dName]] + logger.info("For template key (${resourceAssignment.name}) setting value as ($dbColumnValue)") + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, dbColumnValue) + } + in BluePrintTypes.validCollectionTypes() -> { + val entrySchemaType = returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" } + var arrayNode = JsonNodeFactory.instance.arrayNode() + rows.forEach { + if (entrySchemaType in BluePrintTypes.validPrimitiveTypes()) { + val dbColumnValue = it[outputKeyMapping[dName]] + // Add Array JSON + JacksonUtils.populatePrimitiveValues(dbColumnValue!!, entrySchemaType, arrayNode) + } else { + val arrayChildNode = JsonNodeFactory.instance.objectNode() + for (mapping in outputKeyMapping.entries) { + val dbColumnValue = checkNotNull(it[mapping.key]) + val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, mapping.key) + JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, arrayChildNode) + } + arrayNode.add(arrayChildNode) + } + } + logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)") + // Set the List of Complex Values + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode) + } + else -> { + // Complex Types + val row = rows[0] + var objectNode = JsonNodeFactory.instance.objectNode() + for (mapping in outputKeyMapping.entries) { + val dbColumnValue = checkNotNull(row[mapping.key]) + val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, type, mapping.key) + JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, objectNode) + } + logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)") + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode) + } + } } - override fun recover(runtimeException: RuntimeException, executionRequest: ResourceAssignment) { + override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { } }
\ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt index 11cd3faa..43238a53 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt @@ -17,9 +17,9 @@ package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor +import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BlueprintFunctionNode -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDefinition import org.slf4j.LoggerFactory @@ -28,14 +28,12 @@ abstract class ResourceAssignmentProcessor : BlueprintFunctionNode<ResourceAssig private val log = LoggerFactory.getLogger(ResourceAssignmentProcessor::class.java) - lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> - + lateinit var raRuntimeService: ResourceAssignmentRuntimeService lateinit var resourceDictionaries: Map<String, ResourceDefinition> - open fun resourceDefinition(name: String): ResourceDefinition { return resourceDictionaries[name] - ?: throw BluePrintProcessorException("couldn't get resource definition($name)") + ?: throw BluePrintProcessorException("couldn't get resource definition for ($name)") } override fun prepareRequest(resourceAssignment: ResourceAssignment): ResourceAssignment { diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/SimpleRestResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/SimpleRestResourceAssignmentProcessor.kt index e05261d8..f1a4dbb0 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/SimpleRestResourceAssignmentProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/SimpleRestResourceAssignmentProcessor.kt @@ -17,24 +17,146 @@ package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor +import com.fasterxml.jackson.databind.node.ArrayNode +import com.fasterxml.jackson.databind.node.JsonNodeFactory +import com.fasterxml.jackson.databind.node.NullNode +import com.fasterxml.jackson.databind.node.ObjectNode +import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.RestResourceSource +import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils +import org.onap.ccsdk.apps.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService +import org.onap.ccsdk.apps.controllerblueprints.core.* +import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment +import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDictionaryConstants +import org.slf4j.LoggerFactory import org.springframework.stereotype.Service /** * SimpleRestResourceAssignmentProcessor * - * @author Brinda Santh + * @author Kapil Singal */ -@Service("resource-assignment-processor-mdsal") -open class SimpleRestResourceAssignmentProcessor : ResourceAssignmentProcessor() { +@Service("resource-assignment-processor-primary-config-data") +open class SimpleRestResourceAssignmentProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService) + : ResourceAssignmentProcessor() { + + private val logger = LoggerFactory.getLogger(SimpleRestResourceAssignmentProcessor::class.java) override fun getName(): String { - return "resource-assignment-processor-mdsal" + return "resource-assignment-processor-primary-config-data" } - override fun process(executionRequest: ResourceAssignment) { + override fun process(resourceAssignment: ResourceAssignment) { + try { + validate(resourceAssignment) + + // Check if It has Input + val value = raRuntimeService.getInputValue(resourceAssignment.name) + if (value != null && value !is NullNode) { + logger.info("primary-db source template key (${resourceAssignment.name}) found from input and value is ($value)") + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value) + } else { + val dName = resourceAssignment.dictionaryName + val dSource = resourceAssignment.dictionarySource + val resourceDefinition = resourceDictionaries[dName] + ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName") + val resourceSource = resourceDefinition.sources[dSource] + ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)") + val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " } + val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java) + + val urlPath = checkNotNull(sourceProperties.urlPath) { "failed to get request urlPath for $dName under $dSource properties" } + val path = nullToEmpty(sourceProperties.path) + val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" } + + logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})") + + val restClientService = blueprintRestLibPropertyService.blueprintWebClientService("primary-config-data") + val response = restClientService.getResource(urlPath, String::class.java) + if (response.isNotBlank()) { + logger.warn("Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath)") + } else { + populateResource(resourceAssignment, sourceProperties, response, path) + } + } + // Check the value has populated for mandatory case + ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) + } catch (e: Exception) { + ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) + throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e) + } } - override fun recover(runtimeException: RuntimeException, executionRequest: ResourceAssignment) { + @Throws(BluePrintProcessorException::class) + private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource, restResponse: String, path: String) { + val dName = resourceAssignment.dictionaryName + val dSource = resourceAssignment.dictionarySource + val type = nullToEmpty(resourceAssignment.property?.type) + lateinit var entrySchemaType: String + + val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" } + logger.info("Response processing type($type)") + + val responseNode = checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) { "Failed to find path ($path) in response ($restResponse)" } + logger.info("populating value for output mapping ($outputKeyMapping), from json ($responseNode)") + + + when (type) { + in BluePrintTypes.validPrimitiveTypes() -> { + logger.info("For template key (${resourceAssignment.name}) setting value as ($responseNode)") + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode) + } + in BluePrintTypes.validCollectionTypes() -> { + // Array Types + entrySchemaType = returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" } + val arrayNode = responseNode as ArrayNode + + if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) { + val responseArrayNode = responseNode.toList() + for (responseSingleJsonNode in responseArrayNode) { + val arrayChildNode = JsonNodeFactory.instance.objectNode() + outputKeyMapping.map { + val responseKeyValue = responseSingleJsonNode.get(it.key) + val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key) + logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type ({$propertyTypeForDataType})") + JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, arrayChildNode) + } + arrayNode.add(arrayChildNode) + } + } + logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)") + // Set the List of Complex Values + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode) + } + else -> { + // Complex Types + val objectNode = responseNode as ObjectNode + outputKeyMapping.map { + val responseKeyValue = responseNode.get(it.key) + val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key) + logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type ({$propertyTypeForDataType})") + JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode) + } + + logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)") + // Set the List of Complex Values + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode) + } + } + } + + @Throws(BluePrintProcessorException::class) + private fun validate(resourceAssignment: ResourceAssignment) { + checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined") + checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})") + checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA, resourceAssignment.dictionarySource) { + "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA} but it is ${resourceAssignment.dictionarySource}" + } + checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})") } + + override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { + } + + }
\ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt new file mode 100644 index 00000000..ee8911ee --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt @@ -0,0 +1,178 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils + +import com.att.eelf.configuration.EELFLogger +import com.att.eelf.configuration.EELFManager +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.node.NullNode +import com.fasterxml.jackson.databind.node.ObjectNode +import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService +import org.onap.ccsdk.apps.controllerblueprints.core.* +import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment +import java.util.* + +class ResourceAssignmentUtils { + companion object { + + private val logger: EELFLogger = EELFManager.getInstance().getLogger(ResourceAssignmentUtils::class.toString()) + + @Synchronized + @Throws(BluePrintProcessorException::class) + fun setResourceDataValue(resourceAssignment: ResourceAssignment, raRuntimeService: ResourceAssignmentRuntimeService, value: Any?) { + + val resourceProp = checkNotNull(resourceAssignment.property) { "Failed in setting resource value for resource mapping $resourceAssignment" } + checkNotEmptyOrThrow(resourceAssignment.name, "Failed in setting resource value for resource mapping $resourceAssignment") + + if (checkNotEmpty(resourceAssignment.dictionaryName)) { + resourceAssignment.dictionaryName = resourceAssignment.name + logger.warn("Missing dictionary key, setting with template key (${resourceAssignment.name}) as dictionary key (${resourceAssignment.dictionaryName})") + } + + try { + if (checkNotEmpty(resourceProp.type)) { + val convertedValue = convertResourceValue(resourceProp.type, value) + logger.info("Setting Resource Value ($convertedValue) for Resource Name (${resourceAssignment.dictionaryName}) of type (${resourceProp.type})") + setResourceValue(resourceAssignment, raRuntimeService, convertedValue) + resourceAssignment.updatedDate = Date() + resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM + resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS + } + } catch (e: Exception) { + throw BluePrintProcessorException("Failed in setting value for template key (${resourceAssignment.name}) and " + + "dictionary key (${resourceAssignment.dictionaryName}) of type (${resourceProp.type}) with error message (${e.message})", e) + } + } + + private fun setResourceValue(resourceAssignment: ResourceAssignment, raRuntimeService: ResourceAssignmentRuntimeService, value: JsonNode) { + raRuntimeService.putResolutionStore(resourceAssignment.name, value) + raRuntimeService.putDictionaryStore(resourceAssignment.dictionaryName!!, value) + resourceAssignment.property!!.value = value + } + + private fun convertResourceValue(type: String, value: Any?): JsonNode { + + return if (value == null || value is NullNode) { + logger.info("Returning {} value from convertResourceValue", value) + NullNode.instance + } else if (BluePrintTypes.validPrimitiveTypes().contains(type) && value is String) { + JacksonUtils.convertPrimitiveResourceValue(type, value) + } else if (value is String) { + JacksonUtils.jsonNode(value) + } else { + JacksonUtils.getJsonNode(value) + } + + } + + @Synchronized + fun setFailedResourceDataValue(resourceAssignment: ResourceAssignment, message: String?) { + if (checkNotEmpty(resourceAssignment.name)) { + resourceAssignment.updatedDate = Date() + resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM + resourceAssignment.status = BluePrintConstants.STATUS_FAILURE + resourceAssignment.message = message + } + } + + @Synchronized + @Throws(BluePrintProcessorException::class) + fun assertTemplateKeyValueNotNull(resourceAssignment: ResourceAssignment) { + val resourceProp = checkNotNull(resourceAssignment.property) { "Failed to populate mandatory resource resource mapping $resourceAssignment" } + if (resourceProp.required != null && resourceProp.required!! && (resourceProp.value == null || resourceProp.value !is NullNode)) { + logger.error("failed to populate mandatory resource mapping ($resourceAssignment)") + throw BluePrintProcessorException("failed to populate mandatory resource mapping ($resourceAssignment)") + } + } + + @Synchronized + @Throws(BluePrintProcessorException::class) + fun generateResourceDataForAssignments(assignments: List<ResourceAssignment>): String { + var result = "{}" + try { + val mapper = ObjectMapper() + val root = mapper.readTree(result) + + assignments.forEach { + if (checkNotEmpty(it.name) && it.property != null) { + val rName = it.name + val type = nullToEmpty(it.property?.type).toLowerCase() + val value = it.property?.value + logger.info("Generating Resource name ($rName), type ($type), value ($value)") + + when (value) { + null -> (root as ObjectNode).set(rName, null) + is JsonNode -> (root as ObjectNode).set(rName, value) + else -> { + when (type) { + BluePrintConstants.DATA_TYPE_TIMESTAMP -> (root as ObjectNode).put(rName, value as String) + BluePrintConstants.DATA_TYPE_STRING -> (root as ObjectNode).put(rName, value as String) + BluePrintConstants.DATA_TYPE_BOOLEAN -> (root as ObjectNode).put(rName, value as Boolean) + BluePrintConstants.DATA_TYPE_INTEGER -> (root as ObjectNode).put(rName, value as Int) + BluePrintConstants.DATA_TYPE_FLOAT -> (root as ObjectNode).put(rName, value as Float) + else -> { + if (JacksonUtils.getJsonNode(value) != null) { + (root as ObjectNode).set(rName, JacksonUtils.getJsonNode(value)) + } else { + (root as ObjectNode).set(rName, null) + } + } + } + } + } + } + } + result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root) + logger.info("Generated Resource Param Data ($result)") + } catch (e: Exception) { + throw BluePrintProcessorException("Resource Assignment is failed with $e.message", e) + } + + return result + } + + fun transformToRARuntimeService(blueprintRuntimeService: BluePrintRuntimeService<*>, templateArtifactName: String): ResourceAssignmentRuntimeService { + val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService(blueprintRuntimeService.id(), blueprintRuntimeService.bluePrintContext()) + resourceAssignmentRuntimeService.createUniqueId(templateArtifactName) + resourceAssignmentRuntimeService.setExecutionContext(blueprintRuntimeService.getExecutionContext() as MutableMap<String, JsonNode>) + + return resourceAssignmentRuntimeService + } + + /* + * Populate the Field property type for the Data type + */ + @Synchronized + @Throws(BluePrintProcessorException::class) + fun getPropertyType(raRuntimeService: ResourceAssignmentRuntimeService, dataTypeName: String, propertyName: String): String { + lateinit var type: String + try { + val dataTypeProps = checkNotNull(raRuntimeService.bluePrintContext().dataTypeByName(dataTypeName)?.properties) + val propertyDefinition = checkNotNull(dataTypeProps[propertyName]) + type = returnNotEmptyOrThrow(propertyDefinition.type) { "Couldn't get data type ($dataTypeName)" } + logger.trace("Data type({})'s property ({}) is ({})", dataTypeName, propertyName, type) + } catch (e: Exception) { + logger.error("couldn't get data type($dataTypeName)'s property ($propertyName), error message $e") + throw BluePrintProcessorException("${e.message}", e) + } + return type + } + } +}
\ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt index 8adde863..574d235b 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt @@ -19,23 +19,36 @@ package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution import com.fasterxml.jackson.databind.JsonNode import org.junit.Test import org.junit.runner.RunWith +import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintProperties +import org.onap.ccsdk.apps.blueprintsprocessor.core.BlueprintPropertyConfiguration import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.apps.blueprintsprocessor.core.utils.PayloadUtils +import org.onap.ccsdk.apps.blueprintsprocessor.db.BluePrintDBLibConfiguration +import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.service.PrimaryDBLibGenericService import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor.* import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.apps.controllerblueprints.core.asJsonNode +import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration import org.onap.ccsdk.apps.controllerblueprints.core.putJsonElement import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.EnableAutoConfiguration +import org.springframework.context.annotation.ComponentScan import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource import org.springframework.test.context.junit4.SpringRunner @RunWith(SpringRunner::class) -@ContextConfiguration(classes = [ResourceResolutionComponent::class, ResourceResolutionService::class, +@ContextConfiguration(classes = [ResourceResolutionService::class, InputResourceAssignmentProcessor::class, DefaultResourceAssignmentProcessor::class, PrimaryDataResourceAssignmentProcessor::class, SimpleRestResourceAssignmentProcessor::class, - CapabilityResourceAssignmentProcessor::class]) + CapabilityResourceAssignmentProcessor::class, PrimaryDBLibGenericService::class, + BlueprintPropertyConfiguration::class, BluePrintProperties::class, + BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class]) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) +@EnableAutoConfiguration class ResourceResolutionComponentTest { @Autowired diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt index 6c686753..ef69eb51 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt @@ -19,14 +19,22 @@ package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith +import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintProperties +import org.onap.ccsdk.apps.blueprintsprocessor.core.BlueprintPropertyConfiguration import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.apps.blueprintsprocessor.core.utils.PayloadUtils +import org.onap.ccsdk.apps.blueprintsprocessor.db.BluePrintDBLibConfiguration +import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.service.PrimaryDBLibGenericService import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor.* +import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.EnableAutoConfiguration +import org.springframework.context.annotation.ComponentScan import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource import org.springframework.test.context.junit4.SpringRunner import kotlin.test.assertNotNull import kotlin.test.assertTrue @@ -40,7 +48,12 @@ import kotlin.test.assertTrue @ContextConfiguration(classes = [ResourceResolutionService::class, InputResourceAssignmentProcessor::class, DefaultResourceAssignmentProcessor::class, PrimaryDataResourceAssignmentProcessor::class, SimpleRestResourceAssignmentProcessor::class, - CapabilityResourceAssignmentProcessor::class]) + CapabilityResourceAssignmentProcessor::class, PrimaryDBLibGenericService::class, + BlueprintPropertyConfiguration::class, BluePrintProperties::class, + BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class]) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) +@EnableAutoConfiguration class ResourceResolutionServiceTest { private val log = LoggerFactory.getLogger(ResourceResolutionServiceTest::class.java) @@ -48,12 +61,11 @@ class ResourceResolutionServiceTest { @Autowired lateinit var resourceResolutionService: ResourceResolutionService - @Test fun testRegisteredSource() { val sources = resourceResolutionService.registeredResourceSources() assertNotNull(sources, "failed to get registered sources") - assertTrue(sources.containsAll(arrayListOf("input", "default", "primary-db", "mdsal")), "failed to get registered sources") + assertTrue(sources.containsAll(arrayListOf("input", "default", "primary-db", "primary-config-data")), "failed to get registered sources") } @Test diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/resources/application-test.properties b/ms/blueprintsprocessor/functions/resource-resolution/src/test/resources/application-test.properties new file mode 100644 index 00000000..aed61c46 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/resources/application-test.properties @@ -0,0 +1,32 @@ +# suppress inspection "UnusedProperty" for whole file +# +# Copyright © 2017-2018 AT&T Intellectual Property. +# +# 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. +# +blueprintsprocessor.db.primary.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE +blueprintsprocessor.db.primary.username=sa +blueprintsprocessor.db.primary.password= +blueprintsprocessor.db.primary.driverClassName=org.h2.Driver +blueprintsprocessor.db.primary.hibernateHbm2ddlAuto=create-drop +blueprintsprocessor.db.primary.hibernateDDLAuto=update +blueprintsprocessor.db.primary.hibernateNamingStrategy=org.hibernate.cfg.ImprovedNamingStrategy +blueprintsprocessor.db.primary.hibernateDialect=org.hibernate.dialect.H2Dialect +# Controller Blueprints Core Configuration +blueprintsprocessor.blueprintDeployPath=./target/blueprints/deploy +blueprintsprocessor.blueprintArchivePath=./target/blueprints/archive + +blueprintsprocessor.restclient.primary-config-data.type=basic-auth +blueprintsprocessor.restclient.primary-config-data.url=http://127.0.0.1:9111 +blueprintsprocessor.restclient.primary-config-data.userId=sampleuser +blueprintsprocessor.restclient.primary-config-data.token=sampletoken
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt b/ms/blueprintsprocessor/modules/commons/core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt index b0483dc3..41bbd1df 100644 --- a/ms/blueprintsprocessor/modules/commons/core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt +++ b/ms/blueprintsprocessor/modules/commons/core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt @@ -1,99 +1,123 @@ -/*
- * Copyright © 2017-2018 AT&T Intellectual Property.
- * Modifications Copyright © 2018 IBM.
- *
- * 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.onap.ccsdk.apps.blueprintsprocessor.core.api.data
-
-import com.fasterxml.jackson.annotation.JsonFormat
-import com.fasterxml.jackson.databind.node.ObjectNode
-import io.swagger.annotations.ApiModelProperty
-import java.util.*
-
-/**
- * BlueprintProcessorData
- * @author Brinda Santh
- * DATE : 8/15/2018
- */
-
-open class ExecutionServiceInput {
- @get:ApiModelProperty(required = true)
- lateinit var commonHeader: CommonHeader
- @get:ApiModelProperty(required = true)
- lateinit var actionIdentifiers: ActionIdentifiers
- @get:ApiModelProperty(required = true)
- lateinit var payload: ObjectNode
-}
-
-open class ExecutionServiceOutput {
- @get:ApiModelProperty(required = true)
- lateinit var commonHeader: CommonHeader
- @get:ApiModelProperty(required = true)
- lateinit var actionIdentifiers: ActionIdentifiers
- @get:ApiModelProperty(required = true)
- var status: Status = Status()
- @get:ApiModelProperty(required = true)
- lateinit var payload: ObjectNode
-}
-
-open class ActionIdentifiers {
- @get:ApiModelProperty(required = false)
- lateinit var blueprintName: String
- @get:ApiModelProperty(required = false)
- lateinit var blueprintVersion: String
- @get:ApiModelProperty(required = true)
- lateinit var actionName: String
- @get:ApiModelProperty(required = true, allowableValues = "sync, async")
- lateinit var mode: String
-}
-
-open class CommonHeader {
- @get:ApiModelProperty(required = true, example = "2012-04-23T18:25:43.511Z")
- @get:JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
- var timestamp: Date = Date()
- @get:ApiModelProperty(required = true)
- lateinit var originatorId: String
- @get:ApiModelProperty(required = true)
- lateinit var requestId: String
- @get:ApiModelProperty(required = true)
- lateinit var subRequestId: String
- @get:ApiModelProperty(required = false)
- var flags: Flags? = null
-}
-
-open class Flags {
- var isForce: Boolean = false
- @get:ApiModelProperty(value = "3600")
- var ttl: Int = 3600
-}
-
-open class Status {
- @get:ApiModelProperty(required = true)
- var code: Int = 200
- @get:ApiModelProperty(required = true)
- var eventType: String = "EVENT-ACTION-RESPONSE"
- @get:ApiModelProperty(required = true, example = "2012-04-23T18:25:43.511Z")
- @get:JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
- var timestamp: Date = Date()
- @get:ApiModelProperty(required = false)
- var errorMessage: String? = null
- @get:ApiModelProperty(required = true)
- var message: String = "success"
-}
-
-
-
-
-
+/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * 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.onap.ccsdk.apps.blueprintsprocessor.core.api.data + +import com.fasterxml.jackson.annotation.JsonFormat +import com.fasterxml.jackson.databind.node.ObjectNode +import io.swagger.annotations.ApiModelProperty +import java.util.* + +/** + * BlueprintProcessorData + * @author Brinda Santh + * DATE : 8/15/2018 + */ + +open class ExecutionServiceInput { + @get:ApiModelProperty(required = true) + lateinit var commonHeader: CommonHeader + @get:ApiModelProperty(required = true) + lateinit var actionIdentifiers: ActionIdentifiers + @get:ApiModelProperty(required = true) + lateinit var payload: ObjectNode +} + +open class ExecutionServiceOutput { + @get:ApiModelProperty(required = true) + lateinit var commonHeader: CommonHeader + @get:ApiModelProperty(required = true) + lateinit var actionIdentifiers: ActionIdentifiers + @get:ApiModelProperty(required = true) + var status: Status = Status() + @get:ApiModelProperty(required = true) + lateinit var payload: ObjectNode +} + +const val ACTION_MODE_ASYNC = "async" +const val ACTION_MODE_SYNC = "sync" + +open class ActionIdentifiers { + @get:ApiModelProperty(required = false) + lateinit var blueprintName: String + @get:ApiModelProperty(required = false) + lateinit var blueprintVersion: String + @get:ApiModelProperty(required = true) + lateinit var actionName: String + @get:ApiModelProperty(required = true, allowableValues = "sync, async") + lateinit var mode: String +} + +open class CommonHeader { + @get:ApiModelProperty(required = true, example = "2012-04-23T18:25:43.511Z") + @get:JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + var timestamp: Date = Date() + @get:ApiModelProperty(required = true) + lateinit var originatorId: String + @get:ApiModelProperty(required = true) + lateinit var requestId: String + @get:ApiModelProperty(required = true) + lateinit var subRequestId: String + @get:ApiModelProperty(required = false) + var flags: Flags? = null +} + +open class Flags { + var isForce: Boolean = false + @get:ApiModelProperty(value = "3600") + var ttl: Int = 3600 +} + +open class Status { + @get:ApiModelProperty(required = true) + var code: Int = 200 + @get:ApiModelProperty(required = true) + var eventType: String = "EVENT-ACTION-RESPONSE" + @get:ApiModelProperty(required = true, example = "2012-04-23T18:25:43.511Z") + @get:JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + var timestamp: Date = Date() + @get:ApiModelProperty(required = false) + var errorMessage: String? = null + @get:ApiModelProperty(required = true) + var message: String = "success" +} + +open class BluePrintManagementInput { + @get:ApiModelProperty(required = true) + lateinit var commonHeader: CommonHeader + @get:ApiModelProperty(required = false) + lateinit var blueprintName: String + @get:ApiModelProperty(required = false) + lateinit var blueprintVersion: String + @get:ApiModelProperty(required = true) + lateinit var fileChunk: FileChunk +} + +open class FileChunk { + @get:ApiModelProperty(required = true) + lateinit var chunk: ByteArray +} + +open class BluePrintManagementOutput { + @get:ApiModelProperty(required = true) + lateinit var commonHeader: CommonHeader + @get:ApiModelProperty(required = true) + var status: Status = Status() +} + + + diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/pom.xml b/ms/blueprintsprocessor/modules/commons/db-lib/pom.xml index 53c9b185..590c87f0 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/pom.xml +++ b/ms/blueprintsprocessor/modules/commons/db-lib/pom.xml @@ -30,6 +30,10 @@ <dependencies> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <artifactId>core</artifactId> + </dependency> + <dependency> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> <artifactId>db-resources</artifactId> <version>${project.version}</version> </dependency> diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImpl.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImpl.kt index 89b7f649..dee7ae86 100755 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImpl.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImpl.kt @@ -17,77 +17,98 @@ package org.onap.ccsdk.apps.blueprintsprocessor.db +import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.domain.BlueprintProcessorModel import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.domain.BlueprintProcessorModelContent -import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.repository.BlueprintProcessorModelContentRepository import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.repository.BlueprintProcessorModelRepository import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException import org.onap.ccsdk.apps.controllerblueprints.core.common.ApplicationConstants -import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration import org.onap.ccsdk.apps.controllerblueprints.core.data.ErrorCode import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintValidatorService import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintArchiveUtils -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.apps.controllerblueprints.db.resources.BlueprintCatalogServiceImpl +import org.slf4j.LoggerFactory import org.springframework.dao.DataIntegrityViolationException import org.springframework.stereotype.Service import java.io.File import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths /** -Similar/Duplicate implementation in [org.onap.ccsdk.apps.controllerblueprints.service.load.ControllerBlueprintCatalogServiceImpl] + * Similar/Duplicate implementation in [org.onap.ccsdk.apps.controllerblueprints.service.load.ControllerBlueprintCatalogServiceImpl] */ @Service -class BlueprintProcessorCatalogServiceImpl(bluePrintLoadConfiguration: BluePrintLoadConfiguration, - private val bluePrintValidatorService: BluePrintValidatorService, +class BlueprintProcessorCatalogServiceImpl(bluePrintValidatorService: BluePrintValidatorService, + private val blueprintConfig: BluePrintCoreConfiguration, private val blueprintModelRepository: BlueprintProcessorModelRepository) - : BlueprintCatalogServiceImpl(bluePrintLoadConfiguration) { - - override fun saveToDataBase(extractedDirectory: File, id: String, archiveFile: File, checkValidity: Boolean?) { - var valid = false - val firstItem = BluePrintArchiveUtils.getFirstItemInDirectory(extractedDirectory) - val blueprintBaseDirectory = extractedDirectory.absolutePath + "/" + firstItem - // Validate Blueprint - val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(id, blueprintBaseDirectory) - - // Check Validity of blueprint - if (checkValidity!!) { - valid = bluePrintValidatorService.validateBluePrints(bluePrintRuntimeService) + : BlueprintCatalogServiceImpl(bluePrintValidatorService) { + + private val log = LoggerFactory.getLogger(BlueprintProcessorCatalogServiceImpl::class.toString()) + + init { + + log.info("BlueprintProcessorCatalogServiceImpl initialized") + } + + override fun delete(name: String, version: String) = blueprintModelRepository.deleteByArtifactNameAndArtifactVersion(name, version) + + + override fun get(name: String, version: String, extract: Boolean): Path? { + var path = "${blueprintConfig.archivePath}/$name/$version.zip" + + blueprintModelRepository.findByArtifactNameAndArtifactVersion(name, version)?.also { + it.blueprintModelContent.run { + val file = File(path) + file.parentFile.mkdirs() + file.createNewFile() + file.writeBytes(this!!.content!!).let { + if (extract) { + path = "${blueprintConfig.archivePath}/$name/$version" + BluePrintArchiveUtils.deCompress(file, path) + } + return Paths.get(path) + } + } } + return null + } - if ((valid && checkValidity!!) || (!valid && !checkValidity!!)) { - val metaData = bluePrintRuntimeService.bluePrintContext().metadata!! - // FIXME("Check Duplicate for Artifact Name and Artifact Version") - val blueprintModel = BlueprintProcessorModel() - blueprintModel.id = id - blueprintModel.artifactType = ApplicationConstants.ASDC_ARTIFACT_TYPE_SDNC_MODEL - blueprintModel.published = ApplicationConstants.ACTIVE_N - blueprintModel.artifactName = metaData[BluePrintConstants.METADATA_TEMPLATE_NAME] - blueprintModel.artifactVersion = metaData[BluePrintConstants.METADATA_TEMPLATE_VERSION] - blueprintModel.updatedBy = metaData[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] - blueprintModel.tags = metaData[BluePrintConstants.METADATA_TEMPLATE_TAGS] - blueprintModel.artifactDescription = "Controller Blueprint for ${blueprintModel.artifactName}:${blueprintModel.artifactVersion}" - - val blueprintModelContent = BlueprintProcessorModelContent() - blueprintModelContent.id = id // For quick access both id's are same.always have one to one mapping. - blueprintModelContent.contentType = "CBA_ZIP" - blueprintModelContent.name = "${blueprintModel.artifactName}:${blueprintModel.artifactVersion}" - blueprintModelContent.description = "(${blueprintModel.artifactName}:${blueprintModel.artifactVersion} CBA Zip Content" - blueprintModelContent.content = Files.readAllBytes(archiveFile.toPath()) - - // Set the Blueprint Model into blueprintModelContent - blueprintModelContent.blueprintModel = blueprintModel - - // Set the Blueprint Model Content into blueprintModel - blueprintModel.blueprintModelContent = blueprintModelContent - - try { - blueprintModelRepository.saveAndFlush(blueprintModel) - } catch (ex: DataIntegrityViolationException) { - throw BluePrintException(ErrorCode.CONFLICT_ADDING_RESOURCE.value, "The blueprint entry " + - "is already exist in database: ${ex.message}", ex) + override fun save(metadata: MutableMap<String, String>, archiveFile: File) { + val artifactName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] + val artifactVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] + + log.isDebugEnabled.apply { + blueprintModelRepository.findByArtifactNameAndArtifactVersion(artifactName!!, artifactVersion!!)?.let { + log.debug("Overwriting blueprint model :$artifactName::$artifactVersion") } } + + val blueprintModel = BlueprintProcessorModel() + blueprintModel.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] + blueprintModel.artifactType = ApplicationConstants.ASDC_ARTIFACT_TYPE_SDNC_MODEL + blueprintModel.artifactName = artifactName + blueprintModel.artifactVersion = artifactVersion + blueprintModel.updatedBy = metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] + blueprintModel.tags = metadata[BluePrintConstants.METADATA_TEMPLATE_TAGS] + blueprintModel.artifactDescription = "Controller Blueprint for $artifactName:$artifactVersion" + + val blueprintModelContent = BlueprintProcessorModelContent() + blueprintModelContent.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] + blueprintModelContent.contentType = "CBA_ZIP" + blueprintModelContent.name = "$artifactName:$artifactVersion" + blueprintModelContent.description = "$artifactName:$artifactVersion CBA Zip Content" + blueprintModelContent.content = Files.readAllBytes(archiveFile.toPath()) + blueprintModelContent.blueprintModel = blueprintModel + + blueprintModel.blueprintModelContent = blueprintModelContent + + try { + blueprintModelRepository.saveAndFlush(blueprintModel) + } catch (ex: DataIntegrityViolationException) { + throw BluePrintException(ErrorCode.CONFLICT_ADDING_RESOURCE.value, "The blueprint entry " + + "is already exist in database: ${ex.message}", ex) + } } }
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModel.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModel.kt index 00d4830e..0935d038 100755 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModel.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModel.kt @@ -40,13 +40,11 @@ import javax.persistence.TemporalType @Table(name = "BLUEPRINT_RUNTIME") @Proxy(lazy = false) class BlueprintProcessorModel : Serializable { + @Id - @Column(name = "config_model_id") + @Column(name = "blueprint_runtime_id") var id: String? = null - @Column(name = "artifact_uuid") - var artifactUUId: String? = null - @Column(name = "artifact_type") var artifactType: String? = null @@ -58,9 +56,6 @@ class BlueprintProcessorModel : Serializable { @Column(name = "artifact_description") var artifactDescription: String? = null - @Column(name = "internal_version") - var internalVersion: Int? = null - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @LastModifiedDate @Temporal(TemporalType.TIMESTAMP) @@ -71,10 +66,6 @@ class BlueprintProcessorModel : Serializable { @ApiModelProperty(required = true) var artifactName: String? = null - @Column(name = "published", nullable = false) - @ApiModelProperty(required = true) - var published: String? = null - @Column(name = "updated_by", nullable = false) @ApiModelProperty(required = true) var updatedBy: String? = null @@ -90,4 +81,4 @@ class BlueprintProcessorModel : Serializable { companion object { private const val serialVersionUID = 1L } -}
\ No newline at end of file +} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModelContent.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModelContent.kt index d012af58..58bf8a33 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModelContent.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModelContent.kt @@ -40,7 +40,7 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener class BlueprintProcessorModelContent : Serializable { @Id - @Column(name = "config_model_content_id") + @Column(name = "blueprint_content_runtime_id") var id: String? = null @Column(name = "name", nullable = false) @@ -52,7 +52,7 @@ class BlueprintProcessorModelContent : Serializable { var contentType: String? = null @OneToOne - @JoinColumn(name = "config_model_id") + @JoinColumn(name = "blueprint_runtime_id") var blueprintModel: BlueprintProcessorModel? = null @Lob @@ -98,4 +98,4 @@ class BlueprintProcessorModelContent : Serializable { private const val serialVersionUID = 1L } -}
\ No newline at end of file +} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt new file mode 100644 index 00000000..4c953163 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * 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.onap.ccsdk.apps.blueprintsprocessor.db + +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.EnableAutoConfiguration +import org.springframework.context.annotation.ComponentScan +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import java.io.File +import java.nio.file.Paths +import kotlin.test.assertTrue + +@RunWith(SpringRunner::class) +@EnableAutoConfiguration +@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +class BlueprintProcessorCatalogServiceImplTest { + + @Autowired + lateinit var blueprintCatalog: BluePrintCatalogService + + @Test + fun `test catalog service`() { + val file = Paths.get("./src/test/resources/test-cba.zip").toFile() + assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") + + blueprintCatalog.saveToDatabase(file) + + blueprintCatalog.getFromDatabase("baseconfiguration", "1.0.0") + + blueprintCatalog.deleteFromDatabase("baseconfiguration", "1.0.0") + + File("./src/test/resources/baseconfiguration").deleteRecursively() + } +}
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/application-test.properties b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/application-test.properties index 6f10626e..3ac7ec38 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/application-test.properties +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/application-test.properties @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -blueprintsprocessor.db.primary.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE +blueprintsprocessor.db.primary.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 blueprintsprocessor.db.primary.username=sa blueprintsprocessor.db.primary.password= blueprintsprocessor.db.primary.driverClassName=org.h2.Driver @@ -22,7 +22,6 @@ blueprintsprocessor.db.primary.hibernateHbm2ddlAuto=create-drop blueprintsprocessor.db.primary.hibernateDDLAuto=update blueprintsprocessor.db.primary.hibernateNamingStrategy=org.hibernate.cfg.ImprovedNamingStrategy blueprintsprocessor.db.primary.hibernateDialect=org.hibernate.dialect.H2Dialect - # Controller Blueprints Core Configuration blueprintsprocessor.blueprintDeployPath=./target/blueprints/deploy -blueprintsprocessor.blueprintArchivePath=./target/blueprints/archive
\ No newline at end of file +blueprintsprocessor.blueprintArchivePath=./target/blueprints/archive diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/test-cba.zip b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/test-cba.zip Binary files differnew file mode 100644 index 00000000..a62d4bfb --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/test-cba.zip diff --git a/ms/blueprintsprocessor/modules/commons/pom.xml b/ms/blueprintsprocessor/modules/commons/pom.xml index 4df89857..8d900a89 100644..100755 --- a/ms/blueprintsprocessor/modules/commons/pom.xml +++ b/ms/blueprintsprocessor/modules/commons/pom.xml @@ -2,6 +2,8 @@ <!-- ~ Copyright © 2017-2018 AT&T Intellectual Property. ~ + ~ Modifications Copyright © 2019 Bell Canada. + ~ ~ 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 diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/pom.xml b/ms/blueprintsprocessor/modules/commons/rest-lib/pom.xml index 82e8cd73..773746b4 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/pom.xml +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/pom.xml @@ -28,6 +28,10 @@ <description>Blueprints Processor Rest Lib</description> <dependencies> <dependency> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <artifactId>core</artifactId> + </dependency> + <dependency> <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> <artifactId>core</artifactId> </dependency> diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml b/ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml index 6395963b..dcf42c20 100644 --- a/ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml +++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml @@ -15,16 +15,16 @@ ~ limitations under the License. --> <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> - <parent> - <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> - <artifactId>inbounds</artifactId> - <version>0.4.1-SNAPSHOT</version> - </parent> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> + <artifactId>inbounds</artifactId> + <version>0.4.1-SNAPSHOT</version> + </parent> - <artifactId>resource-api</artifactId> - <packaging>jar</packaging> - <name>Blueprints Processor Resource API</name> - <description>Blueprints Processor Resource API</description> + <artifactId>resource-api</artifactId> + <packaging>jar</packaging> + <name>Blueprints Processor Resource API</name> + <description>Blueprints Processor Resource API</description> </project> diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml index db6fdd27..818adf9d 100644..100755 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml @@ -2,6 +2,8 @@ <!-- ~ Copyright © 2017-2018 AT&T Intellectual Property. ~ + ~ Modifications Copyright © 2019 Bell Canada. + ~ ~ 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 @@ -14,7 +16,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -<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"> +<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> <parent> <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> @@ -29,44 +32,24 @@ <dependencies> <dependency> + <groupId>org.onap.ccsdk.apps.components</groupId> + <artifactId>proto-definition</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <version>${project.version}</version> + <artifactId>core</artifactId> + </dependency> + <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-testing</artifactId> </dependency> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + <scope>test</scope> + </dependency> </dependencies> - <build> - <extensions> - <extension> - <groupId>kr.motd.maven</groupId> - <artifactId>os-maven-plugin</artifactId> - <version>1.6.1</version> - </extension> - </extensions> - <plugins> - <plugin> - <groupId>org.xolstice.maven.plugins</groupId> - <artifactId>protobuf-maven-plugin</artifactId> - <version>0.6.1</version> - <configuration> - <protocArtifact> - com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier} - </protocArtifact> - <pluginId>grpc-java</pluginId> - <pluginArtifact> - io.grpc:protoc-gen-grpc-java:1.16.1:exe:${os.detected.classifier} - </pluginArtifact> - <protoSourceRoot>./../../../../../components/model-catalog/api-definition</protoSourceRoot> - </configuration> - <executions> - <execution> - <goals> - <goal>compile</goal> - <goal>compile-custom</goal> - </goals> - </execution> - </executions> - </plugin> - </plugins> - </build> - </project> diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt index 17191f31..fb0bc567 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt @@ -1,5 +1,6 @@ /* * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,48 +17,96 @@ package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api +import io.grpc.StatusException import io.grpc.stub.StreamObserver -import org.apache.commons.io.FileUtils import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration -import org.onap.ccsdk.apps.controllerblueprints.management.api.* +import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils.currentTimestamp +import org.onap.ccsdk.apps.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.apps.controllerblueprints.common.api.Status +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.apps.controllerblueprints.management.api.BluePrintManagementInput +import org.onap.ccsdk.apps.controllerblueprints.management.api.BluePrintManagementOutput +import org.onap.ccsdk.apps.controllerblueprints.management.api.BluePrintManagementServiceGrpc import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.io.File @Service -class BluePrintManagementGRPCHandler(private val bluePrintCoreConfiguration: BluePrintCoreConfiguration) +class BluePrintManagementGRPCHandler(private val bluePrintCoreConfiguration: BluePrintCoreConfiguration, + private val bluePrintCatalogService: BluePrintCatalogService) : BluePrintManagementServiceGrpc.BluePrintManagementServiceImplBase() { private val log = LoggerFactory.getLogger(BluePrintManagementGRPCHandler::class.java) - override fun uploadBlueprint(request: BluePrintUploadInput, responseObserver: StreamObserver<BluePrintUploadOutput>) { - val response = BluePrintUploadOutput.newBuilder().setCommonHeader(request.commonHeader).build() + override fun uploadBlueprint(request: BluePrintManagementInput, responseObserver: StreamObserver<BluePrintManagementOutput>) { + val blueprintName = request.blueprintName + val blueprintVersion = request.blueprintVersion + val blueprint = "blueprint $blueprintName:$blueprintVersion" + + log.info("request(${request.commonHeader.requestId}): Received upload $blueprint") + + val blueprintArchivedFilePath = "${bluePrintCoreConfiguration.archivePath}/$blueprintName/$blueprintVersion/$blueprintName.zip" try { - val blueprintName = request.blueprintName - val blueprintVersion = request.blueprintVersion - val filePath = "${bluePrintCoreConfiguration.archivePath}/$blueprintName/$blueprintVersion" - val blueprintDir = File(filePath) + val blueprintArchivedFile = File(blueprintArchivedFilePath) + + saveToDisk(request, blueprintArchivedFile) + val blueprintId = bluePrintCatalogService.saveToDatabase(blueprintArchivedFile) + + File("${bluePrintCoreConfiguration.archivePath}/$blueprintName").deleteRecursively() - log.info("Re-creating blueprint directory(${blueprintDir.absolutePath})") - FileUtils.deleteDirectory(blueprintDir) - FileUtils.forceMkdir(blueprintDir) + responseObserver.onNext(successStatus("Successfully uploaded $blueprint with id($blueprintId)", request.commonHeader)) + responseObserver.onCompleted() + } catch (e: Exception) { + failStatus("request(${request.commonHeader.requestId}): Failed to upload $blueprint at path $blueprintArchivedFilePath", e) + } + } - val file = File("${blueprintDir.absolutePath}/$blueprintName.zip") - log.info("Writing CBA File under :${file.absolutePath}") + override fun removeBlueprint(request: BluePrintManagementInput, responseObserver: StreamObserver<BluePrintManagementOutput>) { + val blueprintName = request.blueprintName + val blueprintVersion = request.blueprintVersion + val blueprint = "blueprint $blueprintName:$blueprintVersion" - val fileChunk = request.fileChunk + log.info("request(${request.commonHeader.requestId}): Received delete $blueprint") - file.writeBytes(fileChunk.chunk.toByteArray()).apply { - log.info("CBA file(${file.absolutePath} written successfully") - } + try { + bluePrintCatalogService.deleteFromDatabase(blueprintName, blueprintVersion) + responseObserver.onNext(successStatus("Successfully deleted $blueprint", request.commonHeader)) + responseObserver.onCompleted() } catch (e: Exception) { - log.error("failed to upload file ", e) + failStatus("request(${request.commonHeader.requestId}): Failed to delete $blueprint", e) } - responseObserver.onNext(response) - responseObserver.onCompleted() } - override fun removeBlueprint(request: BluePrintRemoveInput?, responseObserver: StreamObserver<BluePrintRemoveOutput>?) { - //TODO + private fun saveToDisk(request: BluePrintManagementInput, blueprintDir: File) { + log.info("request(${request.commonHeader.requestId}): Writing CBA File under :${blueprintDir.absolutePath}") + if (blueprintDir.exists()) { + log.info("request(${request.commonHeader.requestId}): Re-creating blueprint directory(${blueprintDir.absolutePath})") + //FileUtils.deleteDirectory(blueprintDir.parentFile) + blueprintDir.parentFile.deleteRecursively() + } + blueprintDir.parentFile.mkdirs() + //FileUtils.forceMkdir(blueprintDir.parentFile) + blueprintDir.writeBytes(request.fileChunk.chunk.toByteArray()).apply { + log.info("request(${request.commonHeader.requestId}): CBA file(${blueprintDir.absolutePath} written successfully") + } + + } + + private fun successStatus(message: String, header: CommonHeader): BluePrintManagementOutput = + BluePrintManagementOutput.newBuilder() + .setCommonHeader(header) + .setStatus(Status.newBuilder() + .setTimestamp(currentTimestamp()) + .setMessage(message) + .setCode(200) + .build()) + .build() + + private fun failStatus(message: String, e: Exception): StatusException { + log.error(message, e) + return io.grpc.Status.INTERNAL + .withDescription(message) + .withCause(e) + .asException() } -}
\ No newline at end of file +} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt index 0668d3c9..453306de 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt @@ -16,9 +16,10 @@ package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api -import com.google.protobuf.util.JsonFormat import io.grpc.stub.StreamObserver import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration +import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils.toJava +import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils.toProto import org.onap.ccsdk.apps.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceInput import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceOutput @@ -31,14 +32,29 @@ class BluePrintProcessingGRPCHandler(private val bluePrintCoreConfiguration: Blu : BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() { private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandler::class.java) - override fun process(request: ExecutionServiceInput, - responseObserver: StreamObserver<ExecutionServiceOutput>) { + override fun process(responseObserver: StreamObserver<ExecutionServiceOutput>?): StreamObserver<ExecutionServiceInput> { - //val json = JsonFormat.printer().print(request) - //log.info("Received GRPC request ${json}") - //TODO( Handle Processing Response") - val response = ExecutionServiceOutput.newBuilder().setCommonHeader(request.commonHeader).build() - responseObserver.onNext(response) - responseObserver.onCompleted() + return object : StreamObserver<ExecutionServiceInput> { + override fun onNext(executionServiceInput: ExecutionServiceInput) { + try { + val output = executionServiceHandler.process(executionServiceInput.toJava()) + .toProto(executionServiceInput.payload) + responseObserver?.onNext(output) + } catch (e: Exception) { + onError(e) + } + } + + override fun onError(error: Throwable) { + log.debug("Fail to process message", error) + responseObserver?.onError(io.grpc.Status.INTERNAL + .withDescription(error.message) + .asException()) + } + + override fun onCompleted() { + responseObserver?.onCompleted() + } + } } }
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt index 0a67e878..e4734c44 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt @@ -21,7 +21,14 @@ import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInp import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.MediaType -import org.springframework.web.bind.annotation.* +import org.springframework.http.codec.multipart.FilePart +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RequestPart +import org.springframework.web.bind.annotation.ResponseBody +import org.springframework.web.bind.annotation.RestController import reactor.core.publisher.Mono @RestController @@ -31,18 +38,26 @@ class ExecutionServiceController { @Autowired lateinit var executionServiceHandler: ExecutionServiceHandler - - @RequestMapping(path = arrayOf("/ping"), method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) + @RequestMapping(path = ["/ping"], method = [RequestMethod.GET], produces = [MediaType.APPLICATION_JSON_VALUE]) @ResponseBody fun ping(): Mono<String> { return Mono.just("Success") } - @RequestMapping(path = arrayOf("/process"), method = arrayOf(RequestMethod.POST), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) + @PostMapping(path = ["/upload"], consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) + @ApiOperation(value = "Upload CBA", notes = "Takes a File and load it in the runtime database") + @ResponseBody + fun upload(@RequestPart("file") parts: Mono<FilePart>): Mono<String> { + return parts + .filter { it is FilePart } + .ofType(FilePart::class.java) + .flatMap(executionServiceHandler::upload) + } + + @RequestMapping(path = ["/process"], method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE]) @ApiOperation(value = "Resolve Resource Mappings", notes = "Takes the blueprint information and process as per the payload") @ResponseBody - fun process(@RequestBody executionServiceInput: ExecutionServiceInput): Mono<ExecutionServiceOutput> { - val executionServiceOutput = executionServiceHandler.process(executionServiceInput) - return Mono.just(executionServiceOutput) + fun process(@RequestBody executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { + return executionServiceHandler.process(executionServiceInput) } } diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt index 69758ecf..ec605c1d 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt @@ -16,22 +16,61 @@ package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch +import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration +import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ACTION_MODE_ASYNC +import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ACTION_MODE_SYNC import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Status +import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils.saveCBAFile import org.onap.ccsdk.apps.blueprintsprocessor.services.workflow.BlueprintDGExecutionService +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintFileUtils import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils import org.slf4j.LoggerFactory +import org.springframework.http.codec.multipart.FilePart import org.springframework.stereotype.Service +import reactor.core.publisher.Mono @Service -class ExecutionServiceHandler(private val bluePrintCatalogService: BluePrintCatalogService, +class ExecutionServiceHandler(private val bluePrintCoreConfiguration: BluePrintCoreConfiguration, + private val bluePrintCatalogService: BluePrintCatalogService, private val blueprintDGExecutionService: BlueprintDGExecutionService) { private val log = LoggerFactory.getLogger(ExecutionServiceHandler::class.toString()) + fun upload(filePart: FilePart): Mono<String> { + try { + val archivedPath = BluePrintFileUtils.getCbaStorageDirectory(bluePrintCoreConfiguration.archivePath) + val cbaPath = saveCBAFile(filePart, archivedPath) + bluePrintCatalogService.saveToDatabase(cbaPath.toFile()).let { + return Mono.just("{\"status\": \"Successfully uploaded blueprint with id($it)\"}") + } + } catch (e: Exception) { + return Mono.error<String>(BluePrintException("Error uploading the CBA file.", e)) + } + } + fun process(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { + return when { + executionServiceInput.actionIdentifiers.mode == ACTION_MODE_ASYNC -> { + GlobalScope.launch(Dispatchers.Default) { + // TODO post result in DMaaP + val executionServiceOutput = doProcess(executionServiceInput) + } + response(executionServiceInput) + } + executionServiceInput.actionIdentifiers.mode == ACTION_MODE_SYNC -> doProcess(executionServiceInput) + else -> response(executionServiceInput, "Failed to process request, 'actionIdentifiers.mode' not specified. Valid value are: 'sync' or 'async'.", true) + } + } + private fun doProcess(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { val requestId = executionServiceInput.commonHeader.requestId log.info("processing request id $requestId") @@ -40,13 +79,34 @@ class ExecutionServiceHandler(private val bluePrintCatalogService: BluePrintCata val blueprintName = actionIdentifiers.blueprintName val blueprintVersion = actionIdentifiers.blueprintVersion - val basePath = bluePrintCatalogService.prepareBluePrint(blueprintName, blueprintVersion) + val basePath = bluePrintCatalogService.getFromDatabase(blueprintName, blueprintVersion) log.info("blueprint base path $basePath") - val blueprintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(requestId, basePath) + val blueprintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(requestId, basePath.toString()) return blueprintDGExecutionService.executeDirectedGraph(blueprintRuntimeService, executionServiceInput) } + fun response(executionServiceInput: ExecutionServiceInput, errorMessage: String = "", failure: Boolean = false): ExecutionServiceOutput { + val executionServiceOutput = ExecutionServiceOutput() + executionServiceOutput.commonHeader = executionServiceInput.commonHeader + executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers + executionServiceOutput.payload = executionServiceInput.payload + + val status = Status() + status.errorMessage = errorMessage + if (failure) { + status.eventType = "EVENT-COMPONENT-FAILURE" + status.code = 500 + status.message = BluePrintConstants.STATUS_FAILURE + } else { + status.eventType = "EVENT-COMPONENT-PROCESSING" + status.code = 200 + status.message = BluePrintConstants.STATUS_PROCESSING + } + executionServiceOutput.status = status + + return executionServiceOutput + } }
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappings.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappings.kt new file mode 100644 index 00000000..220a6fd6 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappings.kt @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * 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.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils + +import com.fasterxml.jackson.databind.node.JsonNodeFactory +import com.fasterxml.jackson.databind.node.ObjectNode +import com.google.common.base.Strings +import com.google.protobuf.Struct +import com.google.protobuf.Value +import org.onap.ccsdk.apps.controllerblueprints.common.api.ActionIdentifiers +import org.onap.ccsdk.apps.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.apps.controllerblueprints.common.api.Flag +import org.onap.ccsdk.apps.controllerblueprints.common.api.Status +import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceInput +import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceOutput +import java.text.SimpleDateFormat +import java.util.* + +private val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + +// STRUCT + +fun Struct.toJava(): ObjectNode { + val objectNode = JsonNodeFactory.instance.objectNode() + return getNode(objectNode) +} + +fun Struct.getNode(objectNode: ObjectNode): ObjectNode { + this.fieldsMap.forEach { + when (it.value.kindCase.name) { + "BOOL_VALUE" -> objectNode.put(it.key, it.value.boolValue) + "KIND_NOT_SET" -> objectNode.put(it.key, it.value.toByteArray()) + "LIST_VALUE" -> { + val arrayNode = JsonNodeFactory.instance.arrayNode() + it.value.listValue.valuesList.forEach { arrayNode.addPOJO(it.getValue()) } + objectNode.put(it.key, arrayNode) + } + "NULL_VALUE" -> objectNode.put(it.key, JsonNodeFactory.instance.nullNode()) + "NUMBER_VALUE" -> objectNode.put(it.key, it.value.numberValue) + "STRING_VALUE" -> objectNode.put(it.key, it.value.stringValue) + "STRUCT_VALUE" -> objectNode.put(it.key, it.value.structValue.getNode(JsonNodeFactory.instance.objectNode())) + } + } + return objectNode +} + +fun Value.getValue(): Any { + return when (this.kindCase.name) { + "BOOL_VALUE" -> this.boolValue + "KIND_NOT_SET" -> this.toByteArray() + "LIST_VALUE" -> listOf(this.listValue.valuesList.forEach { it.getValue() }) + "NULL_VALUE" -> JsonNodeFactory.instance.nullNode() + "NUMBER_VALUE" -> this.numberValue + "STRING_VALUE" -> this.stringValue + "STRUCT_VALUE" -> this.structValue.getNode(JsonNodeFactory.instance.objectNode()) + else -> { + "undefined" + } + } +} + +// ACTION IDENTIFIER + +fun org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers.toProto(): ActionIdentifiers { + val actionIdentifier = ActionIdentifiers.newBuilder() + actionIdentifier.actionName = this.actionName + actionIdentifier.blueprintName = this.blueprintName + actionIdentifier.blueprintVersion = this.blueprintVersion + actionIdentifier.mode = this.mode + return actionIdentifier.build() +} + +fun ActionIdentifiers.toJava(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers { + val actionIdentifier = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers() + actionIdentifier.actionName = this.actionName + actionIdentifier.blueprintName = this.blueprintName + actionIdentifier.blueprintVersion = this.blueprintVersion + actionIdentifier.mode = this.mode + return actionIdentifier +} + +// COMMON HEADER + +fun org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.CommonHeader.toProto(): CommonHeader { + val commonHeader = CommonHeader.newBuilder() + commonHeader.originatorId = this.originatorId + commonHeader.requestId = this.requestId + commonHeader.subRequestId = this.subRequestId + commonHeader.timestamp = this.timestamp.toString() + commonHeader.flag = this.flags?.toProto() + return commonHeader.build() +} + +fun CommonHeader.toJava(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.CommonHeader { + val commonHeader = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.CommonHeader() + commonHeader.originatorId = this.originatorId + commonHeader.requestId = this.requestId + commonHeader.subRequestId = this.subRequestId + commonHeader.timestamp = if (!Strings.isNullOrEmpty(this.timestamp)) { + formatter.parse(this.timestamp) + } else { + Date() + } + commonHeader.flags = this.flag?.toJava() + return commonHeader +} + +// FLAG + +fun org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Flags.toProto(): Flag { + val flag = Flag.newBuilder() + flag.isForce = this.isForce + flag.ttl = this.ttl + return flag.build() +} + +fun Flag.toJava(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Flags { + val flag = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Flags() + flag.isForce = this.isForce + flag.ttl = this.ttl + return flag +} + +// STATUS + +fun org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Status.toProto(): Status { + val status = Status.newBuilder() + status.code = this.code + status.errorMessage = this.errorMessage + status.message = this.message + status.timestamp = this.timestamp.toString() + status.eventType = this.eventType + return status.build() +} + +// EXECUTION INPUT + +fun ExecutionServiceInput.toJava(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput { + val executionServiceInput = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput() + executionServiceInput.actionIdentifiers = this.actionIdentifiers.toJava() + executionServiceInput.commonHeader = this.commonHeader.toJava() + executionServiceInput.payload = this.payload.toJava() + return executionServiceInput +} + +// EXECUTION OUPUT + +fun org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput.toProto(payload: Struct): ExecutionServiceOutput { + val executionServiceOuput = ExecutionServiceOutput.newBuilder() + executionServiceOuput.actionIdentifiers = this.actionIdentifiers.toProto() + executionServiceOuput.commonHeader = this.commonHeader.toProto() + executionServiceOuput.status = this.status.toProto() + executionServiceOuput.payload = payload + return executionServiceOuput.build() +}
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/Utils.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/Utils.kt new file mode 100644 index 00000000..6d22fdab --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/Utils.kt @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * 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.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils + +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException +import org.springframework.http.codec.multipart.FilePart +import org.springframework.util.StringUtils +import java.io.File +import java.io.IOException +import java.nio.file.Path +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.util.* + + +fun currentTimestamp(): String { + val now = LocalDateTime.now(ZoneId.systemDefault()) + val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + return formatter.format(now) +} + + +@Throws(BluePrintException::class, IOException::class) +fun saveCBAFile(filePart: FilePart, targetDirectory: Path): Path { + + val fileName = StringUtils.cleanPath(filePart.filename()) + + if (StringUtils.getFilenameExtension(fileName) != "zip") { + throw BluePrintException("Invalid file extension required ZIP") + } + + val changedFileName = UUID.randomUUID().toString() + ".zip" + + val targetLocation = targetDirectory.resolve(changedFileName) + + val file = File(targetLocation.toString()) + if (file.exists()) { + file.delete() + } + file.createNewFile() + + filePart.transferTo(file) + + return targetLocation +}
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt index c870bf7f..264e2aea 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt @@ -1,5 +1,6 @@ /* * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,34 +19,32 @@ package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api import com.google.protobuf.ByteString import io.grpc.testing.GrpcServerRule -import org.apache.commons.io.FileUtils import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration +import org.onap.ccsdk.apps.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.apps.controllerblueprints.management.api.BluePrintManagementInput import org.onap.ccsdk.apps.controllerblueprints.management.api.BluePrintManagementServiceGrpc -import org.onap.ccsdk.apps.controllerblueprints.management.api.BluePrintUploadInput -import org.onap.ccsdk.apps.controllerblueprints.management.api.CommonHeader import org.onap.ccsdk.apps.controllerblueprints.management.api.FileChunk -import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration +import org.springframework.boot.autoconfigure.EnableAutoConfiguration +import org.springframework.context.annotation.ComponentScan +import org.springframework.test.annotation.DirtiesContext import org.springframework.test.context.TestPropertySource import org.springframework.test.context.junit4.SpringRunner import java.io.File -import java.nio.file.Paths import kotlin.test.AfterTest import kotlin.test.BeforeTest -import kotlin.test.assertNotNull +import kotlin.test.assertEquals import kotlin.test.assertTrue @RunWith(SpringRunner::class) -@ContextConfiguration(classes = [BluePrintManagementGRPCHandler::class, BluePrintCoreConfiguration::class]) +@EnableAutoConfiguration +@DirtiesContext +@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) @TestPropertySource(locations = ["classpath:application-test.properties"]) class BluePrintManagementGRPCHandlerTest { - private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandlerTest::class.java)!! - @get:Rule val grpcServerRule = GrpcServerRule().directExecutor() @@ -60,33 +59,58 @@ class BluePrintManagementGRPCHandlerTest { @AfterTest fun cleanDir() { - FileUtils.deleteDirectory(File("./target/blueprints")) + //TODO It's giving fluctuating results, need to look for another way to cleanup + // works sometimes otherwise results IO Exception + // Most probably bufferReader stream is not getting closed when cleanDir is getting invoked + File("./target/blueprints").deleteRecursively() + } + + @Test + fun `test upload blueprint`() { + val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) + val id = "123_upload" + val req = createInputRequest(id) + val output = blockingStub.uploadBlueprint(req) + + assertEquals(200, output.status.code) + assertTrue(output.status.message.contains("Successfully uploaded blueprint sample:1.0.0 with id(")) + assertEquals(id, output.commonHeader.requestId) } @Test - fun testFileUpload() { + fun `test delete blueprint`() { val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) + val id = "123_delete" + val req = createInputRequest(id) + + var output = blockingStub.uploadBlueprint(req) + assertEquals(200, output.status.code) + assertTrue(output.status.message.contains("Successfully uploaded blueprint sample:1.0.0 with id(")) + assertEquals(id, output.commonHeader.requestId) - val file = Paths.get("./src/test/resources/test-cba.zip").toFile() + output = blockingStub.removeBlueprint(req) + assertEquals(200, output.status.code) + } + + private fun createInputRequest(id: String): BluePrintManagementInput { + val file = File("./src/test/resources/test-cba.zip") assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") - val commonHeader = CommonHeader.newBuilder() + val commonHeader = CommonHeader + .newBuilder() .setTimestamp("2012-04-23T18:25:43.511Z") .setOriginatorId("System") - .setRequestId("1234") + .setRequestId(id) .setSubRequestId("1234-56").build() val fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(file.inputStream().readBytes())) .build() - val input = BluePrintUploadInput.newBuilder() + return BluePrintManagementInput.newBuilder() .setCommonHeader(commonHeader) .setBlueprintName("sample") .setBlueprintVersion("1.0.0") .setFileChunk(fileChunk) .build() - - val output = blockingStub.uploadBlueprint(input) - assertNotNull(output, "failed to get upload response") } -}
\ No newline at end of file +} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt index cd871b4a..01984b21 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt @@ -1,5 +1,6 @@ /* * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,33 +19,36 @@ package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api import com.google.protobuf.util.JsonFormat +import io.grpc.stub.StreamObserver import io.grpc.testing.GrpcServerRule +import org.junit.Assert +import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.mock.MockBluePrintCatalogService -import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.mock.MockBlueprintDGExecutionService +import org.onap.ccsdk.apps.controllerblueprints.common.api.ActionIdentifiers +import org.onap.ccsdk.apps.controllerblueprints.common.api.CommonHeader import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.apps.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc -import org.onap.ccsdk.apps.controllerblueprints.processing.api.CommonHeader import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceInput +import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceOutput import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration +import org.springframework.boot.autoconfigure.EnableAutoConfiguration +import org.springframework.context.annotation.ComponentScan +import org.springframework.test.annotation.DirtiesContext import org.springframework.test.context.TestPropertySource import org.springframework.test.context.junit4.SpringRunner import kotlin.test.BeforeTest -import kotlin.test.assertNotNull +@Ignore @RunWith(SpringRunner::class) -@ContextConfiguration(classes = [BluePrintProcessingGRPCHandler::class, ExecutionServiceHandler::class, - MockBlueprintDGExecutionService::class, MockBluePrintCatalogService::class, - BluePrintCoreConfiguration::class]) +@DirtiesContext +@EnableAutoConfiguration +@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) @TestPropertySource(locations = ["classpath:application-test.properties"]) class BluePrintProcessingGRPCHandlerTest { - - private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandlerTest::class.java)!! + private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandlerTest::class.java) @get:Rule val grpcServerRule = GrpcServerRule().directExecutor() @@ -52,17 +56,35 @@ class BluePrintProcessingGRPCHandlerTest { @Autowired lateinit var bluePrintProcessingGRPCHandler: BluePrintProcessingGRPCHandler + lateinit var requestObs: StreamObserver<ExecutionServiceInput> + @BeforeTest fun init() { - // Create a server, add service, start, and register for automatic graceful shutdown. grpcServerRule.serviceRegistry.addService(bluePrintProcessingGRPCHandler) + + val blockingStub = BluePrintProcessingServiceGrpc.newStub(grpcServerRule.channel) + + requestObs = blockingStub.process(object : StreamObserver<ExecutionServiceOutput> { + override fun onNext(executionServiceOuput: ExecutionServiceOutput) { + log.debug("onNext {}", executionServiceOuput) + if ("1234".equals(executionServiceOuput.commonHeader.requestId)) { + Assert.assertEquals("Failed to process request, \'actionIdentifiers.mode\' not specified. Valid value are: \'sync\' or \'async\'.", executionServiceOuput.status.errorMessage) + } + } + + override fun onError(error: Throwable) { + log.debug("Fail to process message", error) + Assert.assertEquals("INTERNAL: Could not find blueprint : from database", error.message) + } + + override fun onCompleted() { + log.info("Done") + } + }) } @Test fun testSelfServiceGRPCHandler() { - - val blockingStub = BluePrintProcessingServiceGrpc.newBlockingStub(grpcServerRule.channel) - val commonHeader = CommonHeader.newBuilder() .setTimestamp("2012-04-23T18:25:43.511Z") .setOriginatorId("System") @@ -78,8 +100,25 @@ class BluePrintProcessingGRPCHandlerTest { .setPayload(payloadBuilder.build()) .build() - val response = blockingStub.process(input) - assertNotNull(response, "Response is null") + requestObs.onNext(input) + + val commonHeader2 = CommonHeader.newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId("2345") + .setSubRequestId("1234-56").build() + + val actionIdentifier = ActionIdentifiers.newBuilder().setMode("sync").build() + + val input2 = ExecutionServiceInput.newBuilder() + .setCommonHeader(commonHeader2) + .setActionIdentifiers(actionIdentifier) + .setPayload(payloadBuilder.build()) + .build() + + requestObs.onNext(input2) + + requestObs.onCompleted() } }
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt index e9e10307..de120148 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt @@ -1,5 +1,6 @@ /* * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,33 +19,70 @@ package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api import org.junit.Test import org.junit.runner.RunWith +import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.mock.MockBluePrintCatalogService -import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.mock.MockBlueprintDGExecutionService -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest +import org.springframework.context.annotation.ComponentScan +import org.springframework.core.io.ByteArrayResource +import org.springframework.http.client.MultipartBodyBuilder import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource import org.springframework.test.context.junit4.SpringRunner +import org.springframework.test.web.reactive.server.WebTestClient +import org.springframework.web.reactive.function.BodyInserters +import java.nio.file.Files +import java.nio.file.Paths +import kotlin.test.assertTrue @RunWith(SpringRunner::class) -@ContextConfiguration(classes = [MockBluePrintCatalogService::class, - MockBlueprintDGExecutionService::class, ExecutionServiceHandler::class]) +@WebFluxTest +@ContextConfiguration(classes = [ExecutionServiceHandler::class, BluePrintCoreConfiguration::class, BluePrintCatalogService::class]) +@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) +@TestPropertySource(locations = ["classpath:application-test.properties"]) class ExecutionServiceHandlerTest { @Autowired - lateinit var executionServiceHandler: ExecutionServiceHandler + lateinit var blueprintCatalog: BluePrintCatalogService + @Autowired + lateinit var webTestClient: WebTestClient + @Test - fun testProcess() { - val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234", - "./../../../../../components/model-catalog/blueprint-model/starter-blueprint/baseconfiguration") + fun `test rest upload blueprint`() { + val file = Paths.get("./src/test/resources/test-cba.zip").toFile() + assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") - val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/default-input.json", ExecutionServiceInput::class.java)!! - executionServiceHandler.process(executionServiceInput) + val body = MultipartBodyBuilder().apply { + part("file", object : ByteArrayResource(Files.readAllBytes(Paths.get("./src/test/resources/test-cba.zip"))) { + override fun getFilename(): String { + return "test-cba.zip" + } + }) + }.build() + webTestClient + .post() + .uri("/api/v1/execution-service/upload") + .body(BodyInserters.fromMultipartData(body)) + .exchange() + .expectStatus().isOk } -} - + @Test + fun `test rest process`() { + val file = Paths.get("./src/test/resources/test-cba.zip").toFile() + assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") + blueprintCatalog.saveToDatabase(file) + val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/default-input.json", ExecutionServiceInput::class.java)!! + webTestClient + .post() + .uri("/api/v1/execution-service/process") + .body(BodyInserters.fromObject(executionServiceInput)) + .exchange() + .expectStatus().isOk + } +}
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/mock/Mock.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/mock/Mock.kt new file mode 100644 index 00000000..c54e6176 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/mock/Mock.kt @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * 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.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.mock + +import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractComponentFunction +import org.onap.ccsdk.apps.controllerblueprints.core.asJsonPrimitive +import org.slf4j.LoggerFactory +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration + +@Configuration +open class MockComponentConfiguration { + + @Bean(name = ["component-resource-assignment", "component-netconf-executor", "component-jython-executor"]) + open fun createComponentFunction(): AbstractComponentFunction { + return MockComponentFunction() + } +} + +class MockComponentFunction : AbstractComponentFunction() { + + private val log = LoggerFactory.getLogger(MockComponentFunction::class.java) + + override fun process(executionRequest: ExecutionServiceInput) { + log.info("Processing component : $operationInputs") + + bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, + "assignment-params", "params".asJsonPrimitive()) + } + + override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { + log.info("Recovering component..") + } +}
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/mock/SelfServiceApiMocks.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/mock/SelfServiceApiMocks.kt deleted file mode 100755 index 656d92f1..00000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/mock/SelfServiceApiMocks.kt +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * 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.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.mock - -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.apps.blueprintsprocessor.services.workflow.BlueprintDGExecutionService -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService -import org.springframework.stereotype.Service -import kotlin.test.assertNotNull - -@Service -class MockBlueprintDGExecutionService : BlueprintDGExecutionService { - override fun executeDirectedGraph(bluePrintRuntimeService: BluePrintRuntimeService<*>, executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { - - assertNotNull(executionServiceInput, "failed to get executionServiceInput") - - val executionServiceOutput = ExecutionServiceOutput() - executionServiceOutput.commonHeader = executionServiceInput.commonHeader - return executionServiceOutput - } -} - -@Service -class MockBluePrintCatalogService : BluePrintCatalogService { - - override fun uploadToDataBase(file: String, validate : Boolean): String { - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. - } - - override fun downloadFromDataBase(name: String, version: String, path: String): String { - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. - } - - override fun prepareBluePrint(name: String, version: String): String { - assertNotNull(name, "failed to get blueprint Name") - assertNotNull(version, "failed to get blueprint version") - return "./../../../../../components/model-catalog/blueprint-model/starter-blueprint/baseconfiguration" - } - - override fun downloadFromDataBase(uuid: String, path: String): String { - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. - } -}
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappingTests.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappingTests.kt new file mode 100644 index 00000000..2e4ba275 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappingTests.kt @@ -0,0 +1,172 @@ +package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils + +import com.fasterxml.jackson.databind.ObjectMapper +import com.google.protobuf.ListValue +import com.google.protobuf.NullValue +import com.google.protobuf.Struct +import com.google.protobuf.Value +import com.google.protobuf.util.JsonFormat +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Flags +import org.onap.ccsdk.apps.controllerblueprints.common.api.ActionIdentifiers +import org.onap.ccsdk.apps.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.apps.controllerblueprints.common.api.Flag +import org.springframework.test.context.junit4.SpringRunner +import java.text.SimpleDateFormat + +@RunWith(SpringRunner::class) +class BluePrintMappingsTest { + + val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + val dateString = "2019-01-16T18:25:43.511Z" + val dateForTest = formatter.parse(dateString) + + val flag = Flag.newBuilder().setIsForce(false).setTtl(1).build() + + fun createFlag(): Flags { + val flag = Flags() + flag.isForce = false + flag.ttl = 1 + return flag + } + + @Test + fun flagToJavaTest() { + val flag2 = flag.toJava() + + Assert.assertEquals(flag.isForce, flag2.isForce) + Assert.assertEquals(flag.ttl, flag2.ttl) + } + + @Test + fun flagToProtoTest() { + val flag = createFlag() + val flag2 = flag.toProto() + + Assert.assertEquals(flag.isForce, flag2.isForce) + Assert.assertEquals(flag.ttl, flag2.ttl) + } + + fun createStatus(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Status { + val status = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Status() + status.code = 400 + status.errorMessage = "Concurrent modification exception" + status.eventType = "Update" + status.message = "Error uploading data" + status.timestamp = dateForTest + return status + } + + @Test + fun statusToProtoTest() { + val status = createStatus() + val status2 = status.toProto() + + Assert.assertEquals(status.code, status2.code) + Assert.assertEquals(status.errorMessage, status2.errorMessage) + Assert.assertEquals(status.eventType, status2.eventType) + Assert.assertEquals(status.message, status2.message) + Assert.assertEquals(status.timestamp.toString(), status2.timestamp) + } + + @Test + fun commonHeaderToJavaTest() { + val flag = Flag.newBuilder().setIsForce(true).setTtl(2).build() + + val commonHeader = CommonHeader.newBuilder().setOriginatorId("Origin").setRequestId("requestID").setSubRequestId("subRequestID").setTimestamp(dateString).setFlag(flag).build() + val commonHeader2 = commonHeader.toJava() + + Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId) + Assert.assertEquals(commonHeader.requestId, commonHeader2.requestId) + Assert.assertEquals(commonHeader.subRequestId, commonHeader2.subRequestId) + Assert.assertEquals(commonHeader.timestamp, formatter.format(commonHeader2.timestamp)) + } + + fun createCommonHeader(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.CommonHeader { + val commonHeader = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.CommonHeader() + commonHeader.flags = createFlag() + commonHeader.originatorId = "1234" + commonHeader.requestId = "2345" + commonHeader.subRequestId = "0123" + commonHeader.timestamp = dateForTest + return commonHeader + } + + @Test + fun commonHeaderToProtoTest() { + val commonHeader = createCommonHeader() + val commonHeader2 = commonHeader.toProto() + Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId) + Assert.assertEquals(commonHeader.requestId, commonHeader2.requestId) + Assert.assertEquals(commonHeader.subRequestId, commonHeader2.subRequestId) + Assert.assertEquals(commonHeader.timestamp.toString(), commonHeader2.timestamp) + } + + @Test + fun actionIdentifierToJavaTest() { + val actionIdentifiers = ActionIdentifiers.newBuilder().setActionName("Process Action").setBlueprintName("BlueprintName").setBlueprintVersion("3.0").setMode("Execution").build() + val actionIdentifiers2 = actionIdentifiers.toJava() + + Assert.assertEquals(actionIdentifiers.actionName, actionIdentifiers2.actionName) + Assert.assertEquals(actionIdentifiers.blueprintName, actionIdentifiers2.blueprintName) + Assert.assertEquals(actionIdentifiers.blueprintVersion, actionIdentifiers2.blueprintVersion) + Assert.assertEquals(actionIdentifiers.mode, actionIdentifiers2.mode) + } + + fun createActionIdentifier(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers { + val ac = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers() + ac.mode = "mode" + ac.blueprintVersion = "version" + ac.blueprintName = "name" + ac.actionName = "action" + return ac + } + + @Test + fun actionIdentifierToProtoTest() { + val actionIdentifiers = createActionIdentifier() + val actionIdentifiers2 = actionIdentifiers.toProto() + + Assert.assertEquals(actionIdentifiers.actionName, actionIdentifiers2.actionName) + Assert.assertEquals(actionIdentifiers.blueprintName, actionIdentifiers2.blueprintName) + Assert.assertEquals(actionIdentifiers.blueprintVersion, actionIdentifiers2.blueprintVersion) + Assert.assertEquals(actionIdentifiers.mode, actionIdentifiers2.mode) + } + + @Test + fun testStructToJava() { + val struct = Struct.newBuilder().putAllFields(createValues()).build() + val struct2 = struct.toJava() + + val mapper = ObjectMapper() + + Assert.assertEquals(JsonFormat.printer().print(struct).replace(" ", "").replace("\r",""), + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(struct2).replace(" ", "").replace("\r","")) + } + + fun createValues(): Map<String, Value> { + val map = mutableMapOf<String, Value>() + + val boolValue = Value.newBuilder().setBoolValue(true).build() + val stringValue = Value.newBuilder().setStringValue("string").build() + val doubleValue = Value.newBuilder().setNumberValue(Double.MAX_VALUE).build() + val jsonValue = Value.newBuilder().setStringValue("{\"bblah\": \"bbblo\"}").build() + val listValue = Value.newBuilder().setListValue(ListValue.newBuilder().addValues(boolValue).addValues(boolValue).build()).build() + val nullValue = Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build() + + map.put("bool", boolValue) + map.put("string", stringValue) + map.put("doublbe", doubleValue) + map.put("json", jsonValue) + map.put("list", listValue) + map.put("null", nullValue) + + val structValue = Value.newBuilder().setStructValue(Struct.newBuilder().putAllFields(map).build()).build() + + map.put("struct", structValue) + + return map + } +}
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/resources/application-test.properties b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/resources/application-test.properties index edb51022..8a26ee6e 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/resources/application-test.properties +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/resources/application-test.properties @@ -13,5 +13,16 @@ # See the License for the specific language governing permissions and # limitations under the License. # +blueprintsprocessor.db.primary.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 +blueprintsprocessor.db.primary.username=sa +blueprintsprocessor.db.primary.password= +blueprintsprocessor.db.primary.driverClassName=org.h2.Driver +blueprintsprocessor.db.primary.hibernateHbm2ddlAuto=create-drop +blueprintsprocessor.db.primary.hibernateDDLAuto=update +blueprintsprocessor.db.primary.hibernateNamingStrategy=org.hibernate.cfg.ImprovedNamingStrategy +blueprintsprocessor.db.primary.hibernateDialect=org.hibernate.dialect.H2Dialect +# Controller Blueprints Core Configuration blueprintsprocessor.blueprintDeployPath=./target/blueprints/deploy blueprintsprocessor.blueprintArchivePath=./target/blueprints/archive +# executor +blueprints.processor.functions.python.executor.executionPath="./target/" diff --git a/ms/blueprintsprocessor/modules/outbounds/pom.xml b/ms/blueprintsprocessor/modules/outbounds/pom.xml index e957c881..b6c26e67 100644 --- a/ms/blueprintsprocessor/modules/outbounds/pom.xml +++ b/ms/blueprintsprocessor/modules/outbounds/pom.xml @@ -15,16 +15,16 @@ ~ limitations under the License. --> <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> - <parent> - <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> - <artifactId>modules</artifactId> - <version>0.4.1-SNAPSHOT</version> - </parent> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> + <artifactId>modules</artifactId> + <version>0.4.1-SNAPSHOT</version> + </parent> - <artifactId>outbounds</artifactId> - <packaging>pom</packaging> - <name>Blueprints Processor Outbounds POM</name> - <description>Blueprints Processor Outbounds</description> + <artifactId>outbounds</artifactId> + <packaging>pom</packaging> + <name>Blueprints Processor Outbounds POM</name> + <description>Blueprints Processor Outbounds</description> </project> diff --git a/ms/blueprintsprocessor/modules/services/execution-service/pom.xml b/ms/blueprintsprocessor/modules/services/execution-service/pom.xml index 035f14d9..96bb09f2 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/pom.xml +++ b/ms/blueprintsprocessor/modules/services/execution-service/pom.xml @@ -29,6 +29,10 @@ <dependencies> <dependency> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <artifactId>core</artifactId> + </dependency> + <dependency> <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> <artifactId>core</artifactId> </dependency> diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/AbstractComponentFunction.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/AbstractComponentFunction.kt index c9e147ba..f7c901df 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/AbstractComponentFunction.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/AbstractComponentFunction.kt @@ -53,17 +53,17 @@ abstract class AbstractComponentFunction : BlueprintFunctionNode<ExecutionServic return stepName
}
- override fun prepareRequest(executionServiceInput: ExecutionServiceInput): ExecutionServiceInput {
+ override fun prepareRequest(executionRequest: ExecutionServiceInput): ExecutionServiceInput { checkNotNull(bluePrintRuntimeService) { "failed to prepare blueprint runtime" }
check(stepName.isNotEmpty()) { "failed to assign step name" }
- this.executionServiceInput = executionServiceInput
+ this.executionServiceInput = executionRequest - processId = executionServiceInput.commonHeader.requestId
+ processId = executionRequest.commonHeader.requestId check(processId.isNotEmpty()) { "couldn't get process id for step($stepName)" }
- workflowName = executionServiceInput.actionIdentifiers.actionName
+ workflowName = executionRequest.actionIdentifiers.actionName check(workflowName.isNotEmpty()) { "couldn't get action name for step($stepName)" }
log.info("preparing request id($processId) for workflow($workflowName) step($stepName)")
@@ -88,12 +88,14 @@ abstract class AbstractComponentFunction : BlueprintFunctionNode<ExecutionServic this.operationInputs.putAll(operationResolvedProperties)
- return executionServiceInput
+ return executionRequest }
override fun prepareResponse(): ExecutionServiceOutput {
log.info("Preparing Response...")
executionServiceOutput.commonHeader = executionServiceInput.commonHeader
+ executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers + executionServiceOutput.payload = executionServiceInput.payload // Resolve the Output Expression
val stepOutputs = bluePrintRuntimeService
diff --git a/ms/blueprintsprocessor/modules/services/pom.xml b/ms/blueprintsprocessor/modules/services/pom.xml index 8cb3c6f1..469899d0 100644..100755 --- a/ms/blueprintsprocessor/modules/services/pom.xml +++ b/ms/blueprintsprocessor/modules/services/pom.xml @@ -2,6 +2,8 @@ <!-- ~ Copyright © 2017-2018 AT&T Intellectual Property. ~ + ~ Modifications Copyright © 2019 Bell Canada. + ~ ~ 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 diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/pom.xml b/ms/blueprintsprocessor/modules/services/workflow-service/pom.xml index 6e3dade6..cc2a0e66 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/pom.xml +++ b/ms/blueprintsprocessor/modules/services/workflow-service/pom.xml @@ -28,6 +28,10 @@ <dependencies> <dependency> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <artifactId>core</artifactId> + </dependency> + <dependency> <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> <artifactId>execution-service</artifactId> </dependency> diff --git a/ms/blueprintsprocessor/parent/pom.xml b/ms/blueprintsprocessor/parent/pom.xml index 401fef0a..472b466b 100644..100755 --- a/ms/blueprintsprocessor/parent/pom.xml +++ b/ms/blueprintsprocessor/parent/pom.xml @@ -3,6 +3,7 @@ ~ Copyright © 2017-2018 AT&T Intellectual Property. ~ ~ Modifications Copyright © 2018 IBM. + ~ Modifications Copyright © 2019 Bell Canada. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. @@ -16,7 +17,8 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -<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"> +<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> <parent> <groupId>org.onap.ccsdk.apps</groupId> @@ -29,12 +31,12 @@ <name>Blueprints Processor Parent</name> <description>Blueprints Processor Parent</description> <properties> - <spring.boot.version>2.1.1.RELEASE</spring.boot.version> - <spring.version>5.1.3.RELEASE</spring.version> - <kotlin.version>1.3.11</kotlin.version> - <kotlin.maven.version>1.3.11</kotlin.maven.version> - <kotlin.couroutines.version>1.1.0</kotlin.couroutines.version> - <grpc.version>1.17.1</grpc.version> + <spring.boot.version>2.1.2.RELEASE</spring.boot.version> + <spring.version>5.1.4.RELEASE</spring.version> + <kotlin.version>1.3.20</kotlin.version> + <kotlin.maven.version>1.3.20</kotlin.maven.version> + <kotlin.couroutines.version>1.1.1</kotlin.couroutines.version> + <grpc.version>1.18.0</grpc.version> <protobuff.java.utils.version>3.6.1</protobuff.java.utils.version> <eelf.version>1.0.0</eelf.version> <sli.version>0.4.1-SNAPSHOT</sli.version> @@ -125,14 +127,26 @@ </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-stdlib-common</artifactId> + <version>${kotlin.version}</version> + </dependency> + <!--Use kotlin-compiler-embeddable instead koltin-compiler wrap--> + <!--guava dependency inside kotlin-compiler creating classpath issues at runtime--> + <dependency> + <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-scripting-jvm-host</artifactId> <version>${kotlin.version}</version> + <exclusions> + <exclusion> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-compile</artifactId> + </exclusion> + </exclusions> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-compiler-embeddable</artifactId> <version>${kotlin.version}</version> - <scope>runtime</scope> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> @@ -246,6 +260,11 @@ <!-- Application Module Dependencies --> <dependency> <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> + <artifactId>application</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.ccsdk.apps.blueprintsprocessor</groupId> <artifactId>db-lib</artifactId> <version>${project.version}</version> </dependency> @@ -303,6 +322,11 @@ <artifactId>resource-dict</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <artifactId>core</artifactId> + <version>${project.version}</version> + </dependency> <!-- Database --> <dependency> @@ -400,7 +424,19 @@ </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-compiler-embeddable</artifactId> + </dependency> + <dependency> + <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-scripting-jvm-host</artifactId> + <!--Use kotlin-compiler-embeddable as koltin-compiler wrap--> + <!--guava dependency creating classpath issues at runtime--> + <exclusions> + <exclusion> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-compiler</artifactId> + </exclusion> + </exclusions> </dependency> <!-- GRPC Dependencies --> <dependency> diff --git a/ms/blueprintsprocessor/pom.xml b/ms/blueprintsprocessor/pom.xml index df4932cd..774e177e 100644..100755 --- a/ms/blueprintsprocessor/pom.xml +++ b/ms/blueprintsprocessor/pom.xml @@ -1,6 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright © 2017-2018 AT&T Intellectual Property. + ~ Modifications Copyright © 2019 Bell Canada. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. @@ -15,34 +16,35 @@ ~ limitations under the License. --> <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> - <parent> - <groupId>org.onap.ccsdk.apps</groupId> - <artifactId>ccsdk-apps-ms</artifactId> - <version>0.4.1-SNAPSHOT</version> - </parent> - <artifactId>blueprintsprocessor</artifactId> - <packaging>pom</packaging> - <name>Blueprints Processor Root</name> - <description>Blueprints Processor Root</description> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.ccsdk.apps</groupId> + <artifactId>ccsdk-apps-ms</artifactId> + <version>0.4.1-SNAPSHOT</version> + </parent> + <artifactId>blueprintsprocessor</artifactId> + <packaging>pom</packaging> + <name>Blueprints Processor Root</name> + <description>Blueprints Processor Root</description> - <properties> - <service.name>BlueprintsProcessor</service.name> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> - <maven.build.timestamp.format>yyyyMMdd'T'HHmmss'Z'</maven.build.timestamp.format> - <build.number>${maven.build.timestamp}</build.number> - <java.version>1.8</java.version> - <maven.compiler.target>1.8</maven.compiler.target> - <maven.compiler.source>1.8</maven.compiler.source> - <ccsdk.project.version>${project.version}</ccsdk.project.version> - </properties> + <properties> + <service.name>BlueprintsProcessor</service.name> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> + <maven.build.timestamp.format>yyyyMMdd'T'HHmmss'Z'</maven.build.timestamp.format> + <build.number>${maven.build.timestamp}</build.number> + <java.version>1.8</java.version> + <maven.compiler.target>1.8</maven.compiler.target> + <maven.compiler.source>1.8</maven.compiler.source> + <ccsdk.project.version>${project.version}</ccsdk.project.version> + </properties> - <modules> - <module>parent</module> - <module>modules</module> - <module>functions</module> - <module>application</module> - </modules> + <modules> + <module>parent</module> + <module>modules</module> + <module>functions</module> + <module>application</module> + <module>distribution</module> + </modules> </project> diff --git a/ms/controllerblueprints/application/etc/run.source b/ms/controllerblueprints/application/etc/run.source index fc1b4e55..1d0ac070 100644..100755 --- a/ms/controllerblueprints/application/etc/run.source +++ b/ms/controllerblueprints/application/etc/run.source @@ -9,8 +9,5 @@ java -classpath "/etc:${APP_HOME}/lib/*:/lib/*:/src:/schema:/generated-sources:$ -Djava.security.egd=file:/dev/./urandom \ -DAPPNAME=${APP_NAME} -DAPPENV=${APP_ENV} -DAPPVERSION=${APP_VERSION} -DNAMESPACE=${NAMESPACE} \ -Dspring.config.location=${APP_CONFIG_HOME}/ \ --Dspring.datasource.url=${DB_URL} \ --Dspring.datasource.username=${DB_USER} \ --Dspring.datasource.password=${DB_PASSWORD} \ -Dblueprints.load.initial-data=${INIT_DATA_LOAD} \ -org.onap.ccsdk.apps.controllerblueprints.ControllerBluprintsApplication +org.onap.ccsdk.apps.controllerblueprints.ControllerBlueprintsApplication diff --git a/ms/controllerblueprints/application/opt/app/onap/config/application-dev.properties b/ms/controllerblueprints/application/opt/app/onap/config/application-dev.properties index e574778e..81b3061a 100755 --- a/ms/controllerblueprints/application/opt/app/onap/config/application-dev.properties +++ b/ms/controllerblueprints/application/opt/app/onap/config/application-dev.properties @@ -49,7 +49,7 @@ spring.jpa.hibernate.ddl-auto=none spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect # Load Resource Source Mappings -resourceSourceMappings=db=source-db,input=source-input,default=source-default,mdsal=source-rest,capability=source-capability +resourceSourceMappings=primary-db=source-primary-db,input=source-input,default=source-default,primary-config-data=source-rest,capability=source-capability # Controller Blueprints Core Configuration controllerblueprints.blueprintDeployPath=/etc/blueprints/deploy controllerblueprints.blueprintArchivePath=/etc/blueprints/archive @@ -64,4 +64,7 @@ controllerblueprints.loadResourceDictionary=true controllerblueprints.loadResourceDictionaryPaths=./../../../components/model-catalog/resource-dictionary/starter-dictionary # CBA file extension -controllerblueprints.loadCbaExtension=zip
\ No newline at end of file +controllerblueprints.loadCbaExtension=zip + +# Web server config +server.port=8080
\ No newline at end of file diff --git a/ms/controllerblueprints/application/opt/app/onap/config/application.properties b/ms/controllerblueprints/application/opt/app/onap/config/application.properties index 91792394..5b651e66 100755 --- a/ms/controllerblueprints/application/opt/app/onap/config/application.properties +++ b/ms/controllerblueprints/application/opt/app/onap/config/application.properties @@ -1,6 +1,7 @@ # # Copyright © 2017-2018 AT&T Intellectual Property. # Modifications Copyright © 2018 IBM. +# Modifications Copyright © 2019 Bell Canada. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -41,17 +42,17 @@ spring.jpa.properties.hibernate.use_sql_comments=true spring.jpa.properties.hibernate.format_sql=true # spring.datasource.url, spring.datasource.username,spring.datasource.password may be overridden by ENV variables -spring.datasource.url=jdbc:mysql://localhost:3306/sdnctl +spring.datasource.url=jdbc:mysql://db:3306/sdnctl spring.datasource.username=sdnctl spring.datasource.password=sdnctl spring.datasource.driver-class-name=org.mariadb.jdbc.Driver -spring.jpa.show-sql = true -spring.jpa.hibernate.ddl-auto = none -spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy -spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect +spring.jpa.show-sql=true +spring.jpa.hibernate.ddl-auto=none +spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect # Load Resource Source Mappings -resourceSourceMappings=db=source-db,input=source-input,default=source-default,mdsal=source-rest,capability=source-capability +resourceSourceMappings=primary-db=source-primary-db,input=source-input,default=source-default,primary-config-data=source-rest,capability=source-capability # Controller Blueprints Core Configuration controllerblueprints.blueprintDeployPath=/etc/blueprints/deploy @@ -61,11 +62,14 @@ controllerblueprints.blueprintEnrichmentPath=/etc/blueprints/enrichment # blueprints.load.initial-data may be overridden by ENV variables controllerblueprints.loadInitialData=true controllerblueprints.loadBluePrint=false -controllerblueprints.loadBluePrintPaths=model-catalog/blueprint-model/starter-blueprint +controllerblueprints.loadBluePrintPaths=/model-catalog/blueprint-model/starter-blueprint controllerblueprints.loadModelType=true -controllerblueprints.loadModeTypePaths=model-catalog/definition-type/starter-type +controllerblueprints.loadModeTypePaths=/model-catalog/definition-type/starter-type controllerblueprints.loadResourceDictionary=true -controllerblueprints.loadResourceDictionaryPaths=model-catalog/resource-dictionary/starter-dictionary +controllerblueprints.loadResourceDictionaryPaths=/model-catalog/resource-dictionary/starter-dictionary # CBA file extension -controllerblueprints.loadCbaExtension=zip
\ No newline at end of file +controllerblueprints.loadCbaExtension=zip + +# Web server config +server.port=8080
\ No newline at end of file diff --git a/ms/controllerblueprints/application/opt/app/onap/config/logback.xml b/ms/controllerblueprints/application/opt/app/onap/config/logback.xml new file mode 100755 index 00000000..01ae4f6c --- /dev/null +++ b/ms/controllerblueprints/application/opt/app/onap/config/logback.xml @@ -0,0 +1,44 @@ +<!--
+ ~ Copyright © 2017-2018 AT&T Intellectual Property.
+ ~
+ ~ 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.
+ -->
+
+<configuration>
+
+ <property name="localPattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{100} - %msg%n" />
+
+ <property name="defaultPattern" value="%date{ISO8601,UTC}|%X{RequestID}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}| %msg%n" />
+
+ <property name="debugLoggerPattern" value="%date{ISO8601,UTC}|%X{RequestID}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|[%caller{3}]| %msg%n" />
+
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <!-- encoders are assigned the type
+ ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
+ <encoder>
+ <pattern>${defaultPattern}</pattern>
+ </encoder>
+ </appender>
+
+
+ <logger name="org.springframework" level="info"/>
+ <logger name="org.springframework.web" level="info"/>
+ <logger name="org.springframework.security.web.authentication" level="warn"/>
+ <logger name="org.hibernate" level="error"/>
+ <logger name="org.onap.ccsdk.apps" level="info"/>
+
+ <root level="warn">
+ <appender-ref ref="STDOUT"/>
+ </root>
+
+</configuration>
diff --git a/ms/controllerblueprints/application/src/main/java/org/onap/ccsdk/apps/controllerblueprints/ApplicationConstants.java b/ms/controllerblueprints/application/src/main/java/org/onap/ccsdk/apps/controllerblueprints/ApplicationConstants.java index 2471bd5b..c4759b56 100644 --- a/ms/controllerblueprints/application/src/main/java/org/onap/ccsdk/apps/controllerblueprints/ApplicationConstants.java +++ b/ms/controllerblueprints/application/src/main/java/org/onap/ccsdk/apps/controllerblueprints/ApplicationConstants.java @@ -17,7 +17,7 @@ package org.onap.ccsdk.apps.controllerblueprints;
/**
- * ApplicationConstants.java Purpose: Provide ControllerBluprintsApplication Constant Information
+ * ApplicationConstants.java Purpose: Provide ControllerBlueprintsApplication Constant Information
*
* @author Brinda Santh
* @version 1.0
diff --git a/ms/controllerblueprints/application/src/main/java/org/onap/ccsdk/apps/controllerblueprints/ControllerBluprintsApplication.java b/ms/controllerblueprints/application/src/main/java/org/onap/ccsdk/apps/controllerblueprints/ControllerBlueprintsApplication.java index 6b0efd87..e925c69c 100644 --- a/ms/controllerblueprints/application/src/main/java/org/onap/ccsdk/apps/controllerblueprints/ControllerBluprintsApplication.java +++ b/ms/controllerblueprints/application/src/main/java/org/onap/ccsdk/apps/controllerblueprints/ControllerBlueprintsApplication.java @@ -31,12 +31,12 @@ import org.springframework.web.reactive.config.EnableWebFlux; @EnableWebFlux
@ComponentScan(basePackages = {"org.onap.ccsdk.apps.controllerblueprints"})
@EnableAutoConfiguration
-public class ControllerBluprintsApplication {
- private static EELFLogger log = EELFManager.getInstance().getLogger(ControllerBluprintsApplication.class);
+public class ControllerBlueprintsApplication {
+ private static EELFLogger log = EELFManager.getInstance().getLogger(ControllerBlueprintsApplication.class);
public static void main(String[] args) {
log.info("****** Starting Controlled Blueprints Application ******");
- SpringApplication.run(ControllerBluprintsApplication.class, args);
+ SpringApplication.run(ControllerBlueprintsApplication.class, args);
}
}
\ No newline at end of file diff --git a/ms/controllerblueprints/application/src/main/resources/application-dev.properties b/ms/controllerblueprints/application/src/main/resources/application-dev.properties new file mode 100755 index 00000000..30b71fb4 --- /dev/null +++ b/ms/controllerblueprints/application/src/main/resources/application-dev.properties @@ -0,0 +1,70 @@ +# +# Copyright © 2017-2018 AT&T Intellectual Property. +# +# 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. +# +appName=ControllerBluePrints +ms_name=org.onap.ccsdk.apps.controllerblueprints +appVersion=1.0.0 + +# Basic Authentication +basic-auth.user-name=ccsdkapps +basic-auth.hashed-pwd={bcrypt}$2a$10$MJxhNiOAffxbyrV9.rrOUewP9Q/ASg5Nit2cmP.yBaXGsVXo8BW3y + +#logging.pattern.console=%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr($ threadId: {PID:- }){magenta} %clr(---){faint} %clr([ hostname: %X{hostname} serviceName: %X{serviceName} version: %X{version} transactionId: %X{transactionId} requestTimeStamp: %X{requestTimestamp} responseTimeStamp: %X{responseTimestamp} duration: %X{duration}]){yellow} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wex + +logging.level.org.springframework.web=INFO +logging.level.org.hibernate.SQL=warn +logging.level.org.hibernate.type.descriptor.sql=debug + +#To Remove Null in JSON API Response +spring.jackson.default-property-inclusion=non_null + +#Swagger Configuration +swagger.contact.name=Brinda Santh Muthuramalingam +swagger.contact.url=www.onap.com +swagger.contact.email=brindasanth@onap.com + +spring.jpa.properties.hibernate.show_sql=true +spring.jpa.properties.hibernate.use_sql_comments=true +spring.jpa.properties.hibernate.format_sql=true + +# spring.datasource.url, spring.datasource.username,spring.datasource.password may be overridden by ENV variables +spring.datasource.url=jdbc:mysql://localhost:3306/sdnctl +spring.datasource.username=sdnctl +spring.datasource.password=sdnctl +spring.datasource.driver-class-name=org.mariadb.jdbc.Driver +spring.jpa.show-sql=true +spring.jpa.hibernate.ddl-auto=none +spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect +# Load Resource Source Mappings +resourceSourceMappings=db=source-db,input=source-input,default=source-default,mdsal=source-rest,capability=source-capability +# Controller Blueprints Core Configuration +controllerblueprints.blueprintDeployPath=/etc/blueprints/deploy +controllerblueprints.blueprintArchivePath=/etc/blueprints/archive +controllerblueprints.blueprintEnrichmentPath=/etc/blueprints/enrichment +# Controller Blueprint Load Configurations +controllerblueprints.loadInitialData=true +controllerblueprints.loadBluePrint=false +controllerblueprints.loadBluePrintPaths=./../../../components/model-catalog/blueprint-model/starter-blueprint +controllerblueprints.loadModelType=true +controllerblueprints.loadModeTypePaths=./../../../components/model-catalog/definition-type/starter-type +controllerblueprints.loadResourceDictionary=true +controllerblueprints.loadResourceDictionaryPaths=./../../../components/model-catalog/resource-dictionary/starter-dictionary + +# CBA file extension +controllerblueprints.loadCbaExtension=zip + +# Web server config +server.port=8080
\ No newline at end of file diff --git a/ms/controllerblueprints/application/src/main/resources/application.properties b/ms/controllerblueprints/application/src/main/resources/application.properties new file mode 100755 index 00000000..ec61be48 --- /dev/null +++ b/ms/controllerblueprints/application/src/main/resources/application.properties @@ -0,0 +1,74 @@ +# +# Copyright © 2017-2018 AT&T Intellectual Property. +# Modifications Copyright © 2019 Bell Canada. +# +# 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. +# +appName=ControllerBluePrints +ms_name=org.onap.ccsdk.apps.controllerblueprints +appVersion=1.0.0 + +# Basic Authentication +basic-auth.user-name=ccsdkapps +basic-auth.hashed-pwd={bcrypt}$2a$10$MJxhNiOAffxbyrV9.rrOUewP9Q/ASg5Nit2cmP.yBaXGsVXo8BW3y + +#logging.pattern.console=%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr($ threadId: {PID:- }){magenta} %clr(---){faint} %clr([ hostname: %X{hostname} serviceName: %X{serviceName} version: %X{version} transactionId: %X{transactionId} requestTimeStamp: %X{requestTimestamp} responseTimeStamp: %X{responseTimestamp} duration: %X{duration}]){yellow} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wex + +logging.level.org.springframework.web=INFO +logging.level.org.hibernate.SQL=warn +logging.level.org.hibernate.type.descriptor.sql=debug + +#To Remove Null in JSON API Response +spring.jackson.default-property-inclusion=non_null + +#Swagger Configuration +swagger.contact.name=Brinda Santh Muthuramalingam +swagger.contact.url=www.onap.com +swagger.contact.email=brindasanth@onap.com + +spring.jpa.properties.hibernate.show_sql=true +spring.jpa.properties.hibernate.use_sql_comments=true +spring.jpa.properties.hibernate.format_sql=true + +# spring.datasource.url, spring.datasource.username,spring.datasource.password may be overridden by ENV variables +spring.datasource.url=jdbc:mysql://localhost:3306/sdnctl +spring.datasource.username=sdnctl +spring.datasource.password=sdnctl +spring.datasource.driver-class-name=org.mariadb.jdbc.Driver +spring.jpa.show-sql=true +spring.jpa.hibernate.ddl-auto=none +spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect + +# Load Resource Source Mappings +resourceSourceMappings=db=source-db,input=source-input,default=source-default,mdsal=source-rest,capability=source-capability + +# Controller Blueprints Core Configuration +controllerblueprints.blueprintDeployPath=/etc/blueprints/deploy +controllerblueprints.blueprintArchivePath=/etc/blueprints/archive +controllerblueprints.blueprintEnrichmentPath=/etc/blueprints/enrichment +# Controller Blueprint Load Configurations +# blueprints.load.initial-data may be overridden by ENV variables +controllerblueprints.loadInitialData=true +controllerblueprints.loadBluePrint=false +controllerblueprints.loadBluePrintPaths=/model-catalog/blueprint-model/starter-blueprint +controllerblueprints.loadModelType=true +controllerblueprints.loadModeTypePaths=/model-catalog/definition-type/starter-type +controllerblueprints.loadResourceDictionary=true +controllerblueprints.loadResourceDictionaryPaths=/model-catalog/resource-dictionary/starter-dictionary + +# CBA file extension +controllerblueprints.loadCbaExtension=zip + +# Web server config +server.port=8080
\ No newline at end of file diff --git a/ms/controllerblueprints/application/src/test/java/org/onap/ccsdk/apps/controllerblueprints/ControllerBluprintsApplicationTest.java b/ms/controllerblueprints/application/src/test/java/org/onap/ccsdk/apps/controllerblueprints/ControllerBlueprintsApplicationTest.java index 969f8042..cf9b3e71 100644 --- a/ms/controllerblueprints/application/src/test/java/org/onap/ccsdk/apps/controllerblueprints/ControllerBluprintsApplicationTest.java +++ b/ms/controllerblueprints/application/src/test/java/org/onap/ccsdk/apps/controllerblueprints/ControllerBlueprintsApplicationTest.java @@ -30,7 +30,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
-public class ControllerBluprintsApplicationTest {
+public class ControllerBlueprintsApplicationTest {
@Autowired
private TestRestTemplate restTemplate;
diff --git a/ms/controllerblueprints/application/src/test/resources/application.properties b/ms/controllerblueprints/application/src/test/resources/application.properties index 1fafd8bc..9aebd793 100755 --- a/ms/controllerblueprints/application/src/test/resources/application.properties +++ b/ms/controllerblueprints/application/src/test/resources/application.properties @@ -33,7 +33,7 @@ swagger.contact.url=www.onap.com swagger.contact.email=brindasanth@onap.com
# Load Resource Source Mappings
-resourceSourceMappings=db=source-db,input=source-input,default=source-default,mdsal=source-rest,capability=source-capability
+resourceSourceMappings=primary-db=source-primary-db,input=source-input,default=source-default,primary-config-data=source-rest,capability=source-capability
# Controller Blueprints Core Configuration
controllerblueprints.blueprintDeployPath=./target/blueprints/deploy
@@ -52,4 +52,7 @@ controllerblueprints.loadResourceDictionaryPaths=./../../../../components/model- controllerblueprints.loadCbaExtension=zip
# CBA examples for tests cases
-controllerblueprints.loadBlueprintsExamplesPath=./../../../../components/model-catalog/blueprint-model/test-blueprints
\ No newline at end of file +controllerblueprints.loadBlueprintsExamplesPath=./../../../../components/model-catalog/blueprint-model/test-blueprints
+
+# Web server config
+server.port=8080
\ No newline at end of file diff --git a/ms/controllerblueprints/distribution/pom.xml b/ms/controllerblueprints/distribution/pom.xml index 30571293..91d4bbca 100644..100755 --- a/ms/controllerblueprints/distribution/pom.xml +++ b/ms/controllerblueprints/distribution/pom.xml @@ -1,6 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright © 2017-2018 AT&T Intellectual Property. + ~ Modifications Copyright © 2019 Bell Canada. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. @@ -30,10 +31,10 @@ <name.space>org.onap.ccsdk.apps</name.space> <!-- <name.space>${namespace}</name.space> --> <serviceArtifactName>controllerblueprints</serviceArtifactName> <image.name>onap/ccsdk-controllerblueprints</image.name> - <docker.buildArg.https_proxy>${https_proxy}</docker.buildArg.https_proxy> - <docker.push.phase>deploy</docker.push.phase> - <docker.verbose>true</docker.verbose> - </properties> + <docker.buildArg.https_proxy>${https_proxy}</docker.buildArg.https_proxy> + <docker.push.phase>deploy</docker.push.phase> + <docker.verbose>true</docker.verbose> + </properties> <dependencies> <dependency> @@ -120,20 +121,20 @@ </goals> <configuration> <source> - println project.properties['ccsdk.project.version']; - def versionArray; + println project.properties['ccsdk.project.version'] + def versionArray if (project.properties['ccsdk.project.version'] != null ) { - versionArray = project.properties['ccsdk.project.version'].split('\\.'); + versionArray = project.properties['ccsdk.project.version'].split('\\.') } if (project.properties['ccsdk.project.version'].endsWith("-SNAPSHOT")) { - project.properties['project.docker.latesttag.version']=versionArray[0] + '.' + versionArray[1] + "-STAGING-latest"; + project.properties['project.docker.latesttag.version']=versionArray[0] + '.' + versionArray[1] + "-STAGING-latest" } else { - project.properties['project.docker.latesttag.version']=versionArray[0]+'.' + versionArray[1]+"-STAGING-latest"; + project.properties['project.docker.latesttag.version']=versionArray[0]+'.' + versionArray[1]+"-STAGING-latest" } - println 'New Tag for docker:' + project.properties['project.docker.latesttag.version']; + println 'New Tag for docker:' + project.properties['project.docker.latesttag.version'] </source> </configuration> </execution> @@ -143,34 +144,34 @@ </plugins> </build> - <profiles> - <profile> - <id>docker</id> - <build> - <plugins> - <plugin> - <groupId>io.fabric8</groupId> - <artifactId>docker-maven-plugin</artifactId> - <version>0.26.1</version> - <inherited>false</inherited> - <configuration> - <images> - <image> - <name>${image.name}</name> - <build> - <cleanup>try</cleanup> - <dockerFileDir>${basedir}/target/docker-stage</dockerFileDir> - <tags> - <tag>${project.version}</tag> - <tag>${project.version}-STAGING-${maven.build.timestamp}</tag> - <tag>${project.docker.latesttag.version}</tag> - </tags> - </build> - </image> - </images> - <verbose>true</verbose> - </configuration> - <executions> + <profiles> + <profile> + <id>docker</id> + <build> + <plugins> + <plugin> + <groupId>io.fabric8</groupId> + <artifactId>docker-maven-plugin</artifactId> + <version>0.26.1</version> + <inherited>false</inherited> + <configuration> + <images> + <image> + <name>${image.name}</name> + <build> + <cleanup>try</cleanup> + <dockerFileDir>${basedir}/target/docker-stage</dockerFileDir> + <tags> + <tag>${project.version}</tag> + <tag>${project.version}-STAGING-${maven.build.timestamp}</tag> + <tag>${project.docker.latesttag.version}</tag> + </tags> + </build> + </image> + </images> + <verbose>true</verbose> + </configuration> + <executions> <execution> <id>generate-images</id> <phase>package</phase> @@ -186,11 +187,11 @@ <goal>push</goal> </goals> </execution> - </executions> - </plugin> - </plugins> - </build> - </profile> + </executions> + </plugin> + </plugins> + </build> + </profile> - </profiles> + </profiles> </project> diff --git a/ms/controllerblueprints/distribution/src/main/dc/docker-compose.yaml b/ms/controllerblueprints/distribution/src/main/dc/docker-compose.yaml index eae24703..232bfc01 100644..100755 --- a/ms/controllerblueprints/distribution/src/main/dc/docker-compose.yaml +++ b/ms/controllerblueprints/distribution/src/main/dc/docker-compose.yaml @@ -1,37 +1,33 @@ -version: '3.3' - -services: - db: - image: mariadb:latest - container_name: cb-mariadb - ports: - - "3306:3306" - volumes: - - ~/vm_mysql:/var/lib/mysql - restart: always - environment: - MYSQL_ROOT_PASSWORD: sdnctl - MYSQL_DATABASE: sdnctl - MYSQL_USER: sdnctl - MYSQL_PASSWORD: sdnctl - controller-blueprints: - depends_on: - - db - image: onap/ccsdk-controllerblueprints:latest - container_name: cb-rest - ports: - - "8080:8080" - restart: always - volumes: - - ~/share/vm_ms/controllerblueprints/config:/opt/app/onap/config - - ~/share/vm_ms/controllerblueprints/logs:/logs - environment: - APPLICATIONNAME : ControllerBluePrints - BUNDLEVERSION: 1.0.0 - APP_CONFIG_HOME: /opt/app/onap/config - DB_URL: jdbc:mysql://db:3306/sdnctl - DB_USER: sdnctl - DB_PASSWORD: sdnctl - INIT_DATA_LOAD: "true" - STICKYSELECTORKEY: - ENVCONTEXT: DEV
\ No newline at end of file +version: '3.3'
+
+services:
+ db:
+ image: mariadb:latest
+ container_name: ccsdk-mariadb
+ ports:
+ - "3306:3306"
+ volumes:
+ - ~/vm_mysql:/var/lib/mysql
+ restart: always
+ environment:
+ MYSQL_ROOT_PASSWORD: sdnctl
+ MYSQL_DATABASE: sdnctl
+ MYSQL_USER: sdnctl
+ MYSQL_PASSWORD: sdnctl
+ controller-blueprints:
+ depends_on:
+ - db
+ image: onap/ccsdk-controllerblueprints:latest
+ container_name: cb-rest
+ ports:
+ - "8080:8080"
+ restart: always
+ volumes:
+ - ~/share/vm_ms/controllerblueprints/config:/opt/app/onap/config
+ - ~/share/vm_ms/controllerblueprints/logs:/logs
+ environment:
+ APPLICATIONNAME: ControllerBluePrints
+ BUNDLEVERSION: 1.0.0
+ APP_CONFIG_HOME: /opt/app/onap/config
+ STICKYSELECTORKEY:
+ ENVCONTEXT: dev
\ No newline at end of file diff --git a/ms/controllerblueprints/distribution/src/main/docker/Dockerfile b/ms/controllerblueprints/distribution/src/main/docker/Dockerfile index 6de589da..88577f5a 100644..100755 --- a/ms/controllerblueprints/distribution/src/main/docker/Dockerfile +++ b/ms/controllerblueprints/distribution/src/main/docker/Dockerfile @@ -15,6 +15,7 @@ RUN (mkdir -p /source /opt/app/onap) && (tar -xzf /source.tar.gz -C /source) \ && (cp -rf /source/app/opt/app/onap/lib /opt/app/onap/) \ && (cp -rf /source/app/etc /) \ && (cp -rf /source/app/model-catalog /) \ +&& (cp -rf /source/app/config /) \ && (rm -rf /source) -ENTRYPOINT /startService.sh +ENTRYPOINT /startService.sh
\ No newline at end of file diff --git a/ms/controllerblueprints/distribution/src/main/docker/distribution.xml b/ms/controllerblueprints/distribution/src/main/docker/distribution.xml index c929f98e..1555b43e 100644..100755 --- a/ms/controllerblueprints/distribution/src/main/docker/distribution.xml +++ b/ms/controllerblueprints/distribution/src/main/docker/distribution.xml @@ -1,6 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright © 2017-2018 AT&T Intellectual Property. + ~ Modifications Copyright © 2019 Bell Canada. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. @@ -59,6 +60,11 @@ <useDefaultExcludes>true</useDefaultExcludes> </fileSet> <fileSet> + <directory>${project.basedir}/../application/opt/app/onap/config</directory> + <outputDirectory>./config</outputDirectory> + <useDefaultExcludes>true</useDefaultExcludes> + </fileSet> + <fileSet> <directory>${project.basedir}/../../../components/model-catalog</directory> <outputDirectory>./model-catalog</outputDirectory> <useDefaultExcludes>true</useDefaultExcludes> diff --git a/ms/controllerblueprints/distribution/src/main/docker/startService.sh b/ms/controllerblueprints/distribution/src/main/docker/startService.sh index 7077c224..84b2e5ac 100644..100755 --- a/ms/controllerblueprints/distribution/src/main/docker/startService.sh +++ b/ms/controllerblueprints/distribution/src/main/docker/startService.sh @@ -5,4 +5,5 @@ nodeName=ControllerBlueprints_1.0.0_$(cat /proc/self/cgroup | grep docker | sed echo "APP Config HOME : ${APP_CONFIG_HOME}" export APP_HOME=/opt/app/onap +cp -rf /config /opt/app/onap/ source /etc/run.source diff --git a/ms/controllerblueprints/modules/blueprint-scripts/pom.xml b/ms/controllerblueprints/modules/blueprint-scripts/pom.xml new file mode 100644 index 00000000..46c88b4c --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/pom.xml @@ -0,0 +1,59 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ Copyright © 2017-2018 AT&T Intellectual Property. + ~ + ~ 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. + --> + +<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"> + <parent> + <artifactId>modules</artifactId> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <version>0.4.1-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>blueprint-scripts</artifactId> + <name>Controller Blueprints Scripts</name> + + <dependencies> + <dependency> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <artifactId>resource-dict</artifactId> + </dependency> + <dependency> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-compiler-embeddable</artifactId> + </dependency> + <dependency> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-scripting-jvm-host</artifactId> + <exclusions> + <exclusion> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-compiler</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-script-util</artifactId> + </dependency> + <dependency> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-script-runtime</artifactId> + </dependency> + </dependencies> + +</project>
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintCompiledScript.kt b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintCompiledScript.kt new file mode 100644 index 00000000..8ac915bd --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintCompiledScript.kt @@ -0,0 +1,56 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.onap.ccsdk.apps.controllerblueprints.scripts + +import java.io.File +import java.io.Serializable +import java.net.URL +import java.net.URLClassLoader +import kotlin.reflect.KClass +import kotlin.script.experimental.api.* + +open class BluePrintCompiledScript<out JarFile : File>( + private val scriptCompilationConfiguration: ScriptCompilationConfiguration, + private val compiledJar: File) : + CompiledScript<JarFile>, Serializable { + + lateinit var scriptClassFQName: String + + override val compilationConfiguration: ScriptCompilationConfiguration + get() = scriptCompilationConfiguration + + override suspend fun getClass(scriptEvaluationConfiguration: ScriptEvaluationConfiguration?): ResultWithDiagnostics<KClass<*>> = try { + + val baseClassLoader = Thread.currentThread().contextClassLoader + + val urls = arrayListOf<URL>() + urls.add(compiledJar.toURI().toURL()) + val classLoaderWithDependencies = URLClassLoader(urls.toTypedArray(), baseClassLoader) + + val clazz = classLoaderWithDependencies.loadClass(scriptClassFQName).kotlin + clazz.asSuccess() + } catch (e: Throwable) { + ResultWithDiagnostics.Failure( + ScriptDiagnostic( + "Unable to instantiate class $scriptClassFQName", + exception = e + ) + ) + } + +} + diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintCompilerProxy.kt b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintCompilerProxy.kt new file mode 100644 index 00000000..7e9e8688 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintCompilerProxy.kt @@ -0,0 +1,150 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.onap.ccsdk.apps.controllerblueprints.scripts + +import org.jetbrains.kotlin.com.intellij.openapi.util.Disposer +import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys +import org.jetbrains.kotlin.cli.common.config.addKotlinSourceRoots +import org.jetbrains.kotlin.cli.common.environment.setIdeaIoUseFallback +import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport +import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation +import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity +import org.jetbrains.kotlin.cli.common.messages.MessageCollector +import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles +import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment +import org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler +import org.jetbrains.kotlin.cli.jvm.config.JvmClasspathRoot +import org.jetbrains.kotlin.config.* +import org.slf4j.LoggerFactory +import java.io.File +import kotlin.script.experimental.api.* +import kotlin.script.experimental.host.ScriptingHostConfiguration +import kotlin.script.experimental.jvm.util.classpathFromClasspathProperty +import kotlin.script.experimental.jvmhost.KJvmCompilerProxy + +open class BluePrintsCompilerProxy(private val hostConfiguration: ScriptingHostConfiguration) : KJvmCompilerProxy { + + private val log = LoggerFactory.getLogger(BluePrintsCompilerProxy::class.java)!! + + override fun compile(script: SourceCode, scriptCompilationConfiguration: ScriptCompilationConfiguration) + : ResultWithDiagnostics<CompiledScript<*>> { + + val messageCollector = ScriptDiagnosticsMessageCollector() + + fun failure(vararg diagnostics: ScriptDiagnostic): ResultWithDiagnostics.Failure = + ResultWithDiagnostics.Failure(*messageCollector.diagnostics.toTypedArray(), *diagnostics) + + // Compile the Code + try { + + log.trace("Scripting Host Configuration : $hostConfiguration") + + setIdeaIoUseFallback() + + val blueprintSourceCode = script as BluePrintSourceCode + + val compiledJarFile = blueprintSourceCode.targetJarFile + + if (!compiledJarFile.exists() || blueprintSourceCode.regenerate) { + + var environment: KotlinCoreEnvironment? = null + + val rootDisposable = Disposer.newDisposable() + + val compilerConfiguration = CompilerConfiguration().apply { + + put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, messageCollector) + put(CommonConfigurationKeys.MODULE_NAME, blueprintSourceCode.moduleName) + put(JVMConfigurationKeys.OUTPUT_JAR, compiledJarFile) + put(JVMConfigurationKeys.RETAIN_OUTPUT_IN_MEMORY, false) + + // Load Current Class loader to Compilation Class loader + val currentClassLoader = classpathFromClasspathProperty() + currentClassLoader?.forEach { + add(CLIConfigurationKeys.CONTENT_ROOTS, JvmClasspathRoot(it)) + } + + // Add all Kotlin Sources + addKotlinSourceRoots(blueprintSourceCode.blueprintKotlinSources) + + languageVersionSettings = LanguageVersionSettingsImpl( + LanguageVersion.LATEST_STABLE, ApiVersion.LATEST_STABLE, mapOf(AnalysisFlags.skipMetadataVersionCheck to true) + ) + } + + //log.info("Executing with compiler configuration : $compilerConfiguration") + + environment = KotlinCoreEnvironment.createForProduction(rootDisposable, compilerConfiguration, + EnvironmentConfigFiles.JVM_CONFIG_FILES) + + // Compile Kotlin Sources + val compiled = KotlinToJVMBytecodeCompiler.compileBunchOfSources(environment) + + log.info("Generated jar(${compiledJarFile.absolutePath}) status : $compiled}") + + val analyzerWithCompilerReport = AnalyzerWithCompilerReport(messageCollector, + environment.configuration.languageVersionSettings) + + if (analyzerWithCompilerReport.hasErrors()) { + return failure() + } + } + + val res = BluePrintCompiledScript<File>(scriptCompilationConfiguration, compiledJarFile) + + return ResultWithDiagnostics.Success(res, messageCollector.diagnostics) + + } catch (ex: Throwable) { + return failure(ex.asDiagnostics()) + } + } +} + +class ScriptDiagnosticsMessageCollector : MessageCollector { + + private val _diagnostics = arrayListOf<ScriptDiagnostic>() + + val diagnostics: List<ScriptDiagnostic> get() = _diagnostics + + override fun clear() { + _diagnostics.clear() + } + + override fun hasErrors(): Boolean = + _diagnostics.any { it.severity == ScriptDiagnostic.Severity.ERROR } + + + override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) { + val mappedSeverity = when (severity) { + CompilerMessageSeverity.EXCEPTION, + CompilerMessageSeverity.ERROR -> ScriptDiagnostic.Severity.ERROR + CompilerMessageSeverity.STRONG_WARNING, + CompilerMessageSeverity.WARNING -> ScriptDiagnostic.Severity.WARNING + CompilerMessageSeverity.INFO -> ScriptDiagnostic.Severity.INFO + CompilerMessageSeverity.LOGGING -> ScriptDiagnostic.Severity.DEBUG + else -> null + } + if (mappedSeverity != null) { + val mappedLocation = location?.let { + if (it.line < 0 && it.column < 0) null // special location created by CompilerMessageLocation.create + else SourceCode.Location(SourceCode.Position(it.line, it.column)) + } + _diagnostics.add(ScriptDiagnostic(message, mappedSeverity, location?.path, mappedLocation)) + } + } +} + diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintScriptConfiguration.kt b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintScriptConfiguration.kt new file mode 100644 index 00000000..3b3a5907 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintScriptConfiguration.kt @@ -0,0 +1,61 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.onap.ccsdk.apps.controllerblueprints.scripts + +import java.io.File +import kotlin.script.experimental.annotations.KotlinScript +import kotlin.script.experimental.api.ScriptCompilationConfiguration +import kotlin.script.experimental.api.SourceCode +import kotlin.script.experimental.api.defaultImports +import kotlin.script.experimental.jvm.jvm +import kotlin.script.experimental.jvm.util.classpathFromClassloader + +@KotlinScript( + fileExtension = "cba.kts", + compilationConfiguration = BluePrintScripCompilationConfiguration::class, + displayName = "Controller Blueprint Archive Kotlin Scripts" +) +abstract class BluePrintKotlinScript + +object BluePrintScripCompilationConfiguration : ScriptCompilationConfiguration( + { + defaultImports( + "org.onap.ccsdk.apps.controllerblueprints.core.*", + "org.onap.ccsdk.apps.controllerblueprints.core.data.*", + "org.onap.ccsdk.apps.controllerblueprints.core.interfaces.*", + "org.onap.ccsdk.apps.controllerblueprints.core.services.*", + "org.onap.ccsdk.apps.controllerblueprints.core.utils.*") + jvm { + classpathFromClassloader(BluePrintScripCompilationConfiguration::class.java.classLoader) + } + } +) + +open class BluePrintSourceCode : SourceCode { + lateinit var blueprintKotlinSources: MutableList<String> + lateinit var moduleName: String + lateinit var targetJarFile: File + var regenerate: Boolean = false + + override val text: String + get() = "" + + override val locationId: String? = null + + override val name: String? + get() = moduleName +} diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BlueprintScriptingHost.kt b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BlueprintScriptingHost.kt new file mode 100644 index 00000000..59ce4abb --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BlueprintScriptingHost.kt @@ -0,0 +1,92 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.onap.ccsdk.apps.controllerblueprints.scripts + +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException +import org.slf4j.LoggerFactory +import java.util.* +import kotlin.script.experimental.api.* +import kotlin.script.experimental.host.BasicScriptingHost +import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration +import kotlin.script.experimental.jvmhost.JvmScriptCompiler +import kotlin.script.experimental.jvmhost.impl.withDefaults + +val blueprintScriptCompiler = JvmScriptCompiler(defaultJvmScriptingHostConfiguration, + BluePrintsCompilerProxy(defaultJvmScriptingHostConfiguration.withDefaults())) + +open class BlueprintScriptingHost(evaluator: ScriptEvaluator) : BasicScriptingHost(blueprintScriptCompiler, evaluator) { + + override fun eval( + script: SourceCode, + scriptCompilationConfiguration: ScriptCompilationConfiguration, + configuration: ScriptEvaluationConfiguration? + ): ResultWithDiagnostics<EvaluationResult> = + + runInCoroutineContext { + + compiler(script, scriptCompilationConfiguration) + .onSuccess { + evaluator(it, configuration) + } + } +} + + +open class BluePrintScriptEvaluator<T>(private val scriptClassName: String) : ScriptEvaluator { + + private val log = LoggerFactory.getLogger(BluePrintScriptEvaluator::class.java)!! + + override suspend operator fun invoke( + compiledScript: CompiledScript<*>, + scriptEvaluationConfiguration: ScriptEvaluationConfiguration? + ): ResultWithDiagnostics<EvaluationResult> = + try { + log.info("Getting class name($scriptClassName) of type() from the compiled sources ") + val bluePrintCompiledScript = compiledScript as BluePrintCompiledScript + bluePrintCompiledScript.scriptClassFQName = scriptClassName + + val res = compiledScript.getClass(scriptEvaluationConfiguration) + when (res) { + is ResultWithDiagnostics.Failure -> res + is ResultWithDiagnostics.Success -> { + + val scriptClass = res.value + val args = ArrayList<Any?>() + scriptEvaluationConfiguration?.get(ScriptEvaluationConfiguration.providedProperties)?.forEach { + args.add(it.value) + } + scriptEvaluationConfiguration?.get(ScriptEvaluationConfiguration.implicitReceivers)?.let { + args.addAll(it) + } + scriptEvaluationConfiguration?.get(ScriptEvaluationConfiguration.constructorArgs)?.let { + args.addAll(it) + } + + val instance = scriptClass.java.newInstance() as? T + ?: throw BluePrintProcessorException("failed to create instance from the script") + + log.info("Created script instance successfully....") + + ResultWithDiagnostics.Success(EvaluationResult(ResultValue.Value(scriptClass.qualifiedName!!, + instance, "", instance), + scriptEvaluationConfiguration)) + } + } + } catch (e: Throwable) { + ResultWithDiagnostics.Failure(e.asDiagnostics("Error evaluating script")) + } +}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BlueprintScriptingHostTest.kt b/ms/controllerblueprints/modules/blueprint-scripts/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BlueprintScriptingHostTest.kt new file mode 100644 index 00000000..4b6f2a47 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BlueprintScriptingHostTest.kt @@ -0,0 +1,88 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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.onap.ccsdk.apps.controllerblueprints.scripts + + +import org.apache.commons.io.FileUtils +import org.junit.Ignore +import org.junit.Test +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BlueprintFunctionNode +import java.io.File +import kotlin.script.experimental.jvm.util.classpathFromClass +import kotlin.script.experimental.jvm.util.classpathFromClassloader +import kotlin.script.experimental.jvm.util.classpathFromClasspathProperty +import kotlin.script.experimental.jvmhost.createJvmCompilationConfigurationFromTemplate + +class BlueprintScriptingHostTest { + + @Test + @Ignore + fun `test classpaths`() { + + println(" *********** classpathFromClass *********** ") + classpathFromClass(BlueprintScriptingHostTest::class.java.classLoader, + BlueprintScriptingHostTest::class)!! + .forEach(::println) + + println(" *********** classpathFromClassloader *********** ") + classpathFromClassloader(BlueprintScriptingHostTest::class.java.classLoader)!! + .forEach(::println) + + println(" *********** classpathFromClasspathProperty *********** ") + classpathFromClasspathProperty()!! + .forEach(::println) + } + + @Test + fun `test same script two folders`() { + + FileUtils.forceMkdir(File("target/scripts1/")) + FileUtils.forceMkdir(File("target/scripts2/")) + + val scriptSource1 = BluePrintSourceCode() + scriptSource1.moduleName = "blueprint-test-script" + + scriptSource1.targetJarFile = File("target/scripts1/blueprint-script-generated.jar") + val sources1: MutableList<String> = arrayListOf() + sources1.add("src/test/resources/scripts1") + scriptSource1.blueprintKotlinSources = sources1 + + val scriptClassName = "Simple_cba\$SampleComponentFunction" + + val compilationConfiguration = createJvmCompilationConfigurationFromTemplate<BluePrintKotlinScript>() + + val scriptEvaluator = BluePrintScriptEvaluator<BlueprintFunctionNode<String, String>>(scriptClassName) + + val scriptSource2 = BluePrintSourceCode() + scriptSource2.moduleName = "blueprint-test-script" + + scriptSource2.targetJarFile = File("target/scripts2/blueprint-script-generated.jar") + val sources2: MutableList<String> = arrayListOf() + sources2.add("src/test/resources/scripts2") + scriptSource2.blueprintKotlinSources = sources2 + + for (i in 1..2) { + val evalResponse = BlueprintScriptingHost(scriptEvaluator).eval(scriptSource1, compilationConfiguration, + null) + } + + for (i in 1..2) { + val evalResponse = BlueprintScriptingHost(scriptEvaluator).eval(scriptSource2, compilationConfiguration, + null) + } + } +}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/test/resources/scripts1/simple.cba.kts b/ms/controllerblueprints/modules/blueprint-scripts/src/test/resources/scripts1/simple.cba.kts new file mode 100644 index 00000000..9f61c649 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/test/resources/scripts1/simple.cba.kts @@ -0,0 +1,55 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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. + */ + +import org.onap.ccsdk.apps.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.apps.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BlueprintFunctionNode +import org.springframework.stereotype.Service + +@Service +open class SampleComponentFunction : BlueprintFunctionNode<String, String> { + + override fun getName(): String { + println("Printing Name....." + "sample".asJsonPrimitive()) + return "my Name" + } + + override fun prepareRequest(executionRequest: String): String { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun process(executionRequest: String) { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun recover(runtimeException: RuntimeException, executionRequest: String) { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun prepareResponse(): String { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun apply(t: String): String { + return "Script 1 response - $t" + } +} + +val blueprintFunction = SampleComponentFunction() + +val serviceTemplate = ServiceTemplate() + +println("Simple script printing....") diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/test/resources/scripts2/simple.cba.kts b/ms/controllerblueprints/modules/blueprint-scripts/src/test/resources/scripts2/simple.cba.kts new file mode 100644 index 00000000..84517254 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/test/resources/scripts2/simple.cba.kts @@ -0,0 +1,55 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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. + */ + +import org.onap.ccsdk.apps.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.apps.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BlueprintFunctionNode +import org.springframework.stereotype.Service + +@Service +open class SampleComponentFunction : BlueprintFunctionNode<String, String> { + + override fun getName(): String { + println("Printing Name....." + "sample".asJsonPrimitive()) + return "my Name" + } + + override fun prepareRequest(executionRequest: String): String { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun process(executionRequest: String) { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun recover(runtimeException: RuntimeException, executionRequest: String) { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun prepareResponse(): String { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun apply(t: String): String { + return "Script 2 response - $t" + } +} + +val blueprintFunction = SampleComponentFunction() + +val serviceTemplate = ServiceTemplate() + +println("Simple script printing....") diff --git a/ms/controllerblueprints/modules/db-resources/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/db/resources/BlueprintCatalogServiceImpl.kt b/ms/controllerblueprints/modules/db-resources/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/db/resources/BlueprintCatalogServiceImpl.kt index 881e3bc4..3ba729d1 100644 --- a/ms/controllerblueprints/modules/db-resources/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/db/resources/BlueprintCatalogServiceImpl.kt +++ b/ms/controllerblueprints/modules/db-resources/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/db/resources/BlueprintCatalogServiceImpl.kt @@ -17,66 +17,66 @@ package org.onap.ccsdk.apps.controllerblueprints.db.resources -import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintValidatorService import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintArchiveUtils import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintFileUtils +import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils import java.io.File +import java.nio.file.Path +import java.util.* import javax.persistence.MappedSuperclass @MappedSuperclass -abstract class BlueprintCatalogServiceImpl(private val bluePrintLoadConfiguration: BluePrintLoadConfiguration) : BluePrintCatalogService { - - override fun uploadToDataBase(file: String, validate: Boolean): String { - // The file name provided here is unique as we transform to UUID before storing - val blueprintFile = File(file) - val fileName = blueprintFile.name - val id = BluePrintFileUtils.stripFileExtension(fileName) - // If the file is directory - if (blueprintFile.isDirectory) { - - val zipFile = File("${bluePrintLoadConfiguration.blueprintArchivePath}/$fileName") - // zip the directory - BluePrintArchiveUtils.compress(blueprintFile, zipFile, true) +abstract class BlueprintCatalogServiceImpl(private val blueprintValidator: BluePrintValidatorService) + : BluePrintCatalogService { - // Upload to the Data Base - saveToDataBase(blueprintFile, id, zipFile) + override fun saveToDatabase(blueprintFile: File, validate: Boolean): String { + val extractedDirectory: File + val archivedDirectory: File + val toDeleteDirectory: File + val blueprintId = UUID.randomUUID().toString() - // After Upload to Database delete the zip file - zipFile.delete() + if (blueprintFile.isDirectory) { + extractedDirectory = blueprintFile + archivedDirectory = File(":$blueprintFile.zip") + toDeleteDirectory = archivedDirectory + if (!BluePrintArchiveUtils.compress(blueprintFile, archivedDirectory, true)) { + throw BluePrintException("Fail to compress blueprint") + } } else { - // If the file is ZIP - // unzip the CBA file to validate before store in database - val targetDir = "${bluePrintLoadConfiguration.blueprintDeployPath}/$id/" - val extractedDirectory = BluePrintArchiveUtils.deCompress(blueprintFile, targetDir) + val targetDir = "${blueprintFile.parent}/${BluePrintFileUtils.stripFileExtension(blueprintFile.name)}" - // Upload to the Data Base - saveToDataBase(extractedDirectory, id, blueprintFile) + extractedDirectory = BluePrintArchiveUtils.deCompress(blueprintFile, targetDir) + archivedDirectory = blueprintFile + toDeleteDirectory = extractedDirectory + } - // After Upload to Database delete the zip file - blueprintFile.delete() - extractedDirectory.delete() + if (validate) { + blueprintValidator.validateBluePrints(extractedDirectory.path) } - return id - } + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(blueprintId, extractedDirectory.path) + val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! + metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] = blueprintId - override fun downloadFromDataBase(name: String, version: String, path: String): String { - // If path ends with zip, then compress otherwise download as extracted folder + save(metadata, archivedDirectory) - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. - } + toDeleteDirectory.deleteRecursively() - override fun downloadFromDataBase(uuid: String, path: String): String { - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + return blueprintId } - override fun prepareBluePrint(name: String, version: String): String { - val preparedPath = "${bluePrintLoadConfiguration.blueprintDeployPath}/$name/$version" - downloadFromDataBase(name, version, preparedPath) - return preparedPath - } + override fun getFromDatabase(name: String, version: String, extract: Boolean): Path = get(name, version, extract) + ?: throw BluePrintException("Could not find blueprint $name:$version from database") + + override fun deleteFromDatabase(name: String, version: String) = delete(name, version) + + abstract fun save(metadata: MutableMap<String, String>, archiveFile: File) + abstract fun get(name: String, version: String, extract: Boolean): Path? + abstract fun delete(name: String, version: String) - abstract fun saveToDataBase(extractedDirectory: File, id: String, archiveFile: File, checkValidity: Boolean? = false) }
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/db-resources/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/db/resources/repository/ModelContentRepository.kt b/ms/controllerblueprints/modules/db-resources/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/db/resources/repository/ModelContentRepository.kt index 4965677e..680f1b2c 100644 --- a/ms/controllerblueprints/modules/db-resources/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/db/resources/repository/ModelContentRepository.kt +++ b/ms/controllerblueprints/modules/db-resources/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/db/resources/repository/ModelContentRepository.kt @@ -43,25 +43,24 @@ interface ModelContentRepository<T, B> : JpaRepository<B, String> { * * @param blueprintModel blueprintModel * @param contentType contentType - * @return Optional<B> + * @return B? */ - fun findTopByBlueprintModelAndContentType(blueprintModel: T, - contentType: String): Optional<B> + fun findTopByBlueprintModelAndContentType(blueprintModel: T, contentType: String): B? /** * This is a findByBlueprintModelAndContentType method * * @param blueprintModel blueprintModel * @param contentType contentType - * @return Optional<BlueprintModelContent> + * @return List<B> */ fun findByBlueprintModelAndContentType(blueprintModel: T, contentType: String): List<B> /** * This is a findByBlueprintModel method * - * @param blueprintModel B - * @return Optional<T> + * @param blueprintModel T + * @return List<B> */ fun findByBlueprintModel(blueprintModel: T): List<B> @@ -71,15 +70,14 @@ interface ModelContentRepository<T, B> : JpaRepository<B, String> { * @param blueprintModel blueprintModel * @param contentType contentType * @param name name - * @return Optional<B> + * @return B? */ - fun findByBlueprintModelAndContentTypeAndName(blueprintModel: T, - contentType: String, name: String): Optional<B> + fun findByBlueprintModelAndContentTypeAndName(blueprintModel: T, contentType: String, name: String): B? /** * This is a deleteByMdeleteByBlueprintModelodelName method * - * @param blueprintModel B + * @param blueprintModel T */ fun deleteByBlueprintModel(blueprintModel: T) @@ -90,4 +88,4 @@ interface ModelContentRepository<T, B> : JpaRepository<B, String> { */ override fun deleteById(@NotNull id: String) -}
\ No newline at end of file +} diff --git a/ms/controllerblueprints/modules/db-resources/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/db/resources/repository/ModelRepository.kt b/ms/controllerblueprints/modules/db-resources/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/db/resources/repository/ModelRepository.kt index c31f009a..e796c366 100644 --- a/ms/controllerblueprints/modules/db-resources/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/db/resources/repository/ModelRepository.kt +++ b/ms/controllerblueprints/modules/db-resources/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/db/resources/repository/ModelRepository.kt @@ -18,9 +18,10 @@ package org.onap.ccsdk.apps.controllerblueprints.db.resources.repository import org.jetbrains.annotations.NotNull -import java.util.Optional import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.repository.NoRepositoryBean +import java.util.* +import javax.transaction.Transactional /** * @param <T> Model @@ -42,23 +43,23 @@ interface ModelRepository<T> : JpaRepository<T, String> { * * @param artifactName artifactName * @param artifactVersion artifactVersion - * @return Optional<T> + * @return T? */ - fun findByArtifactNameAndArtifactVersion(artifactName: String, artifactVersion: String): Optional<T> + fun findByArtifactNameAndArtifactVersion(artifactName: String, artifactVersion: String): T? /** * This is a findTopByArtifactNameOrderByArtifactIdDesc method * * @param artifactName artifactName - * @return Optional<T> + * @return T? */ - fun findTopByArtifactNameOrderByArtifactVersionDesc(artifactName: String): Optional<T> + fun findTopByArtifactNameOrderByArtifactVersionDesc(artifactName: String): T? /** * This is a findTopByArtifactName method * * @param artifactName artifactName - * @return Optional<T> + * @return List<T> */ fun findTopByArtifactName(artifactName: String): List<T> @@ -66,7 +67,7 @@ interface ModelRepository<T> : JpaRepository<T, String> { * This is a findByTagsContainingIgnoreCase method * * @param tags tags - * @return Optional<ModelType> + * @return List<T> */ fun findByTagsContainingIgnoreCase(tags: String): List<T> @@ -76,6 +77,7 @@ interface ModelRepository<T> : JpaRepository<T, String> { * @param artifactName artifactName * @param artifactVersion artifactVersion */ + @Transactional fun deleteByArtifactNameAndArtifactVersion(artifactName: String, artifactVersion: String) /** @@ -85,4 +87,4 @@ interface ModelRepository<T> : JpaRepository<T, String> { */ override fun deleteById(@NotNull id: String) -} +}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/pom.xml b/ms/controllerblueprints/modules/pom.xml index 3857ef5d..834db24e 100644 --- a/ms/controllerblueprints/modules/pom.xml +++ b/ms/controllerblueprints/modules/pom.xml @@ -30,6 +30,7 @@ <module>service</module> <module>blueprint-validation</module> <module>db-resources</module> + <module>blueprint-scripts</module> </modules> <build> diff --git a/ms/controllerblueprints/modules/service/pom.xml b/ms/controllerblueprints/modules/service/pom.xml index 9868b17b..73fe0739 100644 --- a/ms/controllerblueprints/modules/service/pom.xml +++ b/ms/controllerblueprints/modules/service/pom.xml @@ -32,10 +32,6 @@ <dependencies> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>core</artifactId> - </dependency> - <dependency> - <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> <artifactId>db-resources</artifactId> </dependency> <dependency> @@ -44,7 +40,7 @@ </dependency> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>resource-dict</artifactId> + <artifactId>blueprint-scripts</artifactId> </dependency> <dependency> <groupId>org.apache.velocity</groupId> diff --git a/ms/controllerblueprints/modules/service/src/main/java/org/onap/ccsdk/apps/controllerblueprints/service/BlueprintModelService.java b/ms/controllerblueprints/modules/service/src/main/java/org/onap/ccsdk/apps/controllerblueprints/service/BlueprintModelService.java deleted file mode 100644 index e80fa8cd..00000000 --- a/ms/controllerblueprints/modules/service/src/main/java/org/onap/ccsdk/apps/controllerblueprints/service/BlueprintModelService.java +++ /dev/null @@ -1,291 +0,0 @@ -/*
- * Copyright © 2017-2018 AT&T Intellectual Property.
- * Modifications Copyright © 2019 Bell Canada.
- *
- * 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.onap.ccsdk.apps.controllerblueprints.service;
-
-import org.jetbrains.annotations.NotNull;
-import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException;
-import org.onap.ccsdk.apps.controllerblueprints.core.common.ApplicationConstants;
-import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration;
-import org.onap.ccsdk.apps.controllerblueprints.core.data.ErrorCode;
-import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService;
-import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintFileUtils;
-import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModel;
-import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModelSearch;
-import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelContentRepository;
-import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelRepository;
-import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelSearchRepository;
-import org.onap.ccsdk.apps.controllerblueprints.service.utils.BluePrintEnhancerUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.io.ByteArrayResource;
-import org.springframework.core.io.Resource;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.http.codec.multipart.FilePart;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-import reactor.core.publisher.Mono;
-
-import java.io.IOException;
-import java.nio.file.Path;
-import java.util.List;
-import java.util.Optional;
-
-/**
- * BlueprintModelService.java Purpose: Provide Service Template Service processing BlueprintModelService
- *
- * @author Brinda Santh
- * @version 1.0
- */
-
-@Service
-public class BlueprintModelService {
-
- @Autowired
- private BluePrintLoadConfiguration bluePrintLoadConfiguration;
-
- @Autowired
- private BluePrintCatalogService bluePrintCatalogService;
-
- @Autowired
- private ControllerBlueprintModelSearchRepository blueprintModelSearchRepository;
-
- @Autowired
- private ControllerBlueprintModelRepository blueprintModelRepository;
-
- @Autowired
- private ControllerBlueprintModelContentRepository blueprintModelContentRepository;
-
- private static final String BLUEPRINT_MODEL_ID_FAILURE_MSG = "failed to get blueprint model id(%s) from repo";
- private static final String BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG = "failed to get blueprint model by name(%s)" +
- " and version(%s) from repo";
-
- /**
- * This is a saveBlueprintModel method
- *
- * @param filePart filePart
- * @return Mono<BlueprintModelSearch>
- * @throws BluePrintException BluePrintException
- */
- public Mono<BlueprintModelSearch> saveBlueprintModel(FilePart filePart) throws BluePrintException {
- try {
- Path cbaLocation = BluePrintFileUtils.Companion
- .getCbaStorageDirectory(bluePrintLoadConfiguration.blueprintArchivePath);
- return BluePrintEnhancerUtils.Companion.saveCBAFile(filePart, cbaLocation).map(fileName -> {
- String blueprintId = bluePrintCatalogService
- .uploadToDataBase(cbaLocation.resolve(fileName).toString(), false);
- return blueprintModelSearchRepository.findById(blueprintId).get();
- });
- } catch (IOException e) {
- throw new BluePrintException(ErrorCode.IO_FILE_INTERRUPT.getValue(),
- String.format("I/O Error while uploading the CBA file: %s", e.getMessage()), e);
- }
- }
-
- /**
- * This is a publishBlueprintModel method to change the status published to YES
- *
- * @param id id
- * @return BlueprintModelSearch
- * @throws BluePrintException BluePrintException
- */
- public BlueprintModelSearch publishBlueprintModel(String id) throws BluePrintException {
- BlueprintModelSearch blueprintModelSearch;
- Optional<BlueprintModelSearch> dbBlueprintModel = blueprintModelSearchRepository.findById(id);
- if (dbBlueprintModel.isPresent()) {
- blueprintModelSearch = dbBlueprintModel.get();
- } else {
- String msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id);
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), msg);
- }
- blueprintModelSearch.setPublished(ApplicationConstants.ACTIVE_Y);
- return blueprintModelSearchRepository.saveAndFlush(blueprintModelSearch);
- }
-
- /**
- * This is a searchBlueprintModels method
- *
- * @param tags tags
- * @return List<BlueprintModelSearch>
- */
- public List<BlueprintModelSearch> searchBlueprintModels(String tags) {
- return blueprintModelSearchRepository.findByTagsContainingIgnoreCase(tags);
- }
-
- /**
- * This is a getBlueprintModelSearchByNameAndVersion method
- *
- * @param name name
- * @param version version
- * @return BlueprintModelSearch
- * @throws BluePrintException BluePrintException
- */
- public BlueprintModelSearch getBlueprintModelSearchByNameAndVersion(@NotNull String name, @NotNull String version)
- throws BluePrintException {
- BlueprintModelSearch blueprintModelSearch;
- Optional<BlueprintModelSearch> dbBlueprintModel = blueprintModelSearchRepository
- .findByArtifactNameAndArtifactVersion(name, version);
- if (dbBlueprintModel.isPresent()) {
- blueprintModelSearch = dbBlueprintModel.get();
- } else {
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(),
- String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version));
- }
- return blueprintModelSearch;
- }
-
- /**
- * This is a downloadBlueprintModelFileByNameAndVersion method to download a Blueprint by Name and Version
- *
- * @param name name
- * @param version version
- * @return ResponseEntity<Resource>
- * @throws BluePrintException BluePrintException
- */
- public ResponseEntity<Resource> downloadBlueprintModelFileByNameAndVersion(@NotNull String name, @NotNull String version)
- throws BluePrintException {
- BlueprintModel blueprintModel;
- try {
- blueprintModel = getBlueprintModelByNameAndVersion(name, version);
- } catch (BluePrintException e) {
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), String.format("Error while " +
- "downloading the CBA file: %s", e.getMessage()), e);
- }
- String fileName = blueprintModel.getId() + ".zip";
- byte[] file = blueprintModel.getBlueprintModelContent().getContent();
- return prepareResourceEntity(fileName, file);
- }
-
- /**
- * This is a downloadBlueprintModelFile method to find the target file to download and return a file resource
- *
- * @return ResponseEntity<Resource>
- * @throws BluePrintException BluePrintException
- */
- public ResponseEntity<Resource> downloadBlueprintModelFile(@NotNull String id) throws BluePrintException {
- BlueprintModel blueprintModel;
- try {
- blueprintModel = getBlueprintModel(id);
- } catch (BluePrintException e) {
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), String.format("Error while " +
- "downloading the CBA file: %s", e.getMessage()), e);
- }
- String fileName = blueprintModel.getId() + ".zip";
- byte[] file = blueprintModel.getBlueprintModelContent().getContent();
- return prepareResourceEntity(fileName, file);
- }
-
- /**
- *
- * @param (fileName, file)
- * @return ResponseEntity<Resource>
- */
- private ResponseEntity<Resource> prepareResourceEntity(String fileName, byte[] file) {
- return ResponseEntity.ok()
- .contentType(MediaType.parseMediaType("text/plain"))
- .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
- .body(new ByteArrayResource(file));
- }
-
- /**
- * This is a getBlueprintModel method
- *
- * @param id id
- * @return BlueprintModel
- * @throws BluePrintException BluePrintException
- */
- private BlueprintModel getBlueprintModel(@NotNull String id) throws BluePrintException {
- BlueprintModel blueprintModel;
- Optional<BlueprintModel> dbBlueprintModel = blueprintModelRepository.findById(id);
- if (dbBlueprintModel.isPresent()) {
- blueprintModel = dbBlueprintModel.get();
- } else {
- String msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id);
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), msg);
- }
- return blueprintModel;
- }
-
- /**
- * This is a getBlueprintModelByNameAndVersion method
- *
- * @param name name
- * @param version version
- * @return BlueprintModel
- * @throws BluePrintException BluePrintException
- */
- private BlueprintModel getBlueprintModelByNameAndVersion(@NotNull String name, @NotNull String version)
- throws BluePrintException {
- BlueprintModel blueprintModel;
- Optional<BlueprintModel> dbBlueprintModel = blueprintModelRepository.findByArtifactNameAndArtifactVersion(name, version);
- if (dbBlueprintModel.isPresent()) {
- blueprintModel = dbBlueprintModel.get();
- } else {
- String msg = String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version);
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), msg);
- }
- return blueprintModel;
- }
-
- /**
- * This is a getBlueprintModelSearch method
- *
- * @param id id
- * @return BlueprintModelSearch
- * @throws BluePrintException BluePrintException
- */
- public BlueprintModelSearch getBlueprintModelSearch(@NotNull String id) throws BluePrintException {
- BlueprintModelSearch blueprintModelSearch;
- Optional<BlueprintModelSearch> dbBlueprintModel = blueprintModelSearchRepository.findById(id);
- if (dbBlueprintModel.isPresent()) {
- blueprintModelSearch = dbBlueprintModel.get();
- } else {
- String msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id);
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), msg);
- }
-
- return blueprintModelSearch;
- }
-
- /**
- * This is a deleteBlueprintModel method
- *
- * @param id id
- * @throws BluePrintException BluePrintException
- */
- @Transactional
- public void deleteBlueprintModel(@NotNull String id) throws BluePrintException {
- Optional<BlueprintModel> dbBlueprintModel = blueprintModelRepository.findById(id);
- if (dbBlueprintModel.isPresent()) {
- blueprintModelContentRepository.deleteByBlueprintModel(dbBlueprintModel.get());
- blueprintModelRepository.delete(dbBlueprintModel.get());
- } else {
- String msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id);
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), msg);
- }
- }
-
- /**
- * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database
- *
- * @return List<BlueprintModelSearch> list of the controller blueprint archives
- */
- public List<BlueprintModelSearch> getAllBlueprintModel() {
- return blueprintModelSearchRepository.findAll();
- }
-}
diff --git a/ms/controllerblueprints/modules/service/src/main/java/org/onap/ccsdk/apps/controllerblueprints/service/rs/BlueprintModelRest.java b/ms/controllerblueprints/modules/service/src/main/java/org/onap/ccsdk/apps/controllerblueprints/service/rs/BlueprintModelRest.java deleted file mode 100644 index 255137bf..00000000 --- a/ms/controllerblueprints/modules/service/src/main/java/org/onap/ccsdk/apps/controllerblueprints/service/rs/BlueprintModelRest.java +++ /dev/null @@ -1,97 +0,0 @@ -/*
- * Copyright © 2017-2018 AT&T Intellectual Property.
- * Modifications Copyright © 2019 Bell Canada.
- *
- * 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.onap.ccsdk.apps.controllerblueprints.service.rs;
-
-import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException;
-import org.onap.ccsdk.apps.controllerblueprints.service.BlueprintModelService;
-import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModelSearch;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.io.Resource;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.http.codec.multipart.FilePart;
-import org.springframework.web.bind.annotation.*;
-import reactor.core.publisher.Mono;
-
-import java.util.List;
-
-/**
- * {@inheritDoc}
- */
-@RestController
-@RequestMapping(value = "/api/v1/blueprint-model")
-public class BlueprintModelRest {
-
- @Autowired
- private BlueprintModelService blueprintModelService;
-
- @PostMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- public @ResponseBody
- Mono<BlueprintModelSearch> saveBlueprint(@RequestPart("file") FilePart file) throws BluePrintException{
- return blueprintModelService.saveBlueprintModel(file);
- }
-
- @DeleteMapping(path = "/{id}")
- public void deleteBlueprint(@PathVariable(value = "id") String id) throws BluePrintException {
- this.blueprintModelService.deleteBlueprintModel(id);
- }
-
- @GetMapping(path = "/by-name/{name}/version/{version}", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- BlueprintModelSearch getBlueprintByNameAndVersion(@PathVariable(value = "name") String name,
- @PathVariable(value = "version") String version) throws BluePrintException {
- return this.blueprintModelService.getBlueprintModelSearchByNameAndVersion(name, version);
- }
-
- @GetMapping(path = "/download/by-name/{name}/version/{version}", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- ResponseEntity<Resource> downloadBlueprintByNameAndVersion(@PathVariable(value = "name") String name,
- @PathVariable(value = "version") String version) throws BluePrintException {
- return this.blueprintModelService.downloadBlueprintModelFileByNameAndVersion(name, version);
- }
-
- @GetMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- BlueprintModelSearch getBlueprintModel(@PathVariable(value = "id") String id) throws BluePrintException {
- return this.blueprintModelService.getBlueprintModelSearch(id);
- }
-
- @GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- List<BlueprintModelSearch> getAllBlueprintModel() {
- return this.blueprintModelService.getAllBlueprintModel();
- }
-
- @GetMapping(path = "/download/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- ResponseEntity<Resource> downloadBluePrint(@PathVariable(value = "id") String id) throws BluePrintException {
- return this.blueprintModelService.downloadBlueprintModelFile(id);
- }
-
- @PutMapping(path = "/publish/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- BlueprintModelSearch publishBlueprintModel(@PathVariable(value = "id") String id) throws BluePrintException {
- return this.blueprintModelService.publishBlueprintModel(id);
- }
-
- @GetMapping(path = "/search/{tags}", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- List<BlueprintModelSearch> searchBlueprintModels(@PathVariable(value = "tags") String tags) {
- return this.blueprintModelService.searchBlueprintModels(tags);
- }
-}
diff --git a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/BlueprintModelRest.kt b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/BlueprintModelRest.kt new file mode 100644 index 00000000..0fca07b0 --- /dev/null +++ b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/BlueprintModelRest.kt @@ -0,0 +1,100 @@ +/* + * Copyright © 2019 Bell Canada Intellectual Property. + * + * 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.onap.ccsdk.apps.controllerblueprints.service.controller + +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModelSearch +import org.onap.ccsdk.apps.controllerblueprints.service.handler.BluePrintModelHandler +import org.springframework.core.io.Resource +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.http.codec.multipart.FilePart +import org.springframework.web.bind.annotation.* +import reactor.core.publisher.Mono + +/** + * BlueprintModelRest Purpose: Handle controllerBlueprint API request + * + * @author Vinal Patel + * @version 1.0 + */ +@RestController +@RequestMapping("/api/v1/blueprint-model") +open class BlueprintModelRest(private val bluePrintModelHandler: BluePrintModelHandler) { + + @PostMapping("", produces = [MediaType.APPLICATION_JSON_VALUE], consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) + @ResponseBody + @Throws(BluePrintException::class) + fun saveBlueprint(@RequestPart("file") file: FilePart): Mono<BlueprintModelSearch> { + return bluePrintModelHandler.saveBlueprintModel(file) + } + + @GetMapping("", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + fun allBlueprintModel(): List<BlueprintModelSearch> { + return this.bluePrintModelHandler.allBlueprintModel() + } + + @DeleteMapping("/{id}") + @Throws(BluePrintException::class) + fun deleteBlueprint(@PathVariable(value = "id") id: String) { + this.bluePrintModelHandler.deleteBlueprintModel(id) + } + + @GetMapping("/by-name/{name}/version/{version}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + @Throws(BluePrintException::class) + fun getBlueprintByNameAndVersion(@PathVariable(value = "name") name: String, + @PathVariable(value = "version") version: String): BlueprintModelSearch { + return this.bluePrintModelHandler.getBlueprintModelSearchByNameAndVersion(name, version) + } + + @GetMapping("/download/by-name/{name}/version/{version}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + @Throws(BluePrintException::class) + fun downloadBlueprintByNameAndVersion(@PathVariable(value = "name") name: String, + @PathVariable(value = "version") version: String): ResponseEntity<Resource> { + return this.bluePrintModelHandler.downloadBlueprintModelFileByNameAndVersion(name, version) + } + + @GetMapping("/{id}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + @Throws(BluePrintException::class) + fun getBlueprintModel(@PathVariable(value = "id") id: String): BlueprintModelSearch { + return this.bluePrintModelHandler.getBlueprintModelSearch(id) + } + + @GetMapping("/download/{id}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + @Throws(BluePrintException::class) + fun downloadBluePrint(@PathVariable(value = "id") id: String): ResponseEntity<Resource> { + return this.bluePrintModelHandler.downloadBlueprintModelFile(id) + } + + @PutMapping("/publish/{id}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + @Throws(BluePrintException::class) + fun publishBlueprintModel(@PathVariable(value = "id") id: String): BlueprintModelSearch { + return this.bluePrintModelHandler.publishBlueprintModel(id) + } + + @GetMapping("/search/{tags}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + fun searchBlueprintModels(@PathVariable(value = "tags") tags: String): List<BlueprintModelSearch> { + return this.bluePrintModelHandler.searchBlueprintModels(tags) + } +} diff --git a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/ControllerBlueprintExeptionHandler.kt b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/ControllerBlueprintExeptionHandler.kt index a0e47d72..04753391 100644 --- a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/ControllerBlueprintExeptionHandler.kt +++ b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/ControllerBlueprintExeptionHandler.kt @@ -25,7 +25,7 @@ import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.ExceptionHandler /** - * ControllerBlueprintExceptionHandler.java Purpose: Handle exceptions in controllerBlueprint API and provide the wright + * ControllerBlueprintExceptionHandler Purpose: Handle exceptions in controllerBlueprint API and provide the right * HTTP code status * * @author Vinal Patel diff --git a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/handler/BluePrintModelHandler.kt b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/handler/BluePrintModelHandler.kt new file mode 100644 index 00000000..907566c3 --- /dev/null +++ b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/handler/BluePrintModelHandler.kt @@ -0,0 +1,283 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * + * 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.onap.ccsdk.apps.controllerblueprints.service.handler + +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.apps.controllerblueprints.core.common.ApplicationConstants +import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.apps.controllerblueprints.core.data.ErrorCode +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintFileUtils +import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModel +import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModelSearch +import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelContentRepository +import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelRepository +import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelSearchRepository +import org.onap.ccsdk.apps.controllerblueprints.service.utils.BluePrintEnhancerUtils +import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource +import org.springframework.http.HttpHeaders +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.http.codec.multipart.FilePart +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import reactor.core.publisher.Mono +import java.io.IOException + +/** + * BlueprintModelHandler Purpose: Handler service to handle the request from BlurPrintModelRest + * + * @author Brinda Santh + * @version 1.0 + */ + +@Service +open class BluePrintModelHandler(private val bluePrintCatalogService: BluePrintCatalogService, private val bluePrintLoadConfiguration: BluePrintLoadConfiguration, + private val blueprintModelSearchRepository: ControllerBlueprintModelSearchRepository, + private val blueprintModelRepository: ControllerBlueprintModelRepository, + private val blueprintModelContentRepository: ControllerBlueprintModelContentRepository) { + + /** + * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database + * + * @return List<BlueprintModelSearch> list of the controller blueprint archives + </BlueprintModelSearch> */ + open fun allBlueprintModel(): List<BlueprintModelSearch> { + return blueprintModelSearchRepository.findAll() + } + + /** + * This is a saveBlueprintModel method + * + * @param filePart filePart + * @return Mono<BlueprintModelSearch> + * @throws BluePrintException BluePrintException + </BlueprintModelSearch> */ + @Throws(BluePrintException::class) + open fun saveBlueprintModel(filePart: FilePart): Mono<BlueprintModelSearch> { + try { + val cbaLocation = BluePrintFileUtils.getCbaStorageDirectory(bluePrintLoadConfiguration.blueprintArchivePath) + return BluePrintEnhancerUtils.saveCBAFile(filePart, cbaLocation).map { fileName -> + var blueprintId: String? = null + try { + blueprintId = bluePrintCatalogService.saveToDatabase(cbaLocation.resolve(fileName).toFile(), false) + } catch (e: BluePrintException) { + // FIXME handle expection + } + blueprintModelSearchRepository.findById(blueprintId!!).get() + } + } catch (e: IOException) { + throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value, + String.format("I/O Error while uploading the CBA file: %s", e.message), e) + } + + } + + /** + * This is a publishBlueprintModel method to change the status published to YES + * + * @param id id + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun publishBlueprintModel(id: String): BlueprintModelSearch { + val blueprintModelSearch: BlueprintModelSearch + val dbBlueprintModel = blueprintModelSearchRepository.findById(id) + if (dbBlueprintModel.isPresent) { + blueprintModelSearch = dbBlueprintModel.get() + } else { + val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg) + } + blueprintModelSearch.published = ApplicationConstants.ACTIVE_Y + return blueprintModelSearchRepository.saveAndFlush(blueprintModelSearch) + } + + /** + * This is a searchBlueprintModels method + * + * @param tags tags + * @return List<BlueprintModelSearch> + </BlueprintModelSearch> */ + open fun searchBlueprintModels(tags: String): List<BlueprintModelSearch> { + return blueprintModelSearchRepository.findByTagsContainingIgnoreCase(tags) + } + + /** + * This is a getBlueprintModelSearchByNameAndVersion method + * + * @param name name + * @param version version + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModelSearchByNameAndVersion(name: String, version: String): BlueprintModelSearch { + val blueprintModelSearch: BlueprintModelSearch + val dbBlueprintModel = blueprintModelSearchRepository + .findByArtifactNameAndArtifactVersion(name, version) + if (dbBlueprintModel.isPresent) { + blueprintModelSearch = dbBlueprintModel.get() + } else { + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, + String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version)) + } + return blueprintModelSearch + } + + /** + * This is a downloadBlueprintModelFileByNameAndVersion method to download a Blueprint by Name and Version + * + * @param name name + * @param version version + * @return ResponseEntity<Resource> + * @throws BluePrintException BluePrintException + </Resource> */ + @Throws(BluePrintException::class) + open fun downloadBlueprintModelFileByNameAndVersion(name: String, + version: String): ResponseEntity<Resource> { + val blueprintModel: BlueprintModel + try { + blueprintModel = getBlueprintModelByNameAndVersion(name, version) + } catch (e: BluePrintException) { + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, String.format("Error while " + "downloading the CBA file: %s", e.message), e) + } + + val fileName = blueprintModel.id + ".zip" + val file = blueprintModel.blueprintModelContent.content + return prepareResourceEntity(fileName, file) + } + + /** + * This is a downloadBlueprintModelFile method to find the target file to download and return a file resource + * + * @return ResponseEntity<Resource> + * @throws BluePrintException BluePrintException + </Resource> */ + @Throws(BluePrintException::class) + open fun downloadBlueprintModelFile(id: String): ResponseEntity<Resource> { + val blueprintModel: BlueprintModel + try { + blueprintModel = getBlueprintModel(id) + } catch (e: BluePrintException) { + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, String.format("Error while " + "downloading the CBA file: %s", e.message), e) + } + + val fileName = blueprintModel.id + ".zip" + val file = blueprintModel.blueprintModelContent.content + return prepareResourceEntity(fileName, file) + } + + /** + * @return ResponseEntity<Resource> + </Resource> */ + private fun prepareResourceEntity(fileName: String, file: ByteArray): ResponseEntity<Resource> { + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType("text/plain")) + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"") + .body(ByteArrayResource(file)) + } + + /** + * This is a getBlueprintModel method + * + * @param id id + * @return BlueprintModel + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModel(id: String): BlueprintModel { + val blueprintModel: BlueprintModel + val dbBlueprintModel = blueprintModelRepository.findById(id) + if (dbBlueprintModel.isPresent) { + blueprintModel = dbBlueprintModel.get() + } else { + val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg) + } + return blueprintModel + } + + /** + * This is a getBlueprintModelByNameAndVersion method + * + * @param name name + * @param version version + * @return BlueprintModel + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModelByNameAndVersion(name: String, version: String): BlueprintModel { + val blueprintModel = blueprintModelRepository + .findByArtifactNameAndArtifactVersion(name, version) + if (blueprintModel != null) { + return blueprintModel + } else { + val msg = String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version) + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg) + } + } + + /** + * This is a getBlueprintModelSearch method + * + * @param id id + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModelSearch(id: String): BlueprintModelSearch { + val blueprintModelSearch: BlueprintModelSearch + val dbBlueprintModel = blueprintModelSearchRepository.findById(id) + if (dbBlueprintModel.isPresent) { + blueprintModelSearch = dbBlueprintModel.get() + } else { + val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg) + } + + return blueprintModelSearch + } + + /** + * This is a deleteBlueprintModel method + * + * @param id id + * @throws BluePrintException BluePrintException + */ + @Transactional + @Throws(BluePrintException::class) + open fun deleteBlueprintModel(id: String) { + val dbBlueprintModel = blueprintModelRepository.findById(id) + if (dbBlueprintModel.isPresent) { + blueprintModelContentRepository.deleteByBlueprintModel(dbBlueprintModel.get()) + blueprintModelRepository.delete(dbBlueprintModel.get()) + } else { + val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg) + } + } + + companion object { + + private const val BLUEPRINT_MODEL_ID_FAILURE_MSG = "failed to get blueprint model id(%s) from repo" + private const val BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG = "failed to get blueprint model by name(%s)" + " and version(%s) from repo" + } +} diff --git a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/load/BluePrintCatalogLoadService.kt b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/load/BluePrintCatalogLoadService.kt index d49bcdff..4fd66ed5 100644 --- a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/load/BluePrintCatalogLoadService.kt +++ b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/load/BluePrintCatalogLoadService.kt @@ -59,7 +59,7 @@ open class BluePrintCatalogLoadService(private val bluePrintCatalogService: Blue open fun loadBluePrintModelCatalog(errorBuilder: StrBuilder, file: File) { try { - bluePrintCatalogService.uploadToDataBase(file.absolutePath, true) + bluePrintCatalogService.saveToDatabase(file) } catch (e: Exception) { errorBuilder.appendln("Couldn't load DataType(${file.name}: ${e.message}") } diff --git a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/load/ControllerBlueprintCatalogServiceImpl.kt b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/load/ControllerBlueprintCatalogServiceImpl.kt index 6b367c4d..779be65d 100755 --- a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/load/ControllerBlueprintCatalogServiceImpl.kt +++ b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/load/ControllerBlueprintCatalogServiceImpl.kt @@ -18,74 +18,93 @@ package org.onap.ccsdk.apps.controllerblueprints.service.load import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException import org.onap.ccsdk.apps.controllerblueprints.core.common.ApplicationConstants import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException import org.onap.ccsdk.apps.controllerblueprints.core.data.ErrorCode import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintValidatorService -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintArchiveUtils -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.apps.controllerblueprints.db.resources.BlueprintCatalogServiceImpl import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModel import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModelContent import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelRepository +import org.slf4j.LoggerFactory import org.springframework.dao.DataIntegrityViolationException import org.springframework.stereotype.Service import java.io.File import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths /** -Similar implementation in [org.onap.ccsdk.apps.blueprintsprocessor.db.BlueprintProcessorCatalogServiceImpl] + * Similar implementation in [org.onap.ccsdk.apps.blueprintsprocessor.db.BlueprintProcessorCatalogServiceImpl] */ @Service -class ControllerBlueprintCatalogServiceImpl(bluePrintLoadConfiguration: BluePrintLoadConfiguration, - private val bluePrintValidatorService: BluePrintValidatorService, +class ControllerBlueprintCatalogServiceImpl(bluePrintValidatorService: BluePrintValidatorService, + private val bluePrintLoadConfiguration: BluePrintLoadConfiguration, private val blueprintModelRepository: ControllerBlueprintModelRepository) - : BlueprintCatalogServiceImpl(bluePrintLoadConfiguration) { + : BlueprintCatalogServiceImpl(bluePrintValidatorService) { - override fun saveToDataBase(extractedDirectory: File, id: String, archiveFile: File, checkValidity: Boolean?) { - var valid = false - val firstItem = BluePrintArchiveUtils.getFirstItemInDirectory(extractedDirectory) - val blueprintBaseDirectory = extractedDirectory.absolutePath + "/" + firstItem - // Validate Blueprint - val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(id, blueprintBaseDirectory) - // Check Validity of blueprint - if (checkValidity!!) { - valid = bluePrintValidatorService.validateBluePrints(bluePrintRuntimeService) - } + private val log = LoggerFactory.getLogger(ControllerBlueprintCatalogServiceImpl::class.toString()) - if ((valid && checkValidity!!) || (!valid && !checkValidity!!)) { - val metaData = bluePrintRuntimeService.bluePrintContext().metadata!! - val blueprintModel = BlueprintModel() - blueprintModel.id = id - blueprintModel.artifactType = ApplicationConstants.ASDC_ARTIFACT_TYPE_SDNC_MODEL - blueprintModel.published = ApplicationConstants.ACTIVE_N - blueprintModel.artifactName = metaData[BluePrintConstants.METADATA_TEMPLATE_NAME] - blueprintModel.artifactVersion = metaData[BluePrintConstants.METADATA_TEMPLATE_VERSION] - blueprintModel.updatedBy = metaData[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] - blueprintModel.tags = metaData[BluePrintConstants.METADATA_TEMPLATE_TAGS] - blueprintModel.artifactDescription = "Controller Blueprint for ${blueprintModel.artifactName}:${blueprintModel.artifactVersion}" + init { + log.info("BlueprintProcessorCatalogServiceImpl initialized") + } - val blueprintModelContent = BlueprintModelContent() - blueprintModelContent.id = id // For quick access both id's are same.always have one to one mapping. - blueprintModelContent.contentType = "CBA_ZIP" - blueprintModelContent.name = "${blueprintModel.artifactName}:${blueprintModel.artifactVersion}" - blueprintModelContent.description = "(${blueprintModel.artifactName}:${blueprintModel.artifactVersion} CBA Zip Content" - blueprintModelContent.content = Files.readAllBytes(archiveFile.toPath()) + override fun delete(name: String, version: String) = blueprintModelRepository.deleteByArtifactNameAndArtifactVersion(name, version) - // Set the Blueprint Model into blueprintModelContent - blueprintModelContent.blueprintModel = blueprintModel + override fun get(name: String, version: String, extract: Boolean): Path? { + val path = if (extract) { + Paths.get("${bluePrintLoadConfiguration.blueprintDeployPath}/$name/$version") + } else { + Paths.get("${bluePrintLoadConfiguration.blueprintArchivePath}/$name/$version.zip") + } + blueprintModelRepository.findByArtifactNameAndArtifactVersion(name, version)?.also { + it.blueprintModelContent.run { + path.toFile().writeBytes(this!!.content!!).let { + return path + } + } + } + return null + } + + override fun save(metadata: MutableMap<String, String>, archiveFile: File) { - // Set the Blueprint Model Content into blueprintModel - blueprintModel.blueprintModelContent = blueprintModelContent + val artifactName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] + val artifactVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] - try { - blueprintModelRepository.saveAndFlush(blueprintModel) - } catch (ex: DataIntegrityViolationException) { - throw BluePrintException(ErrorCode.CONFLICT_ADDING_RESOURCE.value, "The blueprint entry " + - "is already exist in database: ${ex.message}", ex) + log.isDebugEnabled.apply { + blueprintModelRepository.findByArtifactNameAndArtifactVersion(artifactName!!, artifactVersion!!)?.let { + log.debug("Overwriting blueprint model :$artifactName::$artifactVersion") } } + + val blueprintModel = BlueprintModel() + blueprintModel.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] + blueprintModel.artifactType = ApplicationConstants.ASDC_ARTIFACT_TYPE_SDNC_MODEL + blueprintModel.published = ApplicationConstants.ACTIVE_N + blueprintModel.artifactName = artifactName + blueprintModel.artifactVersion = artifactVersion + blueprintModel.updatedBy = metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] + blueprintModel.tags = metadata[BluePrintConstants.METADATA_TEMPLATE_TAGS] + blueprintModel.artifactDescription = "Controller Blueprint for $artifactName:$artifactVersion" + + val blueprintModelContent = BlueprintModelContent() + blueprintModelContent.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] + blueprintModelContent.contentType = "CBA_ZIP" + blueprintModelContent.name = "$artifactName:$artifactVersion" + blueprintModelContent.description = "$artifactName:$artifactVersion CBA Zip Content" + blueprintModelContent.content = Files.readAllBytes(archiveFile.toPath()) + blueprintModelContent.blueprintModel = blueprintModel + // Set the Blueprint Model Content into blueprintModel + blueprintModel.blueprintModelContent = blueprintModelContent + + try { + blueprintModelRepository.saveAndFlush(blueprintModel) + } catch (ex: DataIntegrityViolationException) { + throw BluePrintException(ErrorCode.CONFLICT_ADDING_RESOURCE.value, "The blueprint entry " + + "is already exist in database: ${ex.message}", ex) + } } }
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/service/src/test/java/org/onap/ccsdk/apps/controllerblueprints/service/BlueprintModelServiceTest.java b/ms/controllerblueprints/modules/service/src/test/java/org/onap/ccsdk/apps/controllerblueprints/service/BlueprintModelServiceTest.java deleted file mode 100644 index 0ce93b18..00000000 --- a/ms/controllerblueprints/modules/service/src/test/java/org/onap/ccsdk/apps/controllerblueprints/service/BlueprintModelServiceTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright © 2018 IBM. - * - * 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.onap.ccsdk.apps.controllerblueprints.service; - -import org.junit.Test; -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException; -import org.springframework.beans.factory.annotation.Autowired; - -public class BlueprintModelServiceTest { - @Autowired - private BlueprintModelService blueprintModelService; - - @Test - public void testGetInitialConfigModel() throws BluePrintException { - } -} diff --git a/ms/controllerblueprints/modules/service/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/BlueprintModelRestTest.kt b/ms/controllerblueprints/modules/service/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/BlueprintModelRestTest.kt new file mode 100644 index 00000000..f82aace4 --- /dev/null +++ b/ms/controllerblueprints/modules/service/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/BlueprintModelRestTest.kt @@ -0,0 +1,192 @@ +/* + * Copyright © 2019 Bell Canada Intellectual Property. + * + * 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.onap.ccsdk.apps.controllerblueprints.service.controller + +import com.google.gson.Gson +import org.json.JSONException +import org.json.JSONObject +import org.junit.After +import org.junit.Before +import org.junit.FixMethodOrder +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.MethodSorters +import org.onap.ccsdk.apps.controllerblueprints.TestApplication +import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintArchiveUtils +import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModelSearch +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.beans.factory.annotation.Value +import org.springframework.boot.autoconfigure.EnableAutoConfiguration +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.context.annotation.ComponentScan +import org.springframework.core.io.ByteArrayResource +import org.springframework.http.HttpMethod +import org.springframework.http.HttpStatus +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.junit4.SpringRunner +import org.springframework.test.web.reactive.server.WebTestClient +import org.springframework.util.Base64Utils +import org.springframework.web.reactive.function.BodyInserters +import java.io.File +import java.io.IOException +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.Files +import java.nio.file.Paths + +/** + * BlueprintModelRestTest Purpose: Integration test at API level + * + * @author Vinal Patel + * @version 1.0 + */ + +@RunWith(SpringRunner::class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ContextConfiguration(classes = [TestApplication::class]) +@ComponentScan(basePackages = ["org.onap.ccsdk.apps.controllerblueprints"]) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@EnableAutoConfiguration +class BlueprintModelRestTest { + + companion object { + + private var id: String? = null + private var name: String? = null + private var version: String? = null + private var tag: String? = null + private var result: String? = null + } + + @Value("\${controllerblueprints.loadBluePrintPaths}") + private val loadBluePrintPaths: String? = null + + @Autowired + private val webTestClient: WebTestClient? = null + + @Value("\${controllerblueprints.loadBlueprintsExamplesPath}") + private val blueprintArchivePath: String? = null + + private val filename = "test.zip" + private var blueprintFile: File? = null + private var zipBlueprintFile: File? = null + + @Before + @Throws(Exception::class) + fun setUp() { + blueprintFile = File(loadBluePrintPaths+"/baseconfiguration") + if (blueprintFile!!.isDirectory) { + zipBlueprintFile = File(Paths.get(blueprintArchivePath).resolve(filename).toString()) + BluePrintArchiveUtils.compress(blueprintFile!!, zipBlueprintFile!!, true) + } + } + + @After + @Throws(Exception::class) + fun tearDown() { + zipBlueprintFile!!.delete() + } + + @Test + @Throws(IOException::class, JSONException::class) + fun test1_saveBluePrint() { + webTestClient(HttpMethod.POST, + BodyInserters.fromMultipartData("file", object : ByteArrayResource(Files.readAllBytes(zipBlueprintFile!!.toPath())) { + override fun getFilename(): String? { + return "test.zip" + } + }), + "/api/v1/blueprint-model", + HttpStatus.OK, true) + } + + @Test + @Throws(JSONException::class) + fun test2_getBluePrintByNameAndVersion() { + webTestClient(HttpMethod.GET, null, "/api/v1/blueprint-model/by-name/$name/version/$version", HttpStatus.OK, false) + } + + + @Test + @Throws(JSONException::class) + fun test3_getBlueprintModel() { + webTestClient(HttpMethod.GET, null, "/api/v1/blueprint-model/$id", HttpStatus.OK, false) + } + + @Test + @Throws(JSONException::class) + fun test4_getAllBlueprintModel() { + webTestClient(HttpMethod.GET, null, "/api/v1/blueprint-model", HttpStatus.OK, false) + } + + @Test + @Throws(JSONException::class) + fun test5_downloadBluePrint() { + webTestClient(HttpMethod.GET, null, "/api/v1/blueprint-model/download/$id", HttpStatus.OK, false) + } + + @Test + fun test6_publishBlueprintModel() { + } + + @Test + @Throws(JSONException::class) + fun test7_searchBlueprintModels() { + webTestClient(HttpMethod.GET, null, "/api/v1/blueprint-model/search/$name", HttpStatus.OK, false) + } + + @Test + @Throws(JSONException::class) + fun test8_downloadBlueprintByNameAndVersion() { + webTestClient(HttpMethod.GET, null, "/api/v1/blueprint-model/download/by-name/$name/version/$version", HttpStatus.OK, false) + } + + @Test + fun test9_deleteBluePrint() { + //TODO: Use webTestClient function + //webTestClient(HttpMethod.DELETE, null, "/api/v1/blueprint-model/" + id, HttpStatus.OK, false); + webTestClient!!.delete().uri("/api/v1/blueprint-model/$id") + .header("Authorization", "Basic " + Base64Utils + .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8))) + .exchange() + .expectStatus().is2xxSuccessful + } + + @Throws(JSONException::class) + private fun webTestClient(requestMethod: HttpMethod, body: BodyInserters.MultipartInserter?, uri: String, expectedResponceStatus: HttpStatus, setParam: Boolean) { + + result = String(webTestClient!!.method(requestMethod).uri(uri) + .header("Authorization", "Basic " + Base64Utils + .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8))) + .body(body) + .exchange() + .expectStatus().isEqualTo(expectedResponceStatus) + .expectBody() + .returnResult().responseBody!!) + + if (setParam) { + val jsonResponse = JSONObject(result) + val blueprintModelSearchJSON = jsonResponse.getJSONObject("blueprintModel") + val gson = Gson() + val blueprintModelSearch = gson.fromJson(blueprintModelSearchJSON.toString(), BlueprintModelSearch::class.java) + id = blueprintModelSearch.id + name = blueprintModelSearch.artifactName + version = blueprintModelSearch.artifactVersion + tag = blueprintModelSearch.tags + } + } + +}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/service/src/test/resources/application.properties b/ms/controllerblueprints/modules/service/src/test/resources/application.properties index 24cb23a1..1c2c1c08 100755 --- a/ms/controllerblueprints/modules/service/src/test/resources/application.properties +++ b/ms/controllerblueprints/modules/service/src/test/resources/application.properties @@ -20,7 +20,7 @@ logging.level.org.springframework.web=INFO logging.level.org.hibernate.SQL=warn logging.level.org.hibernate.type.descriptor.sql=debug # Load Resource Source Mappings -resourceSourceMappings=primary-db=source-primary-db,input=source-input,default=source-default,mdsal=source-rest,capability=source-capability +resourceSourceMappings=primary-db=source-primary-db,input=source-input,default=source-default,primary-config-data=source-rest,capability=source-capability # Controller Blueprints Core Configuration controllerblueprints.blueprintDeployPath=./target/blueprints/deploy controllerblueprints.blueprintArchivePath=./target/blueprints/archive diff --git a/ms/controllerblueprints/modules/service/src/test/resources/enhance/enhance-resource-assignment.json b/ms/controllerblueprints/modules/service/src/test/resources/enhance/enhance-resource-assignment.json index 1c81b74d..3ed188b9 100644 --- a/ms/controllerblueprints/modules/service/src/test/resources/enhance/enhance-resource-assignment.json +++ b/ms/controllerblueprints/modules/service/src/test/resources/enhance/enhance-resource-assignment.json @@ -56,7 +56,7 @@ "required": true
},
"dictionary-name": "sample-mdsal-source",
- "dictionary-source": "mdsal",
+ "dictionary-source": "primary-config-data",
"dependencies": []
}
]
diff --git a/ms/controllerblueprints/modules/service/src/test/resources/enhance/enhance-template.json b/ms/controllerblueprints/modules/service/src/test/resources/enhance/enhance-template.json index 42978f84..2e48b6d8 100644 --- a/ms/controllerblueprints/modules/service/src/test/resources/enhance/enhance-template.json +++ b/ms/controllerblueprints/modules/service/src/test/resources/enhance/enhance-template.json @@ -243,7 +243,7 @@ },
"input-param": false,
"dictionary-name": "sample-mdsal-source",
- "dictionary-source": "mdsal",
+ "dictionary-source": "primary-config-data",
"dependencies": [
"service-instance-id"
],
@@ -314,7 +314,7 @@ },
"input-param": false,
"dictionary-name": "sample-licenses",
- "dictionary-source": "mdsal",
+ "dictionary-source": "primary-config-data",
"dependencies": [
"service-instance-id"
],
diff --git a/ms/controllerblueprints/modules/service/src/test/resources/enhance/enhanced-template.json b/ms/controllerblueprints/modules/service/src/test/resources/enhance/enhanced-template.json index 66f18f89..6937c719 100644 --- a/ms/controllerblueprints/modules/service/src/test/resources/enhance/enhanced-template.json +++ b/ms/controllerblueprints/modules/service/src/test/resources/enhance/enhanced-template.json @@ -242,7 +242,7 @@ }, "input-param" : false, "dictionary-name" : "sample-mdsal-source", - "dictionary-source" : "mdsal", + "dictionary-source" : "primary-config-data", "dependencies" : [ "service-instance-id" ], "version" : 0 }, { @@ -304,7 +304,7 @@ }, "input-param" : false, "dictionary-name" : "sample-licenses", - "dictionary-source" : "mdsal", + "dictionary-source" : "primary-config-data", "dependencies" : [ "service-instance-id" ], "version" : 0 }, { diff --git a/ms/controllerblueprints/parent/pom.xml b/ms/controllerblueprints/parent/pom.xml index 9042318d..8cbc98e0 100644 --- a/ms/controllerblueprints/parent/pom.xml +++ b/ms/controllerblueprints/parent/pom.xml @@ -28,12 +28,12 @@ <name>Controller Blueprints Parent</name> <packaging>pom</packaging> <properties> - <spring.boot.version>2.1.1.RELEASE</spring.boot.version> - <spring.version>5.1.3.RELEASE</spring.version> - <kotlin.version>1.3.11</kotlin.version> - <kotlin.maven.version>1.3.11</kotlin.maven.version> - <kotlin.couroutines.version>1.1.0</kotlin.couroutines.version> - <grpc.version>1.17.1</grpc.version> + <spring.boot.version>2.1.2.RELEASE</spring.boot.version> + <spring.version>5.1.4.RELEASE</spring.version> + <kotlin.version>1.3.20</kotlin.version> + <kotlin.maven.version>1.3.20</kotlin.maven.version> + <kotlin.couroutines.version>1.1.1</kotlin.couroutines.version> + <grpc.version>1.18.0</grpc.version> <protobuff.java.utils.version>3.6.1</protobuff.java.utils.version> <eelf.version>1.0.0</eelf.version> <guava.version>27.0.1-jre</guava.version> @@ -110,14 +110,26 @@ </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-stdlib-common</artifactId> + <version>${kotlin.version}</version> + </dependency> + <!--Use kotlin-compiler-embeddable instead koltin-compiler wrap--> + <!--guava dependency inside kotlin-compiler creating classpath issues at runtime--> + <dependency> + <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-scripting-jvm-host</artifactId> <version>${kotlin.version}</version> + <exclusions> + <exclusion> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-compile</artifactId> + </exclusion> + </exclusions> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-compiler-embeddable</artifactId> <version>${kotlin.version}</version> - <scope>runtime</scope> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> @@ -198,27 +210,32 @@ </dependency> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>service</artifactId> + <artifactId>resource-dict</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>application</artifactId> + <artifactId>db-resources</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>resource-dict</artifactId> + <artifactId>blueprint-validation</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>db-resources</artifactId> + <artifactId>blueprint-scripts</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>blueprint-validation</artifactId> + <artifactId>service</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <artifactId>application</artifactId> <version>${project.version}</version> </dependency> @@ -270,6 +287,10 @@ <artifactId>json-path</artifactId> </dependency> <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + </dependency> + <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> </dependency> diff --git a/ms/vlantag-api/pom.xml b/ms/vlantag-api/pom.xml index f5da9a6b..ea461056 100644 --- a/ms/vlantag-api/pom.xml +++ b/ms/vlantag-api/pom.xml @@ -1,110 +1,110 @@ <?xml version="1.0" encoding="UTF-8"?> <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> + <modelVersion>4.0.0</modelVersion> - <groupId>org.onap.ccsdk.apps.ms.vlantagapi</groupId> - <artifactId>vlantag-api</artifactId> - <version>0.4.1-SNAPSHOT</version> - <packaging>jar</packaging> + <groupId>org.onap.ccsdk.apps.ms.vlantagapi</groupId> + <artifactId>vlantag-api</artifactId> + <version>0.4.1-SNAPSHOT</version> + <packaging>jar</packaging> - <name>Vlantag API</name> - <description>Vlantag Api Service for Vlantag management of VNFs</description> + <name>Vlantag API</name> + <description>Vlantag Api Service for Vlantag management of VNFs</description> - <properties> - <swagger.directory>${basedir}/target/main/resources/META-INF/resources/swagger-ui/dist</swagger.directory> - <swagger.annotations.version>1.5.8</swagger.annotations.version> - <java.version>1.8</java.version> - <springboot.version>2.0.4.RELEASE</springboot.version> - <mariadb.connector.version>2.1.1</mariadb.connector.version> - <docker.registry>TBD:5100</docker.registry> - <serviceArtifactName>vlantagapi</serviceArtifactName> + <properties> + <swagger.directory>${basedir}/target/main/resources/META-INF/resources/swagger-ui/dist</swagger.directory> + <swagger.annotations.version>1.5.8</swagger.annotations.version> + <java.version>1.8</java.version> + <springboot.version>2.0.4.RELEASE</springboot.version> + <mariadb.connector.version>2.1.1</mariadb.connector.version> + <docker.registry>TBD:5100</docker.registry> + <serviceArtifactName>vlantagapi</serviceArtifactName> - <!-- Sonar --> - <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin> - <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis> - <sonar.surefire.reportsPath>${basedir}/target/surefire-reports</sonar.surefire.reportsPath> - <sonar.failsafe.reportsPath>${basedir}/target/failsafe-reports</sonar.failsafe.reportsPath> - <jacoco.path>${basedir}/target/jacoco_report</jacoco.path> - <jacoco.itPath>${basedir}/target/jacoco_itReport</jacoco.itPath> - <sonar.jacoco.reportPath>${basedir}/target/jacoco-ut.exec</sonar.jacoco.reportPath> - <sonar.jacoco.itReportPath>${basedir}/target/jacoco-it.exec</sonar.jacoco.itReportPath> - <sonar.language>java</sonar.language> - <ilib.version>2.0.7</ilib.version> - <docker.buildArg.https_proxy>${https_proxy}</docker.buildArg.https_proxy> - <docker.push.phase>deploy</docker.push.phase> - <docker.verbose>true</docker.verbose> - <ccsdk.project.version>${project.version}</ccsdk.project.version> - </properties> + <!-- Sonar --> + <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin> + <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis> + <sonar.surefire.reportsPath>${basedir}/target/surefire-reports</sonar.surefire.reportsPath> + <sonar.failsafe.reportsPath>${basedir}/target/failsafe-reports</sonar.failsafe.reportsPath> + <jacoco.path>${basedir}/target/jacoco_report</jacoco.path> + <jacoco.itPath>${basedir}/target/jacoco_itReport</jacoco.itPath> + <sonar.jacoco.reportPath>${basedir}/target/jacoco-ut.exec</sonar.jacoco.reportPath> + <sonar.jacoco.itReportPath>${basedir}/target/jacoco-it.exec</sonar.jacoco.itReportPath> + <sonar.language>java</sonar.language> + <ilib.version>2.0.7</ilib.version> + <docker.buildArg.https_proxy>${https_proxy}</docker.buildArg.https_proxy> + <docker.push.phase>deploy</docker.push.phase> + <docker.verbose>true</docker.verbose> + <ccsdk.project.version>${project.version}</ccsdk.project.version> + </properties> - <parent> - <groupId>org.onap.ccsdk.parent</groupId> - <artifactId>spring-boot-starter-parent</artifactId> - <version>1.2.1-SNAPSHOT</version> - <relativePath/> - </parent> + <parent> + <groupId>org.onap.ccsdk.parent</groupId> + <artifactId>spring-boot-starter-parent</artifactId> + <version>1.2.1-SNAPSHOT</version> + <relativePath/> + </parent> - <dependencies> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-jersey</artifactId> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-web</artifactId> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-test</artifactId> - <scope>test</scope> - </dependency> + <dependencies> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-jersey</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-web</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-test</artifactId> + <scope>test</scope> + </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-actuator</artifactId> - </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-actuator</artifactId> + </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-security</artifactId> - <version>2.0.1.RELEASE</version> - </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-security</artifactId> + <version>2.0.1.RELEASE</version> + </dependency> - <dependency> - <groupId>org.onap.ccsdk.sli.core</groupId> - <artifactId>sli-common</artifactId> - <version>${ccsdk.sli.core.version}</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.onap.ccsdk.sli.adaptors</groupId> - <artifactId>resource-assignment-provider</artifactId> - <version>${ccsdk.sli.adaptors.version}</version> - <exclusions> - <exclusion> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-simple</artifactId> - </exclusion> - </exclusions> - </dependency> + <dependency> + <groupId>org.onap.ccsdk.sli.core</groupId> + <artifactId>sli-common</artifactId> + <version>${ccsdk.sli.core.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.ccsdk.sli.adaptors</groupId> + <artifactId>resource-assignment-provider</artifactId> + <version>${ccsdk.sli.adaptors.version}</version> + <exclusions> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-simple</artifactId> + </exclusion> + </exclusions> + </dependency> - <dependency> - <groupId>org.mariadb.jdbc</groupId> - <artifactId>mariadb-java-client</artifactId> - <version>${mariadb.connector.version}</version> - </dependency> + <dependency> + <groupId>org.mariadb.jdbc</groupId> + <artifactId>mariadb-java-client</artifactId> + <version>${mariadb.connector.version}</version> + </dependency> - <dependency> - <groupId>io.swagger</groupId> - <artifactId>swagger-annotations</artifactId> - <version>1.5.8</version> - </dependency> - </dependencies> + <dependency> + <groupId>io.swagger</groupId> + <artifactId>swagger-annotations</artifactId> + <version>1.5.8</version> + </dependency> + </dependencies> - <build> - <plugins> + <build> + <plugins> <plugin> <groupId>org.codehaus.groovy.maven</groupId> <artifactId>gmaven-plugin</artifactId> @@ -136,7 +136,7 @@ </execution> </executions> </plugin> - <plugin> + <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> @@ -147,154 +147,154 @@ </excludes> </configuration> </plugin> - <plugin> - <groupId>org.jacoco</groupId> - <artifactId>jacoco-maven-plugin</artifactId> - <version>0.7.5.201505241946</version> - <executions> - <!-- Prepares the property pointing to the JaCoCo runtime agent which - is passed as VM argument when Maven the Surefire plugin is executed. --> - <execution> - <id>pre-unit-test</id> - <goals> - <goal>prepare-agent</goal> - </goals> - <configuration> - <!-- Sets the path to the file which contains the execution data. --> - <destFile>${sonar.jacoco.reportPath}</destFile> - <propertyName>surefireArgLine</propertyName> - </configuration> - </execution> - <!-- Ensures that the code coverage report for unit tests is created - after unit tests have been run. --> - <execution> - <id>post-unit-test</id> - <phase>test</phase> - <goals> - <goal>report</goal> - </goals> - <configuration> - <!-- Sets the path to the file which contains the execution data. --> - <dataFile>${sonar.jacoco.reportPath}</dataFile> - <!-- Sets the output directory for the code coverage report. --> - <outputDirectory>${jacoco.path}</outputDirectory> - </configuration> - </execution> - </executions> - </plugin> - <plugin> - <groupId>com.github.kongchen</groupId> - <artifactId>swagger-maven-plugin</artifactId> - <version>3.1.7</version> - <configuration> - <apiSources> - <apiSource> - <schemes> - <scheme>http</scheme> - <scheme>https</scheme> - </schemes> - <host>localhost:9091</host> - <locations> - <location>org.onap.ccsdk.apps.ms.vlantagapi.core.service</location> - <location>org.onap.ccsdk.apps.ms.vlantagapi.core.model</location> - </locations> - <!-- <locations>org.onap.ccsdk.apps.ms.vlantagapi.core.service</locations> --> - <basePath>/vlantagapi</basePath> - <info> - <title>${project.artifactId} Service</title> - <version>${project.version}</version> - </info> - <securityDefinitions> - <securityDefinition> - <name>basicAuth</name> - <type>basic</type> - </securityDefinition> - </securityDefinitions> - <swaggerDirectory>${swagger.directory}</swaggerDirectory> - </apiSource> - </apiSources> - </configuration> - <executions> - <execution> - <!-- <phase>compile</phase> --> - <phase>package</phase> - <goals> - <goal>generate</goal> - </goals> - </execution> - </executions> - </plugin> - <plugin> - <groupId>com.spotify</groupId> - <artifactId>docker-maven-plugin</artifactId> - <version>0.4.11</version> - <configuration> - <imageName>${docker.registry}/org.onap.ccsdk.apps/${serviceArtifactName}</imageName> - <dockerDirectory>src/main/docker</dockerDirectory> - <serverId>docker-hub</serverId> - <registryUrl>https://${docker.registry}</registryUrl> - <imageTags> - <imageTag>${project.version}</imageTag> - <imageTag>latest</imageTag> - </imageTags> - <forceTags>true</forceTags> - <resources> - <resource> - <targetPath>/</targetPath> - <directory>${project.build.directory}</directory> - <include>${project.build.finalName}.jar</include> - </resource> - </resources> - </configuration> - </plugin> - <plugin> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-maven-plugin</artifactId> - <version>${springboot.version}</version> - <executions> - <execution> - <goals> - <goal>repackage</goal> - </goals> - </execution> - </executions> - </plugin> - </plugins> - </build> + <plugin> + <groupId>org.jacoco</groupId> + <artifactId>jacoco-maven-plugin</artifactId> + <version>0.7.5.201505241946</version> + <executions> + <!-- Prepares the property pointing to the JaCoCo runtime agent which + is passed as VM argument when Maven the Surefire plugin is executed. --> + <execution> + <id>pre-unit-test</id> + <goals> + <goal>prepare-agent</goal> + </goals> + <configuration> + <!-- Sets the path to the file which contains the execution data. --> + <destFile>${sonar.jacoco.reportPath}</destFile> + <propertyName>surefireArgLine</propertyName> + </configuration> + </execution> + <!-- Ensures that the code coverage report for unit tests is created + after unit tests have been run. --> + <execution> + <id>post-unit-test</id> + <phase>test</phase> + <goals> + <goal>report</goal> + </goals> + <configuration> + <!-- Sets the path to the file which contains the execution data. --> + <dataFile>${sonar.jacoco.reportPath}</dataFile> + <!-- Sets the output directory for the code coverage report. --> + <outputDirectory>${jacoco.path}</outputDirectory> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>com.github.kongchen</groupId> + <artifactId>swagger-maven-plugin</artifactId> + <version>3.1.7</version> + <configuration> + <apiSources> + <apiSource> + <schemes> + <scheme>http</scheme> + <scheme>https</scheme> + </schemes> + <host>localhost:9091</host> + <locations> + <location>org.onap.ccsdk.apps.ms.vlantagapi.core.service</location> + <location>org.onap.ccsdk.apps.ms.vlantagapi.core.model</location> + </locations> + <!-- <locations>org.onap.ccsdk.apps.ms.vlantagapi.core.service</locations> --> + <basePath>/vlantagapi</basePath> + <info> + <title>${project.artifactId} Service</title> + <version>${project.version}</version> + </info> + <securityDefinitions> + <securityDefinition> + <name>basicAuth</name> + <type>basic</type> + </securityDefinition> + </securityDefinitions> + <swaggerDirectory>${swagger.directory}</swaggerDirectory> + </apiSource> + </apiSources> + </configuration> + <executions> + <execution> + <!-- <phase>compile</phase> --> + <phase>package</phase> + <goals> + <goal>generate</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <groupId>com.spotify</groupId> + <artifactId>docker-maven-plugin</artifactId> + <version>0.4.11</version> + <configuration> + <imageName>${docker.registry}/org.onap.ccsdk.apps/${serviceArtifactName}</imageName> + <dockerDirectory>src/main/docker</dockerDirectory> + <serverId>docker-hub</serverId> + <registryUrl>https://${docker.registry}</registryUrl> + <imageTags> + <imageTag>${project.version}</imageTag> + <imageTag>latest</imageTag> + </imageTags> + <forceTags>true</forceTags> + <resources> + <resource> + <targetPath>/</targetPath> + <directory>${project.build.directory}</directory> + <include>${project.build.finalName}.jar</include> + </resource> + </resources> + </configuration> + </plugin> + <plugin> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-maven-plugin</artifactId> + <version>${springboot.version}</version> + <executions> + <execution> + <goals> + <goal>repackage</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> - <profiles> - <profile> - <id>docker</id> - <build> - <plugins> - <plugin> - <groupId>com.spotify</groupId> - <artifactId>docker-maven-plugin</artifactId> - <version>0.4.11</version> - <configuration> - <imageName>${docker.registry}/org.onap.ccsdk.apps/${serviceArtifactName}</imageName> - <dockerDirectory>src/main/docker</dockerDirectory> - <serverId>docker-hub</serverId> - <registryUrl>https://${docker.registry}</registryUrl> - <imageTags> - <imageTag>${project.version}</imageTag> - <imageTag>${project.version}-STAGING-${maven.build.timestamp}</imageTag> - <imageTag>${project.docker.latesttag.version}</imageTag> - </imageTags> - <forceTags>true</forceTags> - <resources> - <resource> - <targetPath>/</targetPath> - <directory>${project.build.directory}</directory> - <include>${project.build.finalName}.jar</include> - </resource> - </resources> - </configuration> - </plugin> - </plugins> - </build> - </profile> - </profiles> + <profiles> + <profile> + <id>docker</id> + <build> + <plugins> + <plugin> + <groupId>com.spotify</groupId> + <artifactId>docker-maven-plugin</artifactId> + <version>0.4.11</version> + <configuration> + <imageName>${docker.registry}/org.onap.ccsdk.apps/${serviceArtifactName}</imageName> + <dockerDirectory>src/main/docker</dockerDirectory> + <serverId>docker-hub</serverId> + <registryUrl>https://${docker.registry}</registryUrl> + <imageTags> + <imageTag>${project.version}</imageTag> + <imageTag>${project.version}-STAGING-${maven.build.timestamp}</imageTag> + <imageTag>${project.docker.latesttag.version}</imageTag> + </imageTags> + <forceTags>true</forceTags> + <resources> + <resource> + <targetPath>/</targetPath> + <directory>${project.build.directory}</directory> + <include>${project.build.finalName}.jar</include> + </resource> + </resources> + </configuration> + </plugin> + </plugins> + </build> + </profile> + </profiles> </project> |