Code Samples

class RunningExternalScripts {		
	def static os = System.getProperty('os.name')       // load system variables 											 
	def static Map dirCommandMap = ['Windows 7':'dir', 'UNIX':'ls', 'MAC OS X':'ls'] // create  a map	
	static void  printAllSystemVariables(){         // uncomment the line in main below if you want to run this
		System.getenv.each { println it }		// loop through each map and print each time
	}	
	static void runExternalCommandSimple(){
		 def proc = dirCommandMap[os].execute()		// key, value lookup based on key 'OS'
		 proc.waitForOrKill(1000)				// set a timeout on the command just in case
		 (proc.exitValue() !=0) ?  { print 'error occured in command' } : {}  // check exit code 
		 print proc.getText()					// read the buffer result and print
	}	
	public static void main (args ){
		runExternalCommandSimple()
//		printAllSystemVariables()
	}
}

Parallel Processing with Grovy

package parellelTest
@Grab(group='org.codehaus.gpars', module='gpars', version='0.12')
 
import groovyx.gpars.*
 
class TruncateTest {
	static Long parallelTime;
	static Long serialTime;
 
	static void truncateTable(tables ){
		def start = System.nanoTime();	
			tables.each{ table ->
				print ("TRUNCATE $table, " )
				sleep(500)
			}					
		def end = System.nanoTime();
		serialTime = end - start
		println("\n Serially: Nano seconds taken = " + serialTime  )
	}
 
	static void truncateTableParallel(tables ){
		def start = System.nanoTime();
		GParsPool.withPool(20) {				// use a pool of up to 20 threads 
			tables.eachParallel{ table ->		// loop thru the structure in parallel
				print ("TRUNCATE $table ,")		// do this stuff
				sleep(500)						// wait in parallel
			}			
		}
		def end = System.nanoTime();
		parallelTime = end - start
		println("\n Parallel: Nano seconds taken = " + parallelTime )
	}
 
	static main(args) {
		def haloTables = [ "OPERATOR_CONVERSATION_ID_SEQ",
                "PROBLEM_ID_SEQ",
                "CONTACT_DETAILS_ID_SEQ",
                "DELAYED_INSTRUCTION_ID_SEQ",
                "DELIVERY_DETAILS_ID_SEQ",
                "DSL_ORDER_NETWORK_CFG_ID_SEQ",
                "EVENT_ID_SEQ",
                "EXCEPTION_MONITOR_ITEM_ID_SEQ",
                "FOLLOW_UP_ACTIVITY_ID_SEQ",
                "CUSTOMER_CALL_ID_SEQ",
                "JEOPARDY_ID_SEQ",
                "NIM_RELEASE_ID_SEQ",
                "NOTE_ID_SEQ",
                "ORDER_BT_NOTES_ID_SEQ",
                "ORDER_AUDIT_ID_SEQ",
                "ORDER_FILTER_ID_SEQ",
                "ORDER_REFERRAL_ID_SEQ",
                "PHONE_LINE_ID_SEQ",
                "DIRECTORY_NUMBER_ALLOC_ID_SEQ",
                "REFERRAL_ID_SEQ",
                "SERVICE_ID_SEQ",
                "WLR_ADDRESS_ID_SEQ",
                "WLR_NEW_INSTALL_DETAILS_ID_SEQ",
                "WLR_ORDER_FEATURE_ID_SEQ",
                "REAPPOINTMENT_ID_SEQ",
                "EMGY_SERVICES_DETAIL_ID_SEQ",
                "DIR_ENTRY_DETAIL_ID_SEQ"]
		truncateTable(haloTables);
		truncateTableParallel(haloTables);
		println("Parallel is faster by " + (serialTime - parallelTime  ) / 1000000.0 + " mili seconds")
	}
 
}

Groovy Sql

import groovy.sql.Sql
 
// Just copy mysql-connector.jar in $GROOVY_HOME/lib and we
// use the MySql driver.
def sql = Sql.newInstance("jdbc:mysql://localhost/db", "user",
                          "password", "com.mysql.jdbc.Driver")
 
// Make sure we can update the records.
sql.resultSetConcurrency = java.sql.ResultSet.CONCUR_UPDATABLE
 
sql.eachRow("select * from articles where description like '%IN STOCK%'") {
    println "Change record with id ${it.id}"
    it.description = it.description.substring(0, it.description.indexOf('IN STOCK'))
}
 
println "Done."

Groovy Google+

import groovy.json.*
import java.text.SimpleDateFormat
 
class googleApi {
 
	static main(args) {
		// date format: 2011-09-09T08:34:07.000Z
		def sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
		// my top secret API key
		def myKey = "..."
		// that's the ID you'll find in your Google+ profile URL
		def myProfileId = "101854942952701192720"
		// and this is the URL of my activities
		https://www.googleapis.com/plus/v1/people/userId/activities/collection
		def myActivities = "https://www.googleapis.com/plus/v1/people/${myProfileId}/activities/public?key=${myKey}".toURL().text	
		// I simply parse the JSON payload
		def root = new JsonSlurper().parseText(myActivities)
		// I iterate over all the items, and print the date, the URL of the post, and the title
		println 'Getting your google+ list '
		println root.title
		root.items.each {
			println "${sdf.parse(it.published)} - ${it.url} - ${it.title.replaceAll(/\s+/, ' ')}"
		}
	}
 
}

Parallel Sql

	def orderTypes = ['WLR', 'NVN', 'DSL']
			def orderTotals = ['WLR' : [:], 'NVN' : [:], 'DSL': [:]]
 
			println ("Getting orders for $fromDate to $toDate ");
			def sql = Sql.newInstance(  db['pilotdev'] ,'username','password', 'oracle.jdbc.driver.OracleDriver' );
			if ( sql ){
				GParsPool.withPool(3) {
					orderTypes.eachParallel{
						def result = orderTotals[it];
						sql.eachRow ("select parent_order_type_code, to_char(order_received_date, 'YYYY-MM-DD') as receviedDate , count(1) as count " +
								" from penfold_owner.orders" +
								" where parent_order_type_code = '$it'" +
								" and order_received_date >= to_date('$fromDate','YYYY-MM-DD')" +
								" and order_received_date  < to_date('$toDate','YYYY-MM-DD')" +
								" group by parent_order_type_code, to_char(order_received_date, 'YYYY-MM-DD')  "){  
									//println ("$it.PARENT_ORDER_TYPE_CODE $it.receviedDate $it.count  ")  
									result.put("$it.receviedDate", "$it.count");						 }
					}
				}
				orderTotals.each{
					println it;
				}

Scp

import groovy.grape.Grape;
 
Grape.grab(group:"org.apache.ant", module:"ant-jsch", version:"1.8.1", classLoader:this.class.classLoader.rootLoader)
Grape.grab(group:"com.jcraft", module:"jsch", version:"0.1.42", classLoader:this.class.classLoader.rootLoader)
 
 
def ant = new AntBuilder()
ant.scp( file:"appmon@tin.sns.sky.com:/monitor/stats/production/20110921/production-halo-diamondquartz-20110921.csv",
	todir: "C:/Users/Richard/workspace_extjs/testPlay/dropbox/",
	verbose:true,
	password:"insert pw",
	trust: true,)
}
 
learning_groovy_course.txt · Last modified: 2011/09/22 05:13 by root
 
RSS - 200 © CrosswireDigitialMedia Ltd