Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Andrey Adamovich - Groovy 2 Cookbook - 2013.pdf
Скачиваний:
44
Добавлен:
19.03.2016
Размер:
26.28 Mб
Скачать

Using Groovy Language Features

If the Sample class is annotated with @TypeChecked, the compiler will return:

[Static type checking] -

Cannot find matching method java.lang.Object#toUpperCase(). Please check if the declared type is right

and if the method exists. @ line 77, column 44.

wo','three'].collect { println it.toUpper

^

What is happening here? Simply, the compiler has no idea of the type of the implicit variable it, which is often used inside closures to make the code even more terse. This compilation error can be solved by explicitly declaring the closure variable as follows:

['one','two','three'].collect {

myString -> println myString.toUpperCase()

}

Adding automatic logging to Groovy classes

In the Writing less verbose Java Beans with Groovy Beans, Adding the cloning functionality to Groovy Beans, and Inheriting constructors in Groovy classes recipes, we met some of the

annotation-based AST transformations available in Groovy. An AST transformation is a process in which a programmer is able to hook into the bytecode generation process and influence the final shape of the resulting bytecode. Groovy ships with many useful transformations and in this recipe, we are going to look at the family of logging annotations.

How to do it...

The transformation we are going to demonstrate is the @groovy.util.logging.Log annotation that injects java.util.logging.Logger into a Groovy class:

1.Let's apply the annotation to a Groovy class:

@groovy.util.logging.Log class UserService {

def createUser(String username, String password) { log.info("creating user with name ${username}")

}

}

2.And call the method of the new class:

def userService = new UserService() userService.createUser('john', 'secret')

132

www.it-ebooks.info

Chapter 3

3.The output will be:

INFO: creating user with name john

How it works...

The annotation takes a number of steps. First, it creates a logger with the variable name log and injects it in the class as a static final variable. Then it surrounds every call to the logger with a conditional check to verify whether the log level is enabled. No need to pollute your code with hard-to-read if statements just to check whether the log statement should

be evaluated.

The variable that holds the logger can be modified by using an attribute on the annotation:

@groovy.util.logging.Log('someLogger') class UserService { ... }

There's more...

The logging transformation is not limited to use only one logging framework but it also allows to use the following logging facilities by changing the annotation class:

ff @groovy.util.logging.Commons: It injects an Apache Commons logger and initializes it using LogFactory.getLog(class).

ff @groovy.util.logging.Log4j: It injects Log4J org.apache.log4j.Logger into the class and initializes it using Logger.getLogger(class).

ff @groovy.util.logging.Slf4j: It injects a Slf4J logger into the annotated class and initializes it using org.slf4j.LoggerFactory.getLogger(class). Slf4J is the underlying logger used by the newer framework Logback. If you wish to use that framework you should use the @Slf4j annotation.

See also

ff http://groovy.codehaus.org/api/groovy/util/logging/Log.html

ff http://docs.oracle.com/javase/7/docs/api/java/util/logging/ Logger.html

ff http://commons.apache.org/proper/commons-logging/ ff http://logging.apache.org/log4j

ff http://www.slf4j.org/

133

www.it-ebooks.info

www.it-ebooks.info

4

Working with Files in Groovy

In this chapter, we will cover:

ff ff ff ff ff ff ff ff ff ff ff ff ff

Reading from a file

Reading a text file line by line Processing every word in a text file Writing to a file

Replacing tabs with spaces in a text file Filtering a text file's content

Deleting a file or directory

Walking through a directory recursively

Searching for files

Changing file attributes on Windows Reading data from a ZIP file Reading an Excel file

Extracting data from a PDF

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]