import groovy.json.*
import groovyx.net.*
import groovyx.net.http.*
import static groovy.json.JsonOutput.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.activiti.engine.delegate.BpmnError
import com.kronos.activiti.utils.CommonUtil

LOGGER = LoggerFactory.getLogger("com.kronos.pre_multi_service_upgrade_deployer.Fetch_DependentService_Deployment_Detail")

def process_info = execution.getVariable("user_process_info")

CommonUtil commonUtil = new CommonUtil(LOGGER, execution)
if (commonUtil.isAccessTokenExpired()) {
  commonUtil.getAccessToken()
}
LOGGER.info("Starting execution Map Creation for $process_info")

def exec_map = [: ]

String webproxy_hostname = execution.getVariable("webproxy_hostname")
int webproxy_port = execution.getVariable("webproxy_port").toInteger()
//Get rightscale url & api version
String selfservice_url = execution.getVariable("selfservice_url")
String api_version_selfservice = execution.getVariable("api_version_selfservice")
String rightscale_url = execution.getVariable("rightscale_url")
String rs_tags_path = execution.getVariable("rs_tags_path")
String api_version_cloudmgt = execution.getVariable("api_version_cloudmgt")

def dependent_services = execution.getVariable("service_exec_map").get("dependent_services")
execution.removeVariable('is_dr_exists')
execution.removeVariable('is_dr_notification_text')


if (!dependent_services) {
    LOGGER.info("No Dependent service found.")
    execution.setVariable('is_dependent_services_exists', false)
    return
}

try {
    LOGGER.info("==============================================================")
    dependent_services = new JsonSlurper().parseText(dependent_services)
    LOGGER.info("akhilesh dependent services info: " + dependent_services)

    def service_type = execution.getVariable("service_exec_map").get("service_type")
    if (service_type && (service_type.equals('api-gtw-mgt'))) {
        exec_map.put('rmp', dependent_services.get('rmp').get('exec_id'))
        if (dependent_services.get('is_dr_exists') == true) {
            execution.setVariable('is_dr_exists', true)
            exec_map.put('dsms_dr', dependent_services.get('dsms_dr').get('exec_id'))
        } else {
            execution.setVariable('is_dr_exists', false)
            execution.setVariable('is_dr_notification_text', 'No disaster recovery site has been detected for API Gateway DSMS cluster.')
        }
  }

    if (service_type && (service_type.equals('ath-odj'))) {
        if (dependent_services.get('is_dr_exists') == true) {
            dependent_services_map = dependent_services.get('dj_dr_exec_map')
            execution.setVariable('is_dr_exists', true)
            exec_id = dependent_services_map.get('exec_id')
            exec_map.put('opendj_dr', dependent_services.get('dj_dr_exec_map').get('exec_id'))
        } else {
            execution.setVariable('is_dr_exists', false)
        }
    }
    if (service_type && (service_type.equals('idp-odj'))) {
        if (dependent_services.get('is_dr_exists') == true) {
            execution.setVariable('is_dr_exists', true)
            exec_map.put('idpdj_dr', dependent_services.get('dj_dr_exec_map').get('exec_id'))
        } else {
            execution.setVariable('is_dr_exists', false)
        }
    }

    def http = new HTTPBuilder(selfservice_url)
    http.setProxy(webproxy_hostname, webproxy_port, 'https')
    http.setProxy(webproxy_hostname, webproxy_port, 'http')
    http.parser."application/json" = {
        resp -> def data = new InputStreamReader(resp.getEntity().getContent(), "UTF-8");
        def result = data.text

        try {
            result = new JsonSlurper().parseText(result)
        } catch(Exception ex) {
            LOGGER.error("warn: custom parser caught exception. " + ex.getMessage())
        }
        return result
    }
    LOGGER.info("AKHILESH_exec_map : $exec_map")
    for (entry in exec_map) {
        deployment_map = [: ]
        String execution_id = "$entry.value"
        String deployment_key = "$entry.key"
        LOGGER.info("fetch deployment detail for $deployment_key with execution id $execution_id")
        response = http.request(groovyx.net.http.Method.GET, groovyx.net.http.ContentType.JSON) {
            uri.path = '/api/manager/projects/' + rightscale_projectId + '/executions/' + execution_id
            uri.query = ['view': 'expanded']
            headers = ['X_API_VERSION': api_version_selfservice, 'Accept': 'application/json', 'Authorization': 'Bearer ' + execution.getVariable('access_token')]
            response.success = {
                resp, json -> LOGGER.info("Sucessfully fetched blue deployement details. $process_info")
                LOGGER.info("Response For Dependent Service $deployment_key >> $json")
                return json
            }
            response.failure = {
                resp, json -> LOGGER.error("Error Occured while fetching blue with execution id >> $execution_id HTTP Status => $resp.statusLine  Response body => $json $process_info")
                throw new BpmnError("Error Occured while fetching blue with execution id >> $execution_id HTTP Status => $resp.statusLine  Response body => $json")
            }
        }
        LOGGER.info("====================================================================================================")
        if (response) {
            LOGGER.info("Dependent service $deployment_key Data Fetched Success>>" + response.status)
            LOGGER.info("===================================After response.status =======================================")
            execution.setVariable("is_upgradable", true)
            deployment_map << [status: response.status]
            deployment_map << [self: response.href]
            deployment_map << [id: response.id]
            deployment_map << [deployment_url: response.deployment]
            deployment_map << [launched_at: response.timestamps.launched_at]
            deployment_map << [name: response.launched_from_summary.value.name]
            LOGGER.info("===================================After deployment_map =======================================")
            LOGGER.info("deployment_map : $deployment_map")
            def service_name_local = dependent_services.get(deployment_key).get("service_name")
            LOGGER.info("===================================After service_name =======================================")
            def service_version_local = dependent_services.get(deployment_key).get("service_version")
            LOGGER.info("===================================After service_version =======================================")
            deployment_map.put('service_name', service_name_local)
            deployment_map.put('service_version', service_version_local)
            execution.removeVariable(deployment_key)
            execution.setVariable(deployment_key, deployment_map)

            LOGGER.info("$deployment_key Execution Map>>" + deployment_map)
            LOGGER.info("===================================After final =======================================")
        }
    }
} catch(Exception ex) {
    LOGGER.error("Error Occured while creating blue execution map. $process_info" + ex.getMessage())
    throw new BpmnError("Error Occured while creating blue execution map. Executon_id: $execution_id $process_info " + ex.getMessage())
} 

Groovy online compiler

Write, Run & Share Groovy code online using OneCompiler's Groovy online compiler for free. It's one of the robust, feature-rich online compilers for Groovy language, running the latest Groovy version 2.6. Getting started with the OneCompiler's Groovy editor is easy and fast. The editor shows sample boilerplate code when you choose language as Groovy and start coding.

Read inputs from stdin

OneCompiler's Groovy online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Groovy program which takes name as input and prints hello message with your name.

def name = System.in.newReader().readLine()
println "Hello " + name

About Groovy

Groovy is an object-oriented programming language based on java. Apache Groovy is a dynamic and agile language which is similar to Python, Ruby, Smalltalk etc.

Key Features

  • It's not a replacement for java but it's an enhancer to Java with extra features like DSL support, dynamic typing, closures etc.
  • Accepts Java code as it extends JDK
  • Greater flexibility
  • Concise and much simpler compared to Java
  • Can be used as both programming language and scripting language.

Syntax help

Data Types

Data typeDescriptionRange
StringTo represent text literalsNA
charTo represent single character literalNA
intTo represent whole numbers-2,147,483,648 to 2,147,483,647
shortTo represent short numbers-32,768 to 32,767
longTo represent long numbers-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
doubleTo represent 64 bit floating point numbers4.94065645841246544e-324d to 1.79769313486231570e+308d
floatTo represent 32 bit floating point numbers1.40129846432481707e-45 to 3.40282346638528860e+38
byteTo represent byte value-128 to 127
booleanTo represent boolean values either true or falseTrue or False

Variables

You can define variables in two ways

Syntax:

data-type variable-name;

[or]

def variable-name;

Loops

0.upto(n) {println "$it"}

or

n.times{println "$it"}

where n is the number of loops and 0 specifies the starting index

Decision-Making

1. If / Nested-If / If-Else:

When ever you want to perform a set of operations based on a condition or set of conditions, then If / Nested-If / If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(conditional-expression) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

List

List allows you to store ordered collection of data values.

Example:

def mylist = [1,2,3,4,5];
List MethodsDescription
size()To find size of elements
sort()To sort the elements
add()To append new value at the end
contains()Returns true if this List contains requested value.
get()Returns the element of the list at the definite position
pop()To remove the last item from the List
isEmpty()Returns true if List contains no elements
minus()This allows you to exclude few specified elements from the elements of the original
plus()This allows you to add few specified elements to the elements of the original
remove()To remove the element present at the specific position
reverse()To reverse the elements of the original List and creates new list