Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Getter and setter

//class Human{
    //public String name
    //static void main(String[] a){
        //Human h = new Human()
        //println(h.name="Vidya")
    //}
//}

class Human{
    private String name
    def setName(String n){
        name = n
    } 
    String getName(){
        return name
    }
    static void main(String[] a){
        Human h = new Human()
        h.setName("Vidya")
        println(h.getName())
    }
}

getter and setter Methods

public class StartExecution {
    static void main(String[] args) {
        //def data = context.getStringVariable("data")
        def data = '{"users": [{ "username":"user1", "firstName":"One", "lastName":"User", "email":"[email protected]", "role":1}, { "username":"user2", "firstName":"Two", "lastName":"User", "email":"[email protected]", "role":1},{ "username":"user3", "firstName":"Three", "lastName":"User", "email":"[email protected]", "role":1}]}'
        def list = new groovy.json.JsonSlurper().parseText(data)
 	 
        for(int i = 0;i<list.users.size();i++) {
            def uName = list.users[i].username
            def fName = list.users[i].firstName
            def lName = list.users[i].lastName
            def e_mail = list.users[i].email
            def rol = list.users[i].role
            context.logInfo(uName + ': ' + fName + ' ' + lName + ' - ' + e_mail + ' - ' + rol)
        }
        return "Total Records Parsed: " + list.users.size() + " Job Owner: " +  jobDetail.getOwner().getName()
  
        UserInfo uinf = new UserInfo()
        uinf.setuserID("1")
        uinf.setfirstName("Jigar")
        uinf.setlastName("Baraiya")
        uinf.seteMail("[email protected]")
        uinf.setroleID("123")
        
        println(uinf.getuserID())
        println(uinf.getfirstName())
        println(uinf.getlastName())
        println(uinf.geteMail())
        println(uinf.getroleID())
    }
}

public class UserInfo { 
   private String userID
   private String firstName
   private String lastName
   private String eMail
   private String roleID
    
   public void setuserID(String uID) {
      userID = uID
   }
    
   public void setfirstName(String fName) {
      firstName = fName
   }
    
    public void setlastName(String lName) {
      lastName = lName
   }
   public void seteMail(String eml) {
      eMail = eml
   }
    
    public void setroleID(String rol) {
      roleID = rol
   }
    
   public String getuserID() {
      return this.userID
   }
    
   public String getfirstName() {
      return this.firstName
   }
   
   public String getlastName() {
      return this.lastName
   }
    
    public String geteMail() {
      return this.eMail
   }
    
    public String getroleID() {
      return this.roleID
   }
}

Code without class & obj.

def sample(){
    def x = 10
    def z = "Vidya"
    def name = "'Vidya" + "Awesome'";
    println x
    println name
    println(z.length())
    println(z.next())
}
sample()
def test(int a, int b){
    def c = a + b
    println c
}
test(6,2)

ptb2

class QuadEq {
    static void main (String[] args){
        def a = System.in.newReader().readLine()
        def b = System.in.newReader().readLine()
        def c = System.in.newReader().readLine()
        print "${a} ${b} ${c}"
    }
}
        
        /*if (a == 0){
            print "x = " +  -c/b 
        }
        
        def delta = Math.pow(b,2) - 4*a*c
        
        if (delta < 0){
            print "no real root"
        }
        else if (delta == 0){
            def x = -b/(2*a)
            print "x1 = x2 = " +x
            
        }
        else{
        def x1 = ((-b + Math.sqrt(delta))/(2*a))
        def x2 = ((-b - Math.sqrt(delta))/(2*a))
        
        print "x1 = " +x1 + "  " + "x2 = " +x2
        }

    }
}
*/

hanged example

// def Function(x, List y) {
//     multres = 1;
//     for (i = 0; i<y.size(); i++) {
//         multres *= y.get(i);
//         println multres
//     }
//     multres = 1;
//     y.each {multres = it * multres}
//     println multres;
// }

def Mult (y, i) {
    while(i >= 1) {
        println i;
        // println y.get(0);
        //println y[i-1];
        //y[i-1] = y.get(i-1) * y.get(i);
        //y[i].remove();
        //i--;
    }
}

def x = 1;
List y = [1, 2, 3];

public void main() {
    //Function(2, [1, 2, 3]);
    y = [1, 2, 3, 4];
    i = y.size;
    Mult(y, i);
}

main();
//
//
// int mul(int a, int b)
// {
//     if (b == 1)
//         return a;
//     else
//         return a + mul(a, b - 1);
// }

Execute Groovy Online

def a="aa"
println('version:${a}, ${a.getClass() }');

Execute Groovy Online

def sourceKey = ["Winnipeg","Patriots","Cowboys"]

if(sourceKey == "Cowboys") {
        print "Test"
    }   
     
if (sourceKey == "Patriots") {
        print "Test Panels"
    } 
if (sourceKey == "Winnipeg, Patriots, Cowboys") {
        print "Correct"
    }
else {
        print "Good code"
    }


/*def stringName = 'Testing, testing 00, testing'


def stringNew = stringName.tokenize(",")

def nwName = [] as Set

stringName.each {it
nwName << stringNew[0]
}
print nwName*/

/*def stringName = 'Testing, testing 00, testing'


/*def stringNew = stringName.tokenize(",")

/*def nwName = [] as Set

/*stringNew.each {it
/*    nwName << stringNew[0]
/*} 
/*print nwName


/*maidenName = "Patient"
/*aliasName = "One"

/*newName = [maidenName, aliasName]

print newName*/

/*(1..7).each {
    print("Number {it}") /*{it} Is code to iterate through the list it references....
}*/
/*['Dog', 'Cat', 'Horse'].each {animalName ->
    print "${animalName}" /*The point of this code is to show how I didn't use {it} as a variable to the list, I assigned a variable on the fly-setting it
}*/ 
['Dog','Cat','Horse '].eachWithIndex {animalName, index ->
    print " ${index+1}. Animal:${animalName}"
} /*Here I'm setting the temp variable for the index, also when you need to output more than one value, write in code that increments on the temp variable that I'm using as the temp variable for the index*/

/* In GroovyScript, elif is not within it's logic, I'd need to use multiple IF statements*/
newList = [0,1,2,3]
newList.add(4)

if (newList == "") { 
print(newList)
    } 
if (newList == 2) {
print("Dos")    
}
else
{
print("No Data")    
    }


Mothers_Maiden = ["Test", "Testing", "Test", "Testing", "Test", "Testing"]

newMaiden = Mothers_Maiden as Set

print newMaiden

testName = ["One","One","Two","Two"] as Set
print testName

testIng = ["Three","Three","Four","Four"] .toSet()
print testIng



def kList = []  

def oList = [1,2,3,4,4]

kList = oList /*Here I could select an element of the list by using an INDEX []..I could use to Set here as well*/ 
print kList  /*Here I've used as Set to ensure that I get unique-non duplicated values.. I could use INDEX as well*/







test

print "It's groovy, man".drop(15)

Execute Groovy Online

import requests
// import traceback
// import datetime
// import time
//from elasticsearch import helpers, Elasticsearch

auth_token ='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8va2Fycm9zdGVjaC5pbyIsInN1YiI6ImRjYjA5YmQzLTFmZjAtNGY5ZC05ZGYzLWNjMzk5YWJmYzgwZiIsInBlcnNvbklkIjpudWxsLCJpYXQiOjE1MzE4MTk5MDgsImV4cCI6MTU2MzM1NjAwNywiYXVkIjoiMDg0NGM3NzY1MzBhYzRkYTA3ZmRiYmUzZTU4OGVlNjQyYTEzNjU3ZSIsInNjb3BlIjpbIio6RWR1bG9nOkFkbWluIiwiKjpLYXJyb3M6QWRtaW4iXSwiYXV0aG9yaXphdGlvbiI6eyJncm91cHMiOlt7Imdyb3VwTmFtZSI6IkVkdWxvZyIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfSx7Imdyb3VwTmFtZSI6IkRldmVsb3BlciIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfSx7Imdyb3VwTmFtZSI6IkthcnJvcyIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfSx7Imdyb3VwTmFtZSI6IlNjaG9vbCIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfSx7Imdyb3VwTmFtZSI6IlBhcmVudCIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfSx7Imdyb3VwTmFtZSI6IlRlbmFudCIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfSx7Imdyb3VwTmFtZSI6IkRyaXZlciIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfV19fQ.OC_G1MsYmrbUKXgqGC8PRa5KUnL070DKCnTJMK-wzXo'

// hed = {
//     Authorization: 'Bearer ' + auth_token, 
//     ApiKey: '0844c776530ac4da07fdbbe3e588ee642a13657e'
// }

def migrateStudentAccessRequests() {
    	data = {}
	page = 0
	limit = 100
	while(true){
	 	GET_STUDENT_ACCESS_REQUESTS_URL='https://gateway-p01-demo.usw2.karrostech.net/api/v1/studentAccessRequests'
	response = requests.get(GET_STUDENT_ACCESS_REQUESTS_URL, json=data)
	print(data);   
	}
}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

Migrate student access requests

import requests
import traceback
import datetime
import time
from elasticsearch import helpers, Elasticsearch

auth_token ='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8va2Fycm9zdGVjaC5pbyIsInN1YiI6ImRjYjA5YmQzLTFmZjAtNGY5ZC05ZGYzLWNjMzk5YWJmYzgwZiIsInBlcnNvbklkIjpudWxsLCJpYXQiOjE1MzE4MTk5MDgsImV4cCI6MTU2MzM1NjAwNywiYXVkIjoiMDg0NGM3NzY1MzBhYzRkYTA3ZmRiYmUzZTU4OGVlNjQyYTEzNjU3ZSIsInNjb3BlIjpbIio6RWR1bG9nOkFkbWluIiwiKjpLYXJyb3M6QWRtaW4iXSwiYXV0aG9yaXphdGlvbiI6eyJncm91cHMiOlt7Imdyb3VwTmFtZSI6IkVkdWxvZyIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfSx7Imdyb3VwTmFtZSI6IkRldmVsb3BlciIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfSx7Imdyb3VwTmFtZSI6IkthcnJvcyIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfSx7Imdyb3VwTmFtZSI6IlNjaG9vbCIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfSx7Imdyb3VwTmFtZSI6IlBhcmVudCIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfSx7Imdyb3VwTmFtZSI6IlRlbmFudCIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfSx7Imdyb3VwTmFtZSI6IkRyaXZlciIsInJvbGVzIjpbIlN5c3RlbSBBZG1pbiJdfV19fQ.OC_G1MsYmrbUKXgqGC8PRa5KUnL070DKCnTJMK-wzXo'

hed = {'Authorization': 'Bearer ' + auth_token, 'ApiKey': '0844c776530ac4da07fdbbe3e588ee642a13657e'}

def migrateStudentAccessRequests():
	data = {}
	page = 0
	size = 100
	while True:
		print("page: %s, size: %s") %(page, size)
		GET_TENANT_URL = 'https://localhost:6543/api/v2.0old/tenants/search?page=%i&size=%i' %(page, size)
		CREATE_TENANT_URL = "https://localhost:6543/api/v2.0/tenants"
		response = requests.get(GET_TENANT_URL, json=data, headers=hed)
		tenantResponse = response.json()

		if not tenantResponse["content"]["data"]:
			break

		if not tenantResponse["serviceCode"] and tenantResponse["content"]["data"]:
			for tenant in tenantResponse["content"]["data"]:
				try:
					print('createing tenant with id: ' + tenant['id'])
					createTenantResponse = requests.post(CREATE_TENANT_URL, json=tenant, headers=hed)
					if createTenantResponse.status_code != 201 and createTenantResponse.status_code != 200:
						print('create tenant failed with status_code: ' + str(createTenantResponse.status_code))
					else:
						print('create tenant successed')
				except:
					print('An error occured when create tenant with id: ' + tenant['id'])
					traceback.print_exc()

			page += 1

def migrateSchoolsViaTenantService():
	page = 0
	size = 10000
	data = {}
	data["size"] = 10000
	GET_SCHOOL_URL = 'https://localhost:6543/api/v2.0old/schools/search?page=%i&size=%i' %(page, size)
	CREATE_SCHOOL_URL = "https://localhost:6543/api/v1/schools"
	print("start time")
	print(datetime.datetime.now())
	es = Elasticsearch('https://vpc-p01ase1dev-vppzojfv77kazi26fdojnrst6e.ap-southeast-1.es.amazonaws.com')
	while True:
		data["page"] = page
		GET_SCHOOL_URL = 'https://localhost:6543/api/v2.0old/schools/search?page=%i&size=%i' %(page, 10000)
		schoolResponse = requests.post(GET_SCHOOL_URL, json=data, headers=hed).json()

		if schoolResponse["serviceCode"] or not schoolResponse["schools"]:
			break

		for school in schoolResponse["schools"]:
			try:
				#print('createing school with id: ' + school['id'])
				createSchoolResponse = requests.post(CREATE_SCHOOL_URL, json=school, headers=hed)

				if createSchoolResponse.status_code != 201 and createSchoolResponse.status_code != 200:
					print('create school failed with status_code: ' + str(createSchoolResponse.status_code))
			#else:
			#	print('create school successed')
			except:
				print('An error occured when create school with id: ' + school['id'])
				traceback.print_exc()

		page += 1

	print("end time")
	print(datetime.datetime.now())

def transformSchoolAddress(school):
	if 'address' in school and school['address']:
		address = school['address']

		addresskeys = ['address1', 'address2', 'aptNo', 'country', 'city', 'state', 'postalCode']
		for key in addresskeys:
			if key in address and address[key]:
				school[key] = address[key]
			else:
				school[key] = None

		del school['address']

def transformSchoolDistrict(school):
	if 'districtId' in school and school['districtId'] and str(school['districtId']) == '':
		school['districtId'] = None

	if 'districtName' in school and school['districtName'] and str(school['districtName']) == '':
		school['districtId'] = None

def transformSchoolToSchoolIndex(school):
	school['_id'] = school['id']
	if( school['latitude'] and school['longitude']):
		school['location'] = ({'lat': school['latitude'], 'lon': school['longitude']})
	else:
		school['location'] = None

	del school['latitude']
	del school['longitude']

	if str(school['tenantId']) == "":
		school['tenantId'] = None

	if str(school['tenantName']) == "":
		school['tenantName'] = None

	currentTime = int(round(time.time() * 1000))

	if (not 'createdDatetime' in school) or (not school['createdDatetime']):
		school['createdDatetime'] = currentTime

	if (not 'updatedDatetime' in school) or (not school['updatedDatetime']):
		school['updatedDatetime'] = currentTime

	transformSchoolAddress(school)
	transformSchoolDistrict(school)

def migrateSchoolsDirectToElasticSearch():
	page = 0
	size = 10000
	data = {}
	data["size"] = 10000
	GET_SCHOOL_URL = 'https://localhost:6543/api/v2.0old/schools/search?page=%i&size=%i' %(page, size)
	CREATE_SCHOOL_URL = "https://localhost:6543/api/v1/schools"
	print("start time")
	print(datetime.datetime.now())
	es = Elasticsearch('https://vpc-p01ase1dev-vppzojfv77kazi26fdojnrst6e.ap-southeast-1.es.amazonaws.com')
	while True:
		data["page"] = page
		GET_SCHOOL_URL = 'https://localhost:6543/api/v2.0old/schools/search?page=%i&size=%i' %(page, 10000)
		schoolResponse = requests.post(GET_SCHOOL_URL, json=data, headers=hed).json()

		schools = schoolResponse["schools"]
		if schoolResponse["serviceCode"] or not schools:
			break

		try:
			for school in schools:
				transformSchoolToSchoolIndex(school)
			helpers.bulk(es, schools, index='school', doc_type='doc')
		except:
			print('An error occured when bulk create school')
			traceback.print_exc()
		page += 1

	print("end time")
	print(datetime.datetime.now())

migrateStudentAccessRequests()
# migrateSchoolsDirectToElasticSearch()

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.