SlideShare a Scribd company logo
1 of 26
Download to read offline
Open Source GIS

Geographic scripting in uDig - halfway
    between user and developer
  Geoinformation Research Group, Department of Geography
                   University of Potsdam
                        March 2013




                    The scripting console
                        Tutor: Andrea Antonello




    ydroloGIS             nvironmental                 ngineering
 HydroloGIS S.r.l. - Via Siemens, 19 - 39100 Bolzano   www.hydrologis.com
The Geoscript editor




Scritping is one of the powerful things in GIS. Non developers have the

possibility to create great automatisations through it.


uDig's scripting console is based on the groovy java scripting language.


The geoscript geographic scripting engine can be used from within uDig.
Open the console

Two icons can be used to open the scripting editor: one for creating a new

empty script and one to open an existing script.
Let's create a new one. The user will be prompted to save the new script to

file and an empty editor is opened.




There are a few tool inside the editor, needed to start and stop scripts, or set

the heap memory allowed to be used by a script or enable logging.
Script away, with command completion and syntax coloring

Inside the editor some basic command completion is available. For geoscript

objects, as for example the widely use Geometry:
but also for methods, as for example the fromWKT, a handy way to create

geometries on the fly:
The base language: be Groovy!




In order to be able exploit 100% the console and scripting engine, it is

mandatory to get a good insight of the base language that can be used in the

console.


Before we start with the geo part, we will investigate a bit groovy.


Let's create a new script to do so. We should find ourself in front of a nice

empty editor.
Writing strings

To run your first script, simply write the following in the editor

 // write a string
 println "This is a string"



and push the play button.


The result should be the following inside the console window:

 Process started: 2013-02-10 18:02:03

 This is a string

 Process finished: 2013-02-10 18:02:04



The script simply prints the string in the console. It also gives information

about the start and end timestamps of the script execution.


Note that the editor executes only the selected text inside the editor. If

nothing is selected, all of it is used.
Also more complex strings can be used, by surrounding text with triple

quotes:

 // write a complex string
 println """Inside triple quotes

 you can

                                   do almost anything.

     It is kind of an advanced string!"""



Select only the second part and see if it is executed properly.
Variables




// define variables

// a string
def name = "Luis"
// a number
def age = 25

/*
 * insert the variables into a string template
 * through the use of ${}
 */
def myTemplate1 = "Hi, my name is ${name} and I'm ${age}."
println myTemplate1

// strings and numbers can also be concatenated through the + sign
def myTemplate2 = "Hi, my name is " + name + " and I'm " + age + "."
println myTemplate2
Lists




// working with lists

// create a list of strings
def list = ["Merano", "Bolzano", "Trento"];
println list;

// how to access the elements?
println "The elements start at position 0: " + list[0]

// how to add an element to the list?
list << "Potsdam"
println list;

// how to remove an element from the list?

// by object?
list.remove("Potsdam")
println list;

// better by index
list.remove(0)
println list;
Lists magic - part 1




// lists magic - part 1

def list = ["Merano", "Bolzano", "Trento"];
// to loop over a list the default 'it' can be used
list.each {
        println it
}

// ...or your very own variable...
list.each{ myVar ->
    println "This a town: " + myVar
}

// ...or you can use an index, too
list.eachWithIndex{myVar, i ->
    println "${myVar} is town N.${i}"
}
Lists magic - part 2




// lists magic - part 2

def list = ["Merano", "Bolzano", "Trento"];
println "This is the original list: " + list


// lists can be sorted
list.sort();
println "This is the sorted list: " + list


// and reverse sorted
def revList = list.reverse();


// note   that while sort changes the original list, reverse makes a copy
println   "This is list after the sorting: " + list
println   "This is reverse list: " + revList
println   "This is list after the reverse sorting: " + list
Lists magic - part 3




// lists magic - part 3

// concatenate list
def abc = ["a", "b", "c"]
def cde = ["c", "d", "e"]
def newabcde = abc + cde
println newabcde


// through 'join' the list can be concatenated to one single string
println newabcde.join(",")
println newabcde.join(" | ")


// if we are talking about numbers, some functions apply
def nums = [1.0, 2, 3.5]
println nums.max()
println nums.min()
println nums.sum()
Lists magic - part 4




// lists magic - part 4

// modify each element of the list with collect
def abc = ["a", "b", "c"]
println "Original abc: " + abc
abc = abc.collect{
    it += " is a letter"
}
println "Modified abc: " + abc


// flatten nested lists
def abc = ["a", "b", "c"]
def cde = ["c", "d", "e"]
abc << cde
println abc
println abc.flatten()
Maps (Hash)



Groovy speaking a Map is a container of key and value pairs.

 // working with maps

 // create a map
 //                       key1:value1, key2:value2, ...
 def townsProvinceMap = [merano:"BZ", bolzano:"BZ", trento:"TN"]
 println townsProvinceMap

 // ways of accessing the values of a map

 // implicit
 println townsProvinceMap.merano
 // the "array" way
 println townsProvinceMap["merano"]
 // through the "getter"
 println townsProvinceMap.get("merano")

 // ways to add an element
 // implicit
 townsProvinceMap.lagundo = "BZ"
 println townsProvinceMap
 // through the put method
 townsProvinceMap.put("Postdam", "BR")
 println townsProvinceMap
Maps magic




// maps magic

def townsProvinceMap = [merano:"BZ", bolzano:"BZ", trento:"TN"]
// iterate the thing with the default value...
townsProvinceMap.each{
        println it
}

// ...or with key and value separated...
townsProvinceMap.each{
        println "${it.key} is in province of ${it.value}"
}

// ...or with own vars
townsProvinceMap.each{key, value ->
    println "${key} is in province of ${value}"
}
Ranges

Range can be seen at first as a sequence, but there is much more behind it.

 // working with ranges

 // create a range
 def range = 1..3

 // do some iterations
 range.each{
         println it
 }
 range.each{
         println "what?"
 }

 // and what about dates?
 def now = new Date();
 def nextWeek = now + 7;
 (now..nextWeek).each{
     println it
 }

 // since ranges have a from, to and size...
 println "A range from " + range.from + " to " + range.to + " of size " + range.size()
 // ...you can use them in for loops...
 for (i in 1..3){
         println "step number: ${i}"
 }
 // ...which ovbiously could be done like the following
 (1..3).each{
         println "closure step number: ${it}"
 }
Groovy: working with files & filesystem
Groovy allows to access the OS-environment and read the filesystem.

 // working with the filesystem

 // get system info
 System.env.each{ println it}
 // get the home folder
 def userHome = System.getenv("HOME")
 println userHome

 // list a folder's content
 def home = new File(userHome)
 println "The contents of " + home.absolutePath + " are:"
 home.eachFile{ file ->
     println "t" + file
 }
 // list only folders
 println "...of which folders:"
 home.eachDir{ dir ->
     println "t" + dir
 }
 // list only files
 println "...of which files:"
 home.eachFile{ file ->
     if(file.isFile())
         println "t" + file
 }
 // recursive list content
 println "Recursive folders content:"
 home.eachDirRecurse{ dir ->
     println "t" + dir
 }
Reading Files




// reading files

// start with creating a new file to be read afterwards
def newFile = new File(System.getenv("HOME") + "/testFileToBeRemoved.txt");

// one way to writ text to file
newFile.write("""A new header.
A new testline.
A second testline.
""")

// read the file line by line
newFile.eachLine{ line, index ->
        println "line " + index + ". " + line
}

// read the file into a string variable
def content = newFile.text
println content
Writing Files




// writing files

def file = new File(System.getenv("HOME") + "/testFileToBeRemoved.txt");
println file.text
// append some content
file << "Some text after the last line is appended!"
println file.text

// merge files
def file2 = new File(file.absolutePath + "2")
file2.write("Content of file 2");
println file2.text
def mergedFile = new File(file.absolutePath + "_merged")
mergedFile << file.text
mergedFile << file2.text
println "nThe merged file:"
println mergedFile.text

// delete the files
file.delete()
file2.delete()
mergedFile.delete()
Reading CSV Files




// read values from a csv file

// create a sample csv file
def file = new File(System.getenv("HOME") + "/sample.csv");
file.write("""# id, lat, lon, elev
1, 11.0, 46.0, 250

2, 11.1, 46.1, 251
3, 11.2, 46.2, 252
""")

println file.text

// read the csv values
def recordsList = []
file.eachLine{
        if(it.trim().length() == 0) {
                 println "Empty line hit."
        } else if(it.startsWith("#")) {
                 println "Comment line hit."
        } else {
                 def lineSplit = it.split(",")
                 println "Values: ${lineSplit[0]}, ${lineSplit[1]}, ${lineSplit[2]}, ${lineSplit[3]}"
        }
}
Groovy: Data structures for complex scripts


// working with data structures

// create a data structure
class Record {
        def id
        def lat
        def lon
        def elev

        public String toString(){
                "Values: [${id}, ${lat}, ${lon}, ${elev}]"
        }
}

// read the csv into a list of records
def file = new File(System.getenv("HOME") + "/sample.csv");
def recordsList = []
file.eachLine{
        if(it.trim().length() > 0 && !it.startsWith("#")) {
                def lineSplit = it.split(",")
                def record = new Record()
                record.id = lineSplit[0]
                record.lat = lineSplit[1]
                record.lon = lineSplit[2]
                record.elev = lineSplit[3]

                recordsList << record
        }
}
println recordsList
Groovy: most important conditions and loops
If-then-else:

 def x = false
 def y = false

 if ( x ) {
     x = false
 } else {
     y = true
 }



Ternary operator:

 def y = 5
 def x = (y > 1) ? "worked" : "failed"



While loop:

 def x = 0
 def y = 5

 while ( y-- > 0 ) {
     x++
 }
For loop:

 for (int i = 0; i < 5; i++) {
     ...
 }

 def x = 0
 for ( i in 0..9 ) {
     x += i
 }

 x = 0
 for ( i in [0, 1, 2, 3, 4] ) {
     x += i
 }



Loop with closures:

 def stringList = [ "java", "perl", "python", "ruby", "c#", "cobol",
                    "groovy", "jython", "smalltalk", "prolog", "m", "yacc" ];

 stringList.each() {
     print " ${it}"
 }
This work is released under Creative Commons Attribution Share
Alike (CC-BY-SA)

Much of the knowledge needed to create this training material has
been produced by the sparkling knights of the GeoTools, JTS,
Geoscript and uDig community. Their community websites are full of
learning material that can be use to grow knowledge beyond the
boundaries of this set of tutorials.

The Groovy examples base on the great documentation available on
Groovy's homepage.

Another essential source has been the Wikipedia community effort.

Particular thanks go to those friends that directly or indirectly helped
out in the creation and review of this series of handbooks.

This tutorial is brought to you by HydroloGIS.

More Related Content

What's hot

R getting spatial
R getting spatialR getting spatial
R getting spatialFAO
 
10. Getting Spatial
10. Getting Spatial10. Getting Spatial
10. Getting SpatialFAO
 
Create a correlation plot from joined tables and lag times
Create a correlation plot from joined tables and lag timesCreate a correlation plot from joined tables and lag times
Create a correlation plot from joined tables and lag timesDougLoqa
 
5. R basics
5. R basics5. R basics
5. R basicsFAO
 
R Programming: Numeric Functions In R
R Programming: Numeric Functions In RR Programming: Numeric Functions In R
R Programming: Numeric Functions In RRsquared Academy
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processingTim Essam
 
R Programming: Learn To Manipulate Strings In R
R Programming: Learn To Manipulate Strings In RR Programming: Learn To Manipulate Strings In R
R Programming: Learn To Manipulate Strings In RRsquared Academy
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat SheetLaura Hughes
 
Spark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with SparkSpark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with Sparksamthemonad
 
R Programming: Export/Output Data In R
R Programming: Export/Output Data In RR Programming: Export/Output Data In R
R Programming: Export/Output Data In RRsquared Academy
 
Creating a Custom Serialization Format (Gophercon 2017)
Creating a Custom Serialization Format (Gophercon 2017)Creating a Custom Serialization Format (Gophercon 2017)
Creating a Custom Serialization Format (Gophercon 2017)Scott Mansfield
 
Stata cheatsheet transformation
Stata cheatsheet transformationStata cheatsheet transformation
Stata cheatsheet transformationLaura Hughes
 
Stata cheat sheet: data transformation
Stata  cheat sheet: data transformationStata  cheat sheet: data transformation
Stata cheat sheet: data transformationTim Essam
 
Hive function-cheat-sheet
Hive function-cheat-sheetHive function-cheat-sheet
Hive function-cheat-sheetDr. Volkan OBAN
 
Stata cheat sheet analysis
Stata cheat sheet analysisStata cheat sheet analysis
Stata cheat sheet analysisTim Essam
 

What's hot (20)

R getting spatial
R getting spatialR getting spatial
R getting spatial
 
10. Getting Spatial
10. Getting Spatial10. Getting Spatial
10. Getting Spatial
 
Create a correlation plot from joined tables and lag times
Create a correlation plot from joined tables and lag timesCreate a correlation plot from joined tables and lag times
Create a correlation plot from joined tables and lag times
 
5. R basics
5. R basics5. R basics
5. R basics
 
R language introduction
R language introductionR language introduction
R language introduction
 
R Programming: Numeric Functions In R
R Programming: Numeric Functions In RR Programming: Numeric Functions In R
R Programming: Numeric Functions In R
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processing
 
R Programming: Learn To Manipulate Strings In R
R Programming: Learn To Manipulate Strings In RR Programming: Learn To Manipulate Strings In R
R Programming: Learn To Manipulate Strings In R
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat Sheet
 
Spark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with SparkSpark 4th Meetup Londond - Building a Product with Spark
Spark 4th Meetup Londond - Building a Product with Spark
 
R Programming: Export/Output Data In R
R Programming: Export/Output Data In RR Programming: Export/Output Data In R
R Programming: Export/Output Data In R
 
Creating a Custom Serialization Format (Gophercon 2017)
Creating a Custom Serialization Format (Gophercon 2017)Creating a Custom Serialization Format (Gophercon 2017)
Creating a Custom Serialization Format (Gophercon 2017)
 
Stata cheatsheet transformation
Stata cheatsheet transformationStata cheatsheet transformation
Stata cheatsheet transformation
 
Stata cheat sheet: data transformation
Stata  cheat sheet: data transformationStata  cheat sheet: data transformation
Stata cheat sheet: data transformation
 
OpenVX 1.1 Reference Guide
OpenVX 1.1 Reference GuideOpenVX 1.1 Reference Guide
OpenVX 1.1 Reference Guide
 
Jfreechart tutorial
Jfreechart tutorialJfreechart tutorial
Jfreechart tutorial
 
R training3
R training3R training3
R training3
 
Hive function-cheat-sheet
Hive function-cheat-sheetHive function-cheat-sheet
Hive function-cheat-sheet
 
Data transformation-cheatsheet
Data transformation-cheatsheetData transformation-cheatsheet
Data transformation-cheatsheet
 
Stata cheat sheet analysis
Stata cheat sheet analysisStata cheat sheet analysis
Stata cheat sheet analysis
 

Similar to 03 Geographic scripting in uDig - halfway between user and developer

PART 3: THE SCRIPTING COMPOSER AND PYTHON
PART 3: THE SCRIPTING COMPOSER AND PYTHONPART 3: THE SCRIPTING COMPOSER AND PYTHON
PART 3: THE SCRIPTING COMPOSER AND PYTHONAndrea Antonello
 
Node.js basics
Node.js basicsNode.js basics
Node.js basicsBen Lin
 
Devry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filesDevry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filesnoahjamessss
 
Devry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filesDevry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filescskvsmi44
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptxGuy Komari
 
Lab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docx
Lab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docxLab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docx
Lab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docxDIPESH30
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLaurence Svekis ✔
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...Yashpatel821746
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Yashpatel821746
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...Yashpatel821746
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkChristian Trabold
 
The Ring programming language version 1.9 book - Part 7 of 210
The Ring programming language version 1.9 book - Part 7 of 210The Ring programming language version 1.9 book - Part 7 of 210
The Ring programming language version 1.9 book - Part 7 of 210Mahmoud Samir Fayed
 
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationLecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationMohammed Farrag
 
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" DependenciesAnalyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" DependenciesPVS-Studio
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot CampTroy Miles
 
Program Assignment Process ManagementObjective This program a.docx
Program Assignment  Process ManagementObjective This program a.docxProgram Assignment  Process ManagementObjective This program a.docx
Program Assignment Process ManagementObjective This program a.docxwkyra78
 

Similar to 03 Geographic scripting in uDig - halfway between user and developer (20)

PART 3: THE SCRIPTING COMPOSER AND PYTHON
PART 3: THE SCRIPTING COMPOSER AND PYTHONPART 3: THE SCRIPTING COMPOSER AND PYTHON
PART 3: THE SCRIPTING COMPOSER AND PYTHON
 
Tres Gemas De Ruby
Tres Gemas De RubyTres Gemas De Ruby
Tres Gemas De Ruby
 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
 
Devry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filesDevry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-files
 
Devry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filesDevry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-files
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
C# to python
C# to pythonC# to python
C# to python
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Lab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docx
Lab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docxLab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docx
Lab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docx
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase framework
 
The Ring programming language version 1.9 book - Part 7 of 210
The Ring programming language version 1.9 book - Part 7 of 210The Ring programming language version 1.9 book - Part 7 of 210
The Ring programming language version 1.9 book - Part 7 of 210
 
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationLecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administration
 
Book
BookBook
Book
 
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" DependenciesAnalyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
Program Assignment Process ManagementObjective This program a.docx
Program Assignment  Process ManagementObjective This program a.docxProgram Assignment  Process ManagementObjective This program a.docx
Program Assignment Process ManagementObjective This program a.docx
 

More from Andrea Antonello

Smash & Geopaparazzi - State of the art 2021
Smash & Geopaparazzi - State of the art 2021Smash & Geopaparazzi - State of the art 2021
Smash & Geopaparazzi - State of the art 2021Andrea Antonello
 
GEOPAPARAZZI: STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
GEOPAPARAZZI: STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATIONGEOPAPARAZZI: STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
GEOPAPARAZZI: STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATIONAndrea Antonello
 
GEOPAPARAZZI STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
GEOPAPARAZZI STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATIONGEOPAPARAZZI STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
GEOPAPARAZZI STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATIONAndrea Antonello
 
Geopaparazzi Survey Server workshop
Geopaparazzi Survey Server workshopGeopaparazzi Survey Server workshop
Geopaparazzi Survey Server workshopAndrea Antonello
 
Geopaparazzi Survey Server Installation
Geopaparazzi Survey Server InstallationGeopaparazzi Survey Server Installation
Geopaparazzi Survey Server InstallationAndrea Antonello
 
Modelling natural hazards in gvSIG with the HortonMachine plugins
Modelling natural hazards in gvSIG with the HortonMachine pluginsModelling natural hazards in gvSIG with the HortonMachine plugins
Modelling natural hazards in gvSIG with the HortonMachine pluginsAndrea Antonello
 
GEOPAPARAZZI: STATE OF THE ART
GEOPAPARAZZI: STATE OF THE ARTGEOPAPARAZZI: STATE OF THE ART
GEOPAPARAZZI: STATE OF THE ARTAndrea Antonello
 
Geopaparazzi - NEVER OUT OF DATA IN THE FIELD
Geopaparazzi - NEVER OUT OF DATA IN THE FIELDGeopaparazzi - NEVER OUT OF DATA IN THE FIELD
Geopaparazzi - NEVER OUT OF DATA IN THE FIELDAndrea Antonello
 
The HortonMachine, for data analysis to help scientists... and not only
The HortonMachine, for data analysis to help scientists... and not onlyThe HortonMachine, for data analysis to help scientists... and not only
The HortonMachine, for data analysis to help scientists... and not onlyAndrea Antonello
 
Geopaparazzi & gvSIG Mobile - state of the art
Geopaparazzi & gvSIG Mobile - state of the artGeopaparazzi & gvSIG Mobile - state of the art
Geopaparazzi & gvSIG Mobile - state of the artAndrea Antonello
 
PART 6: FROM GEO INTO YOUR REPORT
PART 6: FROM GEO INTO YOUR REPORTPART 6: FROM GEO INTO YOUR REPORT
PART 6: FROM GEO INTO YOUR REPORTAndrea Antonello
 
PART 4: GEOGRAPHIC SCRIPTING
PART 4: GEOGRAPHIC SCRIPTINGPART 4: GEOGRAPHIC SCRIPTING
PART 4: GEOGRAPHIC SCRIPTINGAndrea Antonello
 
Foss4g2016 Geopaparazzi Workshop
Foss4g2016 Geopaparazzi WorkshopFoss4g2016 Geopaparazzi Workshop
Foss4g2016 Geopaparazzi WorkshopAndrea Antonello
 
New tools for LiDAR, forestry, river management and hydro-geomorphology in gvSIG
New tools for LiDAR, forestry, river management and hydro-geomorphology in gvSIGNew tools for LiDAR, forestry, river management and hydro-geomorphology in gvSIG
New tools for LiDAR, forestry, river management and hydro-geomorphology in gvSIGAndrea Antonello
 
Digital field mapping with Geopaparazzi and gvSIG
Digital field mapping with Geopaparazzi and gvSIGDigital field mapping with Geopaparazzi and gvSIG
Digital field mapping with Geopaparazzi and gvSIGAndrea Antonello
 
Geopaparazzi, history of a digital mapping kid
Geopaparazzi, history of a digital mapping kidGeopaparazzi, history of a digital mapping kid
Geopaparazzi, history of a digital mapping kidAndrea Antonello
 
Geopaparazzi, state of the art
Geopaparazzi, state of the artGeopaparazzi, state of the art
Geopaparazzi, state of the artAndrea Antonello
 
Geographic scripting in uDig
Geographic scripting in uDigGeographic scripting in uDig
Geographic scripting in uDigAndrea Antonello
 
LESTO - a GIS toolbox for LiDAR empowered sciences
LESTO - a GIS toolbox for LiDAR empowered sciencesLESTO - a GIS toolbox for LiDAR empowered sciences
LESTO - a GIS toolbox for LiDAR empowered sciencesAndrea Antonello
 
04 Geographic scripting in uDig - halfway between user and developer
04 Geographic scripting in uDig - halfway between user and developer04 Geographic scripting in uDig - halfway between user and developer
04 Geographic scripting in uDig - halfway between user and developerAndrea Antonello
 

More from Andrea Antonello (20)

Smash & Geopaparazzi - State of the art 2021
Smash & Geopaparazzi - State of the art 2021Smash & Geopaparazzi - State of the art 2021
Smash & Geopaparazzi - State of the art 2021
 
GEOPAPARAZZI: STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
GEOPAPARAZZI: STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATIONGEOPAPARAZZI: STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
GEOPAPARAZZI: STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
 
GEOPAPARAZZI STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
GEOPAPARAZZI STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATIONGEOPAPARAZZI STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
GEOPAPARAZZI STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
 
Geopaparazzi Survey Server workshop
Geopaparazzi Survey Server workshopGeopaparazzi Survey Server workshop
Geopaparazzi Survey Server workshop
 
Geopaparazzi Survey Server Installation
Geopaparazzi Survey Server InstallationGeopaparazzi Survey Server Installation
Geopaparazzi Survey Server Installation
 
Modelling natural hazards in gvSIG with the HortonMachine plugins
Modelling natural hazards in gvSIG with the HortonMachine pluginsModelling natural hazards in gvSIG with the HortonMachine plugins
Modelling natural hazards in gvSIG with the HortonMachine plugins
 
GEOPAPARAZZI: STATE OF THE ART
GEOPAPARAZZI: STATE OF THE ARTGEOPAPARAZZI: STATE OF THE ART
GEOPAPARAZZI: STATE OF THE ART
 
Geopaparazzi - NEVER OUT OF DATA IN THE FIELD
Geopaparazzi - NEVER OUT OF DATA IN THE FIELDGeopaparazzi - NEVER OUT OF DATA IN THE FIELD
Geopaparazzi - NEVER OUT OF DATA IN THE FIELD
 
The HortonMachine, for data analysis to help scientists... and not only
The HortonMachine, for data analysis to help scientists... and not onlyThe HortonMachine, for data analysis to help scientists... and not only
The HortonMachine, for data analysis to help scientists... and not only
 
Geopaparazzi & gvSIG Mobile - state of the art
Geopaparazzi & gvSIG Mobile - state of the artGeopaparazzi & gvSIG Mobile - state of the art
Geopaparazzi & gvSIG Mobile - state of the art
 
PART 6: FROM GEO INTO YOUR REPORT
PART 6: FROM GEO INTO YOUR REPORTPART 6: FROM GEO INTO YOUR REPORT
PART 6: FROM GEO INTO YOUR REPORT
 
PART 4: GEOGRAPHIC SCRIPTING
PART 4: GEOGRAPHIC SCRIPTINGPART 4: GEOGRAPHIC SCRIPTING
PART 4: GEOGRAPHIC SCRIPTING
 
Foss4g2016 Geopaparazzi Workshop
Foss4g2016 Geopaparazzi WorkshopFoss4g2016 Geopaparazzi Workshop
Foss4g2016 Geopaparazzi Workshop
 
New tools for LiDAR, forestry, river management and hydro-geomorphology in gvSIG
New tools for LiDAR, forestry, river management and hydro-geomorphology in gvSIGNew tools for LiDAR, forestry, river management and hydro-geomorphology in gvSIG
New tools for LiDAR, forestry, river management and hydro-geomorphology in gvSIG
 
Digital field mapping with Geopaparazzi and gvSIG
Digital field mapping with Geopaparazzi and gvSIGDigital field mapping with Geopaparazzi and gvSIG
Digital field mapping with Geopaparazzi and gvSIG
 
Geopaparazzi, history of a digital mapping kid
Geopaparazzi, history of a digital mapping kidGeopaparazzi, history of a digital mapping kid
Geopaparazzi, history of a digital mapping kid
 
Geopaparazzi, state of the art
Geopaparazzi, state of the artGeopaparazzi, state of the art
Geopaparazzi, state of the art
 
Geographic scripting in uDig
Geographic scripting in uDigGeographic scripting in uDig
Geographic scripting in uDig
 
LESTO - a GIS toolbox for LiDAR empowered sciences
LESTO - a GIS toolbox for LiDAR empowered sciencesLESTO - a GIS toolbox for LiDAR empowered sciences
LESTO - a GIS toolbox for LiDAR empowered sciences
 
04 Geographic scripting in uDig - halfway between user and developer
04 Geographic scripting in uDig - halfway between user and developer04 Geographic scripting in uDig - halfway between user and developer
04 Geographic scripting in uDig - halfway between user and developer
 

Recently uploaded

All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Nikki Chapple
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 

Recently uploaded (20)

All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 

03 Geographic scripting in uDig - halfway between user and developer

  • 1. Open Source GIS Geographic scripting in uDig - halfway between user and developer Geoinformation Research Group, Department of Geography University of Potsdam March 2013 The scripting console Tutor: Andrea Antonello ydroloGIS nvironmental ngineering HydroloGIS S.r.l. - Via Siemens, 19 - 39100 Bolzano www.hydrologis.com
  • 2. The Geoscript editor Scritping is one of the powerful things in GIS. Non developers have the possibility to create great automatisations through it. uDig's scripting console is based on the groovy java scripting language. The geoscript geographic scripting engine can be used from within uDig.
  • 3. Open the console Two icons can be used to open the scripting editor: one for creating a new empty script and one to open an existing script.
  • 4. Let's create a new one. The user will be prompted to save the new script to file and an empty editor is opened. There are a few tool inside the editor, needed to start and stop scripts, or set the heap memory allowed to be used by a script or enable logging.
  • 5. Script away, with command completion and syntax coloring Inside the editor some basic command completion is available. For geoscript objects, as for example the widely use Geometry:
  • 6. but also for methods, as for example the fromWKT, a handy way to create geometries on the fly:
  • 7. The base language: be Groovy! In order to be able exploit 100% the console and scripting engine, it is mandatory to get a good insight of the base language that can be used in the console. Before we start with the geo part, we will investigate a bit groovy. Let's create a new script to do so. We should find ourself in front of a nice empty editor.
  • 8. Writing strings To run your first script, simply write the following in the editor // write a string println "This is a string" and push the play button. The result should be the following inside the console window: Process started: 2013-02-10 18:02:03 This is a string Process finished: 2013-02-10 18:02:04 The script simply prints the string in the console. It also gives information about the start and end timestamps of the script execution. Note that the editor executes only the selected text inside the editor. If nothing is selected, all of it is used.
  • 9. Also more complex strings can be used, by surrounding text with triple quotes: // write a complex string println """Inside triple quotes you can do almost anything. It is kind of an advanced string!""" Select only the second part and see if it is executed properly.
  • 10. Variables // define variables // a string def name = "Luis" // a number def age = 25 /* * insert the variables into a string template * through the use of ${} */ def myTemplate1 = "Hi, my name is ${name} and I'm ${age}." println myTemplate1 // strings and numbers can also be concatenated through the + sign def myTemplate2 = "Hi, my name is " + name + " and I'm " + age + "." println myTemplate2
  • 11. Lists // working with lists // create a list of strings def list = ["Merano", "Bolzano", "Trento"]; println list; // how to access the elements? println "The elements start at position 0: " + list[0] // how to add an element to the list? list << "Potsdam" println list; // how to remove an element from the list? // by object? list.remove("Potsdam") println list; // better by index list.remove(0) println list;
  • 12. Lists magic - part 1 // lists magic - part 1 def list = ["Merano", "Bolzano", "Trento"]; // to loop over a list the default 'it' can be used list.each { println it } // ...or your very own variable... list.each{ myVar -> println "This a town: " + myVar } // ...or you can use an index, too list.eachWithIndex{myVar, i -> println "${myVar} is town N.${i}" }
  • 13. Lists magic - part 2 // lists magic - part 2 def list = ["Merano", "Bolzano", "Trento"]; println "This is the original list: " + list // lists can be sorted list.sort(); println "This is the sorted list: " + list // and reverse sorted def revList = list.reverse(); // note that while sort changes the original list, reverse makes a copy println "This is list after the sorting: " + list println "This is reverse list: " + revList println "This is list after the reverse sorting: " + list
  • 14. Lists magic - part 3 // lists magic - part 3 // concatenate list def abc = ["a", "b", "c"] def cde = ["c", "d", "e"] def newabcde = abc + cde println newabcde // through 'join' the list can be concatenated to one single string println newabcde.join(",") println newabcde.join(" | ") // if we are talking about numbers, some functions apply def nums = [1.0, 2, 3.5] println nums.max() println nums.min() println nums.sum()
  • 15. Lists magic - part 4 // lists magic - part 4 // modify each element of the list with collect def abc = ["a", "b", "c"] println "Original abc: " + abc abc = abc.collect{ it += " is a letter" } println "Modified abc: " + abc // flatten nested lists def abc = ["a", "b", "c"] def cde = ["c", "d", "e"] abc << cde println abc println abc.flatten()
  • 16. Maps (Hash) Groovy speaking a Map is a container of key and value pairs. // working with maps // create a map // key1:value1, key2:value2, ... def townsProvinceMap = [merano:"BZ", bolzano:"BZ", trento:"TN"] println townsProvinceMap // ways of accessing the values of a map // implicit println townsProvinceMap.merano // the "array" way println townsProvinceMap["merano"] // through the "getter" println townsProvinceMap.get("merano") // ways to add an element // implicit townsProvinceMap.lagundo = "BZ" println townsProvinceMap // through the put method townsProvinceMap.put("Postdam", "BR") println townsProvinceMap
  • 17. Maps magic // maps magic def townsProvinceMap = [merano:"BZ", bolzano:"BZ", trento:"TN"] // iterate the thing with the default value... townsProvinceMap.each{ println it } // ...or with key and value separated... townsProvinceMap.each{ println "${it.key} is in province of ${it.value}" } // ...or with own vars townsProvinceMap.each{key, value -> println "${key} is in province of ${value}" }
  • 18. Ranges Range can be seen at first as a sequence, but there is much more behind it. // working with ranges // create a range def range = 1..3 // do some iterations range.each{ println it } range.each{ println "what?" } // and what about dates? def now = new Date(); def nextWeek = now + 7; (now..nextWeek).each{ println it } // since ranges have a from, to and size... println "A range from " + range.from + " to " + range.to + " of size " + range.size() // ...you can use them in for loops... for (i in 1..3){ println "step number: ${i}" } // ...which ovbiously could be done like the following (1..3).each{ println "closure step number: ${it}" }
  • 19. Groovy: working with files & filesystem Groovy allows to access the OS-environment and read the filesystem. // working with the filesystem // get system info System.env.each{ println it} // get the home folder def userHome = System.getenv("HOME") println userHome // list a folder's content def home = new File(userHome) println "The contents of " + home.absolutePath + " are:" home.eachFile{ file -> println "t" + file } // list only folders println "...of which folders:" home.eachDir{ dir -> println "t" + dir } // list only files println "...of which files:" home.eachFile{ file -> if(file.isFile()) println "t" + file } // recursive list content println "Recursive folders content:" home.eachDirRecurse{ dir -> println "t" + dir }
  • 20. Reading Files // reading files // start with creating a new file to be read afterwards def newFile = new File(System.getenv("HOME") + "/testFileToBeRemoved.txt"); // one way to writ text to file newFile.write("""A new header. A new testline. A second testline. """) // read the file line by line newFile.eachLine{ line, index -> println "line " + index + ". " + line } // read the file into a string variable def content = newFile.text println content
  • 21. Writing Files // writing files def file = new File(System.getenv("HOME") + "/testFileToBeRemoved.txt"); println file.text // append some content file << "Some text after the last line is appended!" println file.text // merge files def file2 = new File(file.absolutePath + "2") file2.write("Content of file 2"); println file2.text def mergedFile = new File(file.absolutePath + "_merged") mergedFile << file.text mergedFile << file2.text println "nThe merged file:" println mergedFile.text // delete the files file.delete() file2.delete() mergedFile.delete()
  • 22. Reading CSV Files // read values from a csv file // create a sample csv file def file = new File(System.getenv("HOME") + "/sample.csv"); file.write("""# id, lat, lon, elev 1, 11.0, 46.0, 250 2, 11.1, 46.1, 251 3, 11.2, 46.2, 252 """) println file.text // read the csv values def recordsList = [] file.eachLine{ if(it.trim().length() == 0) { println "Empty line hit." } else if(it.startsWith("#")) { println "Comment line hit." } else { def lineSplit = it.split(",") println "Values: ${lineSplit[0]}, ${lineSplit[1]}, ${lineSplit[2]}, ${lineSplit[3]}" } }
  • 23. Groovy: Data structures for complex scripts // working with data structures // create a data structure class Record { def id def lat def lon def elev public String toString(){ "Values: [${id}, ${lat}, ${lon}, ${elev}]" } } // read the csv into a list of records def file = new File(System.getenv("HOME") + "/sample.csv"); def recordsList = [] file.eachLine{ if(it.trim().length() > 0 && !it.startsWith("#")) { def lineSplit = it.split(",") def record = new Record() record.id = lineSplit[0] record.lat = lineSplit[1] record.lon = lineSplit[2] record.elev = lineSplit[3] recordsList << record } } println recordsList
  • 24. Groovy: most important conditions and loops If-then-else: def x = false def y = false if ( x ) { x = false } else { y = true } Ternary operator: def y = 5 def x = (y > 1) ? "worked" : "failed" While loop: def x = 0 def y = 5 while ( y-- > 0 ) { x++ }
  • 25. For loop: for (int i = 0; i < 5; i++) { ... } def x = 0 for ( i in 0..9 ) { x += i } x = 0 for ( i in [0, 1, 2, 3, 4] ) { x += i } Loop with closures: def stringList = [ "java", "perl", "python", "ruby", "c#", "cobol", "groovy", "jython", "smalltalk", "prolog", "m", "yacc" ]; stringList.each() { print " ${it}" }
  • 26. This work is released under Creative Commons Attribution Share Alike (CC-BY-SA) Much of the knowledge needed to create this training material has been produced by the sparkling knights of the GeoTools, JTS, Geoscript and uDig community. Their community websites are full of learning material that can be use to grow knowledge beyond the boundaries of this set of tutorials. The Groovy examples base on the great documentation available on Groovy's homepage. Another essential source has been the Wikipedia community effort. Particular thanks go to those friends that directly or indirectly helped out in the creation and review of this series of handbooks. This tutorial is brought to you by HydroloGIS.