download

basic

Program structure

Customizable Operators

Operator Method
a + b a.plus(b)
a - b a.minus(b)
a * b a.multiply(b)
a / b a.div(b)
a % b a.mod(b)
a++ or ++a a.next()

assert [ a: true, b: false ]  +  [ a: false ] == [ a: false, b: false ]
assert [ a: true, b: false  ] << [ a: false ] == [ a: false, b: false ]

Special Operators

Operator Meaning Name
a ? b : c if(a) b else c ternary if
a ?: b a ? a : b Elvis
a.?b ( a==null ) ? a : a.b null safe
a(*list) a(list[0], list[1], ...) spread
list*.a() [list[0].a, list[1].a, ...] spread-out
a.&b reference to method b in object a as closure method closure
a.@field direct field access dot-at
  • .& : Method pointer operator

    def str = 'example of method reference'
    def fun = str.&toUpperCase
    assert fun() == str.toUpperCase()
    println fun()
    
    // result
    EXAMPLE OF METHOD REFERENCE
    class Person {
      String name
      Integer age
    }
    def list = [
      new Person( name: 'Bob'   , age: 42 ) ,
      new Person( name: 'Julia' , age: 35 )
    ]
    String describe(Person p) { "$p.name is $p.age" }
    
    def action = this.&describe
    def transform( List<Person> elements, Closure action ) {
      elements.inject([]){ result, e ->
        result << action(e)
        result
      }
    }
    
    println transform( list, action )
    // result
    // [Bob is 42, Julia is 35]

elvis operator

if/elseif{if}/else

references:

usage

  • ?: ( existing Elvis operator )
    displayName = user.name ? user.name : 'Anonymous'
    displayName = user.name ?: 'Anonymous'
  • ?= ( new elvis assignment shorthand )
    name = name ?: 'Hydrogen'   // existing Elvis operator
    atomicNumber ?= 2           // new Elvis assignment shorthand

condition:

  • if fruits is 'apple' or 'orange', get pre-defined number 5 ( number = 5 )
  • if fruits is watermelon, get particular given numbers. number cannot be null
// by using if/elseif{if}/else
Map option = [:]
if ( [ 'apple', 'orange' ].contains(fruits) ) {
  option = [ "${fruits}" : '5' ]
} else if ( [ 'watermelon' ].contains(fruits) ) {
  if (number) {
    option = [ "${fruits}" : number ]
  }
} else {
  println( 'ERROR: number CANNOT be empty while fruits is watermelon. Exit ...' )
}

// by using elvis operator
Map option = ( [ 'apple', 'orange' ].contains(fruits) ) ? [ "${fruits}" : '5' ]
           : ( [ 'watermelon' ].contains(fruits) ) ? ( number )
              ? [ "${fruits}" : number ]
              : println( 'ERROR: number CANNOT be empty while fruits is watermelon. Exit ...' )
           : [:]
  • example

    Closure option = { String fruits, String number = '' ->
        ( [ 'apple', 'orange' ].contains(fruits) ) ? [ (fruits) : '5' ]
        : ( [ 'watermelon' ].contains(fruits) ) ? ( number )
          ? [ (fruits) : number ]
          : println( 'ERROR: number CANNOT be empty while fruits is watermelon. Exit ...' )
        : [:]
    }
    
    assert option('apple') == ['apple' : '5']
    assert option('watermelon', '100') == [ 'watermelon' : '100' ]

    • using [ "${fruits}" : '5' ], the class of key is class org.codehaus.groovy.runtime.GStringImpl
    • using [ (fruits) : '5' ] , the class of key is class java.lang.String

execute shell commands in groovy

Get STDERR & STDERR

Tip

using new StringBuffer() or new StringBuilder()

i.e.:

def stdout = new StringBuffer(), stderr = new StringBuffer()
def proc = "cmd".execute()
proc.waitForProcessOutput( stdout, stderr )
int exitCode = proc.exitValue()
println( (exitCode == 0) ? stdout : "exit with ${exitCode}. error: ${stderr}" )
def stdout = new StringBuilder(), stderr = new StringBuilder()

def proc = "ls /tmp/NoFile".execute()
proc.consumeProcessOutput( stdout, stderr )
proc.waitForOrKill( 1000 )

int exitCode = proc.exitValue()
println( ( exitCode == 0 ) ? stdout : "error with exit code ${exitCode}.\nSTDERR: ${stderr}" )

or

def stdout = new StringBuilder(), stderr = new StringBuilder()
def proc = 'ls /tmp/NoFile'.execute()
proc.consumeProcesstdoutput( stdout, stderr )
proc.waitForOrKill(1000)
println( stdout ? "out> \n${stdout}" : '' + stderr ? "err> \n${stderr}" : '' )

Show output during the process

using System.out and System.err

def proc = "ls /tmp/NoFile".execute()
proc.waitForProcessOutput( System.out, System.err )
proc.waitForOrKill(1000)

int exitCode = proc.exitValue()
if ( exitCode != 0 ) {
  println "error with exit code ${exitCode}."
}

with environment

def envVars = ["GROOVY_HOME=/fake/path/groovy-3.0.7", "CLASSPATH=.:/fake/path/groovy-3.0.7/lib"]

def proc = './run.sh'.execute( envVars, new File(".") )
proc.waitForProcessOutput( System.out, System.err )
int exitCode = proc.exitValue()

println( (exitCode != 0) ? "exit with ${exitCode}" : '' )
  • run.sh

    env
    echo ${GROOVY_HOME}
  • result execute with environemnt

with system environment

List envVars = System.getenv().collect { k, v -> "${k}=${v}" }

def proc = "./run.sh".execute( envVars, new File(".") )
proc.waitForProcessOutput( System.out, System.err )
int exitCode = proc.exitValue()

println( (exitCode != 0) ? "exit with ${exitCode}" : '' )

with partular path

reference:

def command = "git log -1"
def proc = command.execute( null, new File('/path/to/folder') )
proc.waitFor()

println """
  ${proc.err.text ?: ''}
  ${proc.in.text ?: ''}
  Process exit code: ${proc.exitValue()}
"""

groovyConsole

environment

> setx JAVA_OPT '-Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8'
> setx GROOVY_OPT '-Dfile.encoding=UTF-8'
> setx JAVA_TOOL_OPTIONS '-Dfile.encoding=UTF-8'

get console details

  • charset

    import java.nio.charset.Charset
    
    System.out.println( String.format("file.encoding: %s", System.getProperty("file.encoding")) );
    System.out.println( String.format("defaultCharset: %s", Charset.defaultCharset().name()) );
    • result
      file.encoding: UTF-8
      defaultCharset: UTF-8

font

references:

  • check font

    javax.swing.UIManager.getLookAndFeelDefaults()
    
    // or
    javax.swing.UIManager.getLookAndFeelDefaults().each {
      println "... ${it.key} : ${it.value}"
    }
  • or

    import java.awt.Font
    for (Map.Entry<Object, Object> entry : javax.swing.UIManager.getDefaults().entrySet()) {
        Object key = entry.getKey();
        Object value = javax.swing.UIManager.get(key);
        if (value != null && value instanceof javax.swing.plaf.FontUIResource) {
          println ".. ${key} : ${value}"
        }
    }
    result
  • modify font

import javax.swing.plaf.FontUIResource
import javax.swing.UIManager
import java.awt.Font

UIManager.put("Panel.font", new FontUIResource(new Font ("Monaco", Font.PLAIN, 16)));
  • other options

    references:

    other options
Copyright © marslo 2020-2024 all right reserved,powered by GitbookLast Modified: 2024-10-30 04:30:28

results matching ""

    No results matching ""