/root> #-------------------------------------------------------------------------------
/root> # ============LICENSE_START=======================================================
/root> #  Copyright (C) 2016-2019 Huawei. All rights reserved.
/root> # ================================================================================
/root> # Licensed under the Apache License, Version 2.0 (the "License");
/root> # you may not use this file except in compliance with the License.
/root> # You may obtain a copy of the License at
/root> #
/root> #      http://www.apache.org/licenses/LICENSE-2.0
/root> #
/root> # Unless required by applicable law or agreed to in writing, software
/root> # distributed under the License is distributed on an "AS IS" BASIS,
/root> # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/root> # See the License for the specific language governing permissions and
/root> # limitations under the License.
/root> #
/root> # SPDX-License-Identifier: Apache-2.0
/root> # ============LICENSE_END=========================================================
/root> #-------------------------------------------------------------------------------
/root> 
/root> #========> create Policy model 
/root> model create name=NomadicONTPolicyModel version=1.0.0
result: SUCCESS

/root> 
/root> 
/root> #========> Define Schema and Data types 
/root> schema create name=SimpleStringType         flavour=Java schema=java.lang.String
result: SUCCESS

/root> schema create name=SimpleLongType           flavour=Java schema=java.lang.Long
result: SUCCESS

/root> schema create name=SimpleBooleanType        flavour=Java schema=java.lang.Boolean
result: SUCCESS

/root> schema create name=UUIDType                 flavour=Java schema=java.util.UUID
result: SUCCESS

/root> 
/root> schema create name=VirtualControlLoopEventType flavour=Java schema=org.onap.policy.controlloop.VirtualControlLoopEvent
result: SUCCESS

/root> 
/root> schema create name=NomadicONTContextType flavour=Avro schema=LS
{
    "type": "record",
    "name": "NomadicONTContext",
    "fields": [
        {
            "name": "AAI",
            "type": {
                "type": "record",
                "name": "VCPE_AAI_Type",
                "namespace": "org.onap.policy.apex.onap.vcpe",
                "fields": [
                    {
                        "name": "attachmentPoint",
                        "type": "string"
                    },
                    {
                        "name": "service_information_hsia_cfs_service_instance_id",
                        "type": "string"
                    },
                    {
                        "name": "cvlan",
                        "type": "string"
                    },
                    {
                        "name": "svlan",
                        "type": "string"
                    },
                    {
                        "name": "remoteId",
                        "type": "string"
                    }
                ]
            }
        },
        {
            "name": "closedLoopAlarmStart",
            "type": "long"
        },
        {
            "name": "closedLoopAlarmEnd",
            "type": "long"
        },
        {
            "name": "closedLoopControlName",
            "type": "string"
        },
        {
            "name": "version",
            "type": "string"
        },
        {
            "name": "requestID",
            "type": "string"
        },
        {
            "name": "closedLoopEventClient",
            "type": "string"
        },
        {
            "name": "closedLoopEventStatus",
            "type": "string"
        },
        {
            "name": "target_type",
            "type": "string"
        },
        {
            "name": "target",
            "type": "string"
        },
        {
            "name": "from",
            "type": "string"
        },
        {
            "name": "policyScope",
            "type": "string"
        },
        {
            "name": "policyName",
            "type": "string"
        },
        {
            "name": "policyVersion",
            "type": "string"
        },
        {
            "name": "notification",
            "type": "string"
        },
        {
            "name": "notificationTime",
            "type": "long"
        },
        {
            "name": "result",
            "type": "string"
        },
        {
            "name": "message",
            "type": "string"
        },
        {
            "name": "url",
            "type": "string"
        },
        {
            "name": "aai_message",
            "type": "string"
        }
    ]
}
LE
result: SUCCESS

/root> 
/root> #=======================> Create Albums
/root> album create name=NomadicONTContextAlbum scope=policy writable=true schemaName=NomadicONTContextType
result: SUCCESS

/root> 
/root> 
/root> #===================================> Define Events
/root> #=============>Nomadic ONT
/root> event create name=Nomadic_ONT version=1.0.0 nameSpace=org.onap.policy.apex.onap.bbs source=DCAE target=APEX
result: SUCCESS

/root> event parameter create name=Nomadic_ONT parName=VirtualControlLoopEvent schemaName=VirtualControlLoopEventType
result: SUCCESS

/root> 
/root> event create name=AAI_SERVICE_ASSIGNED version=1.0.0 nameSpace=org.onap.policy.apex.onap.bbs source=APEX target=APEX
result: SUCCESS

/root> event parameter create name=AAI_SERVICE_ASSIGNED parName=requestID schemaName=UUIDType
result: SUCCESS

/root> event parameter create name=AAI_SERVICE_ASSIGNED parName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS

/root> event parameter create name=AAI_SERVICE_ASSIGNED parName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS

/root> 
/root> event create name=SDNC_RESOURCE_UPDATE version=1.0.0 nameSpace=org.onap.policy.apex.onap.bbs source=APEX target=APEX
result: SUCCESS

/root> event parameter create name=SDNC_RESOURCE_UPDATE parName=result schemaName=SimpleStringType
result: SUCCESS

/root> event parameter create name=SDNC_RESOURCE_UPDATE parName=requestID schemaName=UUIDType
result: SUCCESS

/root> event parameter create name=SDNC_RESOURCE_UPDATE parName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS

/root> event parameter create name=SDNC_RESOURCE_UPDATE parName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS

/root> 
/root> event create name=AAI_SERVICE_CREATE version=1.0.0 nameSpace=org.onap.policy.apex.onap.bbs source=APEX target=APEX
result: SUCCESS

/root> event parameter create name=AAI_SERVICE_CREATE parName=result schemaName=SimpleStringType
result: SUCCESS

/root> event parameter create name=AAI_SERVICE_CREATE parName=requestID schemaName=UUIDType
result: SUCCESS

/root> event parameter create name=AAI_SERVICE_CREATE parName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS

/root> event parameter create name=AAI_SERVICE_CREATE parName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS

/root> 
/root> event create name=ERROR_LOG version=1.0.0 nameSpace=org.onap.policy.apex.onap.bbs source=APEX target=APEX
result: SUCCESS

/root> event parameter create name=ERROR_LOG parName=errorLogParam schemaName=SimpleStringType
result: SUCCESS

/root> 
/root> event create name=END_CONTROL_LOOP version=1.0.0 nameSpace=org.onap.policy.apex.onap.bbs source=APEX target=APEX
result: SUCCESS

/root> event parameter create name=END_CONTROL_LOOP parName=result schemaName=SimpleStringType
result: SUCCESS

/root> event parameter create name=END_CONTROL_LOOP parName=requestID schemaName=UUIDType
result: SUCCESS

/root> event parameter create name=END_CONTROL_LOOP parName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS

/root> event parameter create name=END_CONTROL_LOOP parName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS

/root> 
/root> 
/root> event create name=END_EVENT version=1.0.0 nameSpace=org.onap.policy.apex.onap.bbs source=APEX target=DCAE
result: SUCCESS

/root> event parameter create name=END_EVENT parName=result schemaName=SimpleStringType optional=true
result: SUCCESS

/root> event parameter create name=END_EVENT parName=requestID schemaName=UUIDType
result: SUCCESS

/root> event parameter create name=END_EVENT parName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS

/root> event parameter create name=END_EVENT parName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS

/root> 
/root> #=============>CPE Authentication
/root> event create name=CPE_Authentication version=1.0.0 nameSpace=org.onap.policy.apex.onap.bbs source=DCAE target=APEX
result: SUCCESS

/root> event parameter create name=CPE_Authentication parName=VirtualControlLoopEvent schemaName=VirtualControlLoopEventType
result: SUCCESS

/root> 
/root> event create name=AAI_CPE_AUTH_UPDATE version=1.0.0 nameSpace=org.onap.policy.apex.onap.bbs source=APEX target=DCAE
result: SUCCESS

/root> event parameter create name=AAI_CPE_AUTH_UPDATE parName=result schemaName=SimpleStringType
result: SUCCESS

/root> event parameter create name=AAI_CPE_AUTH_UPDATE parName=requestID schemaName=UUIDType
result: SUCCESS

/root> event parameter create name=AAI_CPE_AUTH_UPDATE parName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS

/root> event parameter create name=AAI_CPE_AUTH_UPDATE parName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS

/root> 
/root> 
/root> #========> Define Tasks (1)
/root> task create name=GetBBSCloseLoopEventTask
result: SUCCESS

/root> 
/root> task inputfield create name=GetBBSCloseLoopEventTask fieldName=VirtualControlLoopEvent schemaName=VirtualControlLoopEventType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=GetBBSCloseLoopEventTask fieldName=requestID schemaName=UUIDType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=GetBBSCloseLoopEventTask fieldName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=GetBBSCloseLoopEventTask fieldName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task contextref create name=GetBBSCloseLoopEventTask albumName=NomadicONTContextAlbum
result: SUCCESS

/root> 
/root> task logic create name=GetBBSCloseLoopEventTask logicFlavour=JAVASCRIPT logic=LS
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 Huawei. All rights reserved.
 *  Modifications Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

executor.logger.info("Begin Execution GetBBSCloseLoopEventTask.js");
executor.logger.info(executor.subject.id);
executor.logger.info(executor.inFields);
var returnValue = true;

var clEventType = org.onap.policy.controlloop.VirtualControlLoopEvent;
var clEvent = executor.inFields.get("VirtualControlLoopEvent");
executor.logger.info(clEvent.toString());
executor.logger.info(clEvent.getClosedLoopControlName());

var requestID = clEvent.getRequestId();
executor.logger.info("requestID = " + requestID);
var attachmentPoint = null;
var NomadicONTContext = null;
var serviceInstanceId = null;

if (clEvent.getAai().get("attachmentPoint") != null) {
    attachmentPoint = clEvent.getAai().get("attachmentPoint");
    executor.logger.info("attachmentPoint = " + attachmentPoint);
    NomadicONTContext = executor.getContextAlbum("NomadicONTContextAlbum").get(
        attachmentPoint);
    serviceInstanceId = clEvent.getAai().get(
        "service-information.hsia-cfs-service-instance-id");
    executor.logger.info("serviceInstanceId = " + serviceInstanceId);

    if (NomadicONTContext == null) {
        executor.logger.info(
            "Creating context information for new ONT Device \"" +
            attachmentPoint.toString() + "\"");

        NomadicONTContext = executor.getContextAlbum("NomadicONTContextAlbum").getSchemaHelper()
            .createNewInstance();

        NomadicONTContext.put("closedLoopControlName", clEvent.getClosedLoopControlName());
        NomadicONTContext.put("closedLoopAlarmStart", clEvent.getClosedLoopAlarmStart()
            .toEpochMilli());
        NomadicONTContext.put("closedLoopEventClient", clEvent.getClosedLoopEventClient());
        NomadicONTContext.put("closedLoopEventStatus", clEvent.getClosedLoopEventStatus()
            .toString());
        NomadicONTContext.put("version", clEvent.getVersion());
        NomadicONTContext.put("requestID", clEvent.getRequestId().toString());
        NomadicONTContext.put("target_type", clEvent.getTargetType().toString());
        NomadicONTContext.put("target", clEvent.getTarget());
        NomadicONTContext.put("from", clEvent.getFrom());
        NomadicONTContext.put("policyScope", "Nomadic ONT");
        NomadicONTContext.put("policyName", clEvent.getPolicyName());
        NomadicONTContext.put("policyVersion", "1.0.0");
        NomadicONTContext.put("notificationTime", java.lang.System.currentTimeMillis());
        NomadicONTContext.put("message", "");
        NomadicONTContext.put("result", "SUCCESS");
        var aaiInfo = executor.getContextAlbum("NomadicONTContextAlbum").getSchemaHelper()
            .createNewSubInstance("VCPE_AAI_Type");

        aaiInfo.put("attachmentPoint", clEvent.getAai().get("attachmentPoint"));
        aaiInfo.put("cvlan", clEvent.getAai().get("cvlan"));
        aaiInfo.put("service_information_hsia_cfs_service_instance_id", clEvent
            .getAai().get(
                "service-information.hsia-cfs-service-instance-id"));
        aaiInfo.put("svlan", clEvent.getAai().get("svlan"));
        aaiInfo.put("remoteId", clEvent.getAai().get("remoteId"));


        NomadicONTContext.put("AAI", aaiInfo);

        if (clEvent.getClosedLoopAlarmEnd() != null) {
            NomadicONTContext.put("closedLoopAlarmEnd", clEvent.getClosedLoopAlarmEnd()
                .toEpochMilli());
        } else {
            NomadicONTContext.put("closedLoopAlarmEnd", java.lang.Long.valueOf(
                0));
        }

        executor.getContextAlbum("NomadicONTContextAlbum").put(attachmentPoint.toString(),
            NomadicONTContext);
        executor.logger.info("Created context information for new vCPE VNF \"" +
            attachmentPoint.toString() + "\"");
    }

    executor.outFields.put("requestID", requestID);
    executor.outFields.put("attachmentPoint", attachmentPoint);
    executor.outFields.put("serviceInstanceId", serviceInstanceId);
    executor.logger.info(executor.outFields);
    executor.logger.info("Event Successfully Received and stored in album");
}
else
{
    executor.message = "Received NULL attachment-point";
    returnValue = false;
}

returnValue;


LE
result: SUCCESS

/root> 
/root> #========> Define Tasks (2)
/root> task create name=AAIServiceAssignedTask
result: SUCCESS

/root> task inputfield create name=AAIServiceAssignedTask fieldName=requestID schemaName=UUIDType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=AAIServiceAssignedTask fieldName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=AAIServiceAssignedTask fieldName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=AAIServiceAssignedTask fieldName=requestID schemaName=UUIDType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=AAIServiceAssignedTask fieldName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=AAIServiceAssignedTask fieldName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=AAIServiceAssignedTask fieldName=result schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> 
/root> task contextref create name=AAIServiceAssignedTask albumName=NomadicONTContextAlbum
result: SUCCESS

/root> 
/root> task logic create name=AAIServiceAssignedTask logicFlavour=JAVASCRIPT logic=LS
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 Huawei. All rights reserved.
 *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

executor.logger.info("Begin Execution AAIServiceAssignedTask.js");
executor.logger.info(executor.subject.id);
executor.logger.info(executor.inFields);

var attachmentPoint = executor.inFields.get("attachmentPoint");
var requestID = executor.inFields.get("requestID");
var serviceInstanceId = executor.inFields.get("serviceInstanceId");

var NomadicONTContext = executor.getContextAlbum("NomadicONTContextAlbum").get(attachmentPoint);
executor.logger.info(NomadicONTContext);

var jsonObj;
var aaiUpdateResult = true;

var wbClient = org.onap.policy.apex.examples.bbs.WebClient;
var client = new wbClient();

/* Get AAI URL from Configuration file. */
var AAI_URL = "localhost:8080";
var CUSTOMER_ID = requestID;
var SERVICE_INSTANCE_ID = serviceInstanceId;
var AAI_VERSION = "v14";
var resource_version;
var relationship_list;
var HTTP_PROTOCOL = "https://";
var results;
var putUrl;
var service_instance;
try {
    var br = Files.newBufferedReader(Paths.get("/home/apexuser/examples/config/ONAPBBS/config.txt"));
    var line;
    while ((line = br.readLine()) != null) {
        if (line.startsWith("AAI_URL")) {
            var str = line.split("=");
            AAI_URL = str[str.length - 1];
        } else if (line.startsWith("AAI_USERNAME")) {
            var str = line.split("=");
            AAI_USERNAME = str[str.length - 1];
        } else if (line.startsWith("AAI_PASSWORD")) {
            var str = line.split("=");
            AAI_PASSWORD = str[str.length - 1];
        } else if (line.startsWith("AAI_VERSION")) {
            var str = line.split("=");
            AAI_VERSION = str[str.length - 1];
        }
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
}

executor.logger.info("AAI_URL " + AAI_URL);

/* Get service instance Id from AAI */
try {
    var urlGet = HTTP_PROTOCOL + AAI_URL + "/aai/" + AAI_VERSION + "/nodes/service-instances/service-instance/"
            + SERVICE_INSTANCE_ID + "?format=resource_and_url";

    executor.logger.info("Query url" + urlGet);

    result = client.httpRequest(urlGet, "GET", null, AAI_USERNAME, AAI_PASSWORD, "application/json");
    executor.logger.info("Data received From " + urlGet + " " + result);
    jsonObj = JSON.parse(result.toString());

    executor.logger.info(JSON.stringify(jsonObj, null, 4));
    /* Retrieve the service instance id */
    results = jsonObj['results'][0];
    putUrl = results['url'];
    service_instance = results['service-instance'];
    service_instance_id = service_instance['service-instance-id'];
    resource_version = service_instance['resource-version'];
    relationship_list = service_instance['relationship-list'];
    executor.logger.info("After Parse service_instance " + JSON.stringify(service_instance, null, 4) + "\n url "
            + putUrl + "\n Service instace Id " + service_instance_id);

    if (result == "") {
        aaiUpdateResult = false;
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
    aaiUpdateResult = false;
}

/* BBS Policy updates orchestration status of {{bbs-cfs-service-instance-UUID}} [ active --> assigned ] */
var putUpddateServInstance;
putUpddateServInstance = service_instance;
try {
    if (aaiUpdateResult == true) {
        putUpddateServInstance["orchestration-status"] = "active";
        executor.logger.info("ready to putAfter Parse " + JSON.stringify(putUpddateServInstance, null, 4));
        var urlPut = HTTP_PROTOCOL + AAI_URL + putUrl + "?resource_version=" + resource_version;
        result = client.httpRequest(urlPut, "PUT", JSON.stringify(putUpddateServInstance), AAI_USERNAME, AAI_PASSWORD,
                "application/json");
        executor.logger.info("Data received From " + urlPut + " " + result);
        /* If failure to retrieve data proceed to Failure */
        if (result != "") {
            aaiUpdateResult = false;
        }
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
    aaiUpdateResult = false;
}

if (!service_instance.hasOwnProperty('input-parameters') || !service_instance.hasOwnProperty('metadata')) {
    aaiUpdateResult = false;
    executor.logger.info("Validate data failed. input-parameters or metadata is missing");
}

/* update logical link in pnf */
var oldLinkName = "";
try {
    if (aaiUpdateResult == true) {
        var pnfName = "";
        var pnfResponse;
        var pnfUpdate;
        var relationShips = relationship_list["relationship"];

        for (var i = 0; i < relationShips.length; i++) {
            if (relationShips[i]["related-to"] == "pnf") {
                var relationship_data = relationShips[i]["relationship-data"];
                for (var j = 0; j < relationship_data.length; j++) {
                    if (relationship_data[j]["relationship-key"] == "pnf.pnf-name") {
                        pnfName = relationship_data[j]['relationship-value'];
                        break;
                    }
                }
            }
        }
        executor.logger.info("pnf-name found " + pnfName);

        /* 1. Get PNF */
        var urlGetPnf = HTTP_PROTOCOL + AAI_URL + "/aai/" + AAI_VERSION + "/network/pnfs/pnf/" + pnfName;
        pnfResponse = client.httpRequest(urlGetPnf, "GET", null, AAI_USERNAME, AAI_PASSWORD, "application/json");
        executor.logger.info("Data received From " + urlGetPnf + " " + pnfResponse);
        /* If failure to retrieve data proceed to Failure */
        if (result != "") {
            aaiUpdateResult = false;
        }
        pnfUpdate = JSON.parse(pnfResponse.toString());
        executor.logger.info(JSON.stringify(pnfUpdate, null, 4));

        /* 2. Create logical link */
        var link_name = attachmentPoint;
        var logicalLink = {
            "link-name" : link_name,
            "in-maint" : false,
            "link-type" : "attachment-point"
        };
        var urlNewLogicalLink = HTTP_PROTOCOL + AAI_URL + "/aai/" + AAI_VERSION
                + "/network/logical-links/logical-link/" + link_name;
        result = client.httpRequest(urlNewLogicalLink, "PUT", JSON.stringify(logicalLink), AAI_USERNAME, AAI_PASSWORD,
                "application/json");
        executor.logger.info("Data received From " + urlNewLogicalLink + " " + result);
        /* If failure to retrieve data proceed to Failure */
        if (result != "") {
            aaiUpdateResult = false;
        }

        /* 3. Update pnf with new relation */
        for (var i = 0; i < pnfUpdate["relationship-list"]["relationship"].length; i++) {
            if (pnfUpdate["relationship-list"]["relationship"][i]['related-to'] == 'logical-link') {
                pnfUpdate["relationship-list"]["relationship"][i]['related-link'] = "/aai/" + AAI_VERSION
                        + "/network/logical-links/logical-link/" + link_name;
                for (var j = 0; j < pnfUpdate["relationship-list"]["relationship"][i]['relationship-data'].length; j++) {
                    if (pnfUpdate["relationship-list"]["relationship"][i]['relationship-data'][j]['relationship-key'] == "logical-link.link-name") {
                        oldLinkName = pnfUpdate["relationship-list"]["relationship"][i]['relationship-data'][j]['relationship-value'];
                        pnfUpdate["relationship-list"]["relationship"][i]['relationship-data'][j]['relationship-value'] = link_name;
                        break;
                    }
                }
                break;
            }
        }

        executor.logger.info("Put pnf to aai " + JSON.stringify(pnfUpdate, null, 4));
        var urlPutPnf = HTTP_PROTOCOL + AAI_URL + "/aai/" + AAI_VERSION + "/network/pnfs/pnf/" + pnfName;
        result = client.httpRequest(urlPutPnf, "PUT", JSON.stringify(pnfUpdate), AAI_USERNAME, AAI_PASSWORD,
                "application/json");
        executor.logger.info("Data received From " + urlPutPnf + " " + result);

        /* If failure to retrieve data proceed to Failure */
        if (result != "") {
            aaiUpdateResult = false;
        }

        /* Get and Delete the Stale logical link */
        var oldLinkResult;
        var linkResult;
        var urlOldLogicalLink = HTTP_PROTOCOL + AAI_URL + "/aai/" + AAI_VERSION
                + "/network/logical-links/logical-link/" + oldLinkName;
        linkResult = client.httpRequest(urlOldLogicalLink, "GET", null, AAI_USERNAME, AAI_PASSWORD, "application/json");
        executor.logger.info("Data received From " + urlOldLogicalLink + " " + linkResult + " "
                + linkResult.hasOwnProperty("link-name"));
        oldLinkResult = JSON.parse(linkResult.toString());
        if (oldLinkResult.hasOwnProperty("link-name") == true) {
            var res_version = oldLinkResult["resource-version"];
            var urlDelOldLogicalLink = urlOldLogicalLink + "?resource-version=" + res_version;
            executor.logger.info("Delete called for " + urlDelOldLogicalLink);
            result = client.httpRequest(urlDelOldLogicalLink, "DELETE", null, AAI_USERNAME, AAI_PASSWORD,
                    "application/json");
            executor.logger.info("Delete called for " + urlDelOldLogicalLink + " result " + result);
        }
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
    aaiUpdateResult = false;
}

/* If Success then Fill output schema */
if (aaiUpdateResult == true) {
    executor.outFields.put("result", "SUCCESS");
    NomadicONTContext.put("result", "SUCCESS");
    NomadicONTContext.put("aai_message", JSON.stringify(service_instance));
    NomadicONTContext.put("url", putUrl);
} else {
    executor.outFields.put("result", "FAILURE");
    NomadicONTContext.put("result", "FAILURE");
}

executor.outFields.put("requestID", requestID);
executor.outFields.put("attachmentPoint", attachmentPoint);
executor.outFields.put("serviceInstanceId", executor.inFields.get("serviceInstanceId"));

executor.logger.info(executor.outFields);
executor.logger.info("End Execution AAIServiceAssignedTask.js");

true;

/* Utility functions Begin */
function IsValidJSONString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
/* Utility functions End */

LE
result: SUCCESS

/root> 
/root> #========> Define Tasks (3)
/root> task create name=ErrorAAIServiceAssignedLogTask
result: SUCCESS

/root> task inputfield create name=ErrorAAIServiceAssignedLogTask fieldName=result schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=ErrorAAIServiceAssignedLogTask fieldName=requestID schemaName=UUIDType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=ErrorAAIServiceAssignedLogTask fieldName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=ErrorAAIServiceAssignedLogTask fieldName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=ErrorAAIServiceAssignedLogTask fieldName=errorLogParam schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> 
/root> task logic create name=ErrorAAIServiceAssignedLogTask logicFlavour=JAVASCRIPT logic=LS
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 Huawei. All rights reserved.
 *  Modifications Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */
executor.logger.info("Begin Execution ErrorServiceUpdateOneLogTask.js");
executor.logger.info(executor.subject.id);
executor.logger.info(executor.inFields);

executor.logger.info(executor.outFields);

executor.logger.info("Begin Execution ErrorServiceUpdateOneLogTask.js");

true;

LE
result: SUCCESS

/root> 
/root> #========> Define Tasks (4)
/root> task create name=SdncResourceUpdateTask
result: SUCCESS

/root> task inputfield create name=SdncResourceUpdateTask fieldName=requestID schemaName=UUIDType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=SdncResourceUpdateTask fieldName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=SdncResourceUpdateTask fieldName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=SdncResourceUpdateTask fieldName=requestID schemaName=UUIDType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=SdncResourceUpdateTask fieldName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=SdncResourceUpdateTask fieldName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=SdncResourceUpdateTask fieldName=result schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task contextref create name=SdncResourceUpdateTask albumName=NomadicONTContextAlbum
result: SUCCESS

/root> 
/root> task logic create name=SdncResourceUpdateTask logicFlavour=JAVASCRIPT logic=LS
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 Huawei. All rights reserved.
 *  Modifications Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

executor.logger.info("Begin Execution SdncResourceUpdateTask.js");
executor.logger.info(executor.subject.id);
executor.logger.info(executor.inFields);

var attachmentPoint = executor.inFields.get("attachmentPoint");
var requestID = executor.inFields.get("requestID");
var serviceInstanceId = executor.inFields.get("serviceInstanceId");
var uuidType = java.util.UUID;

var wbClient = org.onap.policy.apex.examples.bbs.WebClient;
var client = new wbClient();

var NomadicONTContext = executor.getContextAlbum("NomadicONTContextAlbum").get(attachmentPoint);
var sdncUUID = uuidType.randomUUID();
executor.logger.info(NomadicONTContext);
var jsonObj;
var aaiUpdateResult = true;
var SDNC_URL = "localhost:8080";
var HTTP_PROTOCOL = "http://"
var SVC_NOTIFICATION_URL;
var putUpddateServInstance = JSON.parse(NomadicONTContext.get("aai_message"));
var input_param = JSON.parse(putUpddateServInstance['input-parameters']);
try {
    var br = Files.newBufferedReader(Paths.get("/home/apexuser/examples/config/ONAPBBS/config.txt"));
    var line;
    while ((line = br.readLine()) != null) {
        if (line.startsWith("SDNC_URL")) {
            var str = line.split("=");
            SDNC_URL = str[str.length - 1];
        } else if (line.startsWith("SVC_NOTIFICATION_URL")) {
            var str = line.split("=");
            SVC_NOTIFICATION_URL = str[str.length - 1];
        } else if (line.startsWith("SDNC_USERNAME")) {
            var str = line.split("=");
            SDNC_USERNAME = str[str.length - 1];
        } else if (line.startsWith("SDNC_PASSWORD")) {
            var str = line.split("=");
            SDNC_PASSWORD = str[str.length - 1];
        }
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
}
executor.logger.info("SDNC_URL " + SDNC_URL);

var result;
var jsonObj;
var sdncUpdateResult = true;

/* BBS Policy calls SDN-C GR-API to delete AccessConnectivity VF ID */
/* Prepare Data */
var xmlDeleteAccess = "";
try {
    var br = Files.newBufferedReader(Paths
            .get("/home/apexuser/examples/config/ONAPBBS/sdnc_DeleteAccessConnectivityInstance.txt"));
    var line;
    while ((line = br.readLine()) != null) {
        xmlDeleteAccess += line;
    }

} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
}

/* BBS Policy calls SDN-C GR-API to delete AccessConnectivity */
xmlDeleteAccess = xmlDeleteAccess.replace("svc_request_id_value", sdncUUID);
xmlDeleteAccess = xmlDeleteAccess.replace("svc_notification_url_value", SVC_NOTIFICATION_URL);
xmlDeleteAccess = xmlDeleteAccess.replace("request_id_value", sdncUUID);
xmlDeleteAccess = xmlDeleteAccess.replace("service_id_value", sdncUUID);
xmlDeleteAccess = xmlDeleteAccess.replace("service_instance_id_value", putUpddateServInstance['service-instance-id']);
xmlDeleteAccess = xmlDeleteAccess.replace("service_type_value", input_param['service']['serviceType']);
xmlDeleteAccess = xmlDeleteAccess.replace("customer_id_value", input_param['service']['globalSubscriberId']);
xmlDeleteAccess = xmlDeleteAccess.replace("customer_name_value", input_param['service']['globalSubscriberId']);

xmlDeleteAccess = xmlDeleteAccess.replace("srv_info_model_inv_uuid_value", getResourceInvariantUuid(
        input_param['service']['parameters']['resources'], 'AccessConnectivity'));
xmlDeleteAccess = xmlDeleteAccess.replace("srv_info_model_custom_uuid_value", getResourceCustomizationUuid(
        input_param['service']['parameters']['resources'], 'AccessConnectivity'));
xmlDeleteAccess = xmlDeleteAccess.replace("srv_info_model_uuid_value", getResourceUuid(
        input_param['service']['parameters']['resources'], 'AccessConnectivity'));
xmlDeleteAccess = xmlDeleteAccess.replace("srv_info_model_name_value", "AccessConnectivity");
xmlDeleteAccess = xmlDeleteAccess.replace("network_info_model_inv_uuid_value", getResourceInvariantUuid(
        input_param['service']['parameters']['resources'], 'AccessConnectivity'));
xmlDeleteAccess = xmlDeleteAccess.replace("network_info_model_custom_uuid_value", getResourceCustomizationUuid(
        input_param['service']['parameters']['resources'], 'AccessConnectivity'));
xmlDeleteAccess = xmlDeleteAccess.replace("network_info_model_uuid_value", getResourceUuid(
        input_param['service']['parameters']['resources'], 'AccessConnectivity'));
xmlDeleteAccess = xmlDeleteAccess.replace("network_info_model_name_value", "AccessConnectivity");

xmlDeleteAccess = xmlDeleteAccess.replace("vendor_value",
        input_param['service']['parameters']['requestInputs']['ont_ont_manufacturer']);
xmlDeleteAccess = xmlDeleteAccess.replace("service_id_value", getMetaValue(
        putUpddateServInstance['metadata']['metadatum'], 'controller-service-id'));
executor.logger.info(client.toPrettyString(xmlDeleteAccess, 4));

try {
    var urlPost1 = HTTP_PROTOCOL + SDNC_URL + "/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation";
    result = client.httpRequest(urlPost1, "POST", xmlDeleteAccess, SDNC_USERNAME, SDNC_PASSWORD, "application/xml");
    executor.logger.info("Data received From " + urlPost1 + " " + result);
    if (result == "") {
        sdncUpdateResult = false;
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
    sdncUpdateResult = false;
}

/* BBS Policy calls SDN-C GR-API to create new AccessConnectivity VF */

/* Prepare Data */
var xmlCreateAccess = "";
try {
    var br = Files.newBufferedReader(Paths
            .get("/home/apexuser/examples/config/ONAPBBS/sdnc_CreateAccessConnectivityInstance.txt"));
    var line;
    while ((line = br.readLine()) != null) {
        xmlCreateAccess += line;
    }

} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
}
xmlCreateAccess = xmlCreateAccess.replace("svc_request_id_value", sdncUUID);
xmlCreateAccess = xmlCreateAccess.replace("svc_notification_url_value", SVC_NOTIFICATION_URL);
xmlCreateAccess = xmlCreateAccess.replace("request_id_value", requestID);
xmlCreateAccess = xmlCreateAccess.replace("service_id_value", sdncUUID);
xmlCreateAccess = xmlCreateAccess.replace("service_instance_id_value", putUpddateServInstance['service-instance-id']);
xmlCreateAccess = xmlCreateAccess.replace("service_type_value", input_param['service']['serviceType']);
xmlCreateAccess = xmlCreateAccess.replace("customer_id_value", input_param['service']['globalSubscriberId']);
xmlCreateAccess = xmlCreateAccess.replace("customer_name_value", input_param['service']['globalSubscriberId']);

xmlCreateAccess = xmlCreateAccess.replace("srv_info_model_inv_uuid_value", getResourceInvariantUuid(
        input_param['service']['parameters']['resources'], 'AccessConnectivity'));
xmlCreateAccess = xmlCreateAccess.replace("srv_info_model_custom_uuid_value", getResourceCustomizationUuid(
        input_param['service']['parameters']['resources'], 'AccessConnectivity'));
xmlCreateAccess = xmlCreateAccess.replace("srv_info_model_uuid_value", getResourceUuid(
        input_param['service']['parameters']['resources'], 'AccessConnectivity'));
xmlCreateAccess = xmlCreateAccess.replace("srv_info_model_name_value", "AccessConnectivity");
xmlCreateAccess = xmlCreateAccess.replace("network_info_model_inv_uuid_value", getResourceInvariantUuid(
        input_param['service']['parameters']['resources'], 'AccessConnectivity'));
xmlCreateAccess = xmlCreateAccess.replace("network_info_model_custom_uuid_value", getResourceCustomizationUuid(
        input_param['service']['parameters']['resources'], 'AccessConnectivity'));
xmlCreateAccess = xmlCreateAccess.replace("network_info_model_uuid_value", getResourceUuid(
        input_param['service']['parameters']['resources'], 'AccessConnectivity'));
xmlCreateAccess = xmlCreateAccess.replace("network_info_model_name_value", "AccessConnectivity");

xmlCreateAccess = xmlCreateAccess.replace("vendor_value",
        input_param['service']['parameters']['requestInputs']['ont_ont_manufacturer']);
xmlCreateAccess = xmlCreateAccess.replace("ont_sn_value",
        input_param['service']['parameters']['requestInputs']['ont_ont_serial_num']);
xmlCreateAccess = xmlCreateAccess.replace("s_vlan_value", getMetaValue(putUpddateServInstance['metadata']['metadatum'],
        'svlan'));
xmlCreateAccess = xmlCreateAccess.replace("c_vlan_value", getMetaValue(putUpddateServInstance['metadata']['metadatum'],
        'cvlan'));
xmlCreateAccess = xmlCreateAccess.replace("remote_id_value", getMetaValue(
        putUpddateServInstance['metadata']['metadatum'], 'remote-id'));
executor.logger.info(client.toPrettyString(xmlCreateAccess, 4));

try {
    if (sdncUpdateResult == true) {
        var urlPost2 = HTTP_PROTOCOL + SDNC_URL
                + "/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation";
        result = client.httpRequest(urlPost2, "POST", xmlCreateAccess, SDNC_USERNAME, SDNC_PASSWORD, "application/xml");
        executor.logger.info("Data received From " + urlPost2 + " " + result);
        if (result == "") {
            sdncUpdateResult = false;
        }
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
    sdncUpdateResult = false;
}

/* BBS Policy calls SDN-C GR-API to create change Internet Profile */
var xmlChangeProfile = "";
try {
    var br = Files.newBufferedReader(Paths
            .get("/home/apexuser/examples/config/ONAPBBS/sdnc_ChangeInternetProfileInstance.txt"));
    var line;
    while ((line = br.readLine()) != null) {
        xmlChangeProfile += line;
    }

} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
}

xmlChangeProfile = xmlChangeProfile.replace("svc_request_id_value", sdncUUID);
xmlChangeProfile = xmlChangeProfile.replace("svc_notification_url_value", SVC_NOTIFICATION_URL);
xmlChangeProfile = xmlChangeProfile.replace("request_id_value", requestID);
xmlChangeProfile = xmlChangeProfile.replace("service_id_value", sdncUUID);
xmlChangeProfile = xmlChangeProfile.replace("service_instance_id_value", putUpddateServInstance['service-instance-id']);
xmlChangeProfile = xmlChangeProfile.replace("service_type_value", input_param['service']['serviceType']);
xmlChangeProfile = xmlChangeProfile.replace("customer_id_value", input_param['service']['globalSubscriberId']);
xmlChangeProfile = xmlChangeProfile.replace("customer_name_value", input_param['service']['globalSubscriberId']);

xmlCreateAccess = xmlCreateAccess.replace("srv_info_model_inv_uuid_value", getResourceInvariantUuid(
        input_param['service']['parameters']['resources'], 'InternetProfile'));
xmlCreateAccess = xmlCreateAccess.replace("srv_info_model_custom_uuid_value", getResourceCustomizationUuid(
        input_param['service']['parameters']['resources'], 'InternetProfile'));
xmlCreateAccess = xmlCreateAccess.replace("srv_info_model_uuid_value", getResourceUuid(
        input_param['service']['parameters']['resources'], 'InternetProfile'));
xmlCreateAccess = xmlCreateAccess.replace("srv_info_model_name_value", "InternetProfile");
xmlCreateAccess = xmlCreateAccess.replace("network_info_model_inv_uuid_value", getResourceInvariantUuid(
        input_param['service']['parameters']['resources'], 'InternetProfile'));
xmlCreateAccess = xmlCreateAccess.replace("network_info_model_custom_uuid_value", getResourceCustomizationUuid(
        input_param['service']['parameters']['resources'], 'InternetProfile'));
xmlCreateAccess = xmlCreateAccess.replace("network_info_model_uuid_value", getResourceUuid(
        input_param['service']['parameters']['resources'], 'InternetProfile'));
xmlCreateAccess = xmlCreateAccess.replace("network_info_model_name_value", "InternetProfile");

xmlChangeProfile = xmlChangeProfile.replace("vendor_value",
        input_param['service']['parameters']['requestInputs']['ont_ont_manufacturer']);
xmlChangeProfile = xmlChangeProfile.replace("service_id_value", getMetaValue(
        putUpddateServInstance['metadata']['metadatum'], 'controller-service-id'));
xmlChangeProfile = xmlChangeProfile.replace("remote_id_value", getMetaValue(
        putUpddateServInstance['metadata']['metadatum'], 'remote-id'));
xmlChangeProfile = xmlChangeProfile.replace("ont_sn_value",
        input_param['service']['parameters']['requestInputs']['ont_ont_serial_num']);
xmlChangeProfile = xmlChangeProfile.replace("service_type_value", input_param['service']['serviceType']);
xmlChangeProfile = xmlChangeProfile.replace("mac_value", getMetaValue(putUpddateServInstance['metadata']['metadatum'],
        'rgw-mac-address'));
xmlChangeProfile = xmlChangeProfile.replace("up_speed_value", getMetaValue(
        putUpddateServInstance['metadata']['metadatum'], 'up-speed'));
xmlChangeProfile = xmlChangeProfile.replace("down_speed_value", getMetaValue(
        putUpddateServInstance['metadata']['metadatum'], 'down-speed'));
xmlChangeProfile = xmlChangeProfile.replace("s_vlan_value", getMetaValue(
        putUpddateServInstance['metadata']['metadatum'], 'svlan'));
xmlChangeProfile = xmlChangeProfile.replace("c_vlan_value", getMetaValue(
        putUpddateServInstance['metadata']['metadatum'], 'cvlan'));

executor.logger.info(client.toPrettyString(xmlChangeProfile, 4));
try {
    if (sdncUpdateResult == true) {
        var urlPost3 = HTTP_PROTOCOL + SDNC_URL
                + "/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation";
        result = client
                .httpRequest(urlPost3, "POST", xmlChangeProfile, SDNC_USERNAME, SDNC_PASSWORD, "application/xml");
        executor.logger.info("Data received From " + urlPost3 + " " + result);
        if (result == "") {
            sdncUpdateResult = false;
        }
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
    sdncUpdateResult = false;
}

/* If Success then Fill output schema */

if (sdncUpdateResult == true) {
    NomadicONTContext.put("result", "SUCCESS");
    executor.outFields.put("result", "SUCCESS");
} else {
    NomadicONTContext.put("result", "FAILURE");
    executor.outFields.put("result", "FAILURE");
}

executor.outFields.put("requestID", requestID);
executor.outFields.put("attachmentPoint", attachmentPoint);
executor.outFields.put("serviceInstanceId", executor.inFields.get("serviceInstanceId"));

executor.logger.info(executor.outFields);
executor.logger.info("End Execution SdncResourceUpdateTask.js");

true;

function getMetaValue(metaJson, metaname) {
    for (var i = 0; i < metaJson.length; i++) {
        if (metaJson[i]['metaname'] == metaname) {
            var metaValue = metaJson[i]['metaval'];
            return metaValue;
        }
    }

}

function getResourceInvariantUuid(resJson, resourceName) {
    for (var i = 0; i < resJson.length; i++) {
        if (resJson[i]['resourceName'] == resourceName) {
            var resValue = resJson[i]['resourceInvariantUuid'];
            return resValue;
        }
    }

}

function getResourceUuid(resJson, resourceName) {
    for (var i = 0; i < resJson.length; i++) {
        if (resJson[i]['resourceName'] == resourceName) {
            var resValue = resJson[i]['resourceUuid'];
            return resValue;
        }
    }

}

function getResourceCustomizationUuid(resJson, resourceName) {
    for (var i = 0; i < resJson.length; i++) {
        if (resJson[i]['resourceName'] == resourceName) {
            var resValue = resJson[i]['resourceCustomizationUuid'];
            return resValue;
        }
    }

}

/* Utility functions Begin */
function IsValidJSONString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
/* Utility functions End */
LE
result: SUCCESS

/root> 
/root> #========> Define Tasks (5)
/root> task create name=ErrorSdncResourceUpdateTaskLogTask
result: SUCCESS

/root> task inputfield create name=ErrorSdncResourceUpdateTaskLogTask fieldName=result schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=ErrorSdncResourceUpdateTaskLogTask fieldName=requestID schemaName=UUIDType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=ErrorSdncResourceUpdateTaskLogTask fieldName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=ErrorSdncResourceUpdateTaskLogTask fieldName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=ErrorSdncResourceUpdateTaskLogTask fieldName=errorLogParam schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> 
/root> task logic create name=ErrorSdncResourceUpdateTaskLogTask logicFlavour=JAVASCRIPT logic=LS
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 Huawei. All rights reserved.
 *  Modifications Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */
executor.logger.info("Begin Execution ErrorResourceUpdateLogTask.js");
executor.logger.info(executor.subject.id);
executor.logger.info(executor.inFields);

executor.logger.info("End Execution ErrorResourceUpdateLogTask.js");

true;

LE
result: SUCCESS

/root> 
/root> #========> Define Tasks (6)
/root> task create name=AAIServiceCreateTask
result: SUCCESS

/root> task inputfield create name=AAIServiceCreateTask fieldName=requestID schemaName=UUIDType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=AAIServiceCreateTask fieldName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=AAIServiceCreateTask fieldName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=AAIServiceCreateTask fieldName=requestID schemaName=UUIDType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=AAIServiceCreateTask fieldName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=AAIServiceCreateTask fieldName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=AAIServiceCreateTask fieldName=result   schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task contextref create name=AAIServiceCreateTask albumName=NomadicONTContextAlbum
result: SUCCESS

/root> 
/root> task logic create name=AAIServiceCreateTask logicFlavour=JAVASCRIPT logic=LS
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 Huawei. All rights reserved.
 *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

executor.logger.info("Begin Execution AAIServiceCreateTask.js");
executor.logger.info(executor.subject.id);
executor.logger.info(executor.inFields);

var attachmentPoint = executor.inFields.get("attachmentPoint");
var requestID = executor.inFields.get("requestID");
var serviceInstanceId = executor.inFields.get("serviceInstanceId");

var NomadicONTContext = executor.getContextAlbum("NomadicONTContextAlbum").get(attachmentPoint);
executor.logger.info(NomadicONTContext);

// Get the AAI URL from configuraiotn file
var AAI_URL = "localhost:8080";
var CUSTOMER_ID = requestID;
var BBS_CFS_SERVICE_TYPE = "BBS-CFS-Access_Test";
var SERVICE_INSTANCE_ID = serviceInstanceId;
var AAI_VERSION = "v14";
var HTTP_PROTOCOL = "https://";
var wbClient = org.onap.policy.apex.examples.bbs.WebClient;
var client = new wbClient();
var AAI_USERNAME = null;
var AAI_PASSWORD = null;
try {
    var br = Files.newBufferedReader(Paths.get("/home/apexuser/examples/config/ONAPBBS/config.txt"));
    // read line by line
    var line;
    while ((line = br.readLine()) != null) {
        if (line.startsWith("AAI_URL")) {
            var str = line.split("=");
            AAI_URL = str[str.length - 1];
        } else if (line.startsWith("AAI_USERNAME")) {
            var str = line.split("=");
            AAI_USERNAME = str[str.length - 1];
        } else if (line.startsWith("AAI_PASSWORD")) {
            var str = line.split("=");
            AAI_PASSWORD = str[str.length - 1];
        } else if (line.startsWith("AAI_VERSION")) {
            var str = line.split("=");
            AAI_VERSION = str[str.length - 1];
        }
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
}
executor.logger.info("AAI_URL " + AAI_URL);
var aaiUpdateResult = true;
/* Get service instance Id from AAI */
try {
    var urlGet = HTTP_PROTOCOL + AAI_URL + "/aai/" + AAI_VERSION + "/nodes/service-instances/service-instance/"
            + SERVICE_INSTANCE_ID + "?format=resource_and_url";

    executor.logger.info("Query url" + urlGet);

    result = client.httpRequest(urlGet, "GET", null, AAI_USERNAME, AAI_PASSWORD, "application/json");
    executor.logger.info("Data received From " + urlGet + " " + result);
    jsonObj = JSON.parse(result);

    executor.logger.info(JSON.stringify(jsonObj, null, 4));
    /* Retrieve the service instance id */
    results = jsonObj['results'][0];
    putUrl = results['url'];
    service_instance = results['service-instance'];
    executor.logger.info("After Parse service_instance " + JSON.stringify(service_instance, null, 4) + "\n url "
            + putUrl + "\n Service instace Id " + SERVICE_INSTANCE_ID);

    if (result == "") {
        aaiUpdateResult = false;
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
    aaiUpdateResult = false;
}

var putUpddateServInstance = service_instance;
putUpddateServInstance['orchestration-status'] = "created";
executor.logger.info(" string" + JSON.stringify(putUpddateServInstance, null, 4));
var resource_version = putUpddateServInstance['resource-version'];
var putUrl = NomadicONTContext.get("url");

/* BBS Policy updates {{bbs-cfs-service-instance-UUID}} orchestration-status [ assigned --> created ] */
try {
    if (aaiUpdateResult == true) {
        executor.logger.info("ready to putAfter Parse " + JSON.stringify(putUpddateServInstance, null, 4));
        var urlPut = HTTP_PROTOCOL + AAI_URL + putUrl + "?resource_version=" + resource_version;
        result = client.httpRequest(urlPut, "PUT", JSON.stringify(putUpddateServInstance), AAI_USERNAME, AAI_PASSWORD,
                "application/json");
        executor.logger.info("Data received From " + urlPut + " " + result);
        /* If failure to retrieve data proceed to Failure */
        if (result != "") {
            aaiUpdateResult = false;
        }
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
    aaiUpdateResult = false;
}
/* If Success then Fill output schema */
if (aaiUpdateResult == true) {
    NomadicONTContext.put("result", "SUCCESS");
} else {
    NomadicONTContext.put("result", "FAILURE");

}

executor.outFields.put("requestID", requestID);
executor.outFields.put("attachmentPoint", attachmentPoint);
executor.outFields.put("serviceInstanceId", executor.inFields.get("serviceInstanceId"));

executor.logger.info(executor.outFields);
executor.logger.info("End Execution AAIServiceCreateTask.js");

true;


LE
result: SUCCESS

/root> 
/root> #========> Define Tasks (7)
/root> task create name=NomadicEventSuccessTask
result: SUCCESS

/root> task inputfield create name=NomadicEventSuccessTask fieldName=requestID schemaName=UUIDType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=NomadicEventSuccessTask fieldName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task inputfield create name=NomadicEventSuccessTask fieldName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=NomadicEventSuccessTask fieldName=result schemaName=SimpleStringType optional=true
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task contextref create name=NomadicEventSuccessTask albumName=NomadicONTContextAlbum
result: SUCCESS

/root> 
/root> task logic create name=NomadicEventSuccessTask logicFlavour=JAVASCRIPT logic=LS
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 Huawei. All rights reserved.
 *  Modifications Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

executor.logger.info("Begin Execution NomadicEventSuccess.js");
executor.logger.info(executor.subject.id);
executor.logger.info(executor.inFields);

var attachmentPoint = executor.inFields.get("attachmentPoint");
var NomadicONTContext = executor.getContextAlbum("NomadicONTContextAlbum").get(
    attachmentPoint);

executor.logger.info(executor.outFields);
executor.logger.info(executor.inFields);

result = NomadicONTContext.get("result");
var returnValue = true;

if (result == "SUCCESS") {
    executor.outFields.put("result", "SUCCCESS");
    executor.logger.info("BBS policy Execution Done");
} else {
    executor.logger.info("BBS policy Execution Failed");
    executor.outFields.put("result", "FAILURE");
    returnValue = false;
}

executor.logger.info("End Execution NomadicEventSuccess.js");

returnValue;

LE
result: SUCCESS

/root> 
/root> 
/root> 
/root> #========> Define Tasks (8)
/root> task create name=ServiceUpdateStateCpeAuthTask
result: SUCCESS

/root> task inputfield create name=ServiceUpdateStateCpeAuthTask fieldName=VirtualControlLoopEvent schemaName=VirtualControlLoopEventType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=ServiceUpdateStateCpeAuthTask fieldName=result schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=ServiceUpdateStateCpeAuthTask fieldName=requestID schemaName=UUIDType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=ServiceUpdateStateCpeAuthTask fieldName=attachmentPoint     schemaName=SimpleStringType
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task outputfield create name=ServiceUpdateStateCpeAuthTask fieldName=serviceInstanceId   schemaName=SimpleStringType optional=true
result: SUCCESS
inputFields and outputFields are deprecated from Task definition and will be removed. Instead, inputEvent and outputEvents are automatically populated to Tasks based on State definition

/root> task contextref create name=ServiceUpdateStateCpeAuthTask albumName=NomadicONTContextAlbum
result: SUCCESS

/root> 
/root> task logic create name=ServiceUpdateStateCpeAuthTask logicFlavour=JAVASCRIPT logic=LS
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 Huawei. All rights reserved.
 *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

executor.logger.info("Begin Execution ServiceUpdateStateCpeAuthTask.js");
executor.logger.info(executor.subject.id);
executor.logger.info(executor.inFields);

var clEventType = org.onap.policy.controlloop.VirtualControlLoopEvent;
var clEvent = executor.inFields.get("VirtualControlLoopEvent");

var serviceInstanceId = clEvent.getAai().get("service-information.hsia-cfs-service-instance-id");
var requestID = clEvent.getRequestId();

var jsonObj;
var aaiUpdateResult = true;
var wbClient = org.onap.policy.apex.examples.bbs.WebClient;
var client = new wbClient();
var oldState = clEvent.getAai().get("cpe.old-authentication-state");
var newState = clEvent.getAai().get("cpe.new-authentication-state");
/* Get AAI URL from Configuration file. */
var AAI_URL = "localhost:8080";
var CUSTOMER_ID = requestID;
var SERVICE_INSTANCE_ID = serviceInstanceId;
var resource_version;
var HTTP_PROTOCOL = "https://";
var results;
var putUrl;
var service_instance;
var AAI_VERSION = "v14";
try {
    var br = Files.newBufferedReader(Paths.get("/home/apexuser/examples/config/ONAPBBS/config.txt"));
    var line;
    while ((line = br.readLine()) != null) {
        if (line.startsWith("AAI_URL")) {
            var str = line.split("=");
            AAI_URL = str[str.length - 1];
        } else if (line.startsWith("AAI_USERNAME")) {
            var str = line.split("=");
            AAI_USERNAME = str[str.length - 1];
        } else if (line.startsWith("AAI_PASSWORD")) {
            var str = line.split("=");
            AAI_PASSWORD = str[str.length - 1];
        } else if (line.startsWith("AAI_VERSION")) {
            var str = line.split("=");
            AAI_VERSION = str[str.length - 1];
        }
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
}

executor.logger.info("AAI_URL=>" + AAI_URL);

/* Get service instance Id from AAI */
try {
    var urlGet = HTTP_PROTOCOL + AAI_URL + "/aai/" + AAI_VERSION + "/nodes/service-instances/service-instance/"
            + SERVICE_INSTANCE_ID + "?format=resource_and_url"
    executor.logger.info("Query url" + urlGet);

    result = client.httpRequest(urlGet, "GET", null, AAI_USERNAME, AAI_PASSWORD, "application/json");
    executor.logger.info("Data received From " + urlGet + " " + result);
    jsonObj = JSON.parse(result);

    /* Retrieve the service instance id */
    results = jsonObj['results'][0];
    putUrl = results["url"];
    service_instance = results['service-instance'];
    resource_version = service_instance['resource-version'];
    executor.logger.info("After Parse service_instance " + JSON.stringify(service_instance, null, 4) + "\n url "
            + putUrl + "\n Service instace Id " + SERVICE_INSTANCE_ID);

    if (result == "") {
        aaiUpdateResult = false;
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
    aaiUpdateResult = false;
}

/* BBS Policy updates orchestration status of {{bbs-cfs-service-instance-UUID}} [ active --> assigned ] */
var putUpddateServInstance;
putUpddateServInstance = service_instance;
if (newState == 'inService') {
    putUpddateServInstance['orchestration-status'] = "active";
} else {
    putUpddateServInstance['orchestration-status'] = "inActive";
}
try {
    if (aaiUpdateResult == true) {
        executor.logger.info("ready to put After Parse " + JSON.stringify(putUpddateServInstance, null, 4));
        var urlPut = HTTP_PROTOCOL + AAI_URL + putUrl + "?resource_version=" + resource_version;
        result = client.httpRequest(urlPut, "PUT", JSON.stringify(putUpddateServInstance), AAI_USERNAME, AAI_PASSWORD,
                "application/json");
        executor.logger.info("Data received From " + urlPut + " " + result);
        /* If failure to retrieve data proceed to Failure */
        if (result != "") {
            aaiUpdateResult = false;
        }
    }
} catch (err) {
    executor.logger.info("Failed to retrieve data " + err);
    aaiUpdateResult = false;
}

if (aaiUpdateResult == true) {
    executor.outFields.put("result", "SUCCCESS");
} else {
    executor.outFields.put("result", "FAILURE");
}

executor.logger.info(executor.outFields);
executor.logger.info("End Execution ServiceUpdateStateCpeAuthTask.js");

true;

LE
result: SUCCESS

/root> 
/root> #========> Create Policy (1)
/root> policy create name=ONTRegistrationPolicy template=Freestyle firstState=INIT
result: SUCCESS

/root> 
/root> policy state create name=ONTRegistrationPolicy stateName=NOMADIC_ONT_REG_SUCCESS triggerName=END_CONTROL_LOOP defaultTaskName=NomadicEventSuccessTask
result: SUCCESS

/root> policy state output create name=ONTRegistrationPolicy stateName=NOMADIC_ONT_REG_SUCCESS outputName=NomadicEventSuccessOutPut eventName=END_EVENT
result: SUCCESS

/root> policy state taskref create name=ONTRegistrationPolicy stateName=NOMADIC_ONT_REG_SUCCESS taskName=NomadicEventSuccessTask outputType=DIRECT outputName=NomadicEventSuccessOutPut
result: SUCCESS

/root> 
/root> #========> Create State (1.4)
/root> policy state create name=ONTRegistrationPolicy stateName=AAI_SERVICE_CREATE triggerName=AAI_SERVICE_CREATE defaultTaskName=AAIServiceCreateTask
result: SUCCESS

/root> 
/root> policy state output create name=ONTRegistrationPolicy stateName=AAI_SERVICE_CREATE outputName=AAIServiceCreateTaskOutput eventName=END_CONTROL_LOOP nextState=NOMADIC_ONT_REG_SUCCESS
result: SUCCESS

/root> policy state taskref create name=ONTRegistrationPolicy stateName=AAI_SERVICE_CREATE taskName=AAIServiceCreateTask outputType=DIRECT outputName=AAIServiceCreateTaskOutput
result: SUCCESS

/root> 
/root> policy state output create name=ONTRegistrationPolicy stateName=AAI_SERVICE_CREATE outputName=SdncResourceUpdateErrorLogOutput eventName=ERROR_LOG
result: SUCCESS

/root> policy state taskref create name=ONTRegistrationPolicy stateName=AAI_SERVICE_CREATE taskName=ErrorSdncResourceUpdateTaskLogTask outputType=DIRECT outputName=SdncResourceUpdateErrorLogOutput
result: SUCCESS

/root> 
/root> policy state contextref create name=ONTRegistrationPolicy stateName=AAI_SERVICE_CREATE albumName=NomadicONTContextAlbum
result: SUCCESS

/root> 
/root> policy state selecttasklogic create name=ONTRegistrationPolicy stateName=AAI_SERVICE_CREATE logicFlavour=JAVASCRIPT logic=LS
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 Huawei. All rights reserved.
 *  Modifications Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */
executor.logger.info("Begin Execution SU2orInitStateSelect.js");
executor.logger.info(executor.subject.id);
executor.logger.info(executor.inFields);

var result = null;

var attachmentPoint = executor.inFields.get("attachmentPoint");
var NomadicONTContext = executor.getContextAlbum("NomadicONTContextAlbum").get(
    attachmentPoint);

executor.logger.info(executor.inFields);

result = NomadicONTContext.get("result");

if (result == "SUCCESS") {
    executor.subject.getTaskKey("AAIServiceCreateTask").copyTo(executor.selectedTask);
} else {
    executor.subject.getTaskKey("SdncResourceUpdateErrorLogOutput").copyTo(
        executor.selectedTask);
    onsetFlag = executor.isFalse;
}

executor.logger.info("State Selected Task:" + executor.selectedTask);
executor.logger.info("End Execution SU2orInitStateSelect.js");

true;

LE
result: SUCCESS

/root> 
/root> 
/root> #========> Create State (1.3)
/root> policy state create name=ONTRegistrationPolicy stateName=SDNC_RES_UPDATE triggerName=SDNC_RESOURCE_UPDATE defaultTaskName=SdncResourceUpdateTask
result: SUCCESS

/root> 
/root> policy state output create name=ONTRegistrationPolicy stateName=SDNC_RES_UPDATE outputName=SdncResourceUpdateOutput eventName=AAI_SERVICE_CREATE nextState=AAI_SERVICE_CREATE
result: SUCCESS

/root> policy state taskref create name=ONTRegistrationPolicy stateName=SDNC_RES_UPDATE taskName=SdncResourceUpdateTask outputType=DIRECT outputName=SdncResourceUpdateOutput
result: SUCCESS

/root> 
/root> policy state output create name=ONTRegistrationPolicy stateName=SDNC_RES_UPDATE outputName=AAIServiceAssignedErrorLogOutput eventName=ERROR_LOG
result: SUCCESS

/root> policy state taskref create name=ONTRegistrationPolicy stateName=SDNC_RES_UPDATE taskName=ErrorAAIServiceAssignedLogTask outputType=DIRECT outputName=AAIServiceAssignedErrorLogOutput
result: SUCCESS

/root> 
/root> policy state contextref create name=ONTRegistrationPolicy stateName=SDNC_RES_UPDATE albumName=NomadicONTContextAlbum
result: SUCCESS

/root> 
/root> policy state selecttasklogic create name=ONTRegistrationPolicy stateName=SDNC_RES_UPDATE logicFlavour=JAVASCRIPT logic=LS
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 Huawei. All rights reserved.
 *  Modifications Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */
executor.logger.info("Begin Execution RUorInitStateSelect.js");
executor.logger.info(executor.subject.id);
executor.logger.info(executor.inFields);

var result = null;

var attachmentPoint = executor.inFields.get("attachmentPoint");
var NomadicONTContext = executor.getContextAlbum("NomadicONTContextAlbum").get(
    attachmentPoint);

result = NomadicONTContext.get("result");

if (result == "SUCCESS") {
    executor.subject.getTaskKey("SdncResourceUpdateTask").copyTo(executor.selectedTask);
} else {
    executor.subject.getTaskKey("ErrorAAIServiceAssignedLogTask").copyTo(
        executor.selectedTask);
    onsetFlag = executor.isFalse;
}

executor.logger.info("State Selected Task:" + executor.selectedTask);
executor.logger.info("End Execution RUorInitStateSelect.js");

true;

LE
result: SUCCESS

/root> 
/root> 
/root> 
/root> #========> Create State (1.2)
/root> policy state create name=ONTRegistrationPolicy stateName=AAI_SERVICE_ASSIGN triggerName=AAI_SERVICE_ASSIGNED defaultTaskName=AAIServiceAssignedTask
result: SUCCESS

/root> 
/root> policy state output create name=ONTRegistrationPolicy stateName=AAI_SERVICE_ASSIGN outputName=AAIServiceAssignedOutput eventName=SDNC_RESOURCE_UPDATE nextState=SDNC_RES_UPDATE
result: SUCCESS

/root> policy state taskref create name=ONTRegistrationPolicy stateName=AAI_SERVICE_ASSIGN taskName=AAIServiceAssignedTask outputType=DIRECT outputName=AAIServiceAssignedOutput
result: SUCCESS

/root> 
/root> 
/root> 
/root> 
/root> 
/root> #========> Create State (1.1)
/root> policy state create name=ONTRegistrationPolicy stateName=INIT triggerName=Nomadic_ONT defaultTaskName=GetBBSCloseLoopEventTask
result: SUCCESS

/root> policy state output create name=ONTRegistrationPolicy stateName=INIT outputName=BBSCloseLoopEventOutPut eventName=AAI_SERVICE_ASSIGNED nextState=AAI_SERVICE_ASSIGN
result: SUCCESS

/root> policy state taskref create name=ONTRegistrationPolicy stateName=INIT taskName=GetBBSCloseLoopEventTask outputType=DIRECT outputName=BBSCloseLoopEventOutPut
result: SUCCESS

/root> 
/root> 
/root> 
/root> #========> Create Policy (2)
/root> policy create name=CPEAuthenticationPolicy template=Freestyle firstState=INIT
result: SUCCESS

/root> 
/root> 
/root> #========> Create State (2.1)
/root> policy state create name=CPEAuthenticationPolicy stateName=INIT triggerName=CPE_Authentication defaultTaskName=ServiceUpdateStateCpeAuthTask
result: SUCCESS

/root> policy state output create name=CPEAuthenticationPolicy stateName=INIT outputName=ServiceUpdateCpeAuthOutPut eventName=AAI_CPE_AUTH_UPDATE
result: SUCCESS

/root> policy state taskref create name=CPEAuthenticationPolicy stateName=INIT taskName=ServiceUpdateStateCpeAuthTask outputType=DIRECT outputName=ServiceUpdateCpeAuthOutPut
result: SUCCESS

/root> 
/root> validate
result: SUCCESS
{
  "name": "NomadicONTPolicyModel",
  "version": "1.0.0"
}
***validation of model successful***

/root> 