import { Component, OnInit, ViewChild, EventEmitter, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
+import { Store } from '@ngrx/store';
import { SearchTemplateService } from '../search-template.service';
import { MatAutocompleteTrigger } from '@angular/material';
import { NotificationHandlerService } from 'src/app/common/core/services/notification-handler.service';
import { SearchPipe } from 'src/app/common/shared/pipes/search.pipe';
+import * as JSZip from 'jszip';
+import { SortPipe } from '../../../../../common/shared/pipes/sort.pipe';
+import { LoaderService } from '../../../../../common/core/services/loader.service';
+import { IBlueprint } from '../../../../../common/core/store/models/blueprint.model';
+import { IBlueprintState } from '../../../../../common/core/store/models/blueprintState.model';
+import { IAppState } from '../../../../../common/core/store/state/app.state';
+import { SetBlueprintState } from '../../../../../common/core/store/actions/blueprint.action';
@Component({
selector: 'app-search-from-database',
myControl: FormGroup;
@Output() resourcesData = new EventEmitter();
options: any[] = [];
- @ViewChild('resourceSelect', { read: MatAutocompleteTrigger }) resourceSelect: MatAutocompleteTrigger;
+ // @ViewChild('resourceSelect', { read: MatAutocompleteTrigger }) resourceSelect: MatAutocompleteTrigger;
+
+ validfile: boolean = false;
+ filesTree: any = [];
+ filesData: any = [];
+ private zipFile: JSZip = new JSZip();
+ private paths = [];
+ private tree;
+ private fileObject: any;
+ private activationBlueprint: any;
+ private tocsaMetadaData: any;
+ private blueprintName: string;
+ private entryDefinition: string;
+ uploadedFileName: string;
searchText: string = '';
constructor(private _formBuilder: FormBuilder,
- private searchService: SearchTemplateService, private alertService: NotificationHandlerService, ) { }
+ private searchService: SearchTemplateService, private alertService: NotificationHandlerService,
+ private loader: LoaderService, private store: Store<IAppState>) { }
ngOnInit() {
this.myControl = this._formBuilder.group({
})
}
- editCBA(artifactname: string,option : string) {
-
+ editCBA(artifactName: string,artifactVersion:string, option: string) {
+ this.zipFile.generateAsync({ type: "blob" })
+ .then(blob => {
+ const formData = new FormData();
+ formData.append("file", blob);
+ // this.editorService.enrich("/enrich-blueprint/", formData)
+ this.searchService.getBlueprintZip(artifactName + "/" + artifactVersion)
+ .subscribe(
+ (response) => {
+ // console.log(response);
+ this.zipFile.files = {};
+ this.zipFile.loadAsync(response)
+ .then((zip) => {
+ if (zip) {
+ this.buildFileViewData(zip);
+ // console.log("processed");
+ let data: IBlueprint = this.activationBlueprint ? JSON.parse(this.activationBlueprint.toString()) : this.activationBlueprint;
+ let blueprintState = {
+ blueprint: data,
+ name: this.blueprintName,
+ files: this.tree,
+ filesData: this.paths,
+ uploadedFileName: this.blueprintName,
+ entryDefinition: this.entryDefinition
+ }
+ this.store.dispatch(new SetBlueprintState(blueprintState));
+ // console.log(blueprintState);
+ }
+ });
+ // this.alertService.success('Blueprint enriched successfully');
+ },
+ (error) => {
+ this.alertService.error('Blue print error' + error.message);
+ });
+ });
+ }
+
+ create() {
+ this.filesData.forEach((path) => {
+ let index = path.name.indexOf("/");
+ let name = path.name.slice(index + 1, path.name.length);
+ this.zipFile.file(name, path.data);
+ });
+ }
+
+ async buildFileViewData(zip) {
+ this.validfile = false;
+ this.paths = [];
+ // console.log(zip.files);
+ for (var file in zip.files) {
+ console.log("name: " + zip.files[file].name);
+ this.fileObject = {
+ // nameForUIDisplay: this.uploadedFileName + '/' + zip.files[file].name,
+ // name: zip.files[file].name,
+ name: this.uploadedFileName + '/' + zip.files[file].name,
+ data: ''
+ };
+ const value = <any>await zip.files[file].async('string');
+ this.fileObject.data = value;
+ this.paths.push(this.fileObject);
+ }
+
+ if (this.paths) {
+ this.paths.forEach(path => {
+ if (path.name.includes("TOSCA.meta")) {
+ this.validfile = true
+ }
+ });
+ } else {
+ alert('Please update proper file');
+ }
+
+ if (this.validfile) {
+ this.fetchTOSACAMetadata();
+ this.paths = new SortPipe().transform(this.paths, 'asc', 'name');
+ this.tree = this.arrangeTreeData(this.paths);
+ } else {
+ alert('Please update proper file with TOSCA metadata');
+ }
}
+ arrangeTreeData(paths) {
+ const tree = [];
+ paths.forEach((path) => {
+ const pathParts = path.name.split('/');
+ // pathParts.shift();
+ let currentLevel = tree;
+
+ pathParts.forEach((part) => {
+ const existingPath = currentLevel.filter(level => level.name === part);
+
+ if (existingPath.length > 0) {
+ currentLevel = existingPath[0].children;
+ } else {
+ const newPart = {
+ name: part,
+ children: [],
+ data: path.data,
+ path: path.name
+ };
+ if (part.trim() == this.blueprintName.trim()) {
+ this.activationBlueprint = path.data;
+ newPart.data = JSON.parse(this.activationBlueprint.toString());
+ // console.log('newpart', newPart);
+ this.entryDefinition = path.name.trim();
+ }
+ if (newPart.name !== '') {
+ currentLevel.push(newPart);
+ currentLevel = newPart.children;
+ }
+ }
+ });
+ });
+ this.loader.hideLoader();
+ return tree;
+ }
+
+ fetchTOSACAMetadata() {
+ let toscaData = {};
+ this.paths.forEach(file => {
+ if (file.name.includes('TOSCA.meta')) {
+ let keys = file.data.split("\n");
+ keys.forEach((key) => {
+ let propertyData = key.split(':');
+ toscaData[propertyData[0]] = propertyData[1];
+ });
+ }
+ });
+ this.blueprintName = (((toscaData['Entry-Definitions']).split('/'))[1]).toString();;
+ // console.log(toscaData);
+ }
}
CSAR-Version: 1.0
Created-By: Rodrigo Ottero
Entry-Definitions: Definitions/echo-test.json
-Template-Tags: activation-blueprint
+Template-Name: echo-test
+Template-Version: 1.0.0
+Template-Tags: echo-test
CSAR-Version: 1.0
Created-By: Rodrigo Ottero
Entry-Definitions: Definitions/activation-blueprint.json
+Template-Name: activation-blueprint
+Template-Version: 1.0.0
Template-Tags: activation-blueprint
Rest Source Code:
=================
-{
- "description": "This is Rest Resource Source Node Type",
- "version": "1.0.0",
- "properties": {
- "type": {
- "required": false,
- "type": "string",
- "default": "JSON",
- "constraints": [
- {
- "valid_values": [
- "JSON"
- ]
- }
- ]
- },
- "verb": {
- "required": false,
- "type": "string",
- "default": "GET",
- "constraints": [
- {
- "valid_values": [
- "GET", "POST", "DELETE", "PUT"
- ]
- }
- ]
- },
- "payload": {
- "required": false,
- "type": "string",
- "default": ""
- },
- "endpoint-selector": {
- "required": false,
- "type": "string"
- },
- "url-path": {
- "required": true,
- "type": "string"
- },
- "path": {
- "required": true,
- "type": "string"
- },
- "expression-type": {
- "required": false,
- "type": "string",
- "default": "JSON_PATH",
- "constraints": [
- {
- "valid_values": [
- "JSON_PATH",
- "JSON_POINTER"
- ]
- }
- ]
- },
- "input-key-mapping": {
- "required": false,
- "type": "map",
- "entry_schema": {
- "type": "string"
- }
- },
- "output-key-mapping": {
- "required": false,
- "type": "map",
- "entry_schema": {
- "type": "string"
- }
- },
- "key-dependencies": {
- "required": true,
- "type": "list",
- "entry_schema": {
- "type": "string"
- }
- }
- },
- "derived_from": "tosca.nodes.ResourceSource"
-}
-
+.. code-block:: json
+ :linenos:
+
+ "description": "This is Rest Resource Source Node Type",
+ "version": "1.0.0",
+ "properties": {
+ "type": {
+ "required": false,
+ "type": "string",
+ "default": "JSON",
+ "constraints": [
+ {
+ "valid_values": [
+ "JSON"
+ ]
+ }
+ ]
+ },
+ "verb": {
+ "required": false,
+ "type": "string",
+ "default": "GET",
+ "constraints": [
+ {
+ "valid_values": [
+ "GET", "POST", "DELETE", "PUT"
+ ]
+ }
+ ]
+ },
+ "payload": {
+ "required": false,
+ "type": "string",
+ "default": ""
+ },
+ "endpoint-selector": {
+ "required": false,
+ "type": "string"
+ },
+ "url-path": {
+ "required": true,
+ "type": "string"
+ },
+ "path": {
+ "required": true,
+ "type": "string"
+ },
+ "expression-type": {
+ "required": false,
+ "type": "string",
+ "default": "JSON_PATH",
+ "constraints": [
+ {
+ "valid_values": [
+ "JSON_PATH",
+ "JSON_POINTER"
+ ]
+ }
+ ]
+ },
+ "input-key-mapping": {
+ "required": false,
+ "type": "map",
+ "entry_schema": {
+ "type": "string"
+ }
+ },
+ "output-key-mapping": {
+ "required": false,
+ "type": "map",
+ "entry_schema": {
+ "type": "string"
+ }
+ },
+ "key-dependencies": {
+ "required": true,
+ "type": "list",
+ "entry_schema": {
+ "type": "string"
+ }
+ }
+ },
+ "derived_from": "tosca.nodes.ResourceSource"
\ No newline at end of file
Source Capability Code
======================
-{
- "description": "This is Component Resource Source Node Type",
- "version": "1.0.0",
- "properties": {
- "script-type": {
- "required": true,
- "type": "string",
- "default": "kotlin",
- "constraints": [
- {
- "valid_values": [
- "kotlin",
- "jython"
- ]
- }
- ]
- },
- "script-class-reference": {
- "description": "Capability reference name for internal and kotlin, for jython script file path",
- "required": true,
- "type": "string"
- },
- "instance-dependencies": {
- "required": false,
- "description": "Instance dependency Names to Inject to Kotlin / Jython Script.",
- "type": "list",
- "entry_schema": {
- "type": "string"
- }
- },
- "key-dependencies": {
- "description": "Resource Resolution dependency dictionary names.",
- "required": true,
- "type": "list",
- "entry_schema": {
- "type": "string"
- }
- }
- },
- "derived_from": "tosca.nodes.ResourceSource"
-}
+.. code-block:: json
+ :linenos:
+
+ "description": "This is Component Resource Source Node Type",
+ "version": "1.0.0",
+ "properties": {
+ "script-type": {
+ "required": true,
+ "type": "string",
+ "default": "kotlin",
+ "constraints": [
+ {
+ "valid_values": [
+ "kotlin",
+ "jython"
+ ]
+ }
+ ]
+ },
+ "script-class-reference": {
+ "description": "Capability reference name for internal and kotlin, for jython script file path",
+ "required": true,
+ "type": "string"
+ },
+ "key-dependencies": {
+ "description": "Resource Resolution dependency dictionary names.",
+ "required": true,
+ "type": "list",
+ "entry_schema": {
+ "type": "string"
+ }
+ }
+ },
+ "derived_from": "tosca.nodes.ResourceSource"
+
Source Default code
===================
-{
- "description": "This is Default Resource Source Node Type",
- "version": "1.0.0",
- "properties": {},
- "derived_from": "tosca.nodes.ResourceSource"
-}
\ No newline at end of file
+.. code-block:: json
+ :linenos:
+
+ "description": "This is Default Resource Source Node Type",
+ "version": "1.0.0",
+ "properties": {},
+ "derived_from": "tosca.nodes.ResourceSource"
Source Input code
=================
-{
- "description": "This is Input Resource Source Node Type",
- "version": "1.0.0",
- "properties": {},
- "derived_from": "tosca.nodes.ResourceSource"
-}
\ No newline at end of file
+.. code-block:: json
+ :linenos:
+
+ "description": "This is Input Resource Source Node Type",
+ "version": "1.0.0",
+ "properties": {},
+ "derived_from": "tosca.nodes.ResourceSource"
Source Primary DB Code:
=======================
-{
- "description": "This is Database Resource Source Node Type",
- "version": "1.0.0",
- "properties": {
- "type": {
- "required": true,
- "type": "string",
- "constraints": [
- {
- "valid_values": [
- "SQL"
- ]
- }
- ]
- },
- "endpoint-selector": {
- "required": false,
- "type": "string"
- },
- "query": {
- "required": true,
- "type": "string"
- },
- "input-key-mapping": {
- "required": false,
- "type": "map",
- "entry_schema": {
- "type": "string"
- }
- },
- "output-key-mapping": {
- "required": false,
- "type": "map",
- "entry_schema": {
- "type": "string"
- }
- },
- "key-dependencies": {
- "required": true,
- "type": "list",
- "entry_schema": {
- "type": "string"
- }
- }
- },
- "derived_from": "tosca.nodes.ResourceSource"
-}
\ No newline at end of file
+.. code-block:: json
+ :linenos:
+
+ "description": "This is Database Resource Source Node Type",
+ "version": "1.0.0",
+ "properties": {
+ "type": {
+ "required": true,
+ "type": "string",
+ "constraints": [
+ {
+ "valid_values": [
+ "SQL"
+ ]
+ }
+ ]
+ },
+ "endpoint-selector": {
+ "required": false,
+ "type": "string"
+ },
+ "query": {
+ "required": true,
+ "type": "string"
+ },
+ "input-key-mapping": {
+ "required": false,
+ "type": "map",
+ "entry_schema": {
+ "type": "string"
+ }
+ },
+ "output-key-mapping": {
+ "required": false,
+ "type": "map",
+ "entry_schema": {
+ "type": "string"
+ }
+ },
+ "key-dependencies": {
+ "required": true,
+ "type": "list",
+ "entry_schema": {
+ "type": "string"
+ }
+ }
+ },
+ "derived_from": "tosca.nodes.ResourceSource"
\ No newline at end of file
Services:
-=============
+=========
.. toctree::
:maxdepth: 1
|image1|
-
Modeling Concept
----------------
CBA/index
datadictionary/index
-
-
-
Scripts
-------
~~~~~~~
* NetconfClient
-~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~
In order to facilitate NETCONF interaction within scripts, a python NetconfClient binded to our Kotlin implementation is made available. This NetconfClient can be used when using the component-netconf-executor.
The client can be find here: https://github.com/onap/ccsdk-cds/blob/master/components/scripts/python/ccsdk_netconf/netconfclient.py
* ResolutionHelper
-~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~
When executing a component executor script, designer might want to perform
resource resolution along with template meshing directly from the script
itself.
-The helper can be find here: https://github.com/onap/ccsdk-apps/blob/master/components/scripts/python/ccsdk_netconf/common.py
+The helper can be found in below link:
+https://github.com/onap/ccsdk-apps/blob/master/components/scripts/python/ccsdk_netconf/common.py
.. |image0| image:: media/tosca_model.jpg
:width: 7.88889in
Build CDS locally:
In the checked out directory, type
- mvn clean install -DskipTests=true -Dmaven.test.skip=true -Dmaven.javadoc.skip=true -Dadditionalparam=-Xdoclint:none
+.. code-block:: none
+
+ mvn clean install -DskipTests=true -Dmaven.test.skip=true -Dmaven.javadoc.skip=true -Dadditionalparam=-Xdoclint:none
Create the needed Docker images:
The first step is to create any custom image needed, by building the distribution module. From the CDS home directory (where the code was checked out), navigate to the module:
- cd ms/blueprintsprocessor/distribution/
+.. code-block:: none
+
+ cd ms/blueprintsprocessor/distribution/
+
Build it using the Maven profile called Docker:
- mvn clean install -Pdocker
+.. code-block:: none
+
+ mvn clean install -Pdocker
Start Docker containers using docker-composer:
----------------------------------------------
Navigate to the docker-compose file in the distribution module:
- cd src/main/dc/
+.. code-block:: none
+
+ cd src/main/dc/
From there, start the containers:
- docker-compose up -d
+.. code-block:: none
+
+ docker-compose up -d
+
This will spin the Docker containers declared inside the docker-compose.yaml file in the background.
To verify the logs generated by docker-composer, type:
- docker-compose logs -f
+.. code-block:: none
+
+ docker-compose logs -f
Testing the environment:
|image0|
-.. |image0| image:: media/dynamicapi.jpg
+.. |image0| image:: media/dyanmicapi.jpg
:height: 4.43750in
:width: 7.88889in
\ No newline at end of file
The following shows 2 ways to run CBA enrichment
REST API request:
-----------------
+-----------------
|image0|
CDS UI:
-------
+-------
+
|image1|
+++ /dev/null
-/*
- * 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.cds.controllerblueprints.service;
-
-import com.google.common.base.Preconditions;
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException;
-import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition;
-import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment;
-import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition;
-import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryUtils;
-import org.onap.ccsdk.cds.controllerblueprints.service.domain.ResourceDictionary;
-import org.onap.ccsdk.cds.controllerblueprints.service.model.AutoMapResponse;
-import org.onap.ccsdk.cds.controllerblueprints.service.repository.ResourceDictionaryRepository;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * AutoResourceMappingService.java Purpose: Provide Automapping of Resource Assignments AutoResourceMappingService
- *
- * @author Brinda Santh
- * @version 1.0
- */
-
-@Service
-@SuppressWarnings("unused")
-public class AutoResourceMappingService {
-
- private static Logger log = LoggerFactory.getLogger(AutoResourceMappingService.class);
-
- private ResourceDictionaryRepository dataDictionaryRepository;
-
- /**
- * This is a AutoResourceMappingService constructor
- *
- * @param dataDictionaryRepository dataDictionaryRepository
- */
- public AutoResourceMappingService(ResourceDictionaryRepository dataDictionaryRepository) {
- this.dataDictionaryRepository = dataDictionaryRepository;
- }
-
- /**
- * This is a autoMap service to map the template keys automatically to Dictionary fields.
- *
- * @param resourceAssignments resourceAssignments
- * @return AutoMapResponse
- */
- public AutoMapResponse autoMap(List<ResourceAssignment> resourceAssignments) throws BluePrintException {
- AutoMapResponse autoMapResponse = new AutoMapResponse();
- try {
- if (CollectionUtils.isNotEmpty(resourceAssignments)) {
-
- // Create the Dictionary definitions for the ResourceAssignment Names
- Map<String, ResourceDictionary> dictionaryMap = getDictionaryDefinitions(resourceAssignments);
-
- for (ResourceAssignment resourceAssignment : resourceAssignments) {
- if (resourceAssignment != null && StringUtils.isNotBlank(resourceAssignment.getName())
- && StringUtils.isBlank(resourceAssignment.getDictionaryName())) {
-
- populateDictionaryMapping(dictionaryMap, resourceAssignment);
-
- log.info("Mapped Resource : {}", resourceAssignment);
-
- }
- }
- }
- List<ResourceDictionary> dictionaries = getDictionaryDefinitionsList(resourceAssignments);
- List<ResourceAssignment> resourceAssignmentsFinal = getAllAutomapResourceAssignments(resourceAssignments);
- autoMapResponse.setDataDictionaries(dictionaries);
- autoMapResponse.setResourceAssignments(resourceAssignmentsFinal);
- } catch (Exception e) {
- log.error(String.format("Failed in auto process %s", e.getMessage()));
- throw new BluePrintException(e.getMessage(), e);
- }
- return autoMapResponse;
- }
-
- private void populateDictionaryMapping(Map<String, ResourceDictionary> dictionaryMap, ResourceAssignment resourceAssignment) {
- ResourceDictionary dbDataDictionary = dictionaryMap.get(resourceAssignment.getName());
- if (dbDataDictionary != null && dbDataDictionary.getDefinition() != null) {
-
- ResourceDefinition dictionaryDefinition = dbDataDictionary.getDefinition();
-
- if (dictionaryDefinition != null && StringUtils.isNotBlank(dictionaryDefinition.getName())
- && StringUtils.isBlank(resourceAssignment.getDictionaryName())) {
-
- resourceAssignment.setDictionaryName(dbDataDictionary.getName());
- ResourceDictionaryUtils.populateSourceMapping(resourceAssignment, dictionaryDefinition);
- }
- }
- }
-
- private Map<String, ResourceDictionary> getDictionaryDefinitions(List<ResourceAssignment> resourceAssignments) {
- Map<String, ResourceDictionary> dictionaryMap = new HashMap<>();
- List<String> names = new ArrayList<>();
- for (ResourceAssignment resourceAssignment : resourceAssignments) {
- if (resourceAssignment != null && StringUtils.isNotBlank(resourceAssignment.getName())) {
- names.add(resourceAssignment.getName());
- }
- }
- if (CollectionUtils.isNotEmpty(names)) {
-
- List<ResourceDictionary> dictionaries = dataDictionaryRepository.findByNameIn(names);
- if (CollectionUtils.isNotEmpty(dictionaries)) {
- for (ResourceDictionary dataDictionary : dictionaries) {
- if (dataDictionary != null && StringUtils.isNotBlank(dataDictionary.getName())) {
- dictionaryMap.put(dataDictionary.getName(), dataDictionary);
- }
- }
- }
- }
- return dictionaryMap;
-
- }
-
- private List<ResourceDictionary> getDictionaryDefinitionsList(List<ResourceAssignment> resourceAssignments) {
- List<ResourceDictionary> dictionaries = null;
- List<String> names = new ArrayList<>();
- for (ResourceAssignment resourceAssignment : resourceAssignments) {
- if (resourceAssignment != null && StringUtils.isNotBlank(resourceAssignment.getDictionaryName())) {
-
- if (!names.contains(resourceAssignment.getDictionaryName())) {
- names.add(resourceAssignment.getDictionaryName());
- }
-
- if (resourceAssignment.getDependencies() != null && !resourceAssignment.getDependencies().isEmpty()) {
- List<String> dependencyNames = resourceAssignment.getDependencies();
- for (String dependencyName : dependencyNames) {
- if (StringUtils.isNotBlank(dependencyName) && !names.contains(dependencyName)) {
- names.add(dependencyName);
- }
- }
- }
- }
- }
- if (CollectionUtils.isNotEmpty(names)) {
- dictionaries = dataDictionaryRepository.findByNameIn(names);
- }
- return dictionaries;
-
- }
-
- private List<ResourceAssignment> getAllAutomapResourceAssignments(List<ResourceAssignment> resourceAssignments) {
- List<ResourceDictionary> dictionaries = null;
- List<String> names = new ArrayList<>();
- for (ResourceAssignment resourceAssignment : resourceAssignments) {
- if (resourceAssignment != null && StringUtils.isNotBlank(resourceAssignment.getDictionaryName())) {
- if (resourceAssignment.getDependencies() != null && !resourceAssignment.getDependencies().isEmpty()) {
- List<String> dependencieNames = resourceAssignment.getDependencies();
- for (String dependencieName : dependencieNames) {
- if (StringUtils.isNotBlank(dependencieName) && !names.contains(dependencieName)
- && !checkAssignmentsExists(resourceAssignments, dependencieName)) {
- names.add(dependencieName);
- }
- }
- }
- }
- }
-
- if (!names.isEmpty()) {
- dictionaries = dataDictionaryRepository.findByNameIn(names);
- }
- if (dictionaries != null) {
- for (ResourceDictionary resourcedictionary : dictionaries) {
- ResourceDefinition dictionaryDefinition = resourcedictionary.getDefinition();
- Preconditions.checkNotNull(dictionaryDefinition, "failed to get Resource Definition from dictionary definition");
- PropertyDefinition property = new PropertyDefinition();
- property.setRequired(true);
- ResourceAssignment resourceAssignment = new ResourceAssignment();
- resourceAssignment.setName(resourcedictionary.getName());
- resourceAssignment.setDictionaryName(resourcedictionary
- .getName());
- resourceAssignment.setVersion(0);
- resourceAssignment.setProperty(property);
- ResourceDictionaryUtils.populateSourceMapping(resourceAssignment, dictionaryDefinition);
- resourceAssignments.add(resourceAssignment);
- }
- }
- return resourceAssignments;
-
- }
-
-
- private boolean checkAssignmentsExists(List<ResourceAssignment> resourceAssignmentsWithDepencies, String resourceName) {
- return resourceAssignmentsWithDepencies.stream().anyMatch(names -> names.getName().equalsIgnoreCase(resourceName));
- }
-
-}
--- /dev/null
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2019 Huawei.
+ *
+ * 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.cds.controllerblueprints.service
+
+import com.google.common.base.Preconditions
+import org.apache.commons.collections.CollectionUtils
+import org.apache.commons.lang3.StringUtils
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryUtils
+import org.onap.ccsdk.cds.controllerblueprints.service.domain.ResourceDictionary
+import org.onap.ccsdk.cds.controllerblueprints.service.model.AutoMapResponse
+import org.onap.ccsdk.cds.controllerblueprints.service.repository.ResourceDictionaryRepository
+import org.slf4j.LoggerFactory
+import org.springframework.stereotype.Service
+import java.util.*
+
+@Service
+open class AutoResourceMappingService(private val dataDictionaryRepository: ResourceDictionaryRepository) {
+
+ private val log = LoggerFactory.getLogger(AutoResourceMappingService::class.java)
+
+ @Throws(BluePrintException::class)
+ fun autoMap(resourceAssignments: MutableList<ResourceAssignment>):
+ AutoMapResponse {
+ val autoMapResponse = AutoMapResponse()
+ try {
+ if (CollectionUtils.isNotEmpty(resourceAssignments)) {
+ // Create the Dictionary definitions for the ResourceAssignment Names
+ val dictionaryMap = getDictionaryDefinitions(resourceAssignments)
+
+ for (resourceAssignment in resourceAssignments) {
+ if (StringUtils.isNotBlank(resourceAssignment.name)
+ && StringUtils.isBlank(resourceAssignment.dictionaryName)) {
+ populateDictionaryMapping(dictionaryMap, resourceAssignment)
+ log.info("Mapped Resource : {}", resourceAssignment)
+ }
+ }
+ }
+ val dictionaries = getDictionaryDefinitionsList(resourceAssignments)
+ val resourceAssignmentsFinal = getAllAutoMapResourceAssignments(resourceAssignments)
+ autoMapResponse.dataDictionaries = dictionaries
+ autoMapResponse.resourceAssignments = resourceAssignmentsFinal
+ } catch (e: Exception) {
+ log.error(String.format("Failed in auto process %s", e.message))
+ throw BluePrintException(e, e.message!!)
+ }
+
+ return autoMapResponse
+ }
+
+ private fun populateDictionaryMapping(dictionaryMap: Map<String, ResourceDictionary>, resourceAssignment: ResourceAssignment) {
+ val dbDataDictionary = dictionaryMap[resourceAssignment.name]
+ if (dbDataDictionary != null && dbDataDictionary.definition != null) {
+
+ val dictionaryDefinition = dbDataDictionary.definition
+
+ if (dictionaryDefinition != null && StringUtils.isNotBlank(dictionaryDefinition.name)
+ && StringUtils.isBlank(resourceAssignment.dictionaryName)) {
+
+ resourceAssignment.dictionaryName = dbDataDictionary.name
+ ResourceDictionaryUtils.populateSourceMapping(resourceAssignment, dictionaryDefinition)
+ }
+ }
+ }
+
+ private fun getDictionaryDefinitions(resourceAssignments: List<ResourceAssignment>): Map<String, ResourceDictionary> {
+ val dictionaryMap = HashMap<String, ResourceDictionary>()
+ val names = ArrayList<String>()
+ for (resourceAssignment in resourceAssignments) {
+ if (StringUtils.isNotBlank(resourceAssignment.name)) {
+ names.add(resourceAssignment.name)
+ }
+ }
+ if (CollectionUtils.isNotEmpty(names)) {
+
+ val dictionaries = dataDictionaryRepository.findByNameIn(names)
+ if (CollectionUtils.isNotEmpty(dictionaries)) {
+ for (dataDictionary in dictionaries) {
+ if (StringUtils.isNotBlank(dataDictionary.name)) {
+ dictionaryMap[dataDictionary.name] = dataDictionary
+ }
+ }
+ }
+ }
+ return dictionaryMap
+
+ }
+ private fun getDictionaryDefinitionsList(resourceAssignments: List<ResourceAssignment>): List<ResourceDictionary>? {
+ var dictionaries: List<ResourceDictionary>? = null
+ val names = ArrayList<String>()
+ for (resourceAssignment in resourceAssignments) {
+ if (StringUtils.isNotBlank(resourceAssignment.dictionaryName)) {
+
+ if (!names.contains(resourceAssignment.dictionaryName)) {
+ names.add(resourceAssignment.dictionaryName!!)
+ }
+
+ if (resourceAssignment.dependencies != null && !resourceAssignment.dependencies!!.isEmpty()) {
+ val dependencyNames = resourceAssignment.dependencies
+ for (dependencyName in dependencyNames!!) {
+ if (StringUtils.isNotBlank(dependencyName) && !names.contains(dependencyName)) {
+ names.add(dependencyName)
+ }
+ }
+ }
+ }
+ }
+ if (CollectionUtils.isNotEmpty(names)) {
+ dictionaries = dataDictionaryRepository.findByNameIn(names)
+ }
+ return dictionaries
+
+ }
+
+ private fun getAllAutoMapResourceAssignments(resourceAssignments: MutableList<ResourceAssignment>): List<ResourceAssignment> {
+ var dictionaries: List<ResourceDictionary>? = null
+ val names = ArrayList<String>()
+ for (resourceAssignment in resourceAssignments) {
+ if (StringUtils.isNotBlank(resourceAssignment.dictionaryName)) {
+ if (resourceAssignment.dependencies != null && !resourceAssignment.dependencies!!.isEmpty()) {
+ val dependencyNames = resourceAssignment.dependencies
+ for (dependencyName in dependencyNames!!) {
+ if (StringUtils.isNotBlank(dependencyName) && !names.contains(dependencyName)
+ && !checkAssignmentsExists(resourceAssignments, dependencyName)) {
+ names.add(dependencyName)
+ }
+ }
+ }
+ }
+ }
+
+ if (!names.isEmpty()) {
+ dictionaries = dataDictionaryRepository.findByNameIn(names)
+ }
+ if (dictionaries != null) {
+ for (rscDictionary in dictionaries) {
+ val dictionaryDefinition = rscDictionary.definition
+ Preconditions.checkNotNull(dictionaryDefinition, "failed to get Resource Definition from dictionary definition")
+ val property = PropertyDefinition()
+ property.required = true
+ val resourceAssignment = ResourceAssignment()
+ resourceAssignment.name = rscDictionary.name
+ resourceAssignment.dictionaryName = rscDictionary.name
+ resourceAssignment.version = 0
+ resourceAssignment.property = property
+ ResourceDictionaryUtils.populateSourceMapping(resourceAssignment, dictionaryDefinition)
+ resourceAssignments.add(resourceAssignment)
+ }
+ }
+ return resourceAssignments
+ }
+
+
+ private fun checkAssignmentsExists(resourceAssignmentsWithDepencies: List<ResourceAssignment>, resourceName: String): Boolean {
+ return resourceAssignmentsWithDepencies.stream().anyMatch { names -> names.name.equals(resourceName, ignoreCase = true) }
+ }
+}
\ No newline at end of file